feat: implement portfolio UUID migration and v1 API finalization (BAT-006, BAT-001 re-verified)
Core Changes: - Migrate portfolio_id from string to UUID in schema and repository layer - Update portfolio CLI commands to use name+user combination for identification - Update HTTP API to accept portfolio_id as UUID path parameter - Implement portfolio ownership validation in repository queries Requirements Completed (REQ-016 to REQ-019): - REQ-016: portfolios table UUID schema migration with data migration script - REQ-017: CLI portfolio commands with name+user identification - REQ-018: HTTP API portfolio path parameters and v1 asset_id UUID returns - REQ-019: Portfolio UUID baseline documentation updates BAT-001 Re-verification: - REQ-004~010 marked as Implemented after verification evidence validation - All v1 API endpoints verified with comprehensive test coverage Documentation Updates: - Update data-model.md with portfolio UUID structure - Update interface-contract.md with UUID path parameters - Update runtime-flows.md with ownership-based resolution flows - Update project-structure.md with database layer changes - Add migration script for portfolio UUID transition Testing: - Add test_portfolio_uuid.py for migration validation - Update test_cli.py and test_portfolio_ownership.py for ownership checks
This commit is contained in:
+101
-5
@@ -4,8 +4,8 @@
|
||||
- Baseline Seed: .stagepilot/bootstrap/baseline.yaml
|
||||
- Status: confirmed
|
||||
- Owner: repository-maintainers
|
||||
- Last Updated (KST): 2026-04-30 22:13
|
||||
- Source Discovery / Batch: bootstrap-baseline
|
||||
- Last Updated (KST): 2026-05-11 00:00
|
||||
- Source Discovery / Batch: bootstrap-baseline, bat-001, bat-006, bat-008
|
||||
|
||||
## Project Summary
|
||||
- PortfolioHub exposes portfolio management and trading ledger workflows through a FastAPI service and a companion CLI.
|
||||
@@ -29,6 +29,9 @@
|
||||
|
||||
- Portfolio :: owned investment portfolio with balances, strategy references, tags, comments, and ledger history
|
||||
- User :: authenticated principal that owns portfolios and receives client or service tokens
|
||||
- AuthToken :: issued client or service token with permission and optional runtime_id
|
||||
- BrokerCredential :: encrypted broker API credentials per user-broker pair
|
||||
- LedgerTrade :: idempotent trade execution record keyed by (asset_id, order_id, execution_id)
|
||||
|
||||
## Entity: `Portfolio`
|
||||
|
||||
@@ -38,22 +41,29 @@
|
||||
|
||||
### Key Fields
|
||||
|
||||
- portfolio_id :: text :: stable portfolio primary key
|
||||
- portfolio_id :: uuid :: server-generated UUID primary key; assigned at creation and never changed; BAT-006 migrated all pre-existing TEXT portfolio_id values to UUIDs
|
||||
- name :: text :: human-readable portfolio name; unique per owner_user_id; validated against [a-zA-Z0-9._:-]{1,100}
|
||||
- symbol :: text :: traded asset symbol for the portfolio
|
||||
- market :: text|null :: market identifier for the asset (e.g., exchange code); added by migration 20260502_0014
|
||||
- owner_user_id :: text|null :: owning user reference for attribution and authorization
|
||||
- active_strategy_id :: text|null :: currently selected strategy-set reference
|
||||
- cash_balance :: double precision :: current cash snapshot after the latest ledger event
|
||||
- asset_quantity :: double precision :: current holdings snapshot after the latest ledger event
|
||||
|
||||
### Uniqueness Constraints
|
||||
|
||||
- uq_portfolios_owner_name :: UNIQUE (owner_user_id, name) :: enforces per-user portfolio name uniqueness at the DB level
|
||||
|
||||
### Relationships
|
||||
|
||||
- User :: owner_user_id links a portfolio to its owning user when ownership is assigned
|
||||
- StrategySet :: active_strategy_id and avabile_strategies connect reusable strategy definitions
|
||||
- LedgerEntry, PortfolioComment, PortfolioTag :: child records are keyed by portfolio_id
|
||||
- LedgerEntry, PortfolioComment, PortfolioTag :: child records are keyed by portfolio_id (UUID)
|
||||
|
||||
### State Rules
|
||||
|
||||
- Portfolio names are required and are backfilled from symbol when older rows are migrated.
|
||||
- Portfolio names are required, must be unique per owner_user_id, and are validated at the schema layer before persistence.
|
||||
- portfolio_id is server-generated at creation; clients must never supply or assume a specific portfolio_id value.
|
||||
- Balance-changing commands must update snapshot fields and append a ledger row together.
|
||||
- Tags are unique per portfolio and comments are retrieved in created_at descending order.
|
||||
|
||||
@@ -84,11 +94,95 @@
|
||||
- Bootstrap admin creation only runs when the users table is empty and DB mode is enabled.
|
||||
- Permission changes affect both API guards and CLI mutation capabilities.
|
||||
|
||||
## Entity: `AuthToken`
|
||||
|
||||
- Purpose: represent an issued client or service token linked to a user with permission and optional runtime identifier
|
||||
- Source of Truth: auth_tokens table
|
||||
- Lifecycle: issued -> optionally rotated -> revoked or expired
|
||||
|
||||
### Key Fields
|
||||
|
||||
- id :: text :: primary key; raw token value (stored hashed in practice)
|
||||
- user_id :: text :: owning user reference
|
||||
- token_type :: text :: "client" or "service"
|
||||
- token_source :: text :: "db" for persisted tokens; "env" for environment-injected tokens
|
||||
- permission :: text :: read, trade-write, or admin
|
||||
- service_name :: text|null :: logical name for service tokens (unique within token_type="service")
|
||||
- runtime_id :: text|null :: opaque runtime identifier assigned at service-token issuance; unique (partial index on non-NULL values); added by migration 20260502_0014
|
||||
- expires_at :: timestamptz|null :: token expiry; null for non-expiring tokens
|
||||
- created_at :: timestamptz :: issuance timestamp
|
||||
|
||||
### Uniqueness Constraints
|
||||
|
||||
- idx_auth_tokens_service_name_unique :: UNIQUE (service_name) WHERE token_type='service'
|
||||
- idx_auth_tokens_runtime_id_unique :: UNIQUE (runtime_id) WHERE runtime_id IS NOT NULL
|
||||
|
||||
### State Rules
|
||||
|
||||
- Service tokens with runtime_id are the only tokens accepted by v1 API endpoints; GET /v1/user_info returns HTTP 404 if runtime_id is None.
|
||||
- Token permission gates both HTTP API guards and CLI mutation capabilities.
|
||||
|
||||
## Entity: `BrokerCredential`
|
||||
|
||||
- Purpose: store Fernet-encrypted broker API credentials per user-broker pair for the trex-basic integration
|
||||
- Source of Truth: broker_credentials table (added by migration 20260502_0014)
|
||||
- Lifecycle: upserted via CLI credential command -> optionally rotated
|
||||
|
||||
### Key Fields
|
||||
|
||||
- user_id :: text :: owning user reference (part of composite PK)
|
||||
- broker :: text :: broker identifier, e.g., "KIS" (part of composite PK)
|
||||
- account_ref :: text :: broker account reference or alias
|
||||
- encrypted_payload :: text :: Fernet-encrypted JSON ciphertext; plaintext is `{"app_key": ..., "app_secret": ...}`; decrypted at query time using CREDENTIAL_ENCRYPTION_KEY (REQ-010)
|
||||
- credential_version :: integer :: monotonically increasing rotation counter; server_default=1
|
||||
- last_rotated_at :: timestamptz :: last credential upsert or rotation timestamp; server_default=NOW()
|
||||
|
||||
### Uniqueness Constraints
|
||||
|
||||
- PRIMARY KEY (user_id, broker) :: one credential entry per user per broker
|
||||
|
||||
### State Rules
|
||||
|
||||
- encrypted_payload must never contain plaintext credentials; Fernet encryption is mandatory before persistence.
|
||||
- Decryption failures (wrong key, corrupted payload) log a warning and return `credential_payload: null` in GET /v1/user_info.
|
||||
|
||||
## Entity: `LedgerTrade`
|
||||
|
||||
- Purpose: record idempotent trade execution entries submitted by trex-basic via POST /v1/assets/{asset_id}/ledger/trades
|
||||
- Source of Truth: ledger_trades table (added by migration 20260502_0014)
|
||||
- Lifecycle: inserted once per unique (asset_id, order_id, execution_id) tuple; never updated or deleted
|
||||
|
||||
### Key Fields
|
||||
|
||||
- ledger_entry_id :: bigint (Identity) :: auto-generated sequential primary key
|
||||
- asset_id :: text :: portfolio_id (UUID-format text after BAT-006) referencing the trading portfolio
|
||||
- order_id :: text :: broker-assigned order identifier
|
||||
- execution_id :: text :: broker-assigned execution/fill identifier
|
||||
- side :: text :: "buy" or "sell"
|
||||
- quantity :: numeric(20,8) :: executed quantity
|
||||
- price :: numeric(20,8) :: execution price
|
||||
- fee_amount :: numeric(20,8) :: brokerage fee; server_default=0
|
||||
- tax_amount :: numeric(20,8) :: transaction tax; server_default=0
|
||||
- executed_at :: timestamptz :: broker-reported execution timestamp
|
||||
- recorded_at :: timestamptz :: insertion timestamp; server_default=NOW()
|
||||
|
||||
### Uniqueness Constraints
|
||||
|
||||
- uq_ledger_trades_idempotency :: UNIQUE (asset_id, order_id, execution_id) :: idempotency guarantee; duplicate inserts are detected and return HTTP 200 + status="duplicate"
|
||||
- idx_ledger_trades_asset_executed :: INDEX (asset_id, executed_at) :: time-range query optimization
|
||||
|
||||
### State Rules
|
||||
|
||||
- Rows are immutable after insertion; no UPDATE path exists.
|
||||
- Payload conflict detection: if unique key matches but payload differs → HTTP 409 Conflict.
|
||||
- asset_id is TEXT (not a FK) but must correspond to a valid portfolios.portfolio_id before insertion.
|
||||
|
||||
## Shared Consistency Rules
|
||||
|
||||
- auth_tokens.user_id and portfolios.owner_user_id should resolve to existing users before protected flows run.
|
||||
- strategy_sets.name plus config, strategy_sets.nick, and service token names have uniqueness constraints.
|
||||
- Portfolio snapshot fields and portfolio_ledger history must stay synchronized across mutations.
|
||||
- (owner_user_id, name) uniqueness is enforced at both the DB constraint level and the application layer; violations surface as a 409 Conflict or ValueError with a Korean message.
|
||||
|
||||
## Persistence / Integration Notes
|
||||
|
||||
@@ -110,4 +204,6 @@
|
||||
|
||||
## Change Log
|
||||
|
||||
- 2026-05-11 KST: bat-008 — REQ-011 AC-2: added portfolios.market column; added Entity: AuthToken (runtime_id field); added Entity: BrokerCredential; added Entity: LedgerTrade; updated Model Summary.
|
||||
- 2026-05-11 KST: bat-006 — portfolios.portfolio_id changed to server-generated UUID PK; name column added with UNIQUE (owner_user_id, name) constraint; uq_portfolios_owner_name constraint documented; state rules updated.
|
||||
- 2026-04-30 KST: Bootstrap baseline created from repository observation for initial StagePilot adoption.
|
||||
Reference in New Issue
Block a user