18 Commits
Author SHA1 Message Date
genichin 6e17a53b17 chore(release): prepare portfolio-hub v0.2.0
Publish verified PortfolioHub image / verify (push) Canceled after 0s
Publish verified PortfolioHub image / publish (push) Canceled after 0s
2026-08-21 17:13:34 +09:00
genichin f48a7c5cd7 docs(proofline): capture portfolio ledger discovery 2026-08-20 12:36:24 +09:00
genichin ac742b1150 feat(portfolios): add unified ledger history API 2026-08-20 12:01:28 +09:00
genichin fe22be0b66 docs: record ProofLine specification for issue 28 2026-08-19 17:42:22 +09:00
genichin 5eb8c04266 fix: aggregate investment totals across ledger sources 2026-08-19 17:34:13 +09:00
genichin 02bfa60299 chore(release): prepare portfolio-hub v0.1.3
Publish verified PortfolioHub image / verify (push) Canceled after 0s
Publish verified PortfolioHub image / publish (push) Canceled after 0s
2026-08-16 16:57:26 +09:00
genichin ec912fcde8 docs(proofline): align strategy nickname criteria 2026-08-16 16:50:20 +09:00
genichin 75e55fde9c feat(api): expose strategy nick on portfolio items 2026-08-16 13:13:39 +09:00
genichin ee1af6ef49 fix(api): reject explicit null strategy nick
Publish verified PortfolioHub image / verify (push) Canceled after 0s
Publish verified PortfolioHub image / publish (push) Canceled after 0s
2026-08-16 00:03:25 +09:00
genichin fe2dd3d15e test(postgres): use runtime migration command 2026-08-15 23:51:17 +09:00
genichin c292df0a4b chore(release): harden nick contract for v0.1.2 2026-08-15 23:46:57 +09:00
genichin e6a90800ec feat(strategy): expose configurable nick contract 2026-08-15 23:38:18 +09:00
genichin acfaab7fd4 ci(container): verify published immutable image 2026-08-15 15:40:25 +09:00
genichin d64079f583 test(cli): assert missing owner side effect
Publish verified PortfolioHub image / verify (push) Canceled after 0s
Publish verified PortfolioHub image / publish (push) Canceled after 0s
2026-08-15 15:31:00 +09:00
genichin 63ff4881b0 test(cli): stabilize required option assertion 2026-08-15 15:29:33 +09:00
genichin 6e10f71374 chore(lint): stabilize release import classification 2026-08-15 15:17:13 +09:00
genichin 9c8baac70b feat(container): harden v0.1.1 publication 2026-08-15 15:14:36 +09:00
genichin fd080496b3 feat(release): add verified image publication pipeline 2026-08-15 14:52:01 +09:00
100 changed files with 2895 additions and 190 deletions
+23
View File
@@ -0,0 +1,23 @@
**
!pyproject.toml
!uv.lock
!README.md
!app/
!app/**
# Defense in depth; the allowlist above is authoritative.
.git
.github
.stagepilot
.vendor
.claude
.env
.env.*
**/.env
docs
scripts
tests
temp
**/__pycache__
*.pyc
*.egg-info
+1
View File
@@ -3,6 +3,7 @@ PORTFOLIOHUB_ALLOWED_ORIGINS=http://localhost:3000
PORTFOLIOHUB_READ_TOKENS=read-token-123
PORTFOLIOHUB_TRADE_WRITE_TOKENS=trade-token-456
PORTFOLIOHUB_ADMIN_TOKENS=admin-token-789
PORTFOLIOHUB_LEDGER_CURSOR_SECRET=replace-with-a-long-random-secret
PORTFOLIOHUB_ENVIRONMENT=development
# Enable DB-backed repository (uses TIMESCALEDB_* below)
+101
View File
@@ -0,0 +1,101 @@
name: Publish verified PortfolioHub image
on:
push:
tags:
- "v*.*.*"
permissions:
contents: read
jobs:
verify:
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Reject every event except a strict version tag push
env:
RELEASE_EVENT: ${{ github.event_name }}
RELEASE_REF: ${{ github.ref }}
RELEASE_SHA: ${{ github.sha }}
run: |
python - <<'PY'
import os, re
assert os.environ["RELEASE_EVENT"] == "push"
assert re.fullmatch(r"refs/tags/v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", os.environ["RELEASE_REF"])
assert re.fullmatch(r"[0-9a-f]{40}", os.environ["RELEASE_SHA"])
PY
- name: Check out exact tagged source commit
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: ${{ github.sha }}
fetch-depth: 1
- run: python scripts/image_release.py validate-checkout --actual "$(git rev-parse HEAD)" --expected "${GITHUB_SHA}"
- run: python scripts/image_release.py validate-event --event "${GITHUB_EVENT_NAME}" --ref "${GITHUB_REF}" --commit "${GITHUB_SHA}" --project pyproject.toml
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.11"
- run: python -m pip install "uv==0.11.14"
- run: uv sync --extra dev --locked
- run: uv run pytest -q
- name: Honest scoped lint
run: uv run ruff check --select F,I app/db/migrations.py scripts/image_release.py tests/release
- name: Record exact source migration inventory
run: uv run python -c 'from app.db.migrations import migration_inventory; print("\n".join(migration_inventory()))' > migration-inventory.txt
- name: Create excluded synthetic canary
run: printf '%s\n' 'PORTFOLIO_HUB_SECRET_CANARY_DO_NOT_SHIP' > .env.ci-canary
- name: Build exact source image once
run: docker build --platform linux/amd64 --provenance=false --build-arg "SOURCE_COMMIT=${GITHUB_SHA}" --build-arg "RELEASE_VERSION=${GITHUB_REF_NAME}" --tag "portfolio-hub-ci:${GITHUB_SHA}" .
- name: Smoke installed payload, health, migration and isolated PostgreSQL
run: python scripts/image_release.py smoke --image "portfolio-hub-ci:${GITHUB_SHA}" --inventory migration-inventory.txt --timeout 180
- name: Record tested image ID
run: python scripts/image_release.py record-image-id --image "portfolio-hub-ci:${GITHUB_SHA}" --output portfolio-hub-image.id
- name: Export tested image without rebuilding
run: docker save --output portfolio-hub-image.tar "portfolio-hub-ci:${GITHUB_SHA}"
- name: Scan filesystem, history, inspect, archive metadata and outputs
run: |
set +e
python scripts/image_release.py scan --image "portfolio-hub-ci:${GITHUB_SHA}" --archive portfolio-hub-image.tar >canary-scan.stdout 2>canary-scan.stderr
scan_status=$?
set -e
python scripts/image_release.py assert-clean-output canary-scan.stdout canary-scan.stderr
exit "${scan_status}"
- run: python scripts/image_release.py checksum --archive portfolio-hub-image.tar --output portfolio-hub-image.tar.sha256
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: tested-image-${{ github.run_id }}-${{ github.run_attempt }}
if-no-files-found: error
retention-days: 7
path: |
portfolio-hub-image.tar
portfolio-hub-image.tar.sha256
portfolio-hub-image.id
migration-inventory.txt
scripts/image_release.py
publish:
needs: verify
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: tested-image-${{ github.run_id }}-${{ github.run_attempt }}
path: tested-image
- name: Load same archive, tag and publish without rebuilding
id: publish
env:
GITHUB_ACTOR: ${{ github.actor }}
REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
python tested-image/scripts/image_release.py publish \
--archive tested-image/portfolio-hub-image.tar \
--checksum tested-image/portfolio-hub-image.tar.sha256 \
--image-id tested-image/portfolio-hub-image.id \
--local-image "portfolio-hub-ci:${GITHUB_SHA}" \
--commit "${GITHUB_SHA}" --event "${GITHUB_EVENT_NAME}" --ref "${GITHUB_REF}"
@@ -0,0 +1,69 @@
name: Verify published PortfolioHub image
on:
workflow_dispatch:
inputs:
version:
description: "Strict release tag (for example v0.1.1)"
required: true
type: string
commit:
description: "Exact 40-character lowercase source commit"
required: true
type: string
permissions:
contents: read
packages: read
jobs:
verify:
runs-on: ubuntu-24.04
steps:
- name: Validate immutable selectors and image contract
env:
REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }}
ACTOR: ${{ github.actor }}
VERSION: ${{ inputs.version }}
COMMIT: ${{ inputs.commit }}
IMAGE: ghcr.io/fourblocks2020/portfolio-hub
run: |
set -euo pipefail
[[ "$VERSION" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]
[[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]]
short_sha="${COMMIT:0:12}"
printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io --username "$ACTOR" --password-stdin >/dev/null
version_raw="$(docker buildx imagetools inspect --raw "$IMAGE:$VERSION")"
source_raw="$(docker buildx imagetools inspect --raw "$IMAGE:$short_sha")"
version_digest="sha256:$(printf '%s' "$version_raw" | sha256sum | cut -d' ' -f1)"
source_digest="sha256:$(printf '%s' "$source_raw" | sha256sum | cut -d' ' -f1)"
test "$version_digest" = "$source_digest"
docker pull "$IMAGE@$version_digest" >/dev/null
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{.Architecture}}')" = amd64
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{.Config.User}}')" = 10001:10001
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')" = "$COMMIT"
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.version"}}')" = "$VERSION"
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.source"}}')" = https://github.com/fourblocks2020/portfolio-hub
if docker buildx imagetools inspect "$IMAGE:latest" >/dev/null 2>&1; then
echo "mutable latest selector exists" >&2
exit 1
fi
echo "digest=$version_digest"
echo "version_selector=$IMAGE:$VERSION"
echo "source_selector=$IMAGE:$short_sha"
echo "immutable=$IMAGE@$version_digest"
{
echo "## Verified published PortfolioHub image"
echo
echo "- digest: \`$version_digest\`"
echo "- version selector: \`$IMAGE:$VERSION\`"
echo "- source selector: \`$IMAGE:$short_sha\`"
echo "- source commit: \`$COMMIT\`"
echo "- architecture: \`linux/amd64\`"
echo "- runtime user: \`10001:10001\`"
echo "- latest: absent"
} >> "$GITHUB_STEP_SUMMARY"
+38
View File
@@ -0,0 +1,38 @@
name: Verify container release contracts
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.11"
- run: python -m pip install "uv==0.11.14"
- run: uv sync --extra dev --locked
- run: uv run pytest -q
- name: Honest scoped lint for release additions
run: uv run ruff check --select F,I app/db/migrations.py scripts/image_release.py tests/release
- name: Validate container contracts without registry writes
run: uv run pytest -q tests/release
- name: Build and smoke exact pull-request or main source image
run: |
uv run python -c 'from app.db.migrations import migration_inventory; print("\n".join(migration_inventory()))' > migration-inventory.txt
printf '%s\n' 'PORTFOLIO_HUB_SECRET_CANARY_DO_NOT_SHIP' > .env.ci-canary
RELEASE_VERSION="v$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
docker build --platform linux/amd64 --provenance=false \
--build-arg "SOURCE_COMMIT=${GITHUB_SHA}" --build-arg "RELEASE_VERSION=${RELEASE_VERSION}" \
--tag "portfolio-hub-ci:${GITHUB_SHA}" .
uv run python scripts/image_release.py smoke --image "portfolio-hub-ci:${GITHUB_SHA}" --inventory migration-inventory.txt --timeout 180
docker save --output portfolio-hub-image.tar "portfolio-hub-ci:${GITHUB_SHA}"
uv run python scripts/image_release.py scan --image "portfolio-hub-ci:${GITHUB_SHA}" --archive portfolio-hub-image.tar
+6 -5
View File
@@ -3,14 +3,15 @@ id: "ac-0001"
status: active
---
# 포트폴리오 목록의 ledger 투자금 집계 필드
# 포트폴리오 목록의 source-independent 투자금 집계 필드
## Criterion
`GET /v1/portfolios`의 각 `PortfolioItem`은 기존 응답 필드를 유지하면서 `net_contributed_capital`과 `cumulative_profit_withdrawn`을 float 값으로 포함해야 한다. 전자는 순투자현금, 후자는 누적 수익 인출액을 뜻하며, 해당 portfolio에 유효한 manual ledger가 없거나 집계 결과가 없으면 두 값은 각각 `0.0`이어야 한다.
`GET /v1/portfolios`의 각 `PortfolioItem`은 기존 응답 필드를 유지하면서 `net_contributed_capital`과 `cumulative_profit_withdrawn`을 float 값으로 포함해야 한다. 전자는 모든 source의 유효한 `INVEST` gross 합계에서 유효한 `WITHDRAW` 합계를 뺀 순투자원금이고, 후자는 원금과 분리한 모든 source의 유효한 `PROFIT` 합계다. 해당 portfolio에 유효한 대상 ledger event가 없으면 두 값은 각각 `0.0`이어야 한다.
## Verification
- 성공 조건: ledger 집계가 있는 portfolio는 두 필드에 해당 집계값을 반환하고, ledger 집계가 없는 portfolio는 두 필드를 `0.0`으로 반환한다.
- 실패·경계 조건: 빈 목록은 `portfolios: []`, `total: 0`을 반환하며 신규 필드 추가 때문에 기존 응답 필드가 제거되거나 값의 의미가 바뀌지 않는다.
- 검사 방법: `tests/test_v1_portfolios_list.py`의 목록 집계값 결합·기본값·빈 목록·기존 필드 회귀 테스트와 OpenAPI schema의 `PortfolioItem`을 검사한다.
- 성공 조건: broker-only와 manual/broker mixed-source portfolio가 source와 무관한 side별 합계로 두 필드를 반환하고, ledger 집계가 없는 portfolio는 두 필드를 `0.0`으로 반환한다.
- 실패·경계 조건: `PROFIT`이 원금에 포함되거나 `buffer_out` 등 다른 side가 `INVEST`로 재해석되거나, 기존 응답 필드·token/filter 동작이 변경되면 실패한다.
- 검사 방법: `tests/test_portfolio_ledger_aggregates.py`, `tests/test_v1_portfolios_list.py`, `tests/test_v1_portfolios_manual_ledger.py`와 disposable PostgreSQL integration을 실행한다.
- 현재 구현 평가: focused `39 passed`, actual PostgreSQL semantic integration `1 passed`, clean full regression `661 passed, 16 skipped`이며 독립 재QC가 PASS했다.
+6 -5
View File
@@ -3,14 +3,15 @@ id: "ac-0002"
status: active
---
# REVERSAL-aware manual ledger 산식과 목록·단건 일치
# Source-independent REVERSAL 산식과 목록·단건 일치
## Criterion
`net_contributed_capital`은 `REVERSAL`되지 않은 manual `INVEST` 합계에서 `REVERSAL`되지 않은 manual `WITHDRAW` 합계를 뺀 값이어야 하고, `cumulative_profit_withdrawn`은 `REVERSAL`되지 않은 manual `PROFIT` 합계여야 한다. `REVERSAL`이 참조한 `INVEST`, `WITHDRAW`, `PROFIT` 원거래는 모든 return aggregate에서 제외하고 `REVERSAL` 자체는 금액으로 합산하지 않으며, 목록과 단건 `returns/summary`는 같은 유효 원장 판정과 네 집계값 의미를 사용해야 한다.
`total_invested`는 모든 source의 유효한 `INVEST` gross 합계, `total_withdrawn`은 유효한 `WITHDRAW` 합계, `net_contributed_capital`은 두 값의 차, `cumulative_profit_withdrawn`은 원금에서 제외한 유효한 `PROFIT` 합계여야 한다. 동일 portfolio에서 matching `REVERSAL.target_ledger_entry_id`로 참조된 original `INVEST`, `WITHDRAW`, `PROFIT`은 original과 reversal의 source와 무관하게 모든 return aggregate에서 제외하고 `REVERSAL` 자체는 금액으로 합산하지 않는다. 목록과 단건 `returns/summary`는 같은 repository aggregate와 네 집계값 의미를 사용해야 한다.
## Verification
- 성공 조건: 미취소 `INVEST`, `WITHDRAW`, `PROFIT` 조합에서 `PROFIT`은 `WITHDRAW`와 분리되고 목록과 단건 summary의 `total_invested`, `total_withdrawn`, `net_contributed_capital`, `cumulative_profit_withdrawn`이 일치한다.
- 실패·경계 조건: `INVEST`, `WITHDRAW`, `PROFIT`을 각각 reversal하면 해당 원거래 효과가 제거되며 reversal row 자체가 합계에 더해지지 않는다.
- 검사 방법: `tests/test_portfolio_ledger_aggregates.py`의 shared batch semantics와 `tests/test_v1_portfolios_manual_ledger.py`의 profit 분리 및 세 action reversal 회귀를 실행한다.
- 성공 조건: broker-only와 mixed-source `INVEST`·`WITHDRAW`·`PROFIT` 조합에서 gross·withdrawn·net·profit 값이 승인 산식과 일치하고 목록과 단건 summary가 일치한다.
- 실패·경계 조건: manual reversal→broker original 또는 broker reversal→manual original에서 original 효과가 남거나, `PROFIT`이 원금에 섞이거나 reversal row 자체가 합산되면 실패한다.
- 검사 방법: SQL contract unit test와 실제 PostgreSQL 16 integration에서 production repository SQL, 양방향 cross-source reversal, `buffer_out` 제외를 검사한다.
- 현재 구현 평가: source predicate가 original과 reversal 양쪽에서 제거됐고 actual PostgreSQL semantic integration 및 독립 재QC가 PASS했다.
+6 -5
View File
@@ -3,14 +3,15 @@ id: "ac-0003"
status: active
---
# 다중 포트폴리오 grouped aggregate와 N+1 방지
# 다중 포트폴리오 source-independent grouped aggregate와 N+1 방지
## Criterion
목록용 repository 계약은 반환 대상인 여러 portfolio ID의 유효 manual ledger 집계를 하나의 grouped aggregate query로 계산해 portfolio ID별 결과를 반환해야 하며, 목록 크기에 비례하는 portfolio별 ledger query를 수행해서는 안 된다. 입력 ID 목록이 비어 있으면 schema 확인이나 DB 연결·query 없이 빈 mapping을 반환해야 한다.
목록용 repository 계약은 반환 대상인 여러 portfolio ID의 source-independent valid ledger aggregate를 하나의 grouped query로 계산해 portfolio ID별 결과를 반환해야 하며, 목록 크기에 비례하는 portfolio별 ledger query를 수행해서는 안 된다. 입력 ID 목록이 비어 있으면 schema 확인이나 DB 연결·query 없이 빈 mapping을 반환해야 한다.
## Verification
- 성공 조건: 둘 이상의 portfolio ID를 한 번에 전달했을 때 단일 query가 실행되고 각 ID의 합계가 독립된 mapping으로 반환된다.
- 실패·경계 조건: 빈 ID 입력은 `{}`를 반환하고 DB connection 및 schema/query 호출이 발생하지 않는다.
- 검사 방법: `tests/test_portfolio_ledger_aggregates.py`에서 `GROUP BY ledger.portfolio_id`, portfolio ID 배열 parameter, 단일 `execute`, 빈 입력 no-call을 검사하고 `tests/test_v1_portfolios_list.py`에서 route가 summary batch를 한 번 요청하는지 확인한다.
- 성공 조건: 둘 이상의 portfolio ID를 한 번에 전달했을 때 단일 query가 실행되고 broker/manual source가 섞여도 각 ID의 side별 합계가 독립된 mapping으로 반환된다.
- 실패·경계 조건: source predicate가 다시 도입되거나 portfolio별 N+1 query가 발생하거나, 빈 ID 입력에서 DB 작업이 발생하거나, portfolio ID 사이 금액이 섞이면 실패한다.
- 검사 방법: `tests/test_portfolio_ledger_aggregates.py`에서 `GROUP BY ledger.portfolio_id`, ID 배열 parameter, 단일 execute와 빈 입력 no-call을 검사하고 list route의 summary batch 요청을 검증한다.
- 현재 구현 평가: grouped query 구조와 empty-input fast path를 유지한 채 source predicate만 제거했으며 focused·full regression과 독립 재QC가 PASS했다.
+6 -5
View File
@@ -3,14 +3,15 @@ id: "ac-0005"
status: active
---
# additive API·문서 호환성과 reversal 회귀 보존
# API·문서 호환성과 query-only source-independent 교정
## Criterion
ledger 투자금 집계 확장은 기존 `GET /v1/portfolios` 및 단건 returns summary 계약에 대한 additive 변경이어야 한다. OpenAPI와 repository-owned interface/runtime 문서는 `net_contributed_capital`을 순투자현금, `cumulative_profit_withdrawn`을 누적 수익 인출액으로 정의하고 `portfolio-hub`가 ledger 권위 값을 제공함을 명시해야 하며, 기존 이중 reversal 거부 동작을 유지해야 한다.
Ledger 투자금 집계 교정은 기존 `GET /v1/portfolios` 및 단건 returns summary의 field 이름과 응답 구조를 유지해야 한다. OpenAPI schema와 repository-owned interface/data-model/runtime 문서는 source-independent valid `INVEST`·`WITHDRAW`·`PROFIT`, gross `total_invested`, `INVEST-WITHDRAW` net, 별도 `PROFIT`, source-independent matching reversal과 non-capital side 제외를 일관되게 설명해야 한다. 교정은 existing ledger row mutation/backfill 또는 `buffer_out` 재분류 없이 query semantic에 한정돼야 한다.
## Verification
- 성공 조건: 기존 목록 필드와 token/filter 동작이 보존되고 `docs/interface-contract.md`, `docs/runtime-flows.md`, OpenAPI schema가 두 필드의 산식·REVERSAL·권위 경계를 일관되게 설명한다.
- 실패·경계 조건: `PROFIT`을 `WITHDRAW` 또는 전체 실현손익으로 설명하지 않고, 동일 원거래를 두 번 reversal하려는 기존 요청은 계속 거부된다.
- 검사 방법: 목록·manual ledger 회귀 테스트와 문서·OpenAPI 검사를 실행하고 focused suite 및 전체 프로젝트 suite를 사용해 기존 동작 회귀 여부를 판정한다.
- 성공 조건: `app/schemas/v1.py`, `docs/interface-contract.md`, `docs/data-model.md`, `docs/runtime-flows.md`가 같은 산식·reversal·권위 경계를 설명하고 기존 field·auth·filter 계약을 보존한다.
- 실패·경계 조건: stale manual-only 문구가 남거나 `PROFIT`을 원금/전체 실현손익으로 설명하거나, API rename, ledger mutation/backfill, `buffer_out=INVEST` 재분류 또는 권한 우회가 발생하면 실패한다.
- 검사 방법: docs contract regression, API/list/manual ledger focused suite, 변경 diff와 migration/ledger write 부재를 검사한다.
- 현재 구현 평가: 최초 독립 QC가 발견한 stale interface contract를 보완하고 manual-only 문구 부재 회귀 테스트를 추가했으며 재QC는 PASS(Blocker 0 / Major 0 / Minor 0)했다.
+4 -4
View File
@@ -7,11 +7,11 @@ status: active
## Criterion
일반 사용자와 admin은 `/v1/strategies`의 목록·상세 조회에서 active 전략만 받을 수 있어야 하며, inactive 전략은 목록에서 제외하고 상세에서 전략 본문 대신 `409`를 반환하고 미존재 전략은 `404`를 반환해야 한다.
일반 사용자와 admin은 `/v1/strategies`의 목록·상세 조회에서 active 전략만 받을 수 있어야 하며, 각 응답은 안정적인 ID, 사용자 표시용 `nick`, 내부 전략명 `name`, config, status와 revision을 반환해야 한다. inactive 전략은 목록에서 제외하고 상세에서 전략 본문 대신 `409`를 반환하며 미존재 전략은 `404`를 반환해야 한다.
## Verification
- 성공 조건: active 전략은 목록과 상세에서 안정적인 ID, 이름, config, status와 revision을 반환한다.
- 성공 조건: active 전략은 목록과 상세에서 같은 ID, `nick`, `name`, config, status와 revision을 반환하며 `nick`과 `name`이 서로 달라도 각각 보존된다.
- 실패·경계 조건: inactive 전략은 목록에서 제외되고 일반 상세 조회는 전략 본문 대신 `409`를 반환하며, 미존재 ID는 `404`다.
- 검사 방법: 일반·admin token의 목록/상세 API 회귀 테스트로 active/inactive/missing을 각각 검사한다.
- 현재 구현 평가: working tree의 `app/api/v1_strategies.py`와 `tests/test_v1_strategies.py`가 이 계약을 실행 가능하게 검증하며 scoped 재실행에 포함되어 PASS했다.
- 검사 방법: 일반·admin token의 목록/상세 API 회귀 테스트로 `nick`과 `name`의 독립 보존 및 active/inactive/missing을 각각 검사한다.
- 현재 구현 평가: `app/api/v1_strategies.py`와 `tests/test_v1_strategies.py`가 목록·상세 `nick` 응답과 active/inactive 경계를 실행 가능하게 검증하며 scoped 재실행에 포함되어 PASS했다.
+5 -5
View File
@@ -7,11 +7,11 @@ status: active
## Criterion
admin은 `/v1/admin/strategies`에서 active·inactive 전체 전략을 조회하고 생성·수정·상태 변경·미참조 삭제할 수 있어야 하며, 비-admin 사용자의 모든 관리 mutation은 `403`이어야 한다.
admin은 `/v1/admin/strategies`에서 active·inactive 전체 전략을 `nick`, `name`, config, status와 revision으로 조회하고 생성·수정·상태 변경·미참조 삭제할 수 있어야 하며, 비-admin 사용자의 모든 관리 mutation은 `403`이어야 한다. 동일 `(name, config)` POST는 effective `nick`과 status까지 같을 때만 idempotent 성공해야 하고 하나라도 다르면 기존 row를 바꾸지 않고 `409`를 반환하며, 기존 전략의 변경은 PATCH만 수행해야 한다.
## Verification
- 성공 조건: admin CRUD와 상태 변경이 영속화되고 관리 조회가 active·inactive를 모두 반환한다.
- 실패·경계 조건: 일반 사용자 또는 권한 부족 token의 create/update/delete는 변경 없이 `403`이다.
- 검사 방법: 역할별 token으로 admin 목록·생성·PATCH·DELETE와 비-admin 거부를 API 테스트로 검사한다.
- 현재 구현 평가: working tree의 모든 admin route가 공통 `require_admin` dependency를 사용하고 admin CRUD tests 및 비-admin 관리 GET `403` test가 scoped 재실행에서 PASS했다. 비-admin POST/PATCH/DELETE 각각의 독립 negative test는 현재 없어 mutation별 executable coverage는 `PARTIAL`이다.
- 성공 조건: admin CRUD와 상태 변경이 영속화되고 관리 조회가 active·inactive의 `nick`, `name`, config, status와 revision을 반환하며 완전히 같은 POST 재시도는 기존 row와 revision을 유지한다.
- 실패·경계 조건: 동일 `(name, config)`지만 effective `nick` 또는 status가 다른 POST는 `409`와 무변경이고, 일반 사용자 또는 권한 부족 token의 create/update/delete도 변경 없이 `403`이다.
- 검사 방법: 역할별 token으로 admin 목록·생성·PATCH·DELETE, 동일 POST 재시도, 충돌 POST의 row·revision 무변경과 비-admin mutation 거부를 API 테스트로 검사한다.
- 현재 구현 평가: admin route의 공통 `require_admin`, CRUD와 `nick` 응답 테스트는 존재한다. 다만 현재 create service는 동일 `(name, config)` row의 `nick`이 다르면 POST로 기존 row를 변경할 수 있고 비-admin POST/PATCH/DELETE 각각의 독립 negative test도 없어 이 AC는 `PARTIAL`이다.
+5 -5
View File
@@ -7,11 +7,11 @@ status: active
## Criterion
admin PATCH는 기존 전략 row의 ID를 유지하면서 요청된 `name`·`config`·`status`의 실질적 변경을 원자적으로 반영하고 revision을 증가시켜야 하며, 모든 참조 포트폴리오의 이후 portfolio-hub API 조회는 commit된 최신 설정과 revision을 반환해야 한다.
`nick`은 전략의 독립 저장 identity이며 trim 후 비어 있지 않고 전략 간 유일해야 한다. 생성에서 `nick`을 생략하면 기존 호환성을 위한 결정적 기본값을 만들고 explicit null 또는 blank는 거부해야 하며, PATCH에서 `nick`을 생략하면 `name`·`config` 변경과 관계없이 기존 값을 보존해야 한다. admin PATCH는 기존 전략 row의 ID를 유지하면서 요청된 `nick`·`name`·`config`·`status`의 실질적 변경을 원자적으로 반영하고 revision을 증가시켜야 하며, 모든 참조 포트폴리오의 이후 portfolio-hub API 조회는 commit된 최신 `nick`, 설정과 revision을 반환해야 한다.
## Verification
- 성공 조건: 실질적 PATCH 뒤 ID는 동일하고 revision은 단조 증가하며 derived `nick`과 name/config가 같은 committed state에서 계산되고 참조 포트폴리오 조회에 최신 값이 나타난다.
- 실패·경계 조건: no-op PATCH는 revision을 올리지 않고, 동시 partial PATCH도 서로의 최신 필드를 잃거나 불일치한 `nick`을 만들지 않는다.
- 검사 방법: API/repository 회귀와 실제 PostgreSQL 동시 partial PATCH 시험으로 ID, revision, name/config/nick 및 포트폴리오 응답을 검사한다.
- 현재 구현 평가: `FOR UPDATE` 기반 update와 revision 응답 테스트가 존재하며, 2026-08-15 실제 PostgreSQL integration 재실행 `4 passed`에 동시 partial PATCH 검증이 포함됐다.
- 성공 조건: 사용자 지정 `nick` 생성과 `nick` 단독 PATCH 뒤 ID는 동일하고 revision은 단조 증가하며, `name`·`config`만 바꾼 PATCH는 기존 `nick`을 보존하고 참조 포트폴리오 조회에 최신 `nick`, 설정과 revision이 나타난다.
- 실패·경계 조건: explicit null·blank·중복 `nick`은 무변경으로 거부되고 no-op PATCH는 revision을 올리지 않으며, 동시 partial PATCH도 명시적으로 바꾸지 않은 `nick`이나 다른 최신 필드를 잃지 않는다.
- 검사 방법: API/repository 회귀와 실제 PostgreSQL 동시 partial PATCH 시험으로 omission/null/blank/중복, ID, revision, `nick` 보존·변경, name/config/status 및 포트폴리오 read-back을 검사한다.
- 현재 구현 평가: `FOR UPDATE` 기반 update, 사용자 지정·trim·null/blank·중복·no-op·revision 테스트와 생략된 `nick` 보존 PostgreSQL 시험이 존재한다. 포트폴리오 `strategy_nick` read-back을 직접 단언하는 테스트는 없어 그 검증은 `PARTIAL`이다.
+4 -4
View File
@@ -7,11 +7,11 @@ status: active
## Criterion
`/v1/portfolios`와 legacy `/portfolios`의 생성에는 active `strategy_id`가 필수이고 수정도 ID-only여야 하며, 요청의 `strategy_name`·`strategy_params`는 `422`로 거부하는 동시에 응답의 `active_strategy_id`·`strategy_name`·`strategy_params`·`strategy_revision`은 유지되어야 한다.
`/v1/portfolios`와 legacy `/portfolios`의 생성에는 active `strategy_id`가 필수이고 수정도 ID-only여야 하며, 요청의 `strategy_name`·`strategy_params`는 `422`로 거부해야 한다. v1 `PortfolioItem` 응답은 현재 참조 전략의 `active_strategy_id`·`strategy_nick`·`strategy_name`·`strategy_params`·`strategy_revision`을 같은 committed row에서 반환해야 하고 참조가 없거나 해석할 수 없으면 `strategy_nick`은 `null`이어야 하며, legacy 응답의 기존 호환 필드는 유지되어야 한다.
## Verification
- 성공 조건: 명시한 active ID로만 포트폴리오가 생성·수정되고 응답에 현재 전략 identity·이름·config·revision이 나타난다.
- 성공 조건: 명시한 active ID로만 포트폴리오가 생성·수정되고 v1 create/PATCH/list 응답에 현재 전략 ID·`nick`·이름·config·revision이 나타나며 참조가 없으면 `strategy_nick`은 `null`이다.
- 실패·경계 조건: strategy ID 누락, 제거 필드 전달 또는 malformed 요청은 새 전략 row를 만들지 않고 `422`다.
- 검사 방법: v1·legacy create/update schema와 저장소 row count, 응답 호환 필드를 API/CLI 회귀로 검사한다.
- 현재 구현 평가: schemas와 양쪽 portfolio API가 ID-only 입력 및 `extra="forbid"` 계약을 구현하고 scoped portfolio/CLI 회귀는 PASS했다. 다만 제거된 `strategy_name`·`strategy_params` 각각의 `422`와 응답 호환 필드 전체를 직접 단언하는 전용 negative/response test는 현재 없어 해당 executable coverage는 `PARTIAL`이다.
- 검사 방법: v1·legacy create/update schema와 저장소 row count, v1 create/PATCH/list의 `strategy_nick` read-back, unbound `null` 및 기존 응답 호환 필드를 API/CLI 회귀로 검사한다.
- 현재 구현 평가: schemas와 양쪽 portfolio API가 ID-only 입력 및 `extra="forbid"` 계약을 구현하고 v1 mapper가 `strategy_nick`을 반환한다. 다만 `strategy_nick` read-back, 제거된 `strategy_name`·`strategy_params` 각각의 `422`와 응답 호환 필드 전체를 직접 단언하는 전용 test가 없어 executable coverage는 `PARTIAL`이다.
+5 -5
View File
@@ -7,11 +7,11 @@ status: active
## Criterion
전략 조회·선택·관리 API는 미존재 `404`, inactive 신규 선택과 참조 중 삭제 `409`, 제거 필드·malformed 입력 `422`, 권한 부족 `403`을 서로 구분해 반환해야 한다.
전략 조회·선택·관리 API는 미존재 `404`, inactive 신규 선택·참조 중 삭제·중복 `nick` 및 충돌하는 동일 `(name, config)` POST는 `409`, 제거 필드·malformed 입력·explicit null 또는 trim 후 blank `nick`은 `422`, 권한 부족은 `403`으로 서로 구분해 반환해야 한다. create의 `nick` 생략은 호환 기본값 생성을 허용하고 PATCH의 `nick` 생략은 기존 값을 보존하며 모든 거부 요청은 row와 revision을 변경하지 않아야 한다.
## Verification
- 성공 조건: 각 오류 조건이 승인된 상태 코드와 안정적인 비민감 오류 응답으로 구분된다.
- 실패·경계 조건: 권한 부족을 `404`로, inactive를 `422`로, malformed 입력을 묵시적으로 무시하는 등 오류 클래스가 합쳐지지 않는다.
- 검사 방법: 조건별 독립 API negative test로 status code와 무변경을 검사한다.
- 현재 구현 평가: `tests/test_v1_strategies.py`와 `tests/test_v1_portfolios_crud.py`의 negative matrix가 scoped 재실행에서 PASS했다.
- 성공 조건: omission, explicit null, blank, duplicate와 충돌 POST가 각각 승인된 성공 또는 오류 경계로 처리되고 오류 응답은 안정적이며 비민감하다.
- 실패·경계 조건: 권한 부족을 `404`로, inactive·중복·충돌을 `422`로, null·blank를 묵시적 omission으로 합치거나 거부 요청이 row 또는 revision을 바꾸면 실패한다.
- 검사 방법: 조건별 독립 API negative test로 status code, row identity, `nick`, status와 revision의 무변경을 검사한다.
- 현재 구현 평가: `tests/test_v1_strategies.py`는 omission, explicit null, blank와 duplicate `nick` 경계를 검사하고 기존 negative matrix도 scoped 재실행에서 PASS했다. 충돌하는 동일 `(name, config)` POST의 `409`·무변경 계약은 현재 구현·테스트에 없어 이 부분은 `PARTIAL`이다.
+4 -4
View File
@@ -7,11 +7,11 @@ status: active
## Criterion
전략 PATCH, 포트폴리오 전략 선택, 전략 상태 변경·삭제와 거래 저장이 경합해도 최신 전략 참조와 revision은 직렬화 가능하게 보존되고, stale portfolio snapshot은 현재 전략 선택을 되살리거나 덮어쓰지 않으며 portfolio mutation과 ledger 기록은 원자적이어야 한다.
전략의 `nick`·`name`·`config`·`status` partial PATCH, 포트폴리오 전략 선택, 전략 상태 변경·삭제와 거래 저장이 경합해도 명시적으로 변경하지 않은 독립 catalog field, 최신 전략 참조와 revision은 직렬화 가능하게 보존되고, stale portfolio snapshot은 현재 전략 선택을 되살리거나 덮어쓰지 않으며 portfolio mutation과 ledger 기록은 원자적이어야 한다.
## Verification
- 성공 조건: 동시 partial PATCH는 모든 변경과 단조 revision을 보존하고, A snapshot 후 B 선택·A 삭제·stale 거래 저장에서도 B 참조와 A 삭제가 유지되며 portfolio UPDATE와 ledger INSERT가 함께 commit된다.
- 성공 조건: `nick` PATCH와 name/config/status PATCH의 양방향 동시 실행은 모든 독립 변경과 단조 revision을 보존하고, A snapshot 후 B 선택·A 삭제·stale 거래 저장에서도 B 참조와 A 삭제가 유지되며 portfolio UPDATE와 ledger INSERT가 함께 commit된다.
- 실패·경계 조건: stale write가 삭제된 A를 복원하거나 B를 잃지 않고, transaction 실패 시 portfolio와 ledger가 부분 commit되지 않는다.
- 검사 방법: 실제 PostgreSQL에서 동시 PATCH, select-vs-inactivate/delete, stale BUY/SELL snapshot과 transaction rollback 시나리오를 실행한다.
- 현재 구현 평가: repository transaction/row-lock 경계와 integration tests가 존재하며, 2026-08-15 실제 PostgreSQL integration 재실행 `4 passed`에서 동시 PATCH, 선택-vs-delete, stale BUY snapshot과 migration 시나리오를 확인했다. 독립 source-time QC도 PASS를 기록한다. 다만 portfolio UPDATE 성공 후 ledger INSERT 실패를 의도적으로 주입해 rollback을 관찰하는 fault-injection test는 현재 없어 그 세부 검증은 `PARTIAL`이다.
- 검사 방법: 실제 PostgreSQL에서 `nick`과 다른 catalog field의 양방향 동시 PATCH, select-vs-inactivate/delete, stale BUY/SELL snapshot과 transaction rollback 시나리오를 실행한다.
- 현재 구현 평가: repository transaction/row-lock 경계와 integration tests가 존재하며, 2026-08-15 실제 PostgreSQL integration 재실행 `4 passed`에서 name/config 동시 PATCH 중 기존 `nick` 보존, 선택-vs-delete, stale BUY snapshot과 migration 시나리오를 확인했다. 명시적 `nick` PATCH와 다른 field PATCH의 양방향 경합 및 portfolio UPDATE 성공 후 ledger INSERT 실패 fault-injection test는 없어 해당 검증은 `PARTIAL`이다.
+15
View File
@@ -0,0 +1,15 @@
---
id: "ac-0032"
status: active
---
# Source-neutral portfolio ledger read
## Criterion
Portfolio owner는 `GET /v1/portfolios/{portfolio_id}/ledger`로 source 미지정 시 manual·broker를 포함한 모든 자기 portfolio 원장을 `recorded_at DESC, ledger_entry_id DESC` 순서로 조회할 수 있어야 한다.
## Verification
- mixed manual/broker 행이 최신순으로 반환되고 source 미지정이 모든 source를 포함한다.
- 구현 평가: `tests/test_v1_portfolios_manual_ledger.py` 및 전체 회귀 `664 passed, 16 skipped`에서 확인됐다.
+15
View File
@@ -0,0 +1,15 @@
---
id: "ac-0033"
status: active
---
# Stable keyset pagination and fail-closed cursor
## Criterion
Unified ledger 목록은 `(recorded_at, ledger_entry_id)` keyset cursor로 동시각 행의 중복·누락 없이 page를 이어야 하며 cursor는 portfolio/source에 결속되고 malformed·tampered·scope mismatch는 HTTP 422이어야 한다.
## Verification
- cursor 경계, 변조 및 다른 source cursor 재사용은 각각 정확한 next page 또는 422을 반환한다.
- 구현 평가: focused cursor 회귀와 전체 회귀 `664 passed, 16 skipped`에서 확인됐다.
+15
View File
@@ -0,0 +1,15 @@
---
id: "ac-0034"
status: active
---
# Canonical cross-source ledger representation
## Criterion
Unified ledger item은 canonical 대문자 `action`을 제공하고 internal `side`를 노출하지 않으며 source별로 없는 사실은 명시적 nullable schema 값으로 반환해야 한다.
## Verification
- manual/broker mixed 응답이 action casing과 nullable field 계약을 유지하고 OpenAPI가 해당 schema를 노출한다.
- 구현 평가: focused schema/API regression 및 OpenAPI inspection으로 확인됐다.
+15
View File
@@ -0,0 +1,15 @@
---
id: "ac-0035"
status: active
---
# Owner-only unified read and manual compatibility
## Criterion
Unified ledger read는 user/session portfolio owner만 허용하고 타 owner와 service token을 거부하며 기존 `/ledger/manual`의 manual-only·latest-first·limit 계약을 유지해야 한다.
## Verification
- 타 owner/service token 거부, owner 허용 및 manual endpoint 하위호환 회귀를 실행한다.
- 구현 평가: focused API/auth-surface `29 passed`, 전체 회귀 `664 passed, 16 skipped`에서 확인됐다.
+15
View File
@@ -0,0 +1,15 @@
---
id: "ac-0036"
status: active
---
# Unified ledger persistence and regression evidence
## Criterion
Unified ledger query는 portfolio/source keyset ordering에 맞는 PostgreSQL index migration을 제공하고 API/OpenAPI/repository 계약 회귀로 검증되어야 한다.
## Verification
- disposable PostgreSQL fresh upgrade가 head `20260820_0030`과 `idx_portfolio_ledger_portfolio_recorded_entry_desc` 생성을 확인하고 focused/full suite가 통과한다.
- 구현 평가: fresh migration 확인 및 전체 회귀 `664 passed, 16 skipped`가 있다. 운영 규모 `EXPLAIN ANALYZE` latency 관찰은 비차단 후속이다.
+2 -2
View File
@@ -1,5 +1,5 @@
{
"schema_version": 1,
"next_line_number": 5,
"next_ac_number": 32
"next_line_number": 7,
"next_ac_number": 37
}
+227
View File
@@ -0,0 +1,227 @@
---
id: "dcy-0005"
status: confirmed
---
# Portfolio ledger source-independent return aggregates
## Problem
`GET /v1/portfolios`와 `GET /v1/portfolios/{portfolio_id}/returns/summary`의 투자금 집계가 `portfolio_ledger.source = 'manual'`인 row만 포함해 broker 등 다른 producer가 기록한 유효한 원금·수익 event를 누락했다. 이 때문에 실제 ledger provenance와 API 집계값이 달라질 수 있으며, original source 제한만 제거하고 reversal source 제한을 남기면 cross-source reversal까지 잘못 집계할 수 있었다.
이 Discovery는 요청자가 OQ-1~OQ-5를 모두 결정하고 승인한 GitHub 이슈 #28을 canonical ProofLine 문서로 포착한다. 아래 `Scope`의 승인 이슈 본문은 canonical H2 충돌을 피하기 위해 heading만 한 단계 낮추고 나머지 내용을 최대한 원문 순서대로 보존한다.
## Evidence
### 승인 원문과 provenance
- 승인 원문: https://github.com/fourblocks2020/portfolio-hub/issues/28
- 제목: `Fix investment totals: remove source='manual' filter from ledger aggregates`
- 상태: `closed`
- 최초 작성: `2026-08-18T01:53:37Z`
- 승인 본문 최종 갱신: `2026-08-19T08:39:49Z`
- 승인 본문 SHA-256: `d5e5f65500d163bd5a9c9a97f47222e96373b3b6d0e09b021f1de3a2380a6014`
- Exact 승인 본문 snapshot: `evidence/issue-28-approved-discovery.md`
- 승인 결과: `APPROVED`; OQ-1~OQ-5는 각각 A로 결정됐고 unresolved blocking Open Question은 없다.
### 구현·검증 evidence
- 구현 기준 commit: `02bfa602995b8e1c2f410c9bd5762f062666f2d6`
- 구현 commit: `5eb8c042668b1c383ac59ca9be00aa1a5dfcb37a` (`fix: aggregate investment totals across ledger sources`)
- 구현 진행 comment: https://github.com/fourblocks2020/portfolio-hub/issues/28#issuecomment-5339488232; exact snapshot `evidence/implementation-progress.md`; SHA-256 `ada9617f9fb106e890ab4b232f23cde3b457b429971b664ed9fcc34689d03c52`
- 구현 완료 comment: https://github.com/fourblocks2020/portfolio-hub/issues/28#issuecomment-5339596866; exact snapshot `evidence/implementation-completion.md`; SHA-256 `3458db05561d843a7ecebab816f6aecc6120a6a2d62a4be151efd2876f0d3007`
- Focused repository/API/docs contract tests: `39 passed`.
- Disposable PostgreSQL 16 semantic integration: `1 passed`; broker-only, mixed-source, cross-source reversal 양방향과 `buffer_out` 제외를 실제 production repository SQL로 검증했다.
- 기존 `temp/deleted_20260813/.worktrees/` artifact를 제외한 clean candidate full suite: `661 passed, 16 skipped`.
- 변경 test Ruff와 `git diff --check`: PASS.
- 최초 독립 QC의 stale manual-only interface contract Major를 보완한 뒤 독립 재QC: PASS, Blocker 0 / Major 0 / Minor 0.
### Lifecycle 경계
- 현재 local `main`에 구현·검증·독립 재QC·commit까지 완료됐다.
- Push, PR, 원격 main 반영, release, production deployment/restart, production read-only pre/post check와 production ledger mutation은 수행되지 않았다.
- 이 confirmed Discovery와 사후 approved REQ/active AC는 normative scope와 현재 구현 평가를 기록하며 terminal lifecycle closure나 미수행 외부 반영을 주장하지 않는다.
## Scope
### 승인된 이슈 본문 전체
### Discovery: 투자 원금 집계의 source-independent 의미 복원
- **상태:** `APPROVED`
- **대상 저장소:** `fourblocks2020/portfolio-hub`
- **대상 API:** `GET /v1/portfolios`, `GET /v1/portfolios/{portfolio_id}/returns/summary`
- **관련 이슈:** #23의 manual-only cash-flow 집계 가정 중 Invest-total field 의미를 이 이슈가 대체한다.
#### Problem
`get_return_summaries()`는 현재 투자 원금 집계를 manual ledger row로 제한한다.
```sql
WHERE ledger.source = 'manual'
AND ledger.side IN ('invest', 'withdraw', 'profit')
```
그 결과 `total_invested`와 `net_contributed_capital`은 portfolio ledger 전체의 Invest/net Invest가 아니라 manual source의 cash flow만 반영한다. Broker 등 다른 source가 기록한 유효한 `INVEST`가 제외되므로 사용자에게 표시되는 투자 원금 의미와 실제 집계가 불일치한다.
이 동작은 #23의 manual-cash-flow contract에서 유래했지만, Invest-total field가 모든 유효한 투자 원금을 나타내야 한다면 적합하지 않다.
#### Evidence
- Production 관찰 사례인 portfolio `353200`에는 broker-origin `invest`, `buffer_out`, `buy` ledger entry가 있고 manual `INVEST`/`WITHDRAW`가 없다.
- 현재 portfolio API는 모든 `source='broker'` row를 집계에서 제외하므로 `net_contributed_capital: 0.0`을 반환한다.
- 같은 사례에서 broker `invest` amount는 `0`, `buffer_out`은 `800,000`이다. 이 이슈의 source-filter 수정만으로 `buffer_out`을 `INVEST`로 간주하거나 zero-amount event를 교정하지는 않는다.
#### Target Semantics
승인된 목표 semantics는 다음과 같다.
```text
total_invested = sum(valid INVEST entries from every source)
total_withdrawn = sum(valid WITHDRAW entries from every source)
net_contributed_capital = total_invested - total_withdrawn
cumulative_profit_withdrawn = sum(valid PROFIT entries from every source)
```
`valid`는 원본 ledger entry가 `REVERSAL.target_ledger_entry_id`로 연결된 matching reversal에 의해 취소되지 않았음을 뜻한다.
`total_invested`는 gross value인 `Σ INVEST`로 유지한다. `WITHDRAW`는 `total_withdrawn`과 `net_contributed_capital`에 반영하고, `PROFIT`는 투자 원금 계산에서 제외하여 `cumulative_profit_withdrawn`으로만 별도 집계한다.
#### Scope
- 투자 원금 aggregate에서 `ledger.source = 'manual'` predicate를 제거하고 모든 source의 유효한 `INVEST`·`WITHDRAW`·`PROFIT`을 side별로 집계한다.
- `INVEST`, `WITHDRAW`, `PROFIT` accounting side 의미는 유지한다.
- Original entry와 동일 portfolio에서 `target_ledger_entry_id`가 일치하는 `REVERSAL`이 있으면 reversal 자체의 source와 무관하게 original entry를 제외한다.
- Portfolio list와 single-portfolio returns summary가 동일한 aggregate semantics를 사용하게 한다.
- Non-manual `broker` INVEST와 mixed manual/broker INVEST·WITHDRAW·reversal 회귀를 검증한다.
- API/interface 문서에서 `total_invested`와 `net_contributed_capital`의 manual-only 표현을 승인된 의미로 갱신한다.
- 기존 owner/admin/service visibility와 authorization 경계를 변경하지 않는다.
#### Out of Scope
- `buffer_out`, `buy` 등 non-INVEST event를 INVEST로 재분류하는 작업
- Zero-amount broker `invest`를 non-zero event로 정규화하는 ledger-event modelling
- Existing ledger row의 mutation, backfill 또는 rewrite
- Ledger producer의 event emission 변경
- Reversal model 또는 `REVERSAL.target_ledger_entry_id` 의미 변경
- Owner/admin/service visibility 및 authorization 변경
- 이 Discovery 승인만으로 배포·릴리스·production mutation을 수행하는 것
#### Risks and Constraints
- Source predicate 제거는 과거 모든 source row에 즉시 적용되는 query semantic correction이므로 기존 응답 값이 증가하거나 달라질 수 있다.
- Side label이 같다는 이유만으로 `buffer_out`·`buy` 같은 다른 accounting event를 합산하면 안 된다.
- Reversal exclusion을 source-independent 집계와 함께 유지하지 않으면 reversed principal이 중복 반영될 수 있다.
- List와 detail summary가 다른 query path를 사용한다면 동일 fixture로 semantic parity를 검증해야 한다.
- `total_invested`의 의미 변경은 API field rename 없이 기존 field contract를 교정하는 선택인지 명시해야 한다.
- Production 사례 `353200`은 source-filter defect와 separate ledger-event modelling gap을 동시에 포함하므로, source-filter 수정만으로 `800,000`이 투자 원금으로 표시된다고 보장해서는 안 된다.
#### Open Questions
##### OQ-1 — Invest-total 집계의 source 범위
- [x] **A. 모든 source의 유효한 원금 event를 포함하되 `total_invested`는 gross `Σ INVEST`로 유지한다. — 결정**
- `total_invested = Σ valid INVEST`, `total_withdrawn = Σ valid WITHDRAW`, `net_contributed_capital = Σ valid INVEST - Σ valid WITHDRAW`로 계산한다.
- `PROFIT`는 원금 계산에서 제외하고 `cumulative_profit_withdrawn = Σ valid PROFIT`으로만 별도 집계한다.
- `ledger.source = 'manual'` predicate를 제거하고 source와 무관하게 accounting side와 reversal을 적용한다.
- [ ] **B. `manual`과 `broker`만 포함하는 allowlist를 사용한다.**
- 현재 알려진 두 source만 포함하지만 새 source가 추가되면 다시 누락될 수 있다.
- [ ] **C. Manual-only 의미를 유지하고 별도 all-source field를 추가한다.**
- 기존 값은 보존하지만 API schema와 UI 소비 계약이 확장되며 본 이슈의 단순 semantic correction 범위를 넘어간다.
##### OQ-2 — `buffer_out` 및 zero-amount broker `invest` 처리
- [x] **A. 이 이슈에서는 현행 accounting side를 그대로 사용하고 별도 ledger-event modelling 이슈로 분리한다. — 결정**
- `buffer_out`을 INVEST로 추론하지 않으며 source-filter defect만 교정한다.
- Portfolio `353200`의 `800,000` 표시 문제는 별도 결정 없이는 해결됐다고 주장하지 않는다.
- [ ] **B. `buffer_out`을 이 집계에서 INVEST로 간주한다.**
- 사용자 표시 값은 달라질 수 있지만 accounting event 의미를 query layer에서 재해석한다.
- [ ] **C. Broker producer가 non-zero `INVEST`를 기록하도록 이 이슈 범위를 확장한다.**
- Producer contract, historical data, deduplication과 migration 결정이 추가로 필요하다.
##### OQ-3 — 기존 ledger data 처리 방식
- [x] **A. Query semantic만 교정하고 existing ledger row를 mutation/backfill하지 않는다. — 결정**
- 모든 기존 유효 row가 새 query에 자동 반영되며 원장 provenance를 보존한다.
- [ ] **B. Source 또는 side를 migration으로 backfill한다.**
- Historical ledger mutation 범위, 대상 식별과 rollback/audit 계약이 별도로 필요하다.
- [ ] **C. 별도 aggregate projection/table을 만들어 재계산한다.**
- 지속 materialization, replay, ordering 및 consistency ownership이 추가된다.
##### OQ-4 — API compatibility 방식
- [x] **A. 기존 field 이름을 유지하고 의미를 all-source Invest-total로 교정한다. — 결정**
- `total_invested`, `total_withdrawn`, `net_contributed_capital`, `cumulative_profit_withdrawn`의 문서를 함께 갱신한다.
- [ ] **B. 새 field를 추가하고 기존 field는 manual-only로 유지한다.**
- 하위 호환은 보존하지만 response schema와 consumer 선택이 복잡해진다.
- [ ] **C. Versioned endpoint에서만 새 의미를 제공한다.**
- 가장 강한 contract 분리를 제공하지만 새 API version과 migration 계획이 필요하다.
##### OQ-5 — 배포 후 검증 경계
- [x] **A. Repository tests에 더해 승인된 read-only production query/API pre/post check를 별도 배포 절차에 포함한다. — 결정**
- Source-independent 합계, reversal 제외와 list/detail parity를 확인하되 production row는 변경하지 않는다.
- `353200`은 source-filter 제거 여부를 확인하는 관찰 사례로만 사용하고 `buffer_out=INVEST`를 기대하지 않는다.
- [ ] **B. Repository tests만 수행하고 production 검증은 하지 않는다.**
- 구현 검증은 단순하지만 실제 source 분포와 응답 변화 확인이 남는다.
- [ ] **C. Synthetic staging data에서만 post-deploy 검증한다.**
- Production read를 피하지만 실제 historical source/reversal 조합을 완전히 대표하지 못할 수 있다.
#### Acceptance Criteria
OQ가 확정되면 아래 criterion을 선택 결과에 맞춰 canonical requirement로 전환한다.
- [ ] Investment aggregate에서 original ledger row의 source predicate가 제거되고 모든 source의 유효 row가 side별로 집계된다.
- [ ] `total_invested = Σ valid INVEST`, `total_withdrawn = Σ valid WITHDRAW`, `net_contributed_capital = total_invested - total_withdrawn`이며 `PROFIT`는 원금 계산에서 제외되고 `cumulative_profit_withdrawn`으로만 집계된다.
- [ ] 동일 portfolio에서 matching `target_ledger_entry_id`를 가진 `REVERSAL`이 존재하면 reversal source와 무관하게 original entry가 제외된다.
- [ ] `GET /v1/portfolios`와 single-portfolio returns summary가 동일한 aggregate semantics를 사용한다.
- [ ] Non-manual `broker` INVEST의 non-zero amount 회귀가 검증된다.
- [ ] Mixed manual/broker INVEST·WITHDRAW, reversal과 source-independent total이 검증된다.
- [ ] API/interface 문서가 승인된 field 의미를 정확히 설명한다.
- [ ] Existing owner/admin/service visibility 경계가 유지된다.
- [ ] Out-of-scope인 `buffer_out` 재분류나 historical ledger mutation이 암묵적으로 포함되지 않는다.
#### Approval Record
- **승인 상태:** `APPROVED`
- **승인 결정:** OQ-1-A, OQ-2-A, OQ-3-A, OQ-4-A, OQ-5-A
- **OQ-1:** 모든 source의 유효한 row를 side별로 집계한다. `total_invested`는 gross `Σ INVEST`, `net_contributed_capital`은 `Σ INVEST - Σ WITHDRAW`이며 `PROFIT`는 원금 계산에서 제외한다.
- **OQ-2:** `buffer_out` 재분류와 zero-amount broker `invest` 교정은 별도 ledger-event modelling으로 분리한다.
- **OQ-3:** Query semantic만 교정하고 existing ledger row를 mutation/backfill하지 않는다.
- **OQ-4:** 기존 field 이름을 유지하고 all-source Invest-total 의미로 문서와 contract를 교정한다.
- **OQ-5:** Repository 검증에 더해 별도 배포 절차에서 승인된 read-only production query/API pre/post check를 수행한다. Production row mutation 권한은 포함하지 않는다.
- **Reversal 적용:** all-source original 집계에서 matching reversal도 source와 무관하게 적용한다. `reversal.source = 'manual'` predicate를 보존하면 broker original reversal이 누락되므로 허용하지 않는다.
- **추가 결정 검토:** 현재 구현·data-flow 검토에서 승인을 중지할 추가 material OQ는 발견되지 않았다.
- **권한 경계:** 이 승인은 이 Discovery와 bounded implementation/verification scope를 승인한다. Push, PR, release, deployment, production mutation 또는 issue closure 권한을 자동으로 부여하지 않는다.
### AC admission 분류
- `update`: 기존 active `ac-0001`, `ac-0002`, `ac-0003`, `ac-0005`의 manual-only 의미를 source-independent 계약과 현재 검증 상태로 교정한다.
- `satisfy`: 기존 active `ac-0004`의 목록 가시성·인증·필터 격리는 의미 변경 없이 이번 구현이 충족한다.
- `create`: 없음. 동일 behavior를 새 AC로 중복하지 않는다.
- `retire`: 없음.
- Release evidence와 terminal closure: 없음.
- Housekeeping: GitHub comment exact snapshot 두 건을 Line evidence로 보존한다.
## Out of Scope
- Existing ledger row mutation 또는 historical migration/backfill
- `buffer_out`을 `INVEST`로 재분류하거나 zero-amount broker event를 교정하는 ledger-event modelling
- 별도 aggregate projection/table 및 성능 근거 없는 schema 확장
- API field rename 또는 breaking response change
- Push, PR, 원격 main 반영, release, production deployment/restart
- Production write/mutation과 credential 기록
- 배포 절차의 승인된 read-only production pre/post check를 이미 완료했다고 주장하는 것
## Risks and Unknowns
### Risks
- 모든 source를 집계하므로 producer가 accounting side를 잘못 기록하면 그 modelling 오류가 aggregate에 노출될 수 있다. 이번 범위는 side 재분류가 아니라 유효한 기존 side의 source filter 교정이다.
- Cross-source reversal을 놓치면 original row가 잘못 남으므로 original과 reversal 양쪽의 source 제한을 제거하고 실제 PostgreSQL 테스트로 검증했다.
- 배포 전 실제 production data parity는 아직 미확인이다. 승인된 read-only pre/post check는 별도 배포 절차에서 수행해야 하며 mutation 권한을 포함하지 않는다.
### Open Questions
없음. OQ-1~OQ-5는 승인 이슈 본문에서 모두 결정됐으며 추가 blocking decision은 발견되지 않았다.
@@ -0,0 +1,50 @@
## 구현 완료
### 구현 내용
- Portfolio return aggregate에서 original ledger의 `source='manual'` 제한을 제거해 모든 source의 유효한 `INVEST`·`WITHDRAW`·`PROFIT`을 side별로 집계한다.
- `total_invested`는 gross `Σ INVEST`, `total_withdrawn`은 `Σ WITHDRAW`, `net_contributed_capital`은 두 값의 차로 유지한다.
- `PROFIT`는 투자 원금 계산에서 제외하고 `cumulative_profit_withdrawn`으로만 별도 집계한다.
- Matching `REVERSAL.target_ledger_entry_id`는 original과 reversal의 source와 무관하게 original entry를 제외한다.
- `buffer_out` 등 non-capital side는 `INVEST`로 재해석하거나 집계하지 않는다.
- Existing ledger row mutation/backfill 없이 query semantic만 교정했다.
- List와 단건 returns summary가 동일한 repository aggregate를 사용하도록 유지했다.
- API schema, data model, runtime flow와 외부 interface contract를 all-source 의미로 동기화했다.
### 실제 검증 결과
- Focused repository/API/docs contract tests: **39 passed**
- Disposable PostgreSQL 16 semantic integration: **1 passed**
- Non-zero broker-only INVEST
- Manual/broker mixed INVEST·WITHDRAW·PROFIT
- Manual reversal → broker original
- Broker reversal → manual original
- `buffer_out` 집계 제외
- Clean candidate full suite: **661 passed, 16 skipped**
- 변경 테스트 범위 Ruff: **PASS**
- `git diff --check`: **PASS**
- 최초 독립 QC: Blocker 0 / Major 1 / Minor 0 — stale manual-only interface contract 발견
- 보완 후 독립 재QC: **PASS — Blocker 0 / Major 0 / Minor 0**
원본 checkout의 full suite에서는 기존 `temp/deleted_20260813/.worktrees/` 복제본을 grep하는 auth-surface tests 3건만 실패했다. 해당 pre-existing artifact를 수정·삭제하지 않고 제외한 clean candidate copy에서 전체 회귀가 통과했다.
### 비차단 후속 권고
- 배포 절차에서 승인된 read-only production pre/post check로 실제 portfolio의 source-independent 합계와 list/detail parity를 확인한다.
- Portfolio `353200`은 source-filter 교정 관찰에만 사용하며 `buffer_out=INVEST` 또는 zero-amount broker `invest` 교정 완료를 주장하지 않는다.
- `buffer_out` 재분류나 producer의 ledger-event modelling 변경이 필요하면 별도 Discovery로 결정한다.
### 완료 및 외부 반영 경계
- 로컬 `main` 구현·검증·독립 재QC·커밋 완료:
- `5eb8c042668b1c383ac59ca9be00aa1a5dfcb37a`
- `fix: aggregate investment totals across ledger sources`
- Tracked worktree/index: clean
- 원격 push: **수행하지 않음**
- PR: **생성하지 않음**
- Release: **수행하지 않음**
- Production deployment/restart: **수행하지 않음**
- Production read-only pre/post check: **배포 절차에서 수행 예정이며 현재 미수행**
- Production ledger mutation: **수행하지 않음**
따라서 이 완료는 로컬 제품 구현·검증·커밋 완료를 의미하며 원격 통합, release 또는 production deployment 완료를 의미하지 않는다.
@@ -0,0 +1,46 @@
## 구현 진행 상황
- **대상:** Fix investment totals: remove source='manual' filter from ledger aggregates
- **브랜치:** `main`
- **기준:** `main` (`02bfa602995b8e1c2f410c9bd5762f062666f2d6`)
- **상태:** 로컬 `main` 구현·검증·독립 재QC·커밋 완료 — 미푸시, 미배포
- **최종 업데이트:** 2026-08-19 17:34:13 KST
### 구현 계획 및 작업 목록
- [x] 투자 원금 집계를 모든 source로 확장
- `total_invested`는 유효한 모든 `INVEST`의 gross 합계로 유지하고, `net_contributed_capital`은 `INVEST - WITHDRAW`로 계산한다.
- [x] 수익 인출을 투자 원금과 분리
- `PROFIT`는 원금 계산에서 제외하고 `cumulative_profit_withdrawn`으로만 집계한다.
- [x] Source와 무관한 reversal 제외 보장
- 동일 portfolio의 matching `REVERSAL.target_ledger_entry_id`가 있으면 original row와 reversal의 source와 관계없이 원본을 제외한다.
- [x] 기존 ledger data와 accounting side 경계 보존
- Existing ledger row를 mutation/backfill하지 않고 query semantic만 교정하며 `buffer_out` 등 다른 side를 `INVEST`로 재해석하지 않는다.
- [x] List와 단건 returns summary의 동일한 의미 유지
- `GET /v1/portfolios`와 `GET /v1/portfolios/{portfolio_id}/returns/summary`가 같은 repository aggregate를 사용함을 검증한다.
- [x] Non-manual 및 mixed-source 회귀 테스트 추가
- Non-zero broker `INVEST`, manual/broker 혼합 `INVEST`·`WITHDRAW`·`PROFIT`, source-independent reversal을 검증한다.
- [x] API 및 interface 문서 갱신
- `total_invested`, `total_withdrawn`, `net_contributed_capital`, `cumulative_profit_withdrawn`의 all-source 의미와 `PROFIT` 분리 경계를 명시한다.
- [x] 전체 회귀와 변경 범위 정적 검증
- Focused tests, full repository tests, 변경 범위 lint와 diff 검사를 실행한다.
- [x] 독립 QC 및 완료 경계 기록
- Blocker/Major/Minor를 독립 검토하고 local 구현·검증과 push·release·deployment를 구분해 기록한다.
### 진행 기록
- 2026-08-19 17:23:19 KST — Issue #28의 승인된 OQ-1-A~OQ-5-A와 구현 경계를 확인했다.
- 2026-08-19 17:23:19 KST — 별도 worktree 없이 clean local `main`의 기준 SHA를 고정하고 구현·검증을 시작했다.
- 2026-08-19 17:25:55 KST — Original과 reversal의 `source='manual'` predicate를 제거하고 side별 gross INVEST, WITHDRAW, PROFIT 분리 계산을 구현했다.
- 2026-08-19 17:25:55 KST — API schema와 data-model/runtime-flow 문서를 all-source semantics, PROFIT 분리, source-independent reversal 경계로 갱신했다.
- 2026-08-19 17:25:55 KST — Focused API/repository tests `38 passed`; disposable PostgreSQL 16에서 broker-only, mixed source, 양방향 cross-source reversal, `buffer_out` 제외 semantic test `1 passed`.
- 2026-08-19 17:25:55 KST — 전체 파일 Ruff에는 candidate 이전부터 존재한 오류가 있어 변경 범위와 구분해 기록했고, 신규 파일 lint 및 diff 검사는 PASS했다.
- 2026-08-19 17:28:28 KST — 원본 checkout full suite는 기존 `temp/deleted_20260813/.worktrees/` 복제본을 grep하는 auth surface tests 3건만 실패하고 `657 passed, 16 skipped`였다. 해당 pre-existing artifact를 제외한 clean candidate copy에서 full suite `660 passed, 16 skipped`로 PASS했다.
- 2026-08-19 17:28:28 KST — 구현 범위의 독립 read-only QC를 시작했다. QC 결과 반영 전에는 최종 완료로 표시하지 않는다.
- 2026-08-19 17:32:35 KST — 최초 독립 QC는 Blocker 0 / Major 1 / Minor 0으로, `docs/interface-contract.md`의 manual-only 외부 계약이 구현과 충돌한다고 판정했다.
- 2026-08-19 17:32:35 KST — 외부 interface contract의 list/summary 의미, source-independent reversal, non-capital side 제외와 change log를 갱신하고 문서 계약 회귀 테스트를 추가했다.
- 2026-08-19 17:32:35 KST — 보완 후 focused `39 passed`, test-file Ruff·diff check PASS, clean candidate full suite `661 passed, 16 skipped`로 재검증하고 독립 재QC를 시작했다.
- 2026-08-19 17:34:13 KST — 독립 재QC가 PASS(Blocker 0 / Major 0 / Minor 0)했다.
- 2026-08-19 17:34:13 KST — 로컬 `main`에 `5eb8c042668b1c383ac59ca9be00aa1a5dfcb37a` (`fix: aggregate investment totals across ledger sources`)로 커밋했다. Push, PR, release, deployment와 production read-only pre/post check는 수행하지 않았다.
> 각 작업이 실제로 완료되고 검증될 때마다 이 댓글의 체크박스와 진행 기록을 갱신한다. 체크 표시는 구현 완료 또는 해당 검증의 실제 통과를 의미하며, 배포·릴리스 완료를 의미하지 않는다.
@@ -0,0 +1,147 @@
# Discovery: 투자 원금 집계의 source-independent 의미 복원
- **상태:** `APPROVED`
- **대상 저장소:** `fourblocks2020/portfolio-hub`
- **대상 API:** `GET /v1/portfolios`, `GET /v1/portfolios/{portfolio_id}/returns/summary`
- **관련 이슈:** #23의 manual-only cash-flow 집계 가정 중 Invest-total field 의미를 이 이슈가 대체한다.
## Problem
`get_return_summaries()`는 현재 투자 원금 집계를 manual ledger row로 제한한다.
```sql
WHERE ledger.source = 'manual'
AND ledger.side IN ('invest', 'withdraw', 'profit')
```
그 결과 `total_invested`와 `net_contributed_capital`은 portfolio ledger 전체의 Invest/net Invest가 아니라 manual source의 cash flow만 반영한다. Broker 등 다른 source가 기록한 유효한 `INVEST`가 제외되므로 사용자에게 표시되는 투자 원금 의미와 실제 집계가 불일치한다.
이 동작은 #23의 manual-cash-flow contract에서 유래했지만, Invest-total field가 모든 유효한 투자 원금을 나타내야 한다면 적합하지 않다.
## Evidence
- Production 관찰 사례인 portfolio `353200`에는 broker-origin `invest`, `buffer_out`, `buy` ledger entry가 있고 manual `INVEST`/`WITHDRAW`가 없다.
- 현재 portfolio API는 모든 `source='broker'` row를 집계에서 제외하므로 `net_contributed_capital: 0.0`을 반환한다.
- 같은 사례에서 broker `invest` amount는 `0`, `buffer_out`은 `800,000`이다. 이 이슈의 source-filter 수정만으로 `buffer_out`을 `INVEST`로 간주하거나 zero-amount event를 교정하지는 않는다.
## Target Semantics
승인된 목표 semantics는 다음과 같다.
```text
total_invested = sum(valid INVEST entries from every source)
total_withdrawn = sum(valid WITHDRAW entries from every source)
net_contributed_capital = total_invested - total_withdrawn
cumulative_profit_withdrawn = sum(valid PROFIT entries from every source)
```
`valid`는 원본 ledger entry가 `REVERSAL.target_ledger_entry_id`로 연결된 matching reversal에 의해 취소되지 않았음을 뜻한다.
`total_invested`는 gross value인 `Σ INVEST`로 유지한다. `WITHDRAW`는 `total_withdrawn`과 `net_contributed_capital`에 반영하고, `PROFIT`는 투자 원금 계산에서 제외하여 `cumulative_profit_withdrawn`으로만 별도 집계한다.
## Scope
- 투자 원금 aggregate에서 `ledger.source = 'manual'` predicate를 제거하고 모든 source의 유효한 `INVEST`·`WITHDRAW`·`PROFIT`을 side별로 집계한다.
- `INVEST`, `WITHDRAW`, `PROFIT` accounting side 의미는 유지한다.
- Original entry와 동일 portfolio에서 `target_ledger_entry_id`가 일치하는 `REVERSAL`이 있으면 reversal 자체의 source와 무관하게 original entry를 제외한다.
- Portfolio list와 single-portfolio returns summary가 동일한 aggregate semantics를 사용하게 한다.
- Non-manual `broker` INVEST와 mixed manual/broker INVEST·WITHDRAW·reversal 회귀를 검증한다.
- API/interface 문서에서 `total_invested`와 `net_contributed_capital`의 manual-only 표현을 승인된 의미로 갱신한다.
- 기존 owner/admin/service visibility와 authorization 경계를 변경하지 않는다.
## Out of Scope
- `buffer_out`, `buy` 등 non-INVEST event를 INVEST로 재분류하는 작업
- Zero-amount broker `invest`를 non-zero event로 정규화하는 ledger-event modelling
- Existing ledger row의 mutation, backfill 또는 rewrite
- Ledger producer의 event emission 변경
- Reversal model 또는 `REVERSAL.target_ledger_entry_id` 의미 변경
- Owner/admin/service visibility 및 authorization 변경
- 이 Discovery 승인만으로 배포·릴리스·production mutation을 수행하는 것
## Risks and Constraints
- Source predicate 제거는 과거 모든 source row에 즉시 적용되는 query semantic correction이므로 기존 응답 값이 증가하거나 달라질 수 있다.
- Side label이 같다는 이유만으로 `buffer_out`·`buy` 같은 다른 accounting event를 합산하면 안 된다.
- Reversal exclusion을 source-independent 집계와 함께 유지하지 않으면 reversed principal이 중복 반영될 수 있다.
- List와 detail summary가 다른 query path를 사용한다면 동일 fixture로 semantic parity를 검증해야 한다.
- `total_invested`의 의미 변경은 API field rename 없이 기존 field contract를 교정하는 선택인지 명시해야 한다.
- Production 사례 `353200`은 source-filter defect와 separate ledger-event modelling gap을 동시에 포함하므로, source-filter 수정만으로 `800,000`이 투자 원금으로 표시된다고 보장해서는 안 된다.
## Open Questions
### OQ-1 — Invest-total 집계의 source 범위
- [x] **A. 모든 source의 유효한 원금 event를 포함하되 `total_invested`는 gross `Σ INVEST`로 유지한다. — 결정**
- `total_invested = Σ valid INVEST`, `total_withdrawn = Σ valid WITHDRAW`, `net_contributed_capital = Σ valid INVEST - Σ valid WITHDRAW`로 계산한다.
- `PROFIT`는 원금 계산에서 제외하고 `cumulative_profit_withdrawn = Σ valid PROFIT`으로만 별도 집계한다.
- `ledger.source = 'manual'` predicate를 제거하고 source와 무관하게 accounting side와 reversal을 적용한다.
- [ ] **B. `manual`과 `broker`만 포함하는 allowlist를 사용한다.**
- 현재 알려진 두 source만 포함하지만 새 source가 추가되면 다시 누락될 수 있다.
- [ ] **C. Manual-only 의미를 유지하고 별도 all-source field를 추가한다.**
- 기존 값은 보존하지만 API schema와 UI 소비 계약이 확장되며 본 이슈의 단순 semantic correction 범위를 넘어간다.
### OQ-2 — `buffer_out` 및 zero-amount broker `invest` 처리
- [x] **A. 이 이슈에서는 현행 accounting side를 그대로 사용하고 별도 ledger-event modelling 이슈로 분리한다. — 결정**
- `buffer_out`을 INVEST로 추론하지 않으며 source-filter defect만 교정한다.
- Portfolio `353200`의 `800,000` 표시 문제는 별도 결정 없이는 해결됐다고 주장하지 않는다.
- [ ] **B. `buffer_out`을 이 집계에서 INVEST로 간주한다.**
- 사용자 표시 값은 달라질 수 있지만 accounting event 의미를 query layer에서 재해석한다.
- [ ] **C. Broker producer가 non-zero `INVEST`를 기록하도록 이 이슈 범위를 확장한다.**
- Producer contract, historical data, deduplication과 migration 결정이 추가로 필요하다.
### OQ-3 — 기존 ledger data 처리 방식
- [x] **A. Query semantic만 교정하고 existing ledger row를 mutation/backfill하지 않는다. — 결정**
- 모든 기존 유효 row가 새 query에 자동 반영되며 원장 provenance를 보존한다.
- [ ] **B. Source 또는 side를 migration으로 backfill한다.**
- Historical ledger mutation 범위, 대상 식별과 rollback/audit 계약이 별도로 필요하다.
- [ ] **C. 별도 aggregate projection/table을 만들어 재계산한다.**
- 지속 materialization, replay, ordering 및 consistency ownership이 추가된다.
### OQ-4 — API compatibility 방식
- [x] **A. 기존 field 이름을 유지하고 의미를 all-source Invest-total로 교정한다. — 결정**
- `total_invested`, `total_withdrawn`, `net_contributed_capital`, `cumulative_profit_withdrawn`의 문서를 함께 갱신한다.
- [ ] **B. 새 field를 추가하고 기존 field는 manual-only로 유지한다.**
- 하위 호환은 보존하지만 response schema와 consumer 선택이 복잡해진다.
- [ ] **C. Versioned endpoint에서만 새 의미를 제공한다.**
- 가장 강한 contract 분리를 제공하지만 새 API version과 migration 계획이 필요하다.
### OQ-5 — 배포 후 검증 경계
- [x] **A. Repository tests에 더해 승인된 read-only production query/API pre/post check를 별도 배포 절차에 포함한다. — 결정**
- Source-independent 합계, reversal 제외와 list/detail parity를 확인하되 production row는 변경하지 않는다.
- `353200`은 source-filter 제거 여부를 확인하는 관찰 사례로만 사용하고 `buffer_out=INVEST`를 기대하지 않는다.
- [ ] **B. Repository tests만 수행하고 production 검증은 하지 않는다.**
- 구현 검증은 단순하지만 실제 source 분포와 응답 변화 확인이 남는다.
- [ ] **C. Synthetic staging data에서만 post-deploy 검증한다.**
- Production read를 피하지만 실제 historical source/reversal 조합을 완전히 대표하지 못할 수 있다.
## Acceptance Criteria
OQ가 확정되면 아래 criterion을 선택 결과에 맞춰 canonical requirement로 전환한다.
- [ ] Investment aggregate에서 original ledger row의 source predicate가 제거되고 모든 source의 유효 row가 side별로 집계된다.
- [ ] `total_invested = Σ valid INVEST`, `total_withdrawn = Σ valid WITHDRAW`, `net_contributed_capital = total_invested - total_withdrawn`이며 `PROFIT`는 원금 계산에서 제외되고 `cumulative_profit_withdrawn`으로만 집계된다.
- [ ] 동일 portfolio에서 matching `target_ledger_entry_id`를 가진 `REVERSAL`이 존재하면 reversal source와 무관하게 original entry가 제외된다.
- [ ] `GET /v1/portfolios`와 single-portfolio returns summary가 동일한 aggregate semantics를 사용한다.
- [ ] Non-manual `broker` INVEST의 non-zero amount 회귀가 검증된다.
- [ ] Mixed manual/broker INVEST·WITHDRAW, reversal과 source-independent total이 검증된다.
- [ ] API/interface 문서가 승인된 field 의미를 정확히 설명한다.
- [ ] Existing owner/admin/service visibility 경계가 유지된다.
- [ ] Out-of-scope인 `buffer_out` 재분류나 historical ledger mutation이 암묵적으로 포함되지 않는다.
## Approval Record
- **승인 상태:** `APPROVED`
- **승인 결정:** OQ-1-A, OQ-2-A, OQ-3-A, OQ-4-A, OQ-5-A
- **OQ-1:** 모든 source의 유효한 row를 side별로 집계한다. `total_invested`는 gross `Σ INVEST`, `net_contributed_capital`은 `Σ INVEST - Σ WITHDRAW`이며 `PROFIT`는 원금 계산에서 제외한다.
- **OQ-2:** `buffer_out` 재분류와 zero-amount broker `invest` 교정은 별도 ledger-event modelling으로 분리한다.
- **OQ-3:** Query semantic만 교정하고 existing ledger row를 mutation/backfill하지 않는다.
- **OQ-4:** 기존 field 이름을 유지하고 all-source Invest-total 의미로 문서와 contract를 교정한다.
- **OQ-5:** Repository 검증에 더해 별도 배포 절차에서 승인된 read-only production query/API pre/post check를 수행한다. Production row mutation 권한은 포함하지 않는다.
- **Reversal 적용:** all-source original 집계에서 matching reversal도 source와 무관하게 적용한다. `reversal.source = 'manual'` predicate를 보존하면 broker original reversal이 누락되므로 허용하지 않는다.
- **추가 결정 검토:** 현재 구현·data-flow 검토에서 승인을 중지할 추가 material OQ는 발견되지 않았다.
- **권한 경계:** 이 승인은 이 Discovery와 bounded implementation/verification scope를 승인한다. Push, PR, release, deployment, production mutation 또는 issue closure 권한을 자동으로 부여하지 않는다.
+3
View File
@@ -0,0 +1,3 @@
---
id: "line-0005"
---
+56
View File
@@ -0,0 +1,56 @@
---
id: "req-0005"
status: approved
discovery: "dcy-0005"
criteria:
create: []
update:
- "ac-0001"
- "ac-0002"
- "ac-0003"
- "ac-0005"
retire: []
satisfy:
- "ac-0004"
---
# Portfolio ledger source-independent return aggregates
## Objective
Portfolio return aggregate가 producer source와 무관하게 유효한 accounting event를 반영하도록 교정하면서 gross 투자원금, 회수원금, 순투자원금과 수익 인출을 분리하고, source-independent reversal·목록/단건 일치·기존 권한 경계를 보존한다.
## Scope
- 모든 source의 유효한 `INVEST`, `WITHDRAW`, `PROFIT` row를 side별로 집계한다.
- `total_invested = Σ valid INVEST`, `total_withdrawn = Σ valid WITHDRAW`, `net_contributed_capital = total_invested - total_withdrawn`, `cumulative_profit_withdrawn = Σ valid PROFIT` 의미를 사용한다.
- `PROFIT`을 원금에서 제외하고 별도 수익 인출 합계로 유지한다.
- 동일 portfolio의 matching `REVERSAL.target_ledger_entry_id`가 존재하면 original과 reversal의 source와 무관하게 original `INVEST`·`WITHDRAW`·`PROFIT`을 제외한다.
- `buffer_out` 등 다른 side를 원금·수익 aggregate에 포함하거나 `INVEST`로 재해석하지 않는다.
- 목록은 반환 대상 ID만 하나의 grouped query로 집계하고 단건 summary는 같은 repository aggregate에 위임한다.
- Existing API field 이름과 owner/admin/service authorization 및 filter 경계를 유지한다.
- API schema, data model, runtime flow와 external interface contract를 source-independent 의미로 동기화한다.
## Constraints
- Existing ledger row mutation, migration 또는 backfill 없이 SELECT query semantic만 교정한다.
- 별도 aggregate projection/table 또는 schema migration을 추가하지 않는다.
- Credential, token, password 또는 connection string을 문서와 evidence에 기록하지 않는다.
- Production 확인은 승인된 read-only query/API pre/post check로 제한하며 별도 배포 절차가 소유한다.
### Current Implementation Assessment
- 승인 범위는 local `main` commit `5eb8c042668b1c383ac59ca9be00aa1a5dfcb37a`에 구현됐다.
- Focused repository/API/docs contract tests `39 passed`, disposable PostgreSQL 16 semantic integration `1 passed`, clean candidate full suite `661 passed, 16 skipped`, 변경 test Ruff와 `git diff --check`가 통과했다.
- 최초 독립 QC의 stale manual-only interface contract Major를 보완한 후 독립 재QC는 PASS(Blocker 0 / Major 0 / Minor 0)했다.
- exact GitHub 진행·완료 comment는 `line-0005/evidence/implementation-progress.md`와 `implementation-completion.md`에 보존한다.
- 현재 평가는 local 구현·검증·commit 완료이며 push, PR, 원격 main 반영, release, production deployment/restart와 read-only production pre/post check 완료를 주장하지 않는다.
## Non-Goals
- `buffer_out` 재분류 또는 zero-amount broker event producer 교정
- Historical ledger mutation/backfill
- API field rename 또는 breaking response change
- 별도 projection/table, migration 또는 성능 redesign
- Push, PR, 원격 main 반영, release, production deployment/restart
- Production ledger mutation 또는 배포 lifecycle closure
+41
View File
@@ -0,0 +1,41 @@
---
id: "dcy-0006"
status: confirmed
---
# [portfolio-hub] 포트폴리오 전체 원장 조회 API
## Problem
기존 `GET /v1/portfolios/{portfolio_id}/ledger/manual`는 manual source만 반환하므로, portfolio owner가 broker 체결/원장 이벤트를 포함한 전체 원장을 하나의 안정적인 read 계약으로 조회할 수 없었다. 소비자 UI는 owner가 제공한 원장 사실을 표시할 뿐 action·잔고 효과·PnL을 재계산해서는 안 된다.
## Evidence
- 승인 issue: `https://github.com/fourblocks2020/portfolio-hub/issues/29`; 전체 원문은 `evidence/issue-29-approved-discovery.md`에 body SHA-256 `833b5c8e2dd4bb6c90331bef58a0fdee48534fc1458a82b646f1581877428b66`으로 보존했다.
- 진행 comment: `evidence/implementation-progress.md`, body SHA-256 `e90881b5df47b17650169c0858e7f39c300682ab70d3a88032b6fe41d31f65c7`.
- 완료 comment: `evidence/implementation-completion.md`, body SHA-256 `ce25425fa95afad70221be88a8df88fe39b13f706bbc4f8508a0be34a8327187`.
- 구현 commit `ac742b1150832f6c1cf58744308b4f3ea6803fd4`에서 통합 endpoint, repository keyset query, `20260820_0030` index migration 및 회귀가 확인됐다.
- 실행 evidence: 전체 `pytest -q`는 `664 passed, 16 skipped`; disposable PostgreSQL fresh migration에서 head와 `idx_portfolio_ledger_portfolio_recorded_entry_desc` 생성을 확인했다.
## Scope
- owner-only `GET /v1/portfolios/{portfolio_id}/ledger`가 manual과 broker를 포함한 모든 source를 기본 최신순(`recorded_at DESC, ledger_entry_id DESC`)으로 반환한다.
- optional non-empty exact `source` filter, `(recorded_at, ledger_entry_id)` keyset pagination 및 `next_cursor` 종료 계약을 제공한다. cursor는 portfolio/source 조건에 결속되고 malformed·tampered·다른 조건 재사용은 HTTP 422다.
- 통합 item은 canonical 대문자 `action`을 노출하고 internal `side`는 노출하지 않는다. source별로 없는 사실은 0/추정값이 아닌 schema nullable 값이다.
- user/session owner만 허용한다. owner 밖 사용자와 service token은 기존 정책에 따라 거부한다.
- PostgreSQL index/migration, OpenAPI, mixed source/page/cursor/권한/manual 하위호환 회귀를 포함한다.
- AC admission: 기존 active AC는 aggregate 의미를 소유할 뿐 source-neutral unified read contract를 소유하지 않으므로 durable behavior를 `create`한다.
## Out of Scope
- ledger 생성·수정·삭제, REVERSAL 실행 또는 기존 원장 재해석.
- broker order/fill 생성, strategy signal, outbox/producer 변경.
- API/UI가 원장에 없는 경제 효과·잔고·PnL을 추론하는 동작.
- portfolio return aggregate 의미 변경(#28), trex-web UI, push/PR/merge, 배포·릴리스.
## Risks and Unknowns
### Risks
- 운영 cursor secret은 장기 랜덤 값으로 관리해야 하며 교체 시 기존 cursor의 만료·무효화 정책을 운영 문서에 명시해야 한다.
- 운영 규모 row가 있는 환경에서 source-filter query의 `EXPLAIN ANALYZE` index 사용과 latency 관찰이 필요하다.
@@ -0,0 +1,35 @@
<!-- Source URL: https://github.com/fourblocks2020/portfolio-hub/issues/29#issuecomment-5350993550
Source author: genichin
Source created_at: 2026-08-20T03:28:21Z
Body SHA-256: ce25425fa95afad70221be88a8df88fe39b13f706bbc4f8508a0be34a8327187
Snapshot: exact source body begins after this header.
-->
## 구현 완료
포트폴리오 소유자가 manual·broker를 포함한 모든 출처의 원장을 cursor 기반으로 조회하는 통합 API를 로컬 `main`에 구현·검증·커밋했습니다.
### 구현 내용
- `GET /v1/portfolios/{portfolio_id}/ledger`를 추가해 모든 source의 원장을 `recorded_at DESC, ledger_entry_id DESC` 순서로 반환합니다.
- optional exact `source` filter, HMAC-signed opaque cursor 및 portfolio/source 조건 결속을 구현했습니다. malformed·tampered·다른 조건의 cursor는 HTTP 422로 거부합니다.
- 통합 item은 canonical 대문자 `action`만 노출하며 `side`는 노출하지 않습니다. 출처별로 없는 사실은 추정값 대신 nullable field로 표현합니다.
- PostgreSQL repository keyset query와 `(portfolio_id, recorded_at DESC, ledger_entry_id DESC)` index migration (`20260820_0030`)을 추가했습니다.
- source filter, owner/service-token 권한 경계, cursor 오류, OpenAPI, release migration-head contract 및 `temp/` 제외 source-surface 검사를 회귀로 보완했습니다.
### 검증 결과
전체 회귀와 변경 범위 검증을 완료했습니다.
- `pytest -q` → `664 passed, 16 skipped`
- focused API·release·auth-surface 검증 → `29 passed`
- disposable PostgreSQL fresh migration → head `20260820_0030`, `idx_portfolio_ledger_portfolio_recorded_entry_desc` 생성 확인
- 변경 범위 lint 및 `git diff --check` → 통과
- 로컬 커밋 → `ac742b1150832f6c1cf58744308b4f3ea6803fd4` (`feat(portfolios): add unified ledger history API`)
### 비차단 후속 권고
- 운영 환경에서는 `PORTFOLIOHUB_LEDGER_CURSOR_SECRET`를 장기 랜덤 secret으로 설정하고, cursor secret 교체 시 기존 cursor의 유효기간·무효화 정책을 운영 문서에 명시하는 것을 권고합니다.
- 실제 운영 규모의 ledger row가 있는 환경에서 `EXPLAIN ANALYZE`로 source-filter 포함 query의 index 사용과 latency를 추가 관찰하는 것을 권고합니다.
> 현재 상태는 **로컬 구현·검증·커밋 완료**입니다. push·PR·배포·릴리스 완료를 의미하지 않습니다.
@@ -0,0 +1,36 @@
<!-- Source URL: https://github.com/fourblocks2020/portfolio-hub/issues/29#issuecomment-5349683566
Source author: genichin
Source created_at: 2026-08-20T00:30:07Z
Body SHA-256: e90881b5df47b17650169c0858e7f39c300682ab70d3a88032b6fe41d31f65c7
Snapshot: exact source body begins after this header.
-->
## 구현 진행 상황
- **대상:** [portfolio-hub] discovery: 포트폴리오 전체 원장 조회 API (#29)
- **브랜치:** `main`
- **기준:** `main` (`fe22be0b6686f346f4e6a5c9b64f7b3469e75810`)
- **상태:** 로컬 main 구현·검증·커밋 완료 — 미푸시, 미배포, 미릴리스
- **최종 업데이트:** 2026-08-20T11:05:00+09:00 (KST)
### 구현 계획 및 작업 목록
- [x] 통합 원장 조회 API의 응답·입력 계약을 추가했다.
- 모든 출처를 하나의 대문자 `action` 모델로 표현하고, 출처별로 없는 사실은 `null`로 명시한다.
- [x] source 필터와 cursor 기반 페이지 조회를 구현했다.
- cursor는 portfolio·source 조건과 정렬 기준에 결속하며, 잘못되거나 다른 조건의 cursor는 HTTP 422로 거부한다.
- [x] 소유자 권한과 기존 manual 전용 조회의 하위호환성을 검증했다.
- user/session owner만 허용하고 기존 `/ledger/manual` 계약을 변경하지 않았다.
- [x] API/OpenAPI 문서와 단위·통합 회귀 검증을 추가·실행했다.
- manual·broker 혼합, source filter, 권한 경계와 cursor 오류를 검증했다.
- [x] 실제 PostgreSQL query plan 및 index/migration을 검증했다.
- disposable PostgreSQL DB에서 `20260820_0030` migration head와 `idx_portfolio_ledger_portfolio_recorded_entry_desc` 생성을 확인했다.
### 진행 기록
- 2026-08-20T09:29:48+09:00 (KST): 승인된 Discovery(OQ-001~007)와 현재 `main` 기준 SHA를 확인했다. 별도 구현 worktree는 만들지 않고 `main`에서 구현·검증을 시작한다.
- 2026-08-20T10:40:54+09:00 (KST): source-중립 `GET /v1/portfolios/{portfolio_id}/ledger` vertical slice를 추가했다. focused `tests/test_v1_portfolios_manual_ledger.py`는 `14 passed`였다.
- 2026-08-20T10:55:00+09:00 (KST): disposable PostgreSQL fresh upgrade에서 migration head와 unified-ledger keyset index 생성을 확인했다.
- 2026-08-20T11:05:00+09:00 (KST): 권한/source/OpenAPI/release-contract 회귀를 보완했다. 전체 회귀 `664 passed, 16 skipped`, 변경 범위 lint와 `git diff --check`를 통과했고, 로컬 `main`에 `ac742b1`로 커밋했다. `temp/`는 후보 source가 아니므로 auth-surface 정적 검사의 재귀 대상에서 제외했다.
> 각 작업이 실제로 완료되고 검증될 때마다 이 댓글의 체크박스와 진행 기록을 갱신한다. 체크 표시는 구현 완료 또는 해당 검증의 실제 통과를 의미하며, 배포·릴리스 완료를 의미하지 않는다.
@@ -0,0 +1,140 @@
<!-- Source URL: https://github.com/fourblocks2020/portfolio-hub/issues/29
Source author: genichin
Source created_at: 2026-08-18T10:04:45Z
Body SHA-256: 833b5c8e2dd4bb6c90331bef58a0fdee48534fc1458a82b646f1581877428b66
Snapshot: exact source body begins after this header.
-->
## 배경
`trex-web` 포트폴리오 상세 화면은 현재 다음 manual 전용 계약만 사용합니다.
```http
GET /v1/portfolios/{portfolio_id}/ledger/manual?limit=50
```
이 계약은 수동으로 기록한 원장만 표시하므로, broker에서 유입된 체결/원장 이벤트를 포함한 포트폴리오의 통합 원장 화면을 제공할 수 없습니다.
현재 provider 확인 근거:
- `app/api/v1_portfolios.py`의 manual 목록 route는 `require_read` 뒤에 user/session token 및 portfolio owner를 확인한다.
- `app/repositories/postgres.py`의 `list_manual_ledger_entries()`는 `WHERE portfolio_id = %s AND source = 'manual'`로 필터하고 `recorded_at DESC, ledger_entry_id DESC`로 정렬한다.
- 도메인 `LedgerEntry`는 `source`를 보유하며 기본값은 `broker`; manual 기록은 `source='manual'`이다.
- 현재 응답의 `total`은 전체 일치 건수가 아니라 반환된 `items` 길이이다.
## 목표
포트폴리오 소유자가 manual과 broker를 포함한 **모든 출처의 원장 기록**을 하나의 안정적이고 page 가능한 read 계약으로 조회할 수 있게 한다. 소비자 UI는 owner가 제공한 원장 사실을 표시할 뿐, 원장 action이나 잔고 효과를 재계산하지 않는다.
## 제안 API 초안
```http
GET /v1/portfolios/{portfolio_id}/ledger?limit=50
GET /v1/portfolios/{portfolio_id}/ledger?limit=50&cursor=...
GET /v1/portfolios/{portfolio_id}/ledger?source=manual&limit=50
GET /v1/portfolios/{portfolio_id}/ledger?source=broker&limit=50
```
- `source` 미지정은 모든 출처를 최신순으로 반환한다.
- `source`가 지정되면 비어 있지 않은 provenance 문자열을 exact match로 사용한다. 현재 결과가 없는 값도 오류가 아니라 빈 page(`items=[]`, `next_cursor=null`)를 반환한다.
- 기본 정렬은 `recorded_at DESC, ledger_entry_id DESC`이며, cursor는 두 값을 함께 고정해 동률에서도 중복/누락 없이 다음 페이지를 반환해야 한다.
- 응답 `items`는 적어도 `ledger_entry_id`, `portfolio_id`, `source`, canonical 대문자 `action`, `recorded_at`, `executed_at`(있는 경우), order/execution 식별자(있는 경우), 수량·가격·수수료·세금·note, 기록 후 owner snapshot, reversal 참조와 confirmation evidence를 표현해야 한다.
- 새 통합 endpoint는 `side`를 노출하지 않고 canonical 대문자 `action`만 노출한다. 공통 필드와 출처별 필드는 response schema에 명시하며, 해당 사실에 값이 없을 때만 `null`을 반환한다. broker 원장과 manual 원장의 필드 공백을 0이나 추정값으로 채우지 않는다.
## Open Questions
각 OQ에서 하나의 선택지를 선택해 주세요. 선택은 Discovery 결정을 위한 것이며 구현·push·배포 승인을 뜻하지 않습니다.
### OQ-001 — pagination 계약
- [x] **A. Cursor pagination** — `recorded_at`과 `ledger_entry_id` 기반 opaque cursor, `next_cursor` 반환.
- [ ] **B. Offset pagination** — `offset`과 `limit`으로 페이지 이동.
- [ ] **C. 단일 무제한 응답** — 모든 원장을 한 응답에 반환.
**권장안: A** — 원장은 계속 증가하며, 최신순 목록에 새 행이 들어와도 cursor가 offset보다 중복·누락에 강하다. 무제한 응답은 응답 크기와 DB 부하 경계가 없다.
### OQ-002 — source 필터 정책
- [x] **A. 전체 출처가 기본값이며, 선택적 `source` filter를 제공한다.**
- [ ] **B. 전체 출처만 제공하며, source filter는 제공하지 않는다.**
- [ ] **C. manual/broker 전용 endpoint를 계속 분리하고 통합 endpoint는 만들지 않는다.**
**권장안: A** — 통합 운영 화면의 기본 요구를 충족하면서, manual-only 감사 화면 같은 소비자는 같은 안정적 계약에서 명시적으로 좁힐 수 있다. 기존 `/ledger/manual`은 하위호환성을 위해 유지한다.
### OQ-003 — read 권한 경계
- [x] **A. 현재 manual 조회와 동일하게 user/session token + portfolio owner만 허용한다.**
- [ ] **B. owner 외 admin도 명시적으로 허용한다.**
- [ ] **C. daemon service token에도 portfolio scope 내 조회를 허용한다.**
**권장안: A** — 최초 소비자인 trex-web의 사용자 상세 조회를 최소 권한으로 충족한다. admin/service 조회는 실제 운영 소비자와 audit 노출 범위를 별도로 확정한 뒤 additive하게 설계하는 편이 안전하다.
### OQ-004 — 전체 건수(`total`) 의미
- [x] **A. `next_cursor`만 반환하고 전체 건수는 제공하지 않는다.**
- [ ] **B. 정확한 전체 일치 건수를 `total`로 반환한다.**
- [ ] **C. 현재 page의 반환 건수를 `total`로 반환한다.**
**권장안: A** — 현재 manual endpoint의 `total=len(items)`와 전역 건수 의미를 혼동하지 않으며, 목록 UI에 필요한 다음 페이지 판단도 충족한다. 정확한 total은 필요성이 확인될 때 별도 비용·일관성 계약으로 추가한다.
### OQ-005 — 통합 원장 item의 정규 응답 계약
- [x] **A. 하나의 canonical `action` 필드를 대문자 enum으로 제공하고, 모든 공통·출처별 필드는 schema에 명시적으로 nullable로 선언한다. — 결정**
- 새 통합 endpoint는 `side`를 노출하지 않는다.
- `action`은 manual/broker 모두에서 동일한 대문자 vocabulary를 사용한다.
- 값이 없는 source별 사실은 0 또는 추정값으로 대체하지 않고 `null`로 표현한다.
- [ ] B. `action`과 `side`를 모두 노출하고 source별 field 존재·동치·casing 규칙을 명시한다.
- [ ] C. broker와 manual을 별도 item type/discriminator schema로 제공한다.
### OQ-006 — cursor scope 및 오류 계약
- [x] **A. opaque cursor는 `portfolio_id`, 선택된 `source` filter 및 `(recorded_at, ledger_entry_id)`를 결속한다. malformed·tampered·다른 portfolio/source에 재사용한 cursor는 HTTP 422로 거부한다. 마지막 page의 `next_cursor`는 `null`이다. (권장)**
- 다른 목록 조건의 cursor 혼용을 fail-closed하고, 소비자는 `next_cursor is null`로 종료를 판정한다.
- [ ] B. cursor에는 `(recorded_at, ledger_entry_id)`만 담고, portfolio/source 불일치는 구현이 현재 query 결과로 처리한다.
- cursor 재사용의 의미와 오류가 모호해진다.
- [ ] C. cursor pagination을 유지하되 cursor 오류·scope 동작은 구현 단계에서 정한다.
- 외부 API의 실패 동작을 구현자 재량으로 남긴다.
### OQ-007 — `source` parameter의 허용값 및 결과 없음 의미
- [x] **A. `source`는 비어 있지 않은 provenance 문자열을 exact match로 허용하며, 알 수 없는 값은 빈 page(`items=[]`, `next_cursor=null`)를 반환한다. — 결정**
- all-source 기본값과 미래 producer source를 별도 API 변경 없이 지원한다.
- source 값은 portfolio owner 권한 검증 뒤에만 평가한다.
- [ ] B. `source`는 현재 `manual`·`broker` enum만 허용하고 그 외 값은 HTTP 422로 거부한다.
- [ ] C. known source 조회는 허용하되, source 목록을 API metadata로 제공한 뒤 그 목록 밖 값의 처리 규칙을 별도 계약으로 정한다.
## 포함 범위
- source-중립 통합 원장 read endpoint, request/response schema, repository query와 cursor semantics.
- portfolio ownership 및 선택된 권한 모델의 명시적 검증.
- manual과 broker 행 혼합, 동일 `recorded_at` tie-breaker, page 경계, source filter, token/타인 portfolio 경계에 대한 계약 테스트.
- 필요한 DB index 및 migration 여부 검토. 실제 PostgreSQL에서 pagination query plan과 migration을 검증한다.
- OpenAPI/API interface 문서 갱신.
- 기존 `GET /v1/portfolios/{portfolio_id}/ledger/manual` 계약의 하위호환성 회귀 테스트.
## 제외 범위
- ledger 생성·수정·삭제, `REVERSAL` 실행 또는 기존 원장의 재해석.
- broker 주문/체결 생성, strategy signal, outbox/producer 동작 변경.
- 원장에 없는 경제적 효과·잔고·PnL을 API나 trex-web이 추론하는 기능.
- portfolio return aggregate 의미 변경(관련 이슈 #28의 별도 범위).
- trex-web UI 구현, push/PR/merge, 운영 배포·릴리스.
## 수용 기준 초안
- [ ] OQ-001~007 선택이 issue 본문에 결정으로 기록된다.
- [ ] 소유자가 자신의 portfolio에 대해 선택된 source 범위의 원장을 결정된 정렬·pagination 규칙으로 조회할 수 있다.
- [ ] 서로 다른 출처의 행이 누락 없이 공통 read model로 표현되며, 새 통합 endpoint는 대문자 canonical `action`만 노출한다. 없는 source별 사실은 추정값이 아닌 schema의 명시된 nullable 값이다.
- [ ] cursor 페이지 경계에서 동일 시각 행의 중복·누락이 없고, cursor의 portfolio/source scope 및 malformed·tampered cursor 거부 동작은 OQ-006 결정과 일치한다.
- [ ] 선택된 권한 범위 밖의 token 또는 타인 portfolio는 기존 정책에 맞는 거부 응답을 받는다.
- [ ] `source` 필터가 선택되면 지정 provenance와 exact match인 row만 반환하고, 결과 없는 non-empty 값은 빈 page(`items=[]`, `next_cursor=null`)를 반환한다. 미지정 기본 동작은 OQ-002·OQ-007 결정과 일치한다.
- [ ] `/ledger/manual`의 source=manual 전용·최신순·limit 계약은 하위호환으로 유지된다.
- [ ] API schema/OpenAPI와 실제 응답이 일치하고, focused 및 전체 회귀 테스트가 통과한다.
## 관련
- 소비자 맥락: `fourblocks2020/trex-web#15`
- 별도 집계 의미 변경: #28
- 작성 시각: 2026-08-18T19:04:00+09:00
> **Discovery 상태: APPROVED** — requester가 OQ-001~007을 모두 명시적으로 결정했고, 2026-08-20 KST에 현재 provider/data-flow/ownership 계약과 대조하여 승인했다. 이 승인은 구현·커밋·push·PR·merge·배포·릴리스 승인을 포함하지 않습니다.
+3
View File
@@ -0,0 +1,3 @@
---
id: "line-0006"
---
+35
View File
@@ -0,0 +1,35 @@
---
id: "req-0006"
status: approved
discovery: "dcy-0006"
criteria:
create: ["ac-0032", "ac-0033", "ac-0034", "ac-0035", "ac-0036"]
update: []
retire: []
satisfy: []
---
# 포트폴리오 전체 원장 조회 API
## Objective
Portfolio owner가 manual·broker를 포함한 모든 원장 source를 안정적이고 page 가능한 단일 read 계약으로 조회하도록 한다.
## Scope
- `GET /v1/portfolios/{portfolio_id}/ledger`의 source-neutral 목록, optional exact `source`, latest-first keyset pagination과 signed opaque cursor.
- canonical uppercase `action`, nullable source-specific facts, owner-only authorization, OpenAPI/repository/index migration 및 회귀.
## Constraints
- 기존 `/ledger/manual` 계약을 변경하지 않는다.
- cursor는 portfolio/source와 tuple ordering에 결속하며 잘못된 cursor는 fail-closed HTTP 422다.
- source에 없는 사실을 0 또는 추정값으로 만들지 않는다.
### 현재 구현 평가
구현 commit `ac742b1150832f6c1cf58744308b4f3ea6803fd4`에서 이 REQ의 모든 AC 동작이 구현됐다. `pytest -q`는 `664 passed, 16 skipped`; focused API/release/auth-surface는 `29 passed`; disposable PostgreSQL fresh migration에서 `20260820_0030`과 index 생성을 확인했다. local main은 origin/main보다 1 commit ahead이며 push·PR·배포·릴리스는 수행하지 않았다. 이 평가는 구현 evidence이며 approved/active status는 normative authority다.
## Non-Goals
Ledger write/reversal 실행, broker/strategy/outbox producer 변경, UI 구현, aggregate #28 변경, push·PR·배포·릴리스는 포함하지 않는다.
+31
View File
@@ -0,0 +1,31 @@
# syntax=docker/dockerfile:1@sha256:ecfaec9ed6d810b56388c508f4121597bfbba70d41a6dfeee4d8cad5f295fc32
FROM ghcr.io/astral-sh/uv:0.11.14@sha256:1025398289b62de8269e70c45b91ffa37c373f38118d7da036fb8bb8efc85d97 AS uv
FROM python:3.11-slim@sha256:a630a63cdb314e2d138a2fca3e375e319e8568346ffafac5b980f888630ac4f1 AS build
ARG SOURCE_COMMIT
ARG RELEASE_VERSION
WORKDIR /opt/portfolio-hub
RUN test "${#SOURCE_COMMIT}" -eq 40 && case "${SOURCE_COMMIT}" in *[!0-9a-f]*) false;; *) true;; esac \
&& printf '%s' "${RELEASE_VERSION}" | grep -Eq '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$' \
|| { echo "SOURCE_COMMIT and strict RELEASE_VERSION=vX.Y.Z are required" >&2; exit 1; }
COPY --from=uv /uv /usr/local/bin/uv
COPY pyproject.toml uv.lock README.md ./
COPY app/ ./app/
RUN uv sync --locked --no-dev --no-editable
FROM python:3.11-slim@sha256:a630a63cdb314e2d138a2fca3e375e319e8568346ffafac5b980f888630ac4f1 AS runtime
ARG SOURCE_COMMIT
ARG RELEASE_VERSION
LABEL org.opencontainers.image.source="https://github.com/fourblocks2020/portfolio-hub" \
org.opencontainers.image.revision="${SOURCE_COMMIT}" \
org.opencontainers.image.version="${RELEASE_VERSION}"
RUN test "${#SOURCE_COMMIT}" -eq 40 && case "${SOURCE_COMMIT}" in *[!0-9a-f]*) false;; *) true;; esac \
&& printf '%s' "${RELEASE_VERSION}" | grep -Eq '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$' \
&& groupadd --gid 10001 portfoliohub \
&& useradd --uid 10001 --gid 10001 --create-home --shell /usr/sbin/nologin portfoliohub \
|| { echo "SOURCE_COMMIT and strict RELEASE_VERSION=vX.Y.Z are required" >&2; exit 1; }
WORKDIR /opt/portfolio-hub
COPY --from=build /opt/portfolio-hub/.venv ./.venv
ENV PATH="/opt/portfolio-hub/.venv/bin:${PATH}" PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
USER 10001:10001
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+107 -2
View File
@@ -8,6 +8,11 @@ REQ-043: GET /v1/portfolios/{id}/holdings/cost-basis — current holding WAC cos
from __future__ import annotations
import base64
import binascii
import hashlib
import hmac
import json
import logging
import uuid
from datetime import date, datetime, timedelta, timezone
@@ -15,11 +20,15 @@ from datetime import date, datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from app.core.auth import AuthContext, Permission, require_read, require_trade_write
from app.core.config import get_settings
from app.domain.errors import DaemonInactiveError, DaemonNotFoundError
from app.domain.models import Portfolio, PortfolioComment
from app.domain.pnl import calculate_current_wac, calculate_realized_pnl
from app.repositories.factory import get_portfolio_repository_from_settings
from app.schemas.v1 import (
HoldingsCostBasisResponse,
LedgerHistoryItem,
LedgerHistoryResponse,
LedgerTradeRequest,
LedgerTradeResponse,
ManualLedgerHistoryResponse,
@@ -35,7 +44,6 @@ from app.schemas.v1 import (
PortfolioReturnSummaryResponse,
PortfolioTagListResponse,
PortfolioUpdateRequest,
HoldingsCostBasisResponse,
RealizedPnlItem,
RealizedPnlResponse,
TagApplyRequest,
@@ -44,7 +52,10 @@ from app.schemas.v1 import (
TradeHistoryItem,
TradeHistoryResponse,
)
from app.services.strategy_set_service import StrategyInactiveError, StrategyNotFoundError
from app.services.strategy_set_service import (
StrategyInactiveError,
StrategyNotFoundError,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/v1/portfolios", tags=["v1"])
@@ -108,6 +119,7 @@ def _portfolio_to_item(
# REQ-055: 전략·시장 메타데이터 additive 필드
active_strategy_id=portfolio.active_strategy_id,
strategy_name=portfolio.strategy_name,
strategy_nick=portfolio.strategy_nick,
strategy_params=portfolio.strategy_params,
strategy_revision=portfolio.strategy_revision,
markets=portfolio.markets,
@@ -709,6 +721,62 @@ def _manual_error_code(message: str) -> str:
return "MANUAL_LEDGER_CONFLICT"
def _encode_ledger_cursor(*, portfolio_id: str, source: str | None, recorded_at: datetime, ledger_entry_id: int) -> str:
payload = {
"portfolio_id": portfolio_id,
"source": source,
"recorded_at": recorded_at.isoformat(),
"ledger_entry_id": ledger_entry_id,
}
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode()
signature = hmac.new(get_settings().ledger_cursor_secret.encode(), raw, hashlib.sha256).digest()
return base64.urlsafe_b64encode(raw + signature).decode().rstrip("=")
def _decode_ledger_cursor(cursor: str, *, portfolio_id: str, source: str | None) -> tuple[datetime, int]:
try:
encoded = cursor.encode()
raw_and_signature = base64.urlsafe_b64decode(encoded + b"=" * (-len(encoded) % 4))
if base64.urlsafe_b64encode(raw_and_signature).rstrip(b"=") != encoded:
raise ValueError
raw, signature = raw_and_signature[:-32], raw_and_signature[-32:]
expected = hmac.new(get_settings().ledger_cursor_secret.encode(), raw, hashlib.sha256).digest()
payload = json.loads(raw)
recorded_at = datetime.fromisoformat(payload["recorded_at"])
ledger_entry_id = int(payload["ledger_entry_id"])
if not hmac.compare_digest(signature, expected) or payload["portfolio_id"] != portfolio_id or payload["source"] != source:
raise ValueError
if recorded_at.tzinfo is None:
raise ValueError
return recorded_at, ledger_entry_id
except (KeyError, TypeError, ValueError, json.JSONDecodeError, UnicodeDecodeError, binascii.Error):
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="invalid ledger cursor") from None
def _ledger_entry_to_history_item(entry) -> LedgerHistoryItem:
return LedgerHistoryItem(
ledger_entry_id=entry.ledger_entry_id,
portfolio_id=entry.portfolio_id,
source=entry.source or "broker",
action=(entry.action or entry.side or "").upper(),
recorded_at=entry.recorded_at,
executed_at=entry.executed_at,
order_id=entry.order_id,
execution_id=entry.execution_id,
quantity=entry.quantity,
price=entry.price,
fee_amount=entry.fee_amount,
tax_amount=entry.tax_amount,
note=entry.note,
cash_balance_after=entry.cash_balance_after,
asset_quantity_after=entry.asset_quantity_after,
profit_buffer_after=entry.profit_buffer_after,
total_value_after=entry.total_value_after,
target_ledger_entry_id=entry.target_ledger_entry_id,
confirmation_evidence=entry.confirmation_evidence,
)
@router.post(
"/{portfolio_id}/ledger/manual",
response_model=ManualLedgerResponse,
@@ -787,6 +855,43 @@ def list_manual_ledger_v1(
return ManualLedgerHistoryResponse(items=items, total=len(items))
@router.get("/{portfolio_id}/ledger", response_model=LedgerHistoryResponse)
def list_ledger_v1(
portfolio_id: str,
source: str | None = Query(default=None, min_length=1),
cursor: str | None = Query(default=None),
limit: int = Query(default=50, ge=1, le=200),
auth: AuthContext = Depends(require_read),
) -> LedgerHistoryResponse:
if auth.token_type in {"service", "client"} or auth.user_id is None:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="ledger requires user/session token")
before_recorded_at = before_ledger_entry_id = None
if cursor is not None:
before_recorded_at, before_ledger_entry_id = _decode_ledger_cursor(cursor, portfolio_id=portfolio_id, source=source)
repo = _get_repo()
try:
_get_owner_portfolio_or_404(auth, portfolio_id, repo)
entries = repo.list_ledger_entries(
portfolio_id,
source=source,
before_recorded_at=before_recorded_at,
before_ledger_entry_id=before_ledger_entry_id,
limit=limit + 1,
)
finally:
_close_repo(repo)
page, extra = entries[:limit], entries[limit:]
next_cursor = None
if extra and page:
last = page[-1]
if last.recorded_at is None:
raise RuntimeError("ledger entry is missing recorded_at")
next_cursor = _encode_ledger_cursor(
portfolio_id=portfolio_id, source=source, recorded_at=last.recorded_at, ledger_entry_id=last.ledger_entry_id
)
return LedgerHistoryResponse(items=[_ledger_entry_to_history_item(entry) for entry in page], next_cursor=next_cursor)
@router.get("/{portfolio_id}/returns/summary", response_model=PortfolioReturnSummaryResponse)
def get_portfolio_return_summary_v1(
portfolio_id: str,
+20 -9
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
from typing import NoReturn
from fastapi import APIRouter, Depends, HTTPException, Response, status
@@ -11,7 +12,11 @@ from app.core.config import Settings, get_settings
from app.domain.models import StrategySet
from app.repositories.factory import get_portfolio_repository_from_settings
from app.schemas.portfolio import CreateStrategySetRequest, UpdateStrategySetRequest
from app.schemas.v1 import StrategyCreateRequest, StrategyResponse, StrategyUpdateRequest
from app.schemas.v1 import (
StrategyCreateRequest,
StrategyResponse,
StrategyUpdateRequest,
)
from app.services.strategy_set_service import (
StrategyConflictError,
StrategyInactiveError,
@@ -44,6 +49,7 @@ def _response(strategy: StrategySet) -> StrategyResponse:
parsed = {}
return StrategyResponse(
strategy_id=strategy.id,
nick=strategy.nick,
name=strategy.name,
config=parsed if isinstance(parsed, dict) else {},
status=strategy.status,
@@ -53,7 +59,7 @@ def _response(strategy: StrategySet) -> StrategyResponse:
)
def _raise_strategy_error(exc: ValueError) -> None:
def _raise_strategy_error(exc: ValueError) -> NoReturn:
if isinstance(exc, StrategyNotFoundError):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
if isinstance(exc, (StrategyInactiveError, StrategyInUseError, StrategyConflictError)):
@@ -129,14 +135,18 @@ def create_admin_strategy(
) -> StrategyResponse:
service, repository = _get_service(settings)
try:
strategy = service.create(
CreateStrategySetRequest(
name=body.name,
config=_canonical_config(body.config),
status=body.status,
try:
strategy = service.create(
CreateStrategySetRequest(
name=body.name,
nick=body.nick,
config=_canonical_config(body.config),
status=body.status,
)
)
)
return _response(strategy)
return _response(strategy)
except ValueError as exc:
_raise_strategy_error(exc)
finally:
_close_repository(repository)
@@ -155,6 +165,7 @@ def update_admin_strategy(
strategy_id,
UpdateStrategySetRequest(
name=body.name,
nick=body.nick,
config=_canonical_config(body.config) if body.config is not None else None,
status=body.status,
),
+15 -2
View File
@@ -5,9 +5,13 @@ from __future__ import annotations
import typer
from app.cli.core.utils import print_json
from app.db.migrations import bootstrap_or_upgrade_to_head
from app.db.migrations import (
bootstrap_or_upgrade_to_head,
current_revision,
head_revision,
)
from app.repositories.factory import build_portfolio_db_config
from app.repositories.postgres import PostgresPortfolioRepository, create_database_if_missing, database_exists
from app.repositories.postgres import create_database_if_missing, database_exists
def initialize_database(*, settings, maintenance_db: str = "postgres") -> dict[str, object]:
@@ -90,6 +94,15 @@ def register_health_commands(app: typer.Typer) -> None:
}
if hasattr(repository, "ping"):
repository.ping()
if app_context.settings.db_enabled:
database_revision = current_revision(app_context.settings)
expected_revision = head_revision(app_context.settings)
health["database_revision"] = database_revision
health["expected_revision"] = expected_revision
if database_revision != expected_revision:
raise RuntimeError(
f"database revision {database_revision!r} is not packaged head {expected_revision!r}"
)
except Exception as exc:
app_context.console.print(f"health-check failed: {exc}")
raise typer.Exit(code=1) from exc
+2 -1
View File
@@ -18,7 +18,7 @@ if env_file.exists():
class Settings(BaseSettings):
app_name: str = "PortfolioHub"
app_version: str = "0.1.0"
app_version: str = "0.2.0"
environment: str = "development"
allowed_origins_raw: str = Field(default="http://localhost:3000", validation_alias="PORTFOLIOHUB_ALLOWED_ORIGINS")
bootstrap_username: str = Field(default="", validation_alias="PORTFOLIOHUB_BOOTSTRAP_USERNAME")
@@ -27,6 +27,7 @@ class Settings(BaseSettings):
read_tokens_raw: str = Field(default="", validation_alias="PORTFOLIOHUB_READ_TOKENS")
trade_write_tokens_raw: str = Field(default="", validation_alias="PORTFOLIOHUB_TRADE_WRITE_TOKENS")
admin_tokens_raw: str = Field(default="", validation_alias="PORTFOLIOHUB_ADMIN_TOKENS")
ledger_cursor_secret: str = Field(default="development-ledger-cursor-secret", validation_alias="PORTFOLIOHUB_LEDGER_CURSOR_SECRET")
db_enabled: bool = Field(default=False, validation_alias="PORTFOLIOHUB_DB_ENABLED")
session_token_ttl_hours: int = Field(default=12, validation_alias="PORTFOLIOHUB_SESSION_TOKEN_TTL_HOURS")
client_token_default_ttl_days: int = Field(default=365, validation_alias="PORTFOLIOHUB_CLIENT_TOKEN_DEFAULT_TTL_DAYS")
View File
@@ -0,0 +1,31 @@
"""portfolio_ledger: keyset pagination index for unified ledger reads
Revision ID: 20260820_0030
Revises: 20260814_0029
Create Date: 2026-08-20 10:50:00
"""
from __future__ import annotations
from alembic import op
from sqlalchemy import text
revision = "20260820_0030"
down_revision = "20260814_0029"
branch_labels = None
depends_on = None
_INDEX = "idx_portfolio_ledger_portfolio_recorded_entry_desc"
def upgrade() -> None:
op.get_bind().execute(
text(
f"CREATE INDEX IF NOT EXISTS {_INDEX} "
"ON portfolio_ledger (portfolio_id, recorded_at DESC, ledger_entry_id DESC)"
)
)
def downgrade() -> None:
op.get_bind().execute(text(f"DROP INDEX IF EXISTS {_INDEX}"))
View File
+34 -16
View File
@@ -2,19 +2,34 @@
from __future__ import annotations
from pathlib import Path
from importlib import resources
import psycopg
from alembic import command
from alembic.config import Config
import psycopg
from alembic.script import ScriptDirectory
from app.core.config import Settings
def migration_root():
"""Return the packaged Alembic resource tree for source and wheel installs."""
return resources.files("app.db.alembic")
def migration_inventory() -> tuple[str, ...]:
"""Return the deterministic, non-empty migration revision inventory."""
versions = migration_root().joinpath("versions")
inventory = tuple(sorted(item.name for item in versions.iterdir() if item.name.endswith(".py") and item.name != "__init__.py"))
if not inventory:
raise RuntimeError("packaged Alembic migration inventory is empty")
return inventory
def get_alembic_config(settings: Settings) -> Config:
project_root = Path(__file__).resolve().parents[2]
config = Config(str(project_root / "alembic.ini"))
config.set_main_option("script_location", str(project_root / "migrations"))
root = migration_root()
config = Config(str(root.joinpath("alembic.ini")))
config.set_main_option("script_location", str(root))
config.set_main_option("sqlalchemy.url", settings.active_database_url.replace("%", "%%"))
# migrations/env.py must use this explicit settings object instead of the
# process-global cached Settings. This keeps programmatic callers (notably
@@ -47,15 +62,19 @@ def bootstrap_or_upgrade_to_head(settings: Settings) -> str:
def current_revision(settings: Settings) -> str | None:
output: list[str] = []
"""Read the database revision without applying or stamping migrations."""
with _connect(settings) as conn, conn.cursor() as cur:
cur.execute("SELECT version_num FROM alembic_version")
row = cur.fetchone()
return str(row[0]) if row else None
def capture(message: str, *_args, **_kwargs) -> None:
if message.strip():
output.append(message.strip())
config = get_alembic_config(settings)
command.current(config, verbose=False)
return output[-1] if output else None
def head_revision(settings: Settings) -> str:
"""Return the single packaged Alembic head without touching the database."""
heads = ScriptDirectory.from_config(get_alembic_config(settings)).get_heads()
if len(heads) != 1:
raise RuntimeError(f"expected one Alembic head, found {len(heads)}")
return heads[0]
def _connect(settings: Settings) -> psycopg.Connection:
@@ -73,10 +92,9 @@ def _connect(settings: Settings) -> psycopg.Connection:
def _has_alembic_version_table(settings: Settings) -> bool:
with _connect(settings) as conn:
with conn.cursor() as cur:
cur.execute("SELECT to_regclass('public.alembic_version')")
return cur.fetchone()[0] is not None
with _connect(settings) as conn, conn.cursor() as cur:
cur.execute("SELECT to_regclass('public.alembic_version')")
return cur.fetchone()[0] is not None
def _has_legacy_portfolio_schema(settings: Settings) -> bool:
+1
View File
@@ -120,6 +120,7 @@ class Portfolio:
profit_buffer: float = 0.0
active_strategy_id: str | None = None
strategy_name: str | None = None # REQ-055: strategy_sets.name JOIN 결과
strategy_nick: str | None = None # REQ-055: strategy_sets.nick JOIN 결과
strategy_params: dict[str, Any] = field(default_factory=dict) # REQ-055: strategy_sets.config 파싱 결과
strategy_revision: int | None = None
markets: list[str] = field(default_factory=list) # REQ-055: assets.markets JOIN 결과
+19 -1
View File
@@ -243,7 +243,14 @@ class PortfolioRepository(Protocol):
def get_or_create_strategy_set(self, name: str, config: str) -> StrategySet: ...
def create_strategy_set(self, name: str, config: str, *, status: str = "active") -> StrategySet: ...
def create_strategy_set(
self,
name: str,
config: str,
*,
nick: str | None = None,
status: str = "active",
) -> StrategySet: ...
def get_strategy_set(self, id: str) -> StrategySet | None: ...
@@ -254,6 +261,7 @@ class PortfolioRepository(Protocol):
id: str,
*,
name: str | None = None,
nick: str | None = None,
config: str | None = None,
status: str | None = None,
) -> StrategySet: ...
@@ -325,6 +333,16 @@ class PortfolioRepository(Protocol):
def list_manual_ledger_entries(self, portfolio_id: str, limit: int = 50) -> list[LedgerEntry]: ...
def list_ledger_entries(
self,
portfolio_id: str,
*,
source: str | None = None,
before_recorded_at: datetime | None = None,
before_ledger_entry_id: int | None = None,
limit: int = 50,
) -> list[LedgerEntry]: ...
def get_return_summary(self, portfolio_id: str) -> dict[str, float]: ...
def get_return_summaries(self, portfolio_ids: list[str]) -> dict[str, dict[str, float]]: ...
+76 -27
View File
@@ -73,7 +73,8 @@ _SELECT_PORTFOLIO = """
ss.name,
ss.config,
a.markets,
ss.revision
ss.revision,
ss.nick
FROM portfolios p
JOIN assets a ON p.asset_id = a.asset_id
LEFT JOIN strategy_sets ss ON p.active_strategy_id = ss.id
@@ -572,6 +573,8 @@ class PostgresPortfolioRepository:
_markets_raw = row[21] if len(row) > 21 else None
markets: list[str] = list(_markets_raw) if _markets_raw else []
strategy_revision = int(row[22]) if len(row) > 22 and row[22] is not None else None
# REQ-055: strategy_nick (row[23] = ss.nick from LEFT JOIN strategy_sets)
strategy_nick: str | None = row[23] if len(row) > 23 else None
return Portfolio(
portfolio_id=row[0],
@@ -595,6 +598,7 @@ class PostgresPortfolioRepository:
tag_ids=[str(t) for t in row[17]] if len(row) > 17 and row[17] is not None else [],
display_name=row[18] if len(row) > 18 else None,
strategy_name=strategy_name,
strategy_nick=strategy_nick,
strategy_params=strategy_params,
strategy_revision=strategy_revision,
markets=markets,
@@ -1360,28 +1364,38 @@ class PostgresPortfolioRepository:
def get_or_create_strategy_set(self, name: str, config: str) -> StrategySet:
return self.create_strategy_set(name, config)
def create_strategy_set(self, name: str, config: str, *, status: str = "active") -> StrategySet:
def create_strategy_set(
self,
name: str,
config: str,
*,
nick: str | None = None,
status: str = "active",
) -> StrategySet:
self.ensure_schema()
nick = f"{name}:{hashlib.sha1(config.encode('utf-8')).hexdigest()[:12]}"
with self._connect().cursor() as cur:
new_id = str(uuid.uuid4())
cur.execute(
"""
INSERT INTO strategy_sets (id, name, config, nick, status)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (name, config) DO NOTHING
""",
(new_id, name, config, nick, status),
)
cur.execute(
"""
SELECT id, name, config, nick, status, revision, created_at, updated_at
FROM strategy_sets
WHERE name = %s AND config = %s
""",
(name, config),
)
row = cur.fetchone()
final_nick = nick or f"{name}:{hashlib.sha1(config.encode('utf-8')).hexdigest()[:12]}"
try:
with self._connect().cursor() as cur:
new_id = str(uuid.uuid4())
cur.execute(
"""
INSERT INTO strategy_sets (id, name, config, nick, status)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (name, config) DO NOTHING
""",
(new_id, name, config, final_nick, status),
)
cur.execute(
"""
SELECT id, name, config, nick, status, revision, created_at, updated_at
FROM strategy_sets
WHERE name = %s AND config = %s
""",
(name, config),
)
row = cur.fetchone()
except psycopg.errors.UniqueViolation as exc:
raise ValueError("동일한 nick 전략이 이미 존재합니다") from exc
return self._row_to_strategy_set(row)
def get_strategy_set(self, id: str) -> StrategySet | None:
@@ -1414,6 +1428,7 @@ class PostgresPortfolioRepository:
id: str,
*,
name: str | None = None,
nick: str | None = None,
config: str | None = None,
status: str | None = None,
) -> StrategySet:
@@ -1435,15 +1450,16 @@ class PostgresPortfolioRepository:
raise ValueError("전략을 찾을 수 없습니다")
current = self._row_to_strategy_set(row)
final_name = name if name is not None else current.name
final_nick = nick if nick is not None else current.nick
final_config = config if config is not None else current.config
final_status = status if status is not None else current.status
if (
final_name == current.name
and final_nick == current.nick
and final_config == current.config
and final_status == current.status
):
return current
nick = f"{final_name}:{hashlib.sha1(final_config.encode('utf-8')).hexdigest()[:12]}"
cur.execute(
"""
UPDATE strategy_sets
@@ -1456,11 +1472,11 @@ class PostgresPortfolioRepository:
WHERE id = %s
RETURNING id, name, config, nick, status, revision, created_at, updated_at
""",
(final_name, final_config, nick, final_status, id),
(final_name, final_config, final_nick, final_status, id),
)
updated = cur.fetchone()
except psycopg.errors.UniqueViolation as exc:
raise ValueError("동일한 name/config 전략이 이미 존재합니다") from exc
raise ValueError("동일한 name/config 또는 nick 전략이 이미 존재합니다") from exc
if updated is None:
raise ValueError("전략을 찾을 수 없습니다")
return self._row_to_strategy_set(updated)
@@ -2194,6 +2210,41 @@ class PostgresPortfolioRepository:
)
return [self._row_to_ledger_entry(row) for row in cur.fetchall()]
def list_ledger_entries(
self,
portfolio_id: str,
*,
source: str | None = None,
before_recorded_at: datetime | None = None,
before_ledger_entry_id: int | None = None,
limit: int = 50,
) -> list[LedgerEntry]:
self.ensure_schema()
clauses = ["portfolio_id = %s"]
params: list[Any] = [portfolio_id]
if source is not None:
clauses.append("source = %s")
params.append(source)
if before_recorded_at is not None and before_ledger_entry_id is not None:
clauses.append("(recorded_at, ledger_entry_id) < (%s, %s)")
params.extend([before_recorded_at, before_ledger_entry_id])
params.append(int(limit))
with self._connect().cursor() as cur:
cur.execute(
"""
SELECT ledger_entry_id, portfolio_id, order_id, execution_id, side, quantity, price,
fee_amount, tax_amount, executed_at, recorded_at, cash_balance_after,
asset_quantity_after, total_value_after, profit_buffer_after, strategy_set_id,
note, source, target_ledger_entry_id, confirmation_evidence, actor_user_id
FROM portfolio_ledger
WHERE """ + " AND ".join(clauses) + """
ORDER BY recorded_at DESC, ledger_entry_id DESC
LIMIT %s
""",
params,
)
return [self._row_to_ledger_entry(row) for row in cur.fetchall()]
def get_return_summaries(self, portfolio_ids: list[str]) -> dict[str, dict[str, float]]:
if not portfolio_ids:
return {}
@@ -2207,13 +2258,11 @@ class PostgresPortfolioRepository:
COALESCE(SUM(ledger.price) FILTER (WHERE ledger.side = 'profit'), 0)
FROM portfolio_ledger AS ledger
WHERE ledger.portfolio_id = ANY(%s)
AND ledger.source = 'manual'
AND ledger.side IN ('invest', 'withdraw', 'profit')
AND NOT EXISTS (
SELECT 1
FROM portfolio_ledger AS reversal
WHERE reversal.portfolio_id = ledger.portfolio_id
AND reversal.source = 'manual'
AND reversal.side = 'reversal'
AND reversal.target_ledger_entry_id = ledger.ledger_entry_id
)
+2
View File
@@ -186,6 +186,7 @@ class CreateStrategySetRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
nick: str | None = Field(default=None, min_length=1)
config: str
status: Literal["active", "inactive"] = "active"
@@ -194,6 +195,7 @@ class UpdateStrategySetRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str | None = None
nick: str | None = Field(default=None, min_length=1)
config: str | None = None
status: Literal["active", "inactive"] | None = None
+72 -7
View File
@@ -6,7 +6,7 @@ from datetime import date, datetime
from decimal import Decimal
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
# ---------------------------------------------------------------------------
@@ -220,12 +220,53 @@ class ManualLedgerHistoryResponse(BaseModel):
total: int
class LedgerHistoryItem(BaseModel):
"""Source-neutral, owner-visible ledger fact for GET /ledger."""
ledger_entry_id: int
portfolio_id: str
source: str
action: str
recorded_at: datetime
executed_at: datetime | None = None
order_id: str | None = None
execution_id: str | None = None
quantity: float | None = None
price: float | None = None
fee_amount: float | None = None
tax_amount: float | None = None
note: str | None = None
cash_balance_after: float | None = None
asset_quantity_after: float | None = None
profit_buffer_after: float | None = None
total_value_after: float | None = None
target_ledger_entry_id: int | None = None
confirmation_evidence: str | None = None
class LedgerHistoryResponse(BaseModel):
items: list[LedgerHistoryItem]
next_cursor: str | None = None
class PortfolioReturnSummaryResponse(BaseModel):
portfolio_id: str
total_invested: float = 0.0
total_withdrawn: float = 0.0
net_contributed_capital: float = 0.0
cumulative_profit_withdrawn: float = 0.0
total_invested: float = Field(
default=0.0,
description="총투자원금: source와 무관한 유효 INVEST의 gross 합계",
)
total_withdrawn: float = Field(
default=0.0,
description="총회수원금: source와 무관한 유효 WITHDRAW 합계",
)
net_contributed_capital: float = Field(
default=0.0,
description="순투자원금: total_invested - total_withdrawn (PROFIT 제외)",
)
cumulative_profit_withdrawn: float = Field(
default=0.0,
description="누적 수익 인출액: source와 무관한 유효 PROFIT 합계 (원금 계산 제외)",
)
# ---------------------------------------------------------------------------
@@ -273,11 +314,11 @@ class PortfolioItem(BaseModel):
profit_buffer: float = 0.0
net_contributed_capital: float = Field(
default=0.0,
description="순투자현금: 유효 manual INVEST 합계 - 유효 manual WITHDRAW 합계",
description="순투자원금: source와 무관한 유효 INVEST 합계 - 유효 WITHDRAW 합계 (PROFIT 제외)",
)
cumulative_profit_withdrawn: float = Field(
default=0.0,
description="누적 수익 인출액: 유효 manual PROFIT 합계",
description="누적 수익 인출액: source와 무관한 유효 PROFIT 합계 (원금 계산 제외)",
)
tag_ids: list[str] = Field(default_factory=list)
managed_by_daemon_id: str | None = None
@@ -286,6 +327,7 @@ class PortfolioItem(BaseModel):
# REQ-055: 전략·시장 메타데이터 additive 필드
active_strategy_id: str | None = None
strategy_name: str | None = None
strategy_nick: str | None = None
strategy_params: dict[str, Any] = Field(default_factory=dict)
strategy_revision: int | None = Field(default=None, ge=1)
markets: list[str] = Field(default_factory=list)
@@ -305,6 +347,7 @@ StrategyStatus = Literal["active", "inactive"]
class StrategyResponse(BaseModel):
strategy_id: str
nick: str
name: str
config: dict[str, Any] = Field(default_factory=dict)
status: StrategyStatus
@@ -317,17 +360,39 @@ class StrategyCreateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(..., min_length=1)
nick: str | None = Field(default=None, min_length=1)
config: dict[str, Any] = Field(default_factory=dict)
status: StrategyStatus = "active"
@field_validator("nick")
@classmethod
def normalize_nick(cls, value: str | None) -> str | None:
if value is None:
raise ValueError("nick must not be null")
normalized = value.strip()
if not normalized:
raise ValueError("nick must not be blank")
return normalized
class StrategyUpdateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str | None = Field(default=None, min_length=1)
nick: str | None = Field(default=None, min_length=1)
config: dict[str, Any] | None = None
status: StrategyStatus | None = None
@field_validator("nick")
@classmethod
def normalize_nick(cls, value: str | None) -> str | None:
if value is None:
raise ValueError("nick must not be null")
normalized = value.strip()
if not normalized:
raise ValueError("nick must not be blank")
return normalized
@model_validator(mode="after")
def require_change(self) -> "StrategyUpdateRequest":
if not self.model_fields_set:
+36 -13
View File
@@ -46,26 +46,49 @@ class StrategySetService:
return self.get(strategy_set_id, active_only=True)
def create(self, payload: CreateStrategySetRequest) -> StrategySet:
create_strategy = cast(
Callable[..., StrategySet] | None,
getattr(self._repository, "create_strategy_set", None),
)
if create_strategy is not None:
strategy = create_strategy(payload.name, payload.config, status=payload.status)
else:
strategy = self._repository.get_or_create_strategy_set(payload.name, payload.config)
if payload.status != strategy.status:
strategy = self.update(
strategy.id,
UpdateStrategySetRequest(status=payload.status),
try:
create_strategy = cast(
Callable[..., StrategySet] | None,
getattr(self._repository, "create_strategy_set", None),
)
return strategy
if create_strategy is not None:
strategy = create_strategy(
payload.name,
payload.config,
nick=payload.nick,
status=payload.status,
)
else:
strategy = self._repository.get_or_create_strategy_set(payload.name, payload.config)
if payload.nick is not None and payload.nick != strategy.nick:
strategy = self.update(
strategy.id,
UpdateStrategySetRequest(nick=payload.nick),
)
if payload.status != strategy.status:
strategy = self.update(
strategy.id,
UpdateStrategySetRequest(status=payload.status),
)
return strategy
except StrategyConflictError:
raise
except ValueError as exc:
raise StrategyConflictError(str(exc)) from exc
def update(self, strategy_set_id: str, payload: UpdateStrategySetRequest) -> StrategySet:
try:
if payload.nick is None:
return self._repository.update_strategy_set(
strategy_set_id,
name=payload.name,
config=payload.config,
status=payload.status,
)
return self._repository.update_strategy_set(
strategy_set_id,
name=payload.name,
nick=payload.nick,
config=payload.config,
status=payload.status,
)
+120
View File
@@ -0,0 +1,120 @@
# PortfolioHub v0.2.0 container contract
## Publication is not deployment
Only a requester-authorized push of the strict tag `v0.2.0` can publish this revision. The workflow checks that the tag equals `[project].version`, checks out `github.sha`, runs the complete Python suite, builds one `linux/amd64` image from `uv.lock`, and tests those exact bytes before publication. It gives the same image exactly two selectors:
- `ghcr.io/fourblocks2020/portfolio-hub:<source-commit-first-12>`
- `ghcr.io/fourblocks2020/portfolio-hub:v0.2.0`
It never publishes `latest`. Both selectors must report the same registry digest; deployment and rollback must use the immutable identity:
```text
ghcr.io/fourblocks2020/portfolio-hub@sha256:<64-lowercase-hex-digest>
```
OCI labels are fail-closed build inputs: `org.opencontainers.image.source`, the full 40-character `org.opencontainers.image.revision`, and strict `org.opencontainers.image.version=v0.2.0`. Publication does **not** deploy, replace, start, stop, or restart a production service. This repository provides no production Compose, Kubernetes, Helm, systemd, or Dockge configuration.
The Dockerfile frontend, Python base image, uv image, and GitHub Actions are digest/commit pinned. The workflow intentionally uses `--provenance=false` to preserve the tested `docker save` archive and build-once/no-rebuild identity. Registry-attached provenance, SBOM, signing, and attestations are a nonblocking v0.2.0 supply-chain gap; they must not be added by rebuilding a different image in the publish job.
## Image runtime
- platform: `linux/amd64`;
- process: exec-form `uvicorn app.main:app --host 0.0.0.0 --port 8000` as PID 1;
- network: HTTP on fixed container port `8000` (configure only the host/service mapping, not the container port);
- identity: numeric UID/GID `10001:10001`;
- filesystem: no application data path is written; the root filesystem may be read-only;
- temporary space: a bounded `/tmp` tmpfs is safe but not required by normal application behavior;
- shutdown: send `SIGTERM`, allow at least 10 seconds for Uvicorn graceful shutdown, then escalate only under the deployment platform's policy;
- restart: application replicas may use the platform's normal failure restart policy; the one-shot migration must use restart `no` and must never loop after failure.
Recommended runtime restrictions are a read-only root filesystem, all capabilities dropped, `no-new-privileges`, a bounded PID limit, and no Docker socket or host filesystem mounts. No build argument, label, layer, or image environment contains an application secret.
## Environment contract
Values are read at process start; changing any value requires a container restart. Empty optional values mean the shown default/disabled behavior.
### Production database and secrets
| Variable | Production contract | Default | Secret | Effect |
| --- | --- | --- | --- | --- |
| `PORTFOLIOHUB_DB_ENABLED` | required; `true` for persistent production | `false` | no | Selects PostgreSQL instead of in-memory repository |
| `TIMESCALEDB_HOST` | required when DB enabled | `localhost` | no | PostgreSQL host |
| `TIMESCALEDB_PORT` | optional | `5432` | no | PostgreSQL port |
| `TIMESCALEDB_NAME` | required when DB enabled | `portfoliohub` | no | database name |
| `TIMESCALEDB_USER` | required when DB enabled | `portfoliohub` | usually sensitive | database user |
| `TIMESCALEDB_PASSWORD` | required by production DB policy | empty | **yes** | database password |
| `TIMESCALEDB_SSLMODE` | optional; set explicitly in production | `prefer` | no | psycopg SSL mode |
| `TIMESCALEDB_CONNECT_TIMEOUT_SEC` | optional | `10` | no | connection timeout |
| `TIMESCALEDB_APPLICATION_NAME` | optional | `portfoliohub` | no | PostgreSQL application name |
| `CREDENTIAL_ENCRYPTION_KEY` | required when DB enabled | empty | **yes** | Fernet key for stored broker credentials; startup fails closed if absent |
### Authentication, bootstrap, and HTTP behavior
| Variable | Required/default | Secret | Effect |
| --- | --- | --- | --- |
| `PORTFOLIOHUB_ALLOWED_ORIGINS` | optional; `http://localhost:3000` | no | comma-separated CORS origins; set the trex-web origin in production |
| `PORTFOLIOHUB_ROOT_PATH` | optional; empty | no | reverse-proxy ASGI root path; does not rewrite the actual route paths |
| `PORTFOLIOHUB_READ_TOKENS` | optional; empty | **yes** | comma-separated legacy read service tokens |
| `PORTFOLIOHUB_TRADE_WRITE_TOKENS` | optional; empty | **yes** | comma-separated legacy ledger-write service tokens |
| `PORTFOLIOHUB_ADMIN_TOKENS` | optional; empty | **yes** | comma-separated legacy admin service tokens |
| `PORTFOLIOHUB_SESSION_TOKEN_TTL_HOURS` | optional; `12` | no | login session lifetime |
| `PORTFOLIOHUB_CLIENT_TOKEN_DEFAULT_TTL_DAYS` | optional; `365` | no | retained client-token default |
| `PORTFOLIOHUB_BOT_TOKEN_DEFAULT_TTL_DAYS` | optional; `365` | no | bot-token default |
| `PORTFOLIOHUB_BOOTSTRAP_USERNAME` | optional; empty | no | with password, creates the first admin only when no users exist |
| `PORTFOLIOHUB_BOOTSTRAP_EMAIL` | optional; empty | personal data | bootstrap user email |
| `PORTFOLIOHUB_BOOTSTRAP_PASSWORD` | optional; empty | **yes** | bootstrap password; inject temporarily and remove after first successful start |
| `PORTFOLIOHUB_ENVIRONMENT` | optional; `development` | no | reported environment metadata |
| `PORTFOLIOHUB_APP_NAME` | optional; `PortfolioHub` | no | application/OpenAPI display name |
| `PORTFOLIOHUB_APP_VERSION` | do not override for v0.2.0 | `0.2.0` | no | health/OpenAPI version metadata |
`REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_PASSWORD`, `LOKI_HOST`, `LOKI_PORT`, and `LOKI_ENABLED` are still parsed for source compatibility but the inspected v0.2.0 application does not open Redis or Loki connections. They are not production dependencies of this image.
### Legacy and sibling mapping
The existing database variable names remain `TIMESCALEDB_*`; v0.2.0 deliberately does not invent a `DATABASE_URL` alias. Existing `PORTFOLIOHUB_{READ,TRADE_WRITE,ADMIN}_TOKENS` Bearer-token behavior remains compatible. `trex-core`'s `TREX_PORTFOLIO_HUB_BASE_URL` and TOML `portfolio_hub_token`, and `trex-web`'s server-only `PORTFOLIO_HUB_API_BASE_URL`, are **caller-side** settings: point them to `http://portfolio-hub:8000` (or the equivalent service URL) and do not inject them into this container.
## Liveness and readiness
- **Liveness:** unauthenticated `GET /health` must return HTTP 200 with `status=ok`. It is intentionally process-only and does not query PostgreSQL. `db_enabled` only reports configuration; it is not readiness.
- **Readiness:** run `pfhub --format json health-check` with the same runtime environment. With DB enabled it performs a repository ping, reads `alembic_version` without migration, compares it with the single packaged Alembic head, and exits nonzero on connectivity, missing schema, multiple heads, or revision mismatch.
- **API identity:** `GET /openapi.json` is stable for smoke verification. Health version is `0.2.0`.
Do not route traffic from a static `/health` success alone. Readiness checks never apply, stamp, or repair migrations.
## One-shot migration and 0029 -> 0030 policy
The installed image contains exactly **30** migration files and one Alembic head, `20260820_0030`. The application default command does not invoke Alembic. Migration is a separate pre-start operation using the exact same digest and database environment:
1. back up the database and record the current immutable image digest and `alembic_version`;
2. require the normal upgrade origin `20260814_0029`; for an older revision, review and apply the full ordered chain first;
3. stop writes or otherwise establish an operator-approved maintenance boundary;
4. execute `pfhub migrate-db` once with restart disabled;
5. stop rollout on any nonzero result and preserve sanitized logs;
6. run `pfhub --format json health-check` and require both `database_revision` and `expected_revision` to equal `20260820_0030`;
7. start application replicas and verify `/health`, `/openapi.json`, authenticated caller paths, and strategy data;
8. a repeated `pfhub migrate-db` is expected to be idempotent and remain at `0030`, but it is verification—not an application-start hook.
Migration `0029` is additive/idempotent around the strategy catalog: it preserves existing strategy IDs and portfolio references, reuses the canonical `target_value`/`{}` strategy, and backfills catalog data. Before migration, inspect duplicate or invalid strategy references and take a backup. After migration, verify strategy listing and portfolio active-strategy fields before resuming writes.
v0.2.0 adds migration `0030`, an idempotent index on `(portfolio_id, recorded_at DESC, ledger_entry_id DESC)` for unified-ledger keyset reads. Operators at `0029` must run the same-image one-shot migration before rollout; it advances to `20260820_0030` without mutating ledger rows.
A pre-Alembic legacy schema is detected only when all three tables `strategy_sets`, `portfolios`, and `portfolio_ledger` exist; the CLI stamps `0027` and then runs real upgrades through `0030`. This compatibility path must be used only after backup and schema review. A partially matching schema is not auto-stamped and must fail for operator investigation.
Image rollback is **not** database rollback. Selecting older application bytes does not reverse schema/data changes, tokens, or side effects. Database restore, downgrade, or forward-fix requires separate review and authorization; no automatic downgrade is provided.
## API verification and known caller blockers
v0.2.0 preserves Bearer authentication and adds all-source unified-ledger reads. The release gate runs the complete portfolio-hub source test suite (including auth success/failure, strategy catalog/data, portfolio and ledger APIs), then verifies the built image's health/OpenAPI surface, exact 30-file migration inventory, isolated PostgreSQL migration twice, readiness at `0030`, persistent-volume restart, non-root/read-only operation, secret canary absence, and graceful SIGTERM. Publication consumes the tested archive without rebuilding it.
The strategy catalog API remains additive: strategy responses expose `nick`, admin create/update requests may set it, and portfolio responses expose the current strategy as `strategy_nick`. Existing clients may omit `nick`; supplied values are trimmed and blank-only values are rejected. trex-web v0.2.3 displays `strategy_nick`, but that dependency does not resolve or waive the separate caller blockers below.
Route presence is **not** a positive cross-repository caller-compatibility claim. Direct source comparison found the following unresolved consumers, which the requester explicitly separated as BLOCKED follow-up rather than adding legacy shims to portfolio-hub:
- trex-web omits required `strategy_id` when creating a portfolio, so that mutation currently returns `422`;
- trex-web can omit required `account_ref` when creating or rotating credentials, so those requests currently return `422`;
- trex-web sends daemon activation state through the general PATCH route, which can return `200` without changing activation; it must use the activate/deactivate routes;
- portfolio-hub returns singular `broker` from `/v1/user_info`, while trex-web types `brokers[]`;
- portfolio-hub represents duplicate ledger success as `status="duplicate"`, while trex-core currently checks `duplicate=true`, so the core result classification is inconsistent.
Do not claim trex-core/trex-web compatibility or switch production callers until those consumer changes and cross-repository tests are completed.
+9
View File
@@ -343,6 +343,15 @@
- SELL: asset_quantity -> cash_balance.
- REVERSAL: append-only inverse effect of `target_ledger_entry_id`.
### Return Aggregate Semantics
- `total_invested`: source와 무관한 유효 `INVEST`의 gross 합계.
- `total_withdrawn`: source와 무관한 유효 `WITHDRAW` 합계.
- `net_contributed_capital`: `total_invested - total_withdrawn`; `PROFIT`는 원금 계산에서 제외한다.
- `cumulative_profit_withdrawn`: source와 무관한 유효 `PROFIT` 합계이며 원금과 별도로 노출한다.
- 동일 portfolio에서 matching `REVERSAL.target_ledger_entry_id`가 존재하면 original과 reversal의 source와 무관하게 original entry를 집계에서 제외한다.
- `buffer_out` 등 다른 accounting side를 `INVEST`로 재해석하지 않으며 existing ledger row를 mutation/backfill하지 않는다.
### State Rules
- Manual writes lock the portfolio row while calculating/appending/updating snapshots to avoid lost updates.
+11 -4
View File
@@ -347,10 +347,13 @@
- Response: HTTP 200 `PortfolioListResponse {"portfolios": [{"portfolio_id": "<uuid>", "asset_id": "<uuid>", "symbol": "<assets.symbol|null>", "net_contributed_capital": <float>, "cumulative_profit_withdrawn": <float>, ...}], "total": <int>}`
- Note: list items are serialized from the server-side `portfolios JOIN assets` result; `symbol` must equal the joined `assets.symbol` for each returned `asset_id`.
- Ledger aggregate fields:
- `net_contributed_capital` (**순투자현금**) = 유효 manual `INVEST` 합계 - 유효 manual `WITHDRAW` 합계.
- `cumulative_profit_withdrawn` (**누적 수익 인출액**) = 유효 manual `PROFIT` 합계. 매매상 실현손익 전체가 아니다.
- `REVERSAL.target_ledger_entry_id`로 참조된 `INVEST`, `WITHDRAW`, `PROFIT` 원거래는 유효 집계에서 제외하며 `REVERSAL` 자체는 금액 action으로 합산하지 않는다.
- 목록에 반환될 portfolio ID 집합만 한 번의 grouped aggregate로 조회한다. 해당 유효 manual ledger가 없는 항목은 두 필드 모두 `0.0`이다.
- `total_invested` (**총투자원금**, summary response) = source와 무관한 유효 `INVEST`의 gross 합계.
- `total_withdrawn` (**총회수원금**, summary response) = source와 무관한 유효 `WITHDRAW` 합계.
- `net_contributed_capital` (**순투자원금**) = `total_invested - total_withdrawn`. `PROFIT`는 원금 계산에서 제외한다.
- `cumulative_profit_withdrawn` (**누적 수익 인출액**) = source와 무관한 유효 `PROFIT` 합계. 원금 또는 매매상 실현손익 전체가 아니다.
- 동일 portfolio에서 matching `REVERSAL.target_ledger_entry_id`로 참조된 `INVEST`, `WITHDRAW`, `PROFIT` 원거래는 original과 reversal의 source와 무관하게 제외하며 `REVERSAL` 자체는 금액 action으로 합산하지 않는다.
- `buffer_out` 등 `INVEST`/`WITHDRAW`/`PROFIT` 이외 side는 원금·수익 aggregate에 포함하거나 `INVEST`로 재해석하지 않는다.
- 목록에 반환될 portfolio ID 집합만 한 번의 grouped aggregate로 조회한다. 해당 유효 ledger가 없는 항목은 aggregate field가 `0.0`이다.
- 이 필드들은 portfolio-hub가 소유한 ledger 집계값이다. 소비자는 ledger event를 재해석하지 않는다.
### Endpoint: `GET /v1/portfolios/{portfolio_id}/tags`
@@ -438,6 +441,9 @@
- Auth: owner-scoped user/session token.
- Response: `PortfolioReturnSummaryResponse` with `total_invested`, `total_withdrawn`, `net_contributed_capital`, and `cumulative_profit_withdrawn`.
- Aggregate semantics: `total_invested`는 source-independent valid `INVEST`의 gross 합계, `total_withdrawn`은 valid `WITHDRAW` 합계, `net_contributed_capital`은 두 값의 차이며 `PROFIT`는 원금에서 제외하고 `cumulative_profit_withdrawn`으로만 노출한다.
- Reversal semantics: 동일 portfolio의 matching `REVERSAL.target_ledger_entry_id`는 original과 reversal의 source와 무관하게 original을 제외한다. `buffer_out` 등 다른 side는 집계하지 않는다.
- Consistency: `GET /v1/portfolios`와 동일한 grouped repository aggregate를 portfolio ID 하나에 위임한다.
## Interface: `Tag Management API (BAT-004)`
@@ -562,6 +568,7 @@
## Change Log
- 2026-08-19 KST: Issue #28 — portfolio return aggregate를 manual-only에서 source-independent semantics로 교정; gross `total_invested`, `INVEST-WITHDRAW` net, separate `PROFIT`, cross-source reversal과 non-capital side 제외를 명시.
- 2026-07-14 KST: BAT-024 (REQ-056) — added owner-scoped manual ledger API, manual history, and return summary contracts; clarified PROFIT vs WITHDRAW return semantics and service-token separation from `/ledger/trades`.
- 2026-05-21 KST: BAT-011 (REQ-029) — ledger path migration: "POST /v1/assets/{asset_id}/ledger/trades" 명세 → "POST /v1/portfolios/{portfolio_id}/ledger/trades"로 교체; auth 섹션 + daemon authorization 갱신; 구 path HTTP 404 명시.
- 2026-05-21 KST: BAT-010 (REQ-032) — v1 portfolio surface baseline 회복: "v1 Portfolio API" 섹션 신규 추가 (REQ-025~028 CRUD + REQ-030 tag 서브 라우트 + REQ-031 comment CRUD); POST/DELETE /v1/portfolios/{id}/tags에 disabled 보호(409) 및 service/client 403 명세 추가; GET /v1/portfolios/{id}/tags 신설; ledger path "pending REQ-029" 마킹; Source Discovery/Batch 헤더 갱신.
+3 -3
View File
@@ -152,9 +152,9 @@
2. `service` token: `auth.daemon_id is None` → HTTP 403. `repo.list_portfolios(managed_by_daemon_id=auth.daemon_id, ...)`.
3. `user`/`admin` token: admin with `?user_id=<id>` → filter by that user; else filter by `auth.user_id`.
4. `?include_disabled=false` (default) → `status="enabled"` filter applied. `?include_disabled=true` → no status filter.
5. 필터링된 반환 대상 portfolio ID만 `repo.get_return_summaries(ids)`에 전달한다. repository는 한 번의 grouped query로 유효 manual ledger를 집계한다.
6. `REVERSAL.target_ledger_entry_id`로 참조된 `INVEST`/`WITHDRAW`/`PROFIT`은 제외한다. `REVERSAL` 자체는 금액 action으로 합산하지 않는다.
7. 각 `PortfolioItem`에 순투자현금(`net_contributed_capital`)과 누적 수익 인출액(`cumulative_profit_withdrawn`)을 결합한다. 집계 row가 없으면 두 값은 `0.0`이다.
5. 필터링된 반환 대상 portfolio ID만 `repo.get_return_summaries(ids)`에 전달한다. repository는 한 번의 grouped query로 source와 무관한 유효 ledger를 side별 집계한다.
6. 동일 portfolio에서 matching `REVERSAL.target_ledger_entry_id`로 참조된 `INVEST`/`WITHDRAW`/`PROFIT`은 original과 reversal의 source와 무관하게 제외한다. `REVERSAL` 자체는 금액 action으로 합산하지 않는다.
7. `total_invested`는 유효 `INVEST`의 gross 합계, `total_withdrawn`은 유효 `WITHDRAW` 합계, `net_contributed_capital`은 두 값의 차이다. `PROFIT`는 원금 계산에서 제외하고 `cumulative_profit_withdrawn`으로만 집계한다. 집계 row가 없으면 값은 `0.0`이다.
8. Returns HTTP 200 `PortfolioListResponse`.
단건 `GET /v1/portfolios/{portfolio_id}/returns/summary`도 같은 grouped aggregate 구현을 portfolio ID 하나로 호출하므로 목록과 유효 원장 의미가 일치한다.
+9 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "portfoliohub"
version = "0.1.0"
version = "0.2.0"
description = "PortfolioHub API for portfolio management and ledger access"
readme = "README.md"
requires-python = ">=3.11"
@@ -28,6 +28,7 @@ dev = [
"httpx>=0.27.0,<1.0.0",
"pre-commit>=3.8.0,<4.0.0",
"pytest>=8.3.0,<9.0.0",
"ruff>=0.12.0,<1.0.0",
]
[tool.pytest.ini_options]
@@ -35,8 +36,15 @@ addopts = ["tests"]
testpaths = ["tests"]
norecursedirs = ["temp", ".git", ".venv"]
[tool.ruff.lint.isort]
known-first-party = ["app", "scripts"]
[tool.setuptools]
package-dir = {"" = "."}
[tool.setuptools.packages.find]
include = ["app*"]
[tool.setuptools.package-data]
"app.db.alembic" = ["alembic.ini", "script.py.mako"]
"app.db.alembic.versions" = ["*.py"]
+418
View File
@@ -0,0 +1,418 @@
#!/usr/bin/env python3
"""Fail-closed PortfolioHub image verification and publication helpers."""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
import re
import subprocess
import sys
import tarfile
import tempfile
import time
import tomllib
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol
IMAGE = "ghcr.io/fourblocks2020/portfolio-hub"
CANARY = b"PORTFOLIO_HUB_SECRET_CANARY_DO_NOT_SHIP"
COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
VERSION_REF_RE = re.compile(r"^refs/tags/v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
IMAGE_ID_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
DIGEST_RE = re.compile(r"(?:^|\s)digest:\s*(sha256:[0-9a-f]{64})(?:\s|$)")
EXPECTED_MIGRATION_COUNT = 29
EXPECTED_ALEMBIC_HEAD = "20260814_0029"
@dataclass(frozen=True)
class Result:
stdout: str = ""
stderr: str = ""
class Runner(Protocol):
def run(self, command: Sequence[str], *, input_text: str | None = None,
timeout: int | None = None) -> Result: ...
class SubprocessRunner:
def run(self, command: Sequence[str], *, input_text: str | None = None,
timeout: int | None = None) -> Result:
result = subprocess.run(command, input=input_text, text=True, capture_output=True,
check=True, timeout=timeout)
return Result(result.stdout, result.stderr)
def validate_commit(commit: str) -> str:
if not COMMIT_RE.fullmatch(commit):
raise ValueError("source commit must be 40 lowercase hexadecimal characters")
return commit
def validate_checkout_identity(actual: str, expected: str) -> str:
validate_commit(actual); validate_commit(expected)
if actual != expected:
raise ValueError("checked-out HEAD does not match the tagged source commit")
return actual
def project_release_version(project: Path) -> str:
value = tomllib.loads(project.read_text(encoding="utf-8"))["project"]["version"]
version = f"v{value}"
if not VERSION_REF_RE.fullmatch(f"refs/tags/{version}"):
raise ValueError("project version must be strict semantic version X.Y.Z")
return version
def validate_release_event(
event_name: str, ref: str, commit: str, expected_version: str | None = None
) -> str:
validate_commit(commit)
if event_name != "push" or not VERSION_REF_RE.fullmatch(ref):
raise ValueError("publication requires a push of a strict vX.Y.Z tag")
version = ref.removeprefix("refs/tags/")
if expected_version is not None and version != expected_version:
raise ValueError("release tag does not match the project version")
return version
def release_tags(event_name: str, ref: str, commit: str) -> tuple[str, str]:
version = validate_release_event(event_name, ref, commit)
return f"{IMAGE}:{commit[:12]}", f"{IMAGE}:{version}"
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def write_checksum(archive: Path, output: Path) -> str:
checksum = sha256_file(archive)
output.write_text(f"{checksum} {archive.name}\n", encoding="ascii")
return checksum
def verify_checksum(archive: Path, checksum_path: Path) -> str:
if not archive.is_file() or not checksum_path.is_file():
raise ValueError("image archive or checksum evidence is missing")
fields = checksum_path.read_text(encoding="ascii").strip().split()
if len(fields) != 2 or fields[1] != archive.name or not re.fullmatch(r"[0-9a-f]{64}", fields[0]):
raise ValueError("checksum evidence has an invalid format")
if sha256_file(archive) != fields[0]:
raise ValueError("image archive checksum mismatch")
return fields[0]
def _clean(result: Result) -> Result:
if CANARY in (result.stdout + result.stderr).encode():
raise ValueError("canary marker found on a scanned surface")
return result
def inspect_value(image: str, template: str, runner: Runner) -> str:
return _clean(runner.run(["docker", "image", "inspect", "--format", template, image])).stdout.strip()
def inspect_container_value(container: str, template: str, runner: Runner) -> str:
return _clean(runner.run(["docker", "container", "inspect", "--format", template, container])).stdout.strip()
def inspect_image_id(image: str, runner: Runner) -> str:
value = inspect_value(image, "{{.Id}}", runner)
if not IMAGE_ID_RE.fullmatch(value):
raise ValueError("image ID has an invalid format")
return value
def inspect_revision(image: str, runner: Runner) -> str:
return inspect_value(image, '{{ index .Config.Labels "org.opencontainers.image.revision" }}', runner)
def inspect_version(image: str, runner: Runner) -> str:
return inspect_value(image, '{{ index .Config.Labels "org.opencontainers.image.version" }}', runner)
def write_image_id(image: str, output: Path, runner: Runner) -> str:
image_id = inspect_image_id(image, runner)
output.write_text(image_id + "\n", encoding="ascii")
return image_id
def read_image_id(path: Path) -> str:
value = path.read_text(encoding="ascii").strip()
if not IMAGE_ID_RE.fullmatch(value):
raise ValueError("tested image ID evidence has an invalid format")
return value
def _error_text(error: subprocess.CalledProcessError) -> str:
return "\n".join(str(value or "") for value in (error.stdout, error.stderr)).lower()
def _remove(command: list[str], absent: tuple[str, ...], runner: Runner, timeout: int) -> None:
try:
_clean(runner.run(command, timeout=timeout))
except subprocess.CalledProcessError as error:
if not any(marker in _error_text(error) for marker in absent):
raise
def _cleanup(names: list[str], network: str | None, volume: str | None,
runner: Runner, timeout: int) -> None:
errors: list[BaseException] = []
for name in reversed(names):
try:
_remove(["docker", "rm", "--force", name], ("no such container",), runner, timeout)
except BaseException as error: errors.append(error)
if network:
try:
_remove(["docker", "network", "rm", network], ("not found", "no such network"), runner, timeout)
except BaseException as error: errors.append(error)
if volume:
try:
_remove(["docker", "volume", "rm", "--force", volume], ("no such volume", "not found"), runner, timeout)
except BaseException as error: errors.append(error)
if errors:
raise RuntimeError("image smoke cleanup failed") from errors[0]
def smoke_installed_image(image: str, expected_inventory: tuple[str, ...], runner: Runner,
timeout: int = 30) -> None:
if not expected_inventory:
raise ValueError("expected migration inventory must be non-empty")
if len(expected_inventory) != EXPECTED_MIGRATION_COUNT:
raise ValueError(f"expected exactly {EXPECTED_MIGRATION_COUNT} migrations")
if not expected_inventory[-1].startswith(EXPECTED_ALEMBIC_HEAD):
raise ValueError(f"migration inventory must end at {EXPECTED_ALEMBIC_HEAD}")
inventory_code = (
"import json; from app.db.migrations import migration_inventory; "
f"expected={json.dumps(list(expected_inventory))}; actual=list(migration_inventory()); "
"assert actual == expected, (actual, expected)"
)
probes = (("python", "-I", "-c", "import app"), ("pfhub", "--help"),
("python", "-I", "-c", inventory_code))
for index, probe in enumerate(probes):
name = f"portfolio-hub-install-smoke-{os.getpid()}-{index}"
command = ["docker", "run", "--name", name, "--network", "none", "--read-only",
"--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", "64",
"--tmpfs", "/tmp:rw,noexec,nosuid,size=16m", "--entrypoint", probe[0], image, *probe[1:]]
failure: BaseException | None = None
try: _clean(runner.run(command, timeout=timeout))
except BaseException as error: failure = error
try: _cleanup([name], None, None, runner, timeout)
except BaseException as error:
if failure is None: failure = error
if failure: raise RuntimeError(f"install smoke probe {index + 1} failed") from failure
def _wait(command: list[str], runner: Runner, deadline: float, description: str) -> Result:
last: BaseException | None = None
while time.monotonic() < deadline:
try: return _clean(runner.run(command, timeout=5))
except (OSError, subprocess.SubprocessError) as error:
last = error; time.sleep(1)
raise RuntimeError(f"timed out waiting for {description}") from last
def startup_smoke(image: str, runner: Runner, timeout: int = 120) -> dict:
"""Run isolated health/OpenAPI, repeated migration, readiness, persistence and SIGTERM."""
suffix = f"{os.getpid()}-{time.time_ns()}"
plain = f"portfolio-hub-plain-{suffix}"; db = f"portfolio-hub-db-{suffix}"
migrate = f"portfolio-hub-migrate-{suffix}"; migrate_again = f"portfolio-hub-migrate-again-{suffix}"
app = f"portfolio-hub-app-{suffix}"; app_again = f"portfolio-hub-app-again-{suffix}"
network = f"portfolio-hub-smoke-{suffix}"; volume = f"portfolio-hub-db-{suffix}"
names: list[str] = []
deadline = time.monotonic() + timeout
failure: BaseException | None = None; result: dict = {}
db_env = ["-e", "PORTFOLIOHUB_DB_ENABLED=true", "-e", "TIMESCALEDB_HOST=postgres",
"-e", "TIMESCALEDB_PORT=5432", "-e", "TIMESCALEDB_NAME=smoke",
"-e", "TIMESCALEDB_USER=smoke", "-e", "TIMESCALEDB_PASSWORD=synthetic-db-only",
"-e", "TIMESCALEDB_SSLMODE=disable", "-e", "CREDENTIAL_ENCRYPTION_KEY=bnVsbC1vbmx5LXN5bnRoZXRpYy1rZXktMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwPQ=="]
http_probe = "import json,urllib.request; d=json.load(urllib.request.urlopen('http://TARGET:8000/health')); assert d['status']=='ok'; o=json.load(urllib.request.urlopen('http://TARGET:8000/openapi.json')); required={'/auth/login','/v1/user_info','/v1/portfolios','/v1/strategies','/v1/portfolios/{portfolio_id}/ledger/trades'}; assert required <= set(o['paths']), required-set(o['paths']); print(json.dumps(d,sort_keys=True))"
try:
architecture = inspect_value(image, "{{.Architecture}}", runner)
if architecture != "amd64": raise RuntimeError(f"image architecture must be amd64, got {architecture!r}")
runner.run(["docker", "network", "create", "--internal", network], timeout=10)
runner.run(["docker", "volume", "create", volume], timeout=10)
names.append(plain)
runner.run(["docker", "run", "-d", "--name", plain, "--network", network,
"--network-alias", "plain", "--read-only", "--cap-drop", "ALL",
"--security-opt", "no-new-privileges", "--tmpfs", "/tmp:rw,noexec,nosuid,size=16m",
"-e", "PORTFOLIOHUB_DB_ENABLED=false", image], timeout=20)
plain_result = _wait(["docker", "run", "--rm", "--network", network, "--entrypoint", "python",
image, "-c", http_probe.replace("TARGET", "plain")], runner, deadline, "DB-disabled /health")
plain_payload = json.loads(plain_result.stdout)
if not isinstance(plain_payload, dict) or plain_payload.get("db_enabled") is not False:
raise RuntimeError("DB-disabled health payload has the wrong shape")
names.append(db)
runner.run(["docker", "run", "-d", "--name", db, "--network", network,
"--network-alias", "postgres", "-e", "POSTGRES_DB=smoke", "-e", "POSTGRES_USER=smoke",
"-e", "POSTGRES_PASSWORD=synthetic-db-only", "--mount", f"type=volume,src={volume},dst=/var/lib/postgresql/data",
"postgres:16-alpine"], timeout=30)
_wait(["docker", "exec", db, "pg_isready", "-U", "smoke", "-d", "smoke"], runner, deadline, "PostgreSQL")
names.append(migrate)
runner.run(["docker", "run", "--name", migrate, "--network", network, *db_env,
"--entrypoint", "pfhub", image, "migrate-db"], timeout=60)
names.append(migrate_again)
runner.run(["docker", "run", "--name", migrate_again, "--network", network, *db_env,
"--entrypoint", "pfhub", image, "migrate-db"], timeout=60)
check = "import psycopg; c=psycopg.connect(host='postgres',dbname='smoke',user='smoke',password='synthetic-db-only'); r=c.execute(\"select version_num from alembic_version\").fetchone(); assert r and r[0]; assert c.execute('select 1').fetchone()==(1,); print(r[0])"
head = _clean(runner.run(["docker", "run", "--rm", "--network", network, "--entrypoint", "python",
image, "-c", check], timeout=30)).stdout.strip()
if head != EXPECTED_ALEMBIC_HEAD:
raise RuntimeError(f"Alembic head must be {EXPECTED_ALEMBIC_HEAD}, got {head!r}")
readiness = _clean(runner.run(["docker", "run", "--rm", "--network", network, *db_env,
"--entrypoint", "pfhub", image, "--format", "json", "health-check"], timeout=30))
readiness_payload = json.loads(readiness.stdout)
if readiness_payload.get("database_revision") != EXPECTED_ALEMBIC_HEAD:
raise RuntimeError("readiness did not report the packaged Alembic head")
names.append(app)
runner.run(["docker", "run", "-d", "--name", app, "--network", network, "--network-alias", "app",
"--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--tmpfs", "/tmp:rw,noexec,nosuid,size=16m", *db_env, image], timeout=20)
app_result = _wait(["docker", "run", "--rm", "--network", network, "--entrypoint", "python",
image, "-c", http_probe.replace("TARGET", "app")], runner, deadline, "DB-enabled /health")
app_payload = json.loads(app_result.stdout)
if not isinstance(app_payload, dict) or app_payload.get("db_enabled") is not True:
raise RuntimeError("DB-enabled health payload has the wrong shape")
_clean(runner.run(["docker", "stop", "--time", "10", app], timeout=20))
exit_code = inspect_container_value(app, "{{.State.ExitCode}}", runner)
if exit_code != "0": raise RuntimeError(f"SIGTERM shutdown exit code was {exit_code!r}")
names.append(app_again)
runner.run(["docker", "run", "-d", "--name", app_again, "--network", network,
"--network-alias", "app-again", "--read-only", "--cap-drop", "ALL",
"--security-opt", "no-new-privileges", "--tmpfs", "/tmp:rw,noexec,nosuid,size=16m",
*db_env, image], timeout=20)
repeated_result = _wait(["docker", "run", "--rm", "--network", network, "--entrypoint", "python",
image, "-c", http_probe.replace("TARGET", "app-again")], runner, deadline,
"restarted DB-enabled /health and OpenAPI")
if json.loads(repeated_result.stdout).get("db_enabled") is not True:
raise RuntimeError("persistent restart health payload has the wrong shape")
user = inspect_value(image, "{{.Config.User}}", runner)
if user not in {"10001", "10001:10001"}: raise RuntimeError("image default user must be 10001")
result = {"architecture": architecture, "plain_health": "ok", "db_health": "ok",
"db_readiness": "ok", "db_ping": "ok", "alembic_head": head,
"repeated_migration": "ok", "persistent_restart": "ok", "sigterm": "graceful"}
except BaseException as error: failure = error
try: _cleanup(names, network, volume, runner, 15)
except BaseException as error:
if failure is None: failure = error
if failure:
if isinstance(failure, (KeyboardInterrupt, SystemExit)): raise failure
raise RuntimeError("isolated PortfolioHub startup smoke failed") from failure
return result
def _scan_bytes(data: bytes) -> None:
if CANARY in data: raise ValueError("canary marker found on a scanned surface")
def _scan_tar(data: bytes, nested: bool) -> None:
_scan_bytes(data)
try:
with tarfile.open(fileobj=io.BytesIO(data), mode="r:*") as archive:
for member in archive:
metadata = [member.name, member.linkname, member.uname, member.gname]
for key, value in member.pax_headers.items(): metadata.extend((key, value))
_scan_bytes("\n".join(metadata).encode(errors="replace"))
if member.isfile() and (source := archive.extractfile(member)):
payload = source.read(); _scan_bytes(payload)
if nested: _scan_tar(payload, False)
except (tarfile.TarError, OSError, EOFError): pass
def scan_image(image: str, saved_archive: Path, runner: Runner, timeout: int = 90) -> None:
for command in (["docker", "history", "--no-trunc", image], ["docker", "image", "inspect", image]):
_clean(runner.run(command, timeout=timeout))
# Docker can create the container successfully and still return output that
# fails the canary scan. Retain its identity before scanning the complete
# result so every post-create failure is cleanup-protected.
created = runner.run(["docker", "create", "--network", "none", image], timeout=timeout)
container = created.stdout.strip().splitlines()[0] if created.stdout.strip() else ""
if not container:
_clean(created)
raise RuntimeError("docker create returned no container ID")
failure: BaseException | None = None
try:
_clean(created)
with tempfile.TemporaryDirectory() as directory:
filesystem = Path(directory) / "filesystem.tar"
_clean(runner.run(["docker", "export", "--output", str(filesystem), container], timeout=timeout))
_scan_tar(filesystem.read_bytes(), False)
except BaseException as error:
failure = error
try:
_cleanup([container], None, None, runner, timeout)
except BaseException as error:
if failure is None:
failure = error
if failure:
raise failure
_scan_tar(saved_archive.read_bytes(), True)
def assert_clean_output(paths: Sequence[Path]) -> None:
for path in paths: _scan_bytes(path.read_bytes())
def _push_digest(output: str) -> str:
digests = set(DIGEST_RE.findall(output))
if len(digests) != 1: raise ValueError("registry push did not return exactly one valid digest")
return digests.pop()
def _append(path: Path | None, text: str) -> None:
if path:
with path.open("a", encoding="utf-8") as destination: destination.write(text)
def publish_image(*, archive: Path, checksum: Path, image_id: Path, local_image: str,
commit: str, event_name: str, ref: str, actor: str, token: str,
runner: Runner, output_path: Path | None = None,
summary_path: Path | None = None) -> str:
tags = release_tags(event_name, ref, commit)
archive_sha = verify_checksum(archive, checksum); expected_id = read_image_id(image_id)
loaded = _clean(runner.run(["docker", "load", "--input", str(archive)]))
if f"Loaded image: {local_image}" not in (loaded.stdout + loaded.stderr).splitlines():
raise ValueError("docker load did not report the expected local image")
actual_id = inspect_image_id(local_image, runner)
if actual_id != expected_id: raise ValueError("loaded image ID does not match tested image ID")
if inspect_revision(local_image, runner) != commit: raise ValueError("loaded image revision does not match tagged source commit")
version = validate_release_event(event_name, ref, commit)
if inspect_version(local_image, runner) != version:
raise ValueError("loaded image version label does not match release tag")
if not actor or not token: raise ValueError("registry credentials are missing")
for tag in tags: runner.run(["docker", "tag", local_image, tag])
runner.run(["docker", "login", "ghcr.io", "--username", actor, "--password-stdin"], input_text=token)
digests = []
for tag in tags:
pushed = _clean(runner.run(["docker", "push", tag])); digests.append(_push_digest(pushed.stdout + "\n" + pushed.stderr))
if len(set(digests)) != 1: raise ValueError("published selectors returned different registry digests")
digest = digests[0]; immutable = f"{IMAGE}@{digest}"
evidence = (f"image={immutable}\ndigest={digest}\nsource_commit={commit}\nimage_id={actual_id}\n"
f"archive_sha256={archive_sha}\nsource_selector={tags[0]}\nversion_selector={tags[1]}\n")
_append(output_path, evidence)
_append(summary_path, "## Published PortfolioHub image\n\n" + "".join(f"- {line}\n" for line in evidence.splitlines()))
return digest
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(); commands = parser.add_subparsers(dest="command", required=True)
event = commands.add_parser("validate-event"); event.add_argument("--event", required=True); event.add_argument("--ref", required=True); event.add_argument("--commit", required=True); event.add_argument("--project", type=Path)
checkout = commands.add_parser("validate-checkout"); checkout.add_argument("--actual", required=True); checkout.add_argument("--expected", required=True)
smoke = commands.add_parser("smoke"); smoke.add_argument("--image", required=True); smoke.add_argument("--inventory", type=Path, required=True); smoke.add_argument("--timeout", type=int, default=120)
scan = commands.add_parser("scan"); scan.add_argument("--image", required=True); scan.add_argument("--archive", type=Path, required=True)
checksum = commands.add_parser("checksum"); checksum.add_argument("--archive", type=Path, required=True); checksum.add_argument("--output", type=Path, required=True)
record = commands.add_parser("record-image-id"); record.add_argument("--image", required=True); record.add_argument("--output", type=Path, required=True)
clean = commands.add_parser("assert-clean-output"); clean.add_argument("paths", nargs="+", type=Path)
publish = commands.add_parser("publish")
for option in ("archive", "checksum", "image-id"): publish.add_argument(f"--{option}", type=Path, required=True)
for option in ("local-image", "commit", "event", "ref"): publish.add_argument(f"--{option}", required=True)
return parser
def main(argv: Sequence[str] | None = None) -> int:
args = _parser().parse_args(argv); runner = SubprocessRunner()
if args.command == "validate-event":
expected = project_release_version(args.project) if args.project else None
validate_release_event(args.event, args.ref, args.commit, expected)
elif args.command == "validate-checkout": validate_checkout_identity(args.actual, args.expected)
elif args.command == "smoke":
inventory = tuple(line for line in args.inventory.read_text().splitlines() if line)
smoke_installed_image(args.image, inventory, runner, args.timeout); startup_smoke(args.image, runner, args.timeout)
elif args.command == "scan": scan_image(args.image, args.archive, runner)
elif args.command == "checksum": write_checksum(args.archive, args.output)
elif args.command == "record-image-id": write_image_id(args.image, args.output, runner)
elif args.command == "assert-clean-output": assert_clean_output(args.paths)
elif args.command == "publish":
publish_image(archive=args.archive, checksum=args.checksum, image_id=args.image_id,
local_image=args.local_image, commit=args.commit, event_name=args.event,
ref=args.ref, actor=os.environ.get("GITHUB_ACTOR", ""),
token=os.environ.get("REGISTRY_TOKEN", ""), runner=runner,
output_path=Path(value) if (value := os.environ.get("GITHUB_OUTPUT")) else None,
summary_path=Path(value) if (value := os.environ.get("GITHUB_STEP_SUMMARY")) else None)
return 0
if __name__ == "__main__":
try: raise SystemExit(main())
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
print(f"image release failed: {error}", file=sys.stderr); raise SystemExit(1) from error
+198
View File
@@ -0,0 +1,198 @@
from __future__ import annotations
import io
import subprocess
import tarfile
from pathlib import Path
import pytest
from scripts import image_release
COMMIT = "a" * 40
IMAGE_ID = "sha256:" + "b" * 64
DIGEST = "sha256:" + "c" * 64
LOCAL = f"portfolio-hub-ci:{COMMIT}"
class RecordingRunner:
def __init__(self, fail_on=None):
self.commands = []; self.fail_on = fail_on; self.push_count = 0
def run(self, command, *, input_text=None, timeout=None):
command = list(command); self.commands.append((command, input_text, timeout))
if self.fail_on and command[:len(self.fail_on)] == list(self.fail_on):
raise subprocess.TimeoutExpired(command, timeout or 0)
if command[:2] == ["docker", "load"]: return image_release.Result(f"Loaded image: {LOCAL}\n")
if command[:3] == ["docker", "image", "inspect"] and "{{.Id}}" in command: return image_release.Result(IMAGE_ID + "\n")
if command[:3] == ["docker", "image", "inspect"] and "{{.Config.User}}" in command: return image_release.Result("10001:10001\n")
if command[:3] == ["docker", "image", "inspect"] and "{{.Architecture}}" in command: return image_release.Result("amd64\n")
if command[:3] == ["docker", "container", "inspect"] and "{{.State.ExitCode}}" in command: return image_release.Result("0\n")
if command[:3] == ["docker", "image", "inspect"] and any("org.opencontainers.image.version" in part for part in command): return image_release.Result("v1.2.3\n")
if command[:3] == ["docker", "image", "inspect"]: return image_release.Result(COMMIT + "\n")
if command[:2] == ["docker", "push"]: self.push_count += 1; return image_release.Result(f"digest: {DIGEST} size: 1\n")
if command[:2] == ["docker", "create"]: return image_release.Result("created-container\n")
if command[:3] == ["docker", "run", "--rm"] and "urllib.request" in command[-1]:
enabled = "TARGET:8000" not in command[-1] and "plain" not in command[-1]
return image_release.Result('{"status":"ok","db_enabled":' + str(enabled).lower() + '}')
if command[:3] == ["docker", "run", "--rm"] and "alembic_version" in command[-1]: return image_release.Result("20260814_0029\n")
if command[:3] == ["docker", "run", "--rm"] and "health-check" in command: return image_release.Result('{"database_revision":"20260814_0029"}\n')
return image_release.Result()
def artifacts(tmp_path: Path):
archive = tmp_path / "portfolio-hub-image.tar"; archive.write_bytes(b"tested")
checksum = tmp_path / "portfolio-hub-image.tar.sha256"; image_release.write_checksum(archive, checksum)
image_id = tmp_path / "portfolio-hub-image.id"; image_id.write_text(IMAGE_ID + "\n")
return archive, checksum, image_id
def publish(tmp_path, runner, **extra):
archive, checksum, image_id = artifacts(tmp_path)
values = dict(archive=archive, checksum=checksum, image_id=image_id, local_image=LOCAL,
commit=COMMIT, event_name="push", ref="refs/tags/v1.2.3", actor="actor",
token="synthetic", runner=runner); values.update(extra)
return image_release.publish_image(**values)
def test_strict_tag_and_only_two_non_latest_selectors():
assert image_release.release_tags("push", "refs/tags/v1.2.3", COMMIT) == (
f"{image_release.IMAGE}:{COMMIT[:12]}", f"{image_release.IMAGE}:v1.2.3")
@pytest.mark.parametrize("event,ref", [("pull_request","refs/tags/v1.2.3"),("push","refs/heads/main"),("push","refs/tags/v1.2"),("workflow_dispatch","refs/tags/v1.2.3")])
def test_non_strict_event_rejected(event, ref):
with pytest.raises(ValueError, match="strict vX.Y.Z"): image_release.release_tags(event, ref, COMMIT)
def test_checkout_identity_is_exact():
assert image_release.validate_checkout_identity(COMMIT, COMMIT) == COMMIT
with pytest.raises(ValueError): image_release.validate_checkout_identity("d"*40, COMMIT)
def test_project_version_must_match_release_tag(tmp_path):
project = tmp_path / "pyproject.toml"
project.write_text('[project]\nversion = "0.1.3"\n')
assert image_release.project_release_version(project) == "v0.1.3"
assert image_release.validate_release_event("push", "refs/tags/v0.1.3", COMMIT, "v0.1.3") == "v0.1.3"
with pytest.raises(ValueError, match="project version"):
image_release.validate_release_event("push", "refs/tags/v0.1.4", COMMIT, "v0.1.3")
def test_installed_smoke_has_import_cli_exact_inventory_and_cleanup():
inventory = tuple(
[f"202601{i:02d}_{i:04d}_migration.py" for i in range(1, 29)]
+ ["20260814_0029_strategy_catalog_v1.py"]
)
runner = RecordingRunner(); image_release.smoke_installed_image("candidate", inventory, runner, 17)
runs = [x[0] for x in runner.commands if x[0][:2] == ["docker","run"]]
assert len(runs) == 3 and all("--read-only" in x and "none" in x for x in runs)
assert "migration_inventory" in runs[-1][-1] and "20260814_0029" in runs[-1][-1]
assert len([x for x in runner.commands if x[0][:3] == ["docker","rm","--force"]]) == 3
def _assert_exact_startup_cleanup(commands: list[list[str]]) -> None:
attempted_names = {
command[command.index("--name") + 1]
for command in commands
if command[:2] == ["docker", "run"] and "--name" in command
}
removed_names = {
command[-1]
for command in commands
if command[:3] == ["docker", "rm", "--force"]
}
created_networks = {
command[-1]
for command in commands
if command[:3] == ["docker", "network", "create"]
}
removed_networks = {
command[-1]
for command in commands
if command[:3] == ["docker", "network", "rm"]
}
created_volumes = {
command[-1]
for command in commands
if command[:3] == ["docker", "volume", "create"]
}
removed_volumes = {
command[-1]
for command in commands
if command[:4] == ["docker", "volume", "rm", "--force"]
}
assert attempted_names
assert removed_names == attempted_names
assert removed_networks == created_networks
assert removed_volumes == created_volumes
def test_wrong_shaped_health_cleans_exact_attempted_resources():
class WrongShapeRunner(RecordingRunner):
def run(self, command, **kwargs):
if list(command)[:3] == ["docker", "run", "--rm"] and "urllib.request" in list(command)[-1]:
self.commands.append((list(command), kwargs.get("input_text"), kwargs.get("timeout")))
return image_release.Result("[]")
return super().run(command, **kwargs)
runner = WrongShapeRunner()
with pytest.raises(RuntimeError, match="startup smoke"):
image_release.startup_smoke("candidate", runner, 17)
commands = [x[0] for x in runner.commands]
_assert_exact_startup_cleanup(commands)
def test_timeout_cleans_exact_attempted_resources():
runner = RecordingRunner(fail_on=("docker","run","-d"))
with pytest.raises(RuntimeError): image_release.startup_smoke("candidate", runner, 17)
commands = [x[0] for x in runner.commands]
_assert_exact_startup_cleanup(commands)
def test_scan_create_canary_failure_removes_exact_created_container(tmp_path):
class CreateCanaryRunner(RecordingRunner):
def run(self, command, **kwargs):
command = list(command)
if command[:2] == ["docker", "create"]:
self.commands.append((command, kwargs.get("input_text"), kwargs.get("timeout")))
return image_release.Result(
"created-container\n",
image_release.CANARY.decode(),
)
return super().run(command, **kwargs)
archive = tmp_path / "portfolio-hub-image.tar"
archive.write_bytes(b"unused")
runner = CreateCanaryRunner()
with pytest.raises(ValueError, match="canary"):
image_release.scan_image("candidate", archive, runner, 17)
removals = [
command
for command, _input, _timeout in runner.commands
if command[:3] == ["docker", "rm", "--force"]
]
assert removals == [["docker", "rm", "--force", "created-container"]]
def test_corrupt_archive_stops_before_registry_write(tmp_path):
archive, checksum, image_id = artifacts(tmp_path); archive.write_bytes(b"corrupt"); runner = RecordingRunner()
with pytest.raises(ValueError, match="checksum mismatch"):
image_release.publish_image(archive=archive, checksum=checksum, image_id=image_id, local_image=LOCAL,
commit=COMMIT,event_name="push",ref="refs/tags/v1.2.3",actor="a",token="t",runner=runner)
assert runner.commands == []
def test_publish_loads_without_rebuild_and_records_digest(tmp_path):
runner = RecordingRunner(); output = tmp_path/"output"; assert publish(tmp_path, runner, output_path=output) == DIGEST
commands = [x[0][:2] for x in runner.commands]
assert ["docker","build"] not in commands and commands.count(["docker","push"]) == 2
assert COMMIT in output.read_text() and DIGEST in output.read_text() and ":latest" not in output.read_text()
def test_post_push_bad_digest_emits_no_success_evidence(tmp_path):
class Bad(RecordingRunner):
def run(self, command, **kwargs):
result = super().run(command, **kwargs)
return image_release.Result("pushed without digest") if list(command)[:2] == ["docker","push"] else result
output=tmp_path/"output"
with pytest.raises(ValueError, match="valid digest"): publish(tmp_path, Bad(), output_path=output)
assert not output.exists()
@pytest.mark.parametrize("kind", ["payload","symlink","pax"])
def test_canary_scan_covers_archive_payload_and_metadata(kind):
data=io.BytesIO()
with tarfile.open(fileobj=data, mode="w", format=tarfile.PAX_FORMAT) as archive:
member=tarfile.TarInfo("item")
if kind=="payload": payload=image_release.CANARY; member.size=len(payload); archive.addfile(member,io.BytesIO(payload))
elif kind=="symlink": member.type=tarfile.SYMTYPE; member.linkname=image_release.CANARY.decode(); archive.addfile(member)
else: member.pax_headers={"key":image_release.CANARY.decode()}; archive.addfile(member,io.BytesIO())
with pytest.raises(ValueError, match="canary"): image_release._scan_tar(data.getvalue(), True)
+100
View File
@@ -0,0 +1,100 @@
from __future__ import annotations
import subprocess
import zipfile
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PUBLISH = REPO / ".github/workflows/publish-image.yml"
VERIFY = REPO / ".github/workflows/verify.yml"
def test_lock_exists_and_is_fresh():
assert (REPO/"uv.lock").is_file()
subprocess.run(["uv","lock","--check"],cwd=REPO,check=True,capture_output=True,text=True)
def test_branch_verification_has_no_registry_write_authority_or_path():
text=VERIFY.read_text(); assert "branches: [main]" in text and "pull_request:" in text
for forbidden in ("packages: write","docker login","docker push","REGISTRY_TOKEN","image_release.py publish"):
assert forbidden not in text
assert "uv sync --extra dev --locked" in text and "uv run pytest -q" in text
def test_tag_publication_is_strict_single_build_handoff_without_latest():
text=PUBLISH.read_text(); verify,publish=text.split("\n publish:",1)
assert 'tags:\n - "v*.*.*"' in text and "validate-event" in text and "validate-checkout" in text
assert "ref: ${{ github.sha }}" in text and text.count("docker build ")==1
assert "docker build" not in publish and "packages: write" not in verify and "packages: write" in publish
assert "tested-image/scripts/image_release.py publish" in publish and ":latest" not in text
assert "--platform linux/amd64" in verify and '--build-arg "RELEASE_VERSION=${GITHUB_REF_NAME}"' in verify
for name in ("portfolio-hub-image.tar","portfolio-hub-image.tar.sha256","portfolio-hub-image.id","migration-inventory.txt"):
assert name in text
def test_dockerfile_python311_locked_non_root_explicit_uvicorn_and_resources():
text=(REPO/"Dockerfile").read_text()
assert text.count("FROM python:3.11-slim@sha256:")==2 and "uv sync --locked --no-dev --no-editable" in text
assert "FROM ghcr.io/astral-sh/uv:0.11.14@sha256:" in text
assert text.startswith("# syntax=docker/dockerfile:1@sha256:")
assert "USER 10001:10001" in text and 'CMD ["uvicorn", "app.main:app"' in text
assert "COPY app/ ./app/" in text and "COPY ." not in text
assert "org.opencontainers.image.source" in text and "org.opencontainers.image.revision" in text
assert "org.opencontainers.image.version" in text and "ARG RELEASE_VERSION" in text
def test_workflow_actions_are_commit_pinned_and_verify_version_is_project_derived():
for workflow in (PUBLISH, VERIFY):
for line in workflow.read_text().splitlines():
if "uses: actions/" in line:
revision = line.split("@", 1)[1].split()[0]
assert len(revision) == 40 and all(char in "0123456789abcdef" for char in revision)
verify = VERIFY.read_text()
assert "tomllib" in verify and 'RELEASE_VERSION=${RELEASE_VERSION}' in verify
assert 'RELEASE_VERSION=v0.1.3' not in verify
def test_release_version_and_migration_contract_are_v020_head_0030():
project = (REPO / "pyproject.toml").read_text()
config = (REPO / "app/core/config.py").read_text()
migrations = sorted(
path.name
for path in (REPO / "app/db/alembic/versions").glob("*.py")
if path.name != "__init__.py"
)
assert 'version = "0.2.0"' in project
assert 'app_version: str = "0.2.0"' in config
assert len(migrations) == 30
assert migrations[-1].startswith("20260820_0030")
def test_dockerignore_is_deny_by_default_required_inputs_only():
lines=(REPO/".dockerignore").read_text().splitlines(); assert lines[0]=="**"
assert [x for x in lines if x.startswith("!")] == ["!pyproject.toml","!uv.lock","!README.md","!app/","!app/**"]
def test_source_and_wheel_migration_inventory_are_exact_and_non_empty(tmp_path):
source=sorted(x.name for x in (REPO/"app/db/alembic/versions").glob("*.py") if x.name!="__init__.py")
assert source
subprocess.run(["uv","build","--wheel","--out-dir",str(tmp_path)],cwd=REPO,check=True,capture_output=True,text=True)
wheel=next(tmp_path.glob("*.whl"))
with zipfile.ZipFile(wheel) as archive:
installed=sorted(Path(x).name for x in archive.namelist() if "/db/alembic/versions/" in x and x.endswith(".py") and not x.endswith("/__init__.py"))
assert installed == source
def test_operations_separate_publication_deployment_migration_and_db_rollback():
text = (REPO / "docs/container-operations.md").read_text()
for value in (
"@sha256:<64-lowercase-hex-digest>",
"pfhub migrate-db",
"Publication is not deployment",
"Image rollback is **not** database rollback",
"read-only root filesystem",
"10001:10001",
"PortfolioHub v0.2.0 container contract",
"v0.2.0 adds migration `0030`",
"trex-web v0.2.3 displays `strategy_nick`",
):
assert value in text
for forbidden in (
"docker run -d",
"docker compose up",
"kubectl apply",
"helm install",
"systemctl restart",
):
assert forbidden not in text
+7 -7
View File
@@ -203,21 +203,21 @@ def test_same_user_can_create_two_portfolios_for_same_asset_id() -> None:
def test_migration_rev_a_file_exists() -> None:
import os
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_a_files = [f for f in os.listdir(migrations_dir) if "0017" in f and "assets" in f]
assert len(rev_a_files) == 1, f"rev-A migration (0017 assets) not found in {migrations_dir}"
def test_migration_rev_b_file_exists() -> None:
import os
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_b_files = [f for f in os.listdir(migrations_dir) if "0018" in f]
assert len(rev_b_files) == 1, f"rev-B migration (0018) not found in {migrations_dir}"
def test_migration_rev_a_creates_assets_table() -> None:
import os
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_a = next(f for f in os.listdir(migrations_dir) if "0017" in f)
content = open(os.path.join(migrations_dir, rev_a)).read()
assert "create_table" in content
@@ -230,7 +230,7 @@ def test_migration_rev_a_creates_assets_table() -> None:
def test_migration_rev_b_drops_symbol_and_market_columns() -> None:
import os
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_b = next(f for f in os.listdir(migrations_dir) if "0018" in f)
content = open(os.path.join(migrations_dir, rev_b)).read()
assert "drop_column" in content
@@ -241,7 +241,7 @@ def test_migration_rev_b_drops_symbol_and_market_columns() -> None:
def test_migration_rev_b_has_data_migration_insert() -> None:
import os
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_b = next(f for f in os.listdir(migrations_dir) if "0018" in f)
content = open(os.path.join(migrations_dir, rev_b)).read()
assert "INSERT INTO assets" in content
@@ -770,14 +770,14 @@ def test_portfolio_create_by_symbol() -> None:
def test_migration_assets_tag_ids_file_exists() -> None:
import os
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
matches = [f for f in os.listdir(migrations_dir) if "0023" in f and "assets_tag_ids" in f]
assert len(matches) == 1, f"assets_tag_ids migration (0023) not found in {migrations_dir}"
def test_migration_assets_tag_ids_adds_column_and_gin_index() -> None:
import os
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev = next(f for f in os.listdir(migrations_dir) if "0023" in f and "assets_tag_ids" in f)
content = open(os.path.join(migrations_dir, rev)).read()
# AC-1: tag_ids UUID[] NOT NULL DEFAULT '{}' on assets
@@ -3,41 +3,32 @@
from __future__ import annotations
import subprocess
import sys
# REQ-016 AC-1: 후보 소스에 issue_client_token / CreateClientTokenRequest / IssuedClientTokenResponse 잔여 없음
# REQ-016 AC-1: codebase에 issue_client_token / CreateClientTokenRequest / IssuedClientTokenResponse 잔여 없음
def test_no_issue_client_token_symbol_in_codebase() -> None:
def _source_symbol_matches(symbol: str) -> list[str]:
result = subprocess.run(
["grep", "-r", "--include=*.py", "-l", "issue_client_token"],
["grep", "-r", "--exclude-dir=temp", "--exclude-dir=.git", "--exclude-dir=.venv", "--include=*.py", "-l", symbol],
capture_output=True,
check=False,
text=True,
cwd=str(__import__("pathlib").Path(__file__).parent.parent),
)
matches = [line for line in result.stdout.splitlines() if not line.startswith("tests/test_auth_surface")]
return [line for line in result.stdout.splitlines() if not line.startswith("tests/test_auth_surface")]
def test_no_issue_client_token_symbol_in_codebase() -> None:
matches = _source_symbol_matches("issue_client_token")
assert matches == [], f"issue_client_token 잔여 참조 발견: {matches}"
def test_no_create_client_token_request_symbol_in_codebase() -> None:
result = subprocess.run(
["grep", "-r", "--include=*.py", "-l", "CreateClientTokenRequest"],
capture_output=True,
text=True,
cwd=str(__import__("pathlib").Path(__file__).parent.parent),
)
matches = [line for line in result.stdout.splitlines() if not line.startswith("tests/test_auth_surface")]
matches = _source_symbol_matches("CreateClientTokenRequest")
assert matches == [], f"CreateClientTokenRequest 잔여 참조 발견: {matches}"
def test_no_issued_client_token_response_symbol_in_codebase() -> None:
result = subprocess.run(
["grep", "-r", "--include=*.py", "-l", "IssuedClientTokenResponse"],
capture_output=True,
text=True,
cwd=str(__import__("pathlib").Path(__file__).parent.parent),
)
matches = [line for line in result.stdout.splitlines() if not line.startswith("tests/test_auth_surface")]
matches = _source_symbol_matches("IssuedClientTokenResponse")
assert matches == [], f"IssuedClientTokenResponse 잔여 참조 발견: {matches}"
+16 -1
View File
@@ -783,14 +783,29 @@ def test_cli_write_command_can_abort() -> None:
assert repo._portfolio is None
def test_cli_health_check_reports_repository() -> None:
def test_cli_health_check_reports_repository(monkeypatch) -> None:
repo = FakeRepo(_portfolio())
runner = build_runner(repo)
monkeypatch.setattr(health_commands, "current_revision", lambda _settings: "20260814_0029")
monkeypatch.setattr(health_commands, "head_revision", lambda _settings: "20260814_0029")
result = runner.invoke(runner.app, ["health-check"])
assert result.exit_code == 0
assert "repository: FakeRepo" in result.stdout
assert "database_revision: 20260814_0029" in result.stdout
def test_cli_health_check_rejects_database_behind_packaged_head(monkeypatch) -> None:
repo = FakeRepo(_portfolio())
runner = build_runner(repo)
monkeypatch.setattr(health_commands, "current_revision", lambda _settings: "20260715_0028")
monkeypatch.setattr(health_commands, "head_revision", lambda _settings: "20260814_0029")
result = runner.invoke(runner.app, ["health-check"])
assert result.exit_code == 1
assert "is not packaged head" in result.stdout
def test_cli_init_db_reports_created(monkeypatch) -> None:
+22 -3
View File
@@ -1,9 +1,12 @@
"""Repository contract tests for portfolio ledger return aggregates."""
from pathlib import Path
from unittest.mock import MagicMock, patch
from app.repositories.postgres import PostgresPortfolioRepository
_ROOT = Path(__file__).parents[1]
def _repo_with_cursor(rows: list[tuple[object, ...]]):
repo = PostgresPortfolioRepository.__new__(PostgresPortfolioRepository)
@@ -29,7 +32,7 @@ def test_get_return_summaries_empty_ids_skips_database() -> None:
repo.ensure_schema.assert_not_called()
def test_get_return_summaries_groups_portfolios_and_excludes_reversed_sources() -> None:
def test_get_return_summaries_groups_all_sources_and_excludes_reversed_entries() -> None:
repo, connection, cursor = _repo_with_cursor(
[
("p-001", 500.0, 125.0, 40.0),
@@ -60,8 +63,12 @@ def test_get_return_summaries_groups_portfolios_and_excludes_reversed_sources()
assert "group by ledger.portfolio_id" in normalized_sql
assert "not exists" in normalized_sql
assert "reversal.target_ledger_entry_id = ledger.ledger_entry_id" in normalized_sql
assert "ledger.source = 'manual'" in normalized_sql
assert "ledger.source = 'manual'" not in normalized_sql
assert "reversal.source = 'manual'" not in normalized_sql
assert "ledger.side in ('invest', 'withdraw', 'profit')" in normalized_sql
assert "sum(ledger.price) filter (where ledger.side = 'invest')" in normalized_sql
assert "sum(ledger.price) filter (where ledger.side = 'withdraw')" in normalized_sql
assert "sum(ledger.price) filter (where ledger.side = 'profit')" in normalized_sql
assert params == (["p-001", "p-002"],)
@@ -76,4 +83,16 @@ def test_get_return_summary_delegates_to_shared_batch_semantics() -> None:
repo.get_return_summaries = MagicMock(return_value={"p-001": expected})
assert repo.get_return_summary("p-001") == expected
repo.get_return_summaries.assert_called_once_with(["p-001"])
repo.get_return_summaries.assert_called_once_with(["p-001"])
def test_external_contract_documents_all_source_return_semantics() -> None:
contract = (_ROOT / "docs/interface-contract.md").read_text()
assert "source와 무관한 유효 `INVEST`의 gross 합계" in contract
assert "`net_contributed_capital` (**순투자원금**) = `total_invested - total_withdrawn`" in contract
assert "`PROFIT`는 원금 계산에서 제외" in contract
assert "original과 reversal의 source와 무관하게 제외" in contract
assert "`buffer_out` 등 `INVEST`/`WITHDRAW`/`PROFIT` 이외 side" in contract
assert "유효 manual `INVEST` 합계" not in contract
assert "유효 manual `PROFIT` 합계" not in contract
@@ -0,0 +1,95 @@
"""Real PostgreSQL semantics for all-source portfolio return aggregates.
Run with PORTFOLIOHUB_RUN_LEDGER_AGGREGATE_POSTGRES=1 against a disposable/local
PostgreSQL endpoint. Normal unit-test environments skip this module.
"""
from __future__ import annotations
import os
from unittest.mock import MagicMock
import psycopg
import pytest
from app.repositories.postgres import PostgresPortfolioRepository
pytestmark = pytest.mark.skipif(
os.getenv("PORTFOLIOHUB_RUN_LEDGER_AGGREGATE_POSTGRES") != "1",
reason="set PORTFOLIOHUB_RUN_LEDGER_AGGREGATE_POSTGRES=1 to run real PostgreSQL tests",
)
def _connect() -> psycopg.Connection:
return psycopg.connect(
host=os.getenv("TIMESCALEDB_HOST", "127.0.0.1"),
port=int(os.getenv("TIMESCALEDB_PORT", "5432")),
dbname=os.getenv("TIMESCALEDB_NAME", "portfolio_hub_migration_test"),
user=os.getenv("TIMESCALEDB_USER", "portfolio_hub_user"),
password=os.getenv("TIMESCALEDB_PASSWORD", "change-me"),
sslmode=os.getenv("TIMESCALEDB_SSLMODE", "prefer"),
)
def test_all_sources_mixed_sides_and_cross_source_reversals() -> None:
connection = _connect()
try:
with connection.cursor() as cursor:
cursor.execute(
"""
CREATE TEMP TABLE portfolio_ledger (
ledger_entry_id BIGINT PRIMARY KEY,
portfolio_id TEXT NOT NULL,
price DOUBLE PRECISION NOT NULL,
source TEXT NOT NULL,
side TEXT NOT NULL,
target_ledger_entry_id BIGINT
)
"""
)
cursor.executemany(
"""
INSERT INTO portfolio_ledger (
ledger_entry_id, portfolio_id, price, source, side, target_ledger_entry_id
) VALUES (%s, %s, %s, %s, %s, %s)
""",
[
(1, "broker-only", 700, "broker", "invest", None),
(2, "mixed", 1000, "manual", "invest", None),
(3, "mixed", 500, "broker", "invest", None),
(4, "mixed", 200, "broker", "withdraw", None),
(5, "mixed", 50, "manual", "profit", None),
# A manual reversal excludes a broker original.
(6, "mixed", 300, "broker", "invest", None),
(7, "mixed", 300, "manual", "reversal", 6),
# A broker reversal excludes a manual original.
(8, "mixed", 100, "manual", "withdraw", None),
(9, "mixed", 100, "broker", "reversal", 8),
# Non-capital sides are never inferred as INVEST.
(10, "mixed", 800_000, "broker", "buffer_out", None),
],
)
repo = PostgresPortfolioRepository.__new__(PostgresPortfolioRepository)
repo.ensure_schema = MagicMock()
repo._connect = MagicMock(return_value=connection)
summaries = repo.get_return_summaries(["broker-only", "mixed"])
assert summaries == {
"broker-only": {
"total_invested": 700.0,
"total_withdrawn": 0.0,
"net_contributed_capital": 700.0,
"cumulative_profit_withdrawn": 0.0,
},
"mixed": {
"total_invested": 1500.0,
"total_withdrawn": 200.0,
"net_contributed_capital": 1300.0,
"cumulative_profit_withdrawn": 50.0,
},
}
repo.ensure_schema.assert_called_once_with()
finally:
connection.close()
+2 -2
View File
@@ -440,8 +440,8 @@ def test_create_without_user_fails() -> None:
["portfolio", "create", "MY_PORT", "--asset-id", _TEST_ASSET_ID, "--strategy-id", "set-1", "--force"],
)
assert result.exit_code != 0
assert "--user" in result.output
assert result.exit_code == 2
assert repo._portfolios == []
def test_create_with_unknown_user_fails() -> None:
+1 -1
View File
@@ -10,7 +10,7 @@ from unittest.mock import patch
_MIGRATION_PATH = (
Path(__file__).parents[1]
/ "migrations/versions/20260814_0029_strategy_catalog_v1.py"
/ "app/db/alembic/versions/20260814_0029_strategy_catalog_v1.py"
)
@@ -6,7 +6,6 @@ PostgreSQL endpoint. Normal unit-test environments skip this module.
from __future__ import annotations
import hashlib
import os
import subprocess
import threading
@@ -73,9 +72,12 @@ def _prepare_catalog_fixture(repo: PostgresPortfolioRepository) -> tuple[str, st
return strategy.id, asset_id, owner_user_id
def test_concurrent_strategy_patch_keeps_derived_nick_consistent() -> None:
def test_concurrent_strategy_patch_preserves_existing_nick() -> None:
owner = _repo()
strategy_id, asset_id, owner_user_id = _prepare_catalog_fixture(owner)
initial = owner.get_strategy_set(strategy_id)
assert initial is not None
initial_nick = initial.nick
renamed = f"concurrent-renamed-{uuid.uuid4().hex}"
barrier = threading.Barrier(3)
errors: list[BaseException] = []
@@ -114,8 +116,7 @@ def test_concurrent_strategy_patch_keeps_derived_nick_consistent() -> None:
assert final.name == renamed
assert final.config == '{"window":21}'
assert final.revision == 3
expected_nick = f"{final.name}:{hashlib.sha1(final.config.encode()).hexdigest()[:12]}"
assert final.nick == expected_nick
assert final.nick == initial_nick
portfolio_id = str(uuid.uuid4())
owner.create_portfolio(
portfolio_id,
@@ -288,7 +289,7 @@ def test_alembic_upgrade_is_repeatable_on_fresh_postgres_database() -> None:
)
for _ in range(2):
subprocess.run(
[str(_ROOT / ".venv/bin/python"), "-m", "alembic", "upgrade", "head"],
[str(_ROOT / ".venv/bin/pfhub"), "migrate-db"],
cwd=_ROOT,
env=env,
check=True,
+6 -6
View File
@@ -486,7 +486,7 @@ def test_migration_ac3_portfolio_tag_ids_populated() -> None:
def test_migration_ac4_portfolio_tags_dropped() -> None:
"""REQ-006 AC-4: 마이그레이션 후 portfolio_tags 테이블이 존재하지 않는다 (migration script 검증)."""
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_file = next(f for f in os.listdir(migrations_dir) if "0021" in f)
content = open(os.path.join(migrations_dir, rev_file)).read()
assert "DROP TABLE" in content
@@ -514,14 +514,14 @@ def test_migration_ac6_distinct_tag_count_matches() -> None:
def test_migration_0019_tags_table_exists() -> None:
"""REQ-001 AC-1: tags 테이블 생성 마이그레이션 파일이 존재한다."""
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
files = [f for f in os.listdir(migrations_dir) if "0019" in f]
assert len(files) == 1
def test_migration_0019_creates_tags_table() -> None:
"""REQ-001 AC-1: revision 0019가 tags 테이블을 생성한다."""
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_file = next(f for f in os.listdir(migrations_dir) if "0019" in f)
content = open(os.path.join(migrations_dir, rev_file)).read()
assert '"tags"' in content
@@ -534,7 +534,7 @@ def test_migration_0019_creates_tags_table() -> None:
def test_migration_0020_portfolios_tag_ids_column() -> None:
"""REQ-002/003 AC-1: revision 0020이 portfolios.tag_ids 컬럼과 GIN 인덱스를 추가한다."""
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_file = next(f for f in os.listdir(migrations_dir) if "0020" in f)
content = open(os.path.join(migrations_dir, rev_file)).read()
assert "tag_ids" in content
@@ -544,14 +544,14 @@ def test_migration_0020_portfolios_tag_ids_column() -> None:
def test_migration_0021_data_migration_exists() -> None:
"""REQ-006: revision 0021 데이터 마이그레이션 파일이 존재한다."""
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
files = [f for f in os.listdir(migrations_dir) if "0021" in f]
assert len(files) == 1
def test_migration_0021_has_admin_verification() -> None:
"""REQ-006 AC-5: revision 0021이 admin ID 존재 검증 로직을 포함한다."""
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations", "versions")
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "app", "db", "alembic", "versions")
rev_file = next(f for f in os.listdir(migrations_dir) if "0021" in f)
content = open(os.path.join(migrations_dir, rev_file)).read()
assert "admin_user_id" in content
+80
View File
@@ -158,6 +158,27 @@ class _FakeRepo:
self.get(portfolio_id)
return list(reversed(self.entries))[:limit]
def list_ledger_entries(
self,
portfolio_id: str,
*,
source: str | None = None,
before_recorded_at: datetime | None = None,
before_ledger_entry_id: int | None = None,
limit: int = 50,
) -> list[LedgerEntry]:
self.get(portfolio_id)
entries = sorted(self.entries, key=lambda entry: (entry.recorded_at, entry.ledger_entry_id), reverse=True)
if source is not None:
entries = [entry for entry in entries if entry.source == source]
if before_recorded_at is not None and before_ledger_entry_id is not None:
entries = [
entry
for entry in entries
if (entry.recorded_at, entry.ledger_entry_id) < (before_recorded_at, before_ledger_entry_id)
]
return entries[:limit]
def get_return_summary(self, portfolio_id: str) -> dict[str, float]:
self.get(portfolio_id)
reversed_ids = {
@@ -399,3 +420,62 @@ def test_reversal_rejects_fee_tax_and_missing_target() -> None:
)
assert missing_target.status_code == 404
assert missing_target.json()["detail"]["code"] == "LEDGER_ENTRY_NOT_FOUND"
def test_unified_ledger_paginates_mixed_sources_and_hides_side() -> None:
repo = _FakeRepo()
client = _make_client(repo)
manual = client.post(
f"/v1/portfolios/{_PORTFOLIO_ID}/ledger/manual", json={"action": "INVEST", "amount": 100}, headers=_auth()
)
assert manual.status_code == 201
repo.entries.append(
LedgerEntry(
ledger_entry_id=99, portfolio_id=_PORTFOLIO_ID, side="buy", quantity=2, price=10, source="broker",
recorded_at=datetime.now(timezone.utc), cash_balance_after=900, asset_quantity_after=12,
)
)
first = client.get(f"/v1/portfolios/{_PORTFOLIO_ID}/ledger?limit=1", headers=_auth())
assert first.status_code == 200
first_item = first.json()["items"][0]
assert first_item["source"] == "broker"
assert first_item["action"] == "BUY"
assert "side" not in first_item
assert first.json()["next_cursor"]
second = client.get(
f"/v1/portfolios/{_PORTFOLIO_ID}/ledger?limit=1&cursor={first.json()['next_cursor']}", headers=_auth()
)
assert second.status_code == 200
assert second.json()["items"][0]["ledger_entry_id"] == manual.json()["ledger_entry_id"]
assert second.json()["next_cursor"] is None
def test_unified_ledger_rejects_tampered_or_different_source_cursor() -> None:
repo = _FakeRepo()
client = _make_client(repo)
for amount in (100, 200):
assert client.post(
f"/v1/portfolios/{_PORTFOLIO_ID}/ledger/manual", json={"action": "INVEST", "amount": amount}, headers=_auth()
).status_code == 201
cursor = client.get(f"/v1/portfolios/{_PORTFOLIO_ID}/ledger?limit=1", headers=_auth()).json()["next_cursor"]
assert client.get(f"/v1/portfolios/{_PORTFOLIO_ID}/ledger?limit=1&cursor={cursor[:-1]}x", headers=_auth()).status_code == 422
assert client.get(
f"/v1/portfolios/{_PORTFOLIO_ID}/ledger?limit=1&source=manual&cursor={cursor}", headers=_auth()
).status_code == 422
def test_unified_ledger_source_filter_unknown_value_is_empty_and_owner_scoped() -> None:
repo = _FakeRepo()
client = _make_client(repo)
assert client.post(
f"/v1/portfolios/{_PORTFOLIO_ID}/ledger/manual", json={"action": "INVEST", "amount": 100}, headers=_auth()
).status_code == 201
filtered = client.get(f"/v1/portfolios/{_PORTFOLIO_ID}/ledger?source=unknown-producer", headers=_auth())
assert filtered.status_code == 200
assert filtered.json() == {"items": [], "next_cursor": None}
foreign_client = _make_client(_FakeRepo(_portfolio(owner=_OTHER_USER_ID)))
assert foreign_client.get(f"/v1/portfolios/{_PORTFOLIO_ID}/ledger", headers=_auth()).status_code == 403
service_client = _make_client(_FakeRepo(principal=_token_principal(token_type="service")))
assert service_client.get(f"/v1/portfolios/{_PORTFOLIO_ID}/ledger", headers=_auth()).status_code == 403
+128 -9
View File
@@ -43,19 +43,29 @@ class FakeStrategyRepo:
def get_or_create_strategy_set(self, name: str, config: str) -> StrategySet:
return self.create_strategy_set(name, config)
def create_strategy_set(self, name: str, config: str, *, status: str = "active") -> StrategySet:
def create_strategy_set(
self,
name: str,
config: str,
*,
nick: str | None = None,
status: str = "active",
) -> StrategySet:
existing = next(
(item for item in self.strategies.values() if item.name == name and item.config == config),
None,
)
if existing is not None:
return existing
final_nick = nick or f"{name}:{hashlib.sha1(config.encode()).hexdigest()[:12]}"
if any(item.nick == final_nick for item in self.strategies.values()):
raise ValueError("동일한 nick 전략이 이미 존재합니다")
now = datetime.now(timezone.utc)
item = StrategySet(
id=f"created-{len(self.strategies)}",
name=name,
config=config,
nick=f"{name}:{hashlib.sha1(config.encode()).hexdigest()[:12]}",
nick=final_nick,
status=status,
created_at=now,
updated_at=now,
@@ -68,6 +78,7 @@ class FakeStrategyRepo:
id: str,
*,
name: str | None = None,
nick: str | None = None,
config: str | None = None,
status: str | None = None,
) -> StrategySet:
@@ -75,19 +86,27 @@ class FakeStrategyRepo:
if item is None:
raise ValueError("전략을 찾을 수 없습니다")
final_name = name if name is not None else item.name
final_nick = nick if nick is not None else item.nick
final_config = config if config is not None else item.config
if any(
other.id != id and other.name == final_name and other.config == final_config
for other in self.strategies.values()
):
raise ValueError("동일한 name/config 전략이 이미 존재합니다")
if any(other.id != id and other.nick == final_nick for other in self.strategies.values()):
raise ValueError("동일한 nick 전략이 이미 존재합니다")
final_status = status if status is not None else item.status
if (final_name, final_config, final_status) == (item.name, item.config, item.status):
if (final_name, final_nick, final_config, final_status) == (
item.name,
item.nick,
item.config,
item.status,
):
return item
item.name = final_name
item.nick = final_nick
item.config = final_config
item.status = final_status
item.nick = f"{final_name}:{hashlib.sha1(final_config.encode()).hexdigest()[:12]}"
item.revision += 1
item.updated_at = datetime.now(timezone.utc)
return item
@@ -126,9 +145,13 @@ def test_public_catalog_excludes_inactive_and_inactive_lookup_conflicts() -> Non
repo = FakeStrategyRepo()
with _repos(repo):
response = _client().get("/v1/strategies", headers=_auth("read-token"))
active = _client().get("/v1/strategies/active-1", headers=_auth("read-token"))
inactive = _client().get("/v1/strategies/inactive-1", headers=_auth("read-token"))
assert response.status_code == 200
assert [item["strategy_id"] for item in response.json()] == ["active-1"]
assert response.json()[0]["nick"] == "target_value:base"
assert active.status_code == 200
assert active.json()["nick"] == "target_value:base"
assert inactive.status_code == 409
@@ -141,32 +164,128 @@ def test_admin_catalog_requires_admin_and_reports_missing_strategy() -> None:
assert missing.status_code == 404
def test_admin_create_and_patch_preserve_id_and_revision_semantics() -> None:
def test_admin_create_custom_nick_and_patch_nick_only_preserve_id_and_increment_revision() -> None:
repo = FakeStrategyRepo()
with _repos(repo):
created = _client().post(
"/v1/admin/strategies",
json={"name": "momentum", "config": {"window": 20}},
json={"name": "momentum", "nick": "mom-20", "config": {"window": 20}},
headers=_auth("admin-token"),
)
strategy_id = created.json()["strategy_id"]
changed = _client().patch(
f"/v1/admin/strategies/{strategy_id}",
json={"name": "momentum-v2"},
json={"nick": "mom-primary"},
headers=_auth("admin-token"),
)
no_op = _client().patch(
f"/v1/admin/strategies/{strategy_id}",
json={"name": "momentum-v2"},
json={"nick": "mom-primary"},
headers=_auth("admin-token"),
)
assert created.status_code == 201
assert created.json()["nick"] == "mom-20"
assert created.json()["revision"] == 1
assert changed.status_code == 200
assert changed.json()["strategy_id"] == strategy_id
assert changed.json()["nick"] == "mom-primary"
assert changed.json()["revision"] == 2
assert no_op.json()["revision"] == 2
assert repo.strategies[strategy_id].nick.startswith("momentum-v2:")
assert repo.strategies[strategy_id].nick == "mom-primary"
def test_admin_create_trims_nick() -> None:
repo = FakeStrategyRepo()
with _repos(repo):
created = _client().post(
"/v1/admin/strategies",
json={"name": "momentum", "nick": " mom-20 ", "config": {"window": 20}},
headers=_auth("admin-token"),
)
assert created.status_code == 201
assert created.json()["nick"] == "mom-20"
def test_admin_create_and_patch_reject_whitespace_only_nick() -> None:
repo = FakeStrategyRepo()
with _repos(repo):
created = _client().post(
"/v1/admin/strategies",
json={"name": "momentum", "nick": " \t ", "config": {"window": 20}},
headers=_auth("admin-token"),
)
changed = _client().patch(
"/v1/admin/strategies/active-1",
json={"nick": " \n "},
headers=_auth("admin-token"),
)
assert created.status_code == 422
assert changed.status_code == 422
assert repo.strategies["active-1"].nick == "target_value:base"
def test_admin_patch_omitting_nick_preserves_custom_nick_when_name_and_config_change() -> None:
repo = FakeStrategyRepo()
with _repos(repo):
created = _client().post(
"/v1/admin/strategies",
json={"name": "momentum", "nick": "mom-custom", "config": {"window": 20}},
headers=_auth("admin-token"),
)
strategy_id = created.json()["strategy_id"]
changed = _client().patch(
f"/v1/admin/strategies/{strategy_id}",
json={"name": "momentum-v2", "config": {"window": 30}},
headers=_auth("admin-token"),
)
assert changed.status_code == 200
assert changed.json()["nick"] == "mom-custom"
assert changed.json()["revision"] == 2
def test_admin_create_omitting_nick_retains_legacy_generated_value() -> None:
repo = FakeStrategyRepo()
with _repos(repo):
created = _client().post(
"/v1/admin/strategies",
json={"name": "legacy", "config": {"window": 20}},
headers=_auth("admin-token"),
)
canonical_config = '{"window":20}'
expected = f"legacy:{hashlib.sha1(canonical_config.encode()).hexdigest()[:12]}"
assert created.status_code == 201
assert created.json()["nick"] == expected
def test_admin_create_and_patch_reject_explicit_null_nick_without_mutation() -> None:
repo = FakeStrategyRepo()
with _repos(repo):
created = _client().post(
"/v1/admin/strategies",
json={"name": "legacy-null", "nick": None, "config": {}},
headers=_auth("admin-token"),
)
changed = _client().patch(
"/v1/admin/strategies/active-1",
json={"nick": None},
headers=_auth("admin-token"),
)
assert created.status_code == 422
assert changed.status_code == 422
assert set(repo.strategies) == {"active-1", "inactive-1"}
assert repo.strategies["active-1"].nick == "target_value:base"
assert repo.strategies["active-1"].revision == 1
def test_admin_duplicate_nick_returns_conflict() -> None:
repo = FakeStrategyRepo()
with _repos(repo):
duplicate = _client().post(
"/v1/admin/strategies",
json={"name": "duplicate", "nick": "target_value:base", "config": {}},
headers=_auth("admin-token"),
)
assert duplicate.status_code == 409
def test_admin_create_inactive_starts_at_revision_one() -> None:
Generated
+28 -1
View File
@@ -592,7 +592,7 @@ wheels = [
[[package]]
name = "portfoliohub"
version = "0.1.0"
version = "0.2.0"
source = { editable = "." }
dependencies = [
{ name = "alembic" },
@@ -611,6 +611,7 @@ dev = [
{ name = "httpx" },
{ name = "pre-commit" },
{ name = "pytest" },
{ name = "ruff" },
]
[package.metadata]
@@ -625,6 +626,7 @@ requires-dist = [
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.3.0,<9.0.0" },
{ name = "python-dotenv", specifier = ">=1.0.0,<2.0.0" },
{ name = "rich", specifier = ">=13.9.0,<14.0.0" },
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.12.0,<1.0.0" },
{ name = "typer", specifier = ">=0.12.5,<1.0.0" },
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0,<1.0.0" },
]
@@ -970,6 +972,31 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/19/71/39c7c0d87f8d4e6c020a393182060eaefeeae6c01dab6a84ec346f2567df/rich-13.9.4-py3-none-any.whl", hash = "sha256:6049d5e6ec054bf2779ab3358186963bac2ea89175919d699e378b99738c2a90", size = 242424, upload-time = "2024-11-01T16:43:55.817Z" },
]
[[package]]
name = "ruff"
version = "0.16.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/61/b3/3213589383f8f1b3938781bd1278713f6d18621a14992b3e81fefb8a5ef9/ruff-0.16.3.tar.gz", hash = "sha256:e76d33a347661a84b5be6d043d0347fdc745dfdcf825a8f4fed64b5e26eebdf2", size = 4891904, upload-time = "2026-08-13T15:17:13.381Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/bf/96/493770daebd68c0a67f1549fdf519f53be51fc435186c0585bcc272fd76c/ruff-0.16.3-py3-none-linux_armv6l.whl", hash = "sha256:0c5710e247a58a4521e66e124ba9a74655b414f61ba3a2e9e3811e11098f48f7", size = 10902799, upload-time = "2026-08-13T15:16:27.382Z" },
{ url = "https://files.pythonhosted.org/packages/5e/e6/2becf3942fddc29a29b8df47691d456fb1085391a694f74d84513251418c/ruff-0.16.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:fe155130631a2471fd2e14a7a664a4dfbd7194b8229c3d7b2a40b21178639081", size = 11135539, upload-time = "2026-08-13T15:16:30.87Z" },
{ url = "https://files.pythonhosted.org/packages/3e/1e/4b8b72f0d006dbf19326aa99f9ca0ee2ff374187c4d301cf529a51aa06fe/ruff-0.16.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e2ed719e14aa64d895c2ee922594a90a43c861a93f0575a95ff8c47cdbd13eb9", size = 10475095, upload-time = "2026-08-13T15:16:33.259Z" },
{ url = "https://files.pythonhosted.org/packages/92/32/2201fa49ba1f6c101ee321e83f051ac7a4b8d07b0ef6b4d3f2772b302275/ruff-0.16.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9e0b1da805eb043654645d74d5de1e5ce2edc686e40790d2b86f56d71cc06a84", size = 10668771, upload-time = "2026-08-13T15:16:35.65Z" },
{ url = "https://files.pythonhosted.org/packages/c3/66/4afc5c8363bd04d45effce1b7c8713ca037d7a6740b7451a2403a6e3a972/ruff-0.16.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a37bdea0bbe21780f590bf437d6412c8c4e1b6cd010f91a65c2c40c5e5f5f870", size = 10699568, upload-time = "2026-08-13T15:16:38.195Z" },
{ url = "https://files.pythonhosted.org/packages/53/fd/c67d246bf36bf1698551c56de39e95cd07f70e64433e0098e6267d77061b/ruff-0.16.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:09571e6d1288ed9be475207a3ac04ada404f1cd898104be0f6ab8d7df438575b", size = 11499365, upload-time = "2026-08-13T15:16:40.623Z" },
{ url = "https://files.pythonhosted.org/packages/67/0b/00ecbceb99a263af7b12f6f05ac3c92bc47b905e91adc3f207a836e3bc01/ruff-0.16.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2c18c5a101eb540010638cc1ff3c84944d3adb3df62b8d98ca8f22ba484d3413", size = 12311728, upload-time = "2026-08-13T15:16:43.564Z" },
{ url = "https://files.pythonhosted.org/packages/54/b2/b7b3bb54f4d3f7db504e476ad4ab8de530dceebe2c061384b2757ee419e8/ruff-0.16.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8457c44f15033c85ddbb77b15d451df9e24e4bd03b628396dd3610cedc3b8f82", size = 11699896, upload-time = "2026-08-13T15:16:46.209Z" },
{ url = "https://files.pythonhosted.org/packages/c7/30/4c468429ac195addc5ee1b717b6ab1b66632786737ca3b2ed3443fb0c26a/ruff-0.16.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:294b95c4ae0cda9388525c2047778aa758d6b8d4bb876fd4e9eaa3ebc92343eb", size = 11058736, upload-time = "2026-08-13T15:16:48.823Z" },
{ url = "https://files.pythonhosted.org/packages/43/67/7a113cdaddf24b64d7f75b1242a99d04c82fcef4f6921fdbb832beaffb5f/ruff-0.16.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:3d0c7c40c87c2a820509c31ba007968da6e1306468c067b2d82fbfdbcd0e8474", size = 11586911, upload-time = "2026-08-13T15:16:51.913Z" },
{ url = "https://files.pythonhosted.org/packages/f1/c1/2e66f24c0f3ead25a5e660111778685e505e5da353c82802bf49f0cbe7b9/ruff-0.16.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:9f738c0fdfa8eed0b2ce7fb27ee7258208a92a68d7949e62aa15164bc7b389da", size = 10954265, upload-time = "2026-08-13T15:16:54.763Z" },
{ url = "https://files.pythonhosted.org/packages/c2/ba/4cee23bf52cba9a058d3726de623624daf50ef9638868edd86f4126157f6/ruff-0.16.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:fb785f0be25abe69d320415cd4f833b59e17ba7613d9ba6a958023b6bceb0a50", size = 10709886, upload-time = "2026-08-13T15:16:57.339Z" },
{ url = "https://files.pythonhosted.org/packages/82/df/7da7194fa5d9dc0a285f7e6fa5a4722e7c63faac0b45b614ded9314363a1/ruff-0.16.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:c5536e3acfbf9563085aa2be7b13c629c3077e902afc5b941ac44024dbb9f506", size = 11210392, upload-time = "2026-08-13T15:17:00.171Z" },
{ url = "https://files.pythonhosted.org/packages/35/85/7795f6e817af050e7517bf3e7aa9b061cce70ef33d280aad902c956c1ecf/ruff-0.16.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a2d85c02f9b8e165d85e6779184d38c4132de12603dab59c51c28e22584f9e4d", size = 11626910, upload-time = "2026-08-13T15:17:03.299Z" },
{ url = "https://files.pythonhosted.org/packages/78/9b/475b927cf27a5cbbda3c7bafb69ed6ff77e1d7923d5d85f17c2749d7ae32/ruff-0.16.3-py3-none-win32.whl", hash = "sha256:388cdf2166642bd9b13d52b5932d3170f34f8abed7e8d9a855f1d84b83645a0a", size = 10931415, upload-time = "2026-08-13T15:17:05.726Z" },
{ url = "https://files.pythonhosted.org/packages/b2/99/e2a2bfc4fbf0a1e8a916bc9ebe6fe6c58cc34c28e0ffc6ce281d572d1c2e/ruff-0.16.3-py3-none-win_amd64.whl", hash = "sha256:e80a7d69ca2a6d1c4d352ec91458cdca6e56c83cdbcabd93e4abe1e53591d948", size = 11445993, upload-time = "2026-08-13T15:17:08.353Z" },
{ url = "https://files.pythonhosted.org/packages/69/3e/4132e539aed78c148854d4997a2685b0ed4dc4e87110b59ce528564e184e/ruff-0.16.3-py3-none-win_arm64.whl", hash = "sha256:b8ca152da82c1acc1fa8d5874b15951935f0eef46f10e6954c83859011b6178a", size = 11399302, upload-time = "2026-08-13T15:17:10.908Z" },
]
[[package]]
name = "shellingham"
version = "1.5.4"