Financial Invariants Contract
Status: BETA_NOT_READY — this document is the machine-checkable contract that the independent oracle (S2-02, INDEPENDENT_QA lane) must evaluate. It describes the guarantees the system claims to hold, where each claim is currently enforced, and the residual gaps. Nothing here is a marketing guarantee: every "enforced by" entry cites code that exists at the documented base SHA, and anything not verified against code is marked NOT_VERIFIED.
- Base: backend
be-cloudflare(Rust Cloudflare Worker + D1), base SHAd910a68a106d345e3533528cf9b504883842fde6. - Scope: capture → refund → settlement → payout → entitlement → audit. Axum parity backend is out of scope (no equivalent surface).
- Money unit: KRW integer minor unit (won — no fractional unit in this system). All money comparisons are
INTEGERequality; no float sums are trusted (checks.rs:5).
0. Storage and vocabulary facts (verified)
These are the facts the oracle must encode. Each cites the migration or code that establishes it.
Tables and join keys
| Table | Key columns | Join keys | Source |
|---|---|---|---|
orders | id PK, order_no UNIQUE, idempotency_key UNIQUE, amount_krw, refunded_krw (013), status, payment_id, license_id, subscription_id, seller_id, settlement_id | orders.payment_id → payments.id; orders.settlement_id → settlements.id or 'run:<run_id>' tag | 001_init.sql:36-43, 008:20-21, 013, 020 |
payments | id PK, order_id FK, provider, payment_key (012), amount_krw, status, purpose, target_type, target_id, used_at | payments.order_id → orders.id; payments.payment_key ↔ Toss paymentKey | 001:45-49, 003, 012 |
refund_attempts | id PK, order_id FK, payment_id FK, provider, amount_krw, status, provider_ref, idem_key, request_hash | order_id; provider_ref = Toss cancel transactionKey | 012:14-26, 019 |
transaction_ledger | id PK, event_type, ledger_kind (money|game_currency), direction, asset, entity, entity_id, amount_krw, ref_id, idem_key | entity='order' entity_id=order.id; ref_id=payment.id for capture; ref_id=order_id for refund | 006, 008:10-16 |
settlements | id PK, settlement_no UNIQUE, seller_id, gross_krw, pg_fee_krw, platform_fee_krw, net_krw, status, order_ids_json, run_id, rules_version, pg_fee_bp, platform_fee_bp, paid_at, payout_ref | settlements.id ← orders.settlement_id | 008:26-40, 020:63-72 |
settlement_runs | run_id PK, seller_id, status, settlement_id, pg_fee_bp, platform_fee_bp, gross_krw, fee_krw, net_krw, order_count, claimed_count, lease_owner, lease_expires_at, fence, recovery_action | run_id ↔ orders.settlement_id='run:<run_id>' | 020 |
inbox_events | event_id PK, payload_sha256, status, received_at | Toss eventId or toss:<sha256(payload)> | 015 |
outbox | id PK, topic, status, claimed_at, lease_owner | — | 001:116-118, 005, 008:3, 009 |
audit_events (v1) | id, actor, actor_role, action, entity, entity_id, detail_json, integrity_hash | entity_id → domain row | 001:110, 004, 007 |
audit_events_v2 / audit_evidence / audit_checkpoints | sequence UNIQUE, key_id, prev_sequence, prev_hash, integrity_hash; evidence payload_hash | evidence audit_event_id → audit_events_v2.id | 023 |
reconciliation_runs / reconciliation_checks / reconciliation_findings / reconciliation_exceptions | run status, per-check status/scanned/total/remaining/cursor_json, finding state, exception fingerprint UNIQUE | findings.run_id, checks.(run_id,check_name) | 017, 021, 022 |
financial_operations / financial_operation_approvals | operation_id PK, idempotency_key UNIQUE, status, actor, approver, before_evidence_json, after_evidence_json, receipt_json, verification_json | approvals.operation_id | 022 |
Status vocabularies (authoritative sets in code)
| Column | Values | Source |
|---|---|---|
orders.status | pending, confirm_pending (toss only), paid, partially_refunded, refunded, failed, canceled | 012 header comment, toss_impl.rs:384, checkout_impl.rs:208, refund_impl.rs:724,788 |
payments.status | pending, paid, captured (PAID_FEEDBACK path only — endpoints_impl.rs:990), refunded | toss_impl.rs:95,409, refund_impl.rs:727 |
refund_attempts.status | attempted → confirmed → succeeded; failed (terminal); needs_review (uncertain, occupies remainder) | 019 state-machine comment, refund_impl.rs |
settlement_runs.status | CREATED, CLAIMING, CLAIMED, VALIDATING, RELEASING, COMMITTED, FAILED, RELEASED, NEEDS_REVIEW | 020, settle_impl.rs:18-21 |
settlements.status | pending (computed, not paid) → paid (payout confirmed with paid_at + payout_ref); pre-020 rows defaulted paid with paid_at NULL | 020 comments, settle_impl.rs:809-816 |
licenses.status | active, suspended, expired, revoked | verify_impl.rs:28-33, events_impl.rs:166-175, refund_impl.rs:761 |
subscriptions.status | trialing, active, past_due, expired, canceled | checkout_impl.rs:224, events_impl.rs:157-175 |
inbox_events.status | received, processing, processed, failed, ignored | 015, toss_impl.rs:526-536 |
Ledger event vocabulary
event_type values actually written in code: payment_captured, payment_refunded, license_issued, license_revoked, currency_grant, currency_revoke, settlement, settlement_payout (checkout_impl.rs:262, toss_impl.rs:432, purchase_impl.rs:122, endpoints_impl.rs:996, events_impl.rs:154, refund_impl.rs:718,754,762, settle_impl.rs:381,853).
Money rows use ledger_kind='money', asset='KRW'; captures are direction='credit', refunds/payouts direction='debit'.
Deterministic idem_key conventions: capture-<order_id>, refund-<order_id>-<attempt_id>, settle-<settlement_id>, payout-<settlement_id>, licissue-<order_id>, licrevoke-<order_id>, grant-<fulfillment_id>, revoke-<fulfillment_id>. Enforced by uidx_ledger_idem — UNIQUE(idem_key) WHERE idem_key IS NOT NULL (008:16).
1. Invariant specifications
Each invariant is specified as a machine-checkable record. "Enforcement" entries name the code path; "Detection" entries name the asynchronous detector (recon check id or verify endpoint) that surfaces residual drift. NONE — gap means no current enforcement or detection exists.
INV-CAPTURE — confirmed approval ↔ internal payment + ledger, unique
| Field | Specification |
|---|---|
| Claim | Every internally captured order has exactly one capture authority and exactly one money-credit ledger row; every payment_captured ledger row belongs to a capture-state order. |
| Input set | orders (all), payments (order_id join), transaction_ledger (event_type='payment_captured' AND ledger_kind='money') |
| Join keys | orders.payment_id → payments.id; ledger entity='order', entity_id=order.id; ledger ref_id=payment.id |
| Amount rule | Σ ledger payment_captured.amount_krw == orders.amount_krw when orders.status ∈ {paid, partially_refunded, refunded}; == 0 for all other statuses (checks.rs:163-174) |
| Uniqueness | Exactly one payment_captured money row per order (checks.rs:311-317); idem_key globally unique (008:16) |
| Status drift | payments.status ∈ {paid,captured} while orders.status ∉ {paid,partially_refunded,refunded} → violation (checks.rs:178-183) |
| PG authority | provider=mock: none (staging-only, live_payments gate checkout_impl.rs:148). provider=toss: DONE status from POST /v1/payments/confirm response or webhook GET recheck, with orderId+totalAmount matching internal order (toss_impl.rs:259-284, 675-676). |
| Enforcement | Guarded transition UPDATE orders … WHERE status IN ('pending','confirm_pending') executed before the effects batch; non-paid unexpected state → no ledger/effects + unexpected_state audit (toss_impl.rs:384-405, LEDGER-5). Mock path: single atomic batch for order+payment+ledger (checkout_impl.rs:231-270). |
| Detection | recon capture_consistency (checks.rs:158-187), ledger_uniqueness dup-capture (checks.rs:283-318), reference_integrity (checks.rs:362-392); GET /api/v1/ledger/verify captured_sum — global Σ captured == Σ orders.amount_krw over orders that have a payments row with status ∈ {paid,captured,refunded} and purpose ∈ {PRODUCT_PURCHASE,DONATION,SUBSCRIPTION,GAME_ITEM_PURCHASE,PAID_FEEDBACK} (verify_impl.rs:315-331) |
| Tolerated exceptions | refunded orders retain the full capture row (refund is a separate debit, not a capture deletion). Orders in pending/confirm_pending legitimately have zero capture rows. |
| Gaps | payments.amount_krw == orders.amount_krw is asserted at write time but no check verifies it post-hoc — NONE — gap. Toss payments.payment_key binding vs provider state is verified at confirm/webhook time only; no periodic provider↔internal diff exists — NONE — gap (needs PG access; out of recon scope). |
INV-REFUND — cumulative confirmed refunds ≤ capture; exact decrement + license policy
| Field | Specification |
|---|---|
| Claim | For each order: Σ refund_attempts[status='succeeded'].amount_krw == Σ ledger payment_refunded (debit) == orders.refunded_krw, and cumulative refund ≤ orders.amount_krw. |
| Input set | refund_attempts (per order_id), transaction_ledger (event_type='payment_refunded' AND direction='debit' AND ledger_kind='money'), orders.refunded_krw |
| Join keys | refund_attempts.order_id → orders.id; ledger entity='order', entity_id=order.id; ledger ref_id=payment.id (nullable) |
| Cap rule | Authority for the cap is committed = Σ amount_krw WHERE status<>'failed' — in-flight attempts occupy the remainder (refund_impl.rs:332-338). New attempt requires requested ≤ amount_krw − committed; remaining ≤ 0 → 409/already_processed (refund_impl.rs:172-189). |
| State machine | attempted(recorded, PG call pending) → confirmed(PG-committed, provider_ref held) → succeeded(internal effects committed); failed(terminal, excluded from cap); needs_review(uncertain, occupies remainder, blocks new attempts) — 019 header, refund_impl.rs |
| Single in-flight | INSERT … WHERE NOT EXISTS(status IN ('attempted','confirmed','needs_review')) — atomic check-then-act (refund_impl.rs:198-204) |
| Attempt staleness | non-terminal attempt untouched >10 min → recon finding stale_refund_attempt (checks.rs:555-573); non-toss stale attempted auto-expires to failed at 5 min (refund_impl.rs:11,342-347) |
| Partial refund | Exact decrement in the same atomic batch: refunded_krw += amount, orders.status='partially_refunded', attempt→succeeded, ledger debit, audit, outbox (refund_impl.rs:714-721,788-794). License is kept — entitlement retained on partial refund. |
| Full refund | refund_amount == remaining → orders.status='refunded', payments.status='refunded', fulfillments canceled + game-currency clawback, licenses.status='revoked' (+subscription-linked license), subscriptions.status='canceled' (refund_impl.rs:723-784) |
| Duplicate detection | uidx_refund_attempts_pref — (order_id, provider_ref) unique (019:52-53); recon ledger_uniqueness dup provider_ref (checks.rs:321-334); webhook cumulative-authority delta max(0, keyed_canceled − committed) converges re-deliveries to 0 (toss_impl.rs:774-802) |
| Enforcement | refund_impl.rs:38-326 (endpoint), apply_refund_effects (refund_impl.rs:693-822), apply_provider_cancel (refund_impl.rs:623-683), reconcile_attempts (refund_impl.rs:408-609) |
| Detection | recon refund_consistency (checks.rs:209-228), refund_attempt_liveness (checks.rs:555-573) |
| Tolerated exceptions | needs_review attempts are legal non-terminal states until reconciled; they occupy the cap (conservative). |
| Gaps | Internal committed is never compared against provider-side cumulative cancels by a check — only reconcile_attempts/webhook do it opportunistically. NONE — gap for scheduled provider↔internal refund diff. |
INV-NET — capture − confirmed refunds = net settlement amount
| Field | Specification |
|---|---|
| Claim | Per order: orders.amount_krw − Σ refund_attempts[succeeded].amount_krw == Σ ledger payment_captured − Σ ledger payment_refunded(debit) |
| Input set | orders, refund_attempts (status='succeeded'), transaction_ledger (capture credit + refund debit) |
| Join keys | all on orders.id |
| State filter | Evaluated only on orders with ledger or refund activity (lcap>0 OR lref>0 OR att>0) — unpaid orders belong to capture_consistency (checks.rs:265) |
| Rounding | none — exact integer equality; no tolerance |
| Anti-pattern note | Do not compare payments.amount_krw against order amount across refund states — payments keeps the original amount while orders.refunded_krw accumulates. The old net-vs-paid-sum check was replaced by this formula (VERIFY-2/F2-3, checks.rs:230-246, verify_impl.rs:305-314) |
| Detection | recon net_amount (checks.rs:248-269); ledger/verify captured_sum reports ledger_net vs expected_net globally (verify_impl.rs:328-331) |
| Enforcement | atomicity of write paths (refund effect batch keeps refunded_krw and ledger debit in one db.batch, refund_impl.rs:714-795) |
| Gaps | none structural; formula is exact-match only — any DB write outside the batch paths drifts it. |
INV-IDEM — no duplicate financial effect from retries/redelivery
| Field | Specification |
|---|---|
| Claim | Approval (confirm/finalize), webhook delivery, refund request, refund provider call, settlement run, payout confirm, and recovery op each produce at most one financial effect per logical operation. |
| Input set | orders.idempotency_key, transaction_ledger.idem_key, refund_attempts.(order_id,idem_key)/(order_id,provider_ref), inbox_events.event_id, settlement_runs, financial_operations.idempotency_key |
| Mechanisms | (a) orders.idempotency_key UNIQUE + replay compare on product_id+plan_id+amount_krw (checkout) / game_item_id+player_id (purchase) → already_processed or 409 IDEMPOTENCY_CONFLICT (checkout_impl.rs:126-144,285-304, purchase_impl.rs:24-40). (b) finalize effects use deterministic ids (sub_<ord>, lic_<ord>, led_capture_<ord>, aud_paid_<ord>, out_paid_<ord>) + INSERT OR IGNORE (toss_impl.rs:360-439). (c) inbox dedup on event_id PK + payload_sha256; same-id different-body → Conflict (processed anyway, audited), byte-identical → Duplicate (toss_impl.rs:451-519). (d) refund idem_key scoped (order_id, idem_key) + request_hash fingerprint; PG-side idempotency = attempt id as Toss Idempotency-Key (refund_impl.rs:196-241,358-395). (e) one in-flight settlement run per seller (IN_FLIGHT gate, settle_impl.rs:17-18,458-476); payout CAS paid_at IS NULL + same-ref replay (settle_impl.rs:839-881). (f) financial_operations.idempotency_key UNIQUE (022). |
| Detection | recon ledger_uniqueness (dup idem_key, dup payment_captured per order, dup provider_ref across attempts — checks.rs:276-334) |
| Gaps | Duplicate audit_events/outbox rows are prevented only by deterministic ids in the finalize path — mock checkout/purchase use random led_/aud_/out_ ids inside an atomic batch, so a retried batch is safe, but a recon check for duplicate audit/outbox per logical event does not exist — NONE — gap (low value; ids are the dedup). The Toss payments.payment_key cross-order uniqueness is checked in code at bind time (toss_impl.rs:243-256) but there is no unique index — detection is best-effort ledger_uniqueness-adjacent only — NONE — gap. |
INV-SETTLE — settleable set, fee snapshot, rounding, recomputable
| Field | Specification |
|---|---|
| Claim | A settlement's order set, gross, fees, and net are independently recomputable from orders + the fee snapshot stored on settlement_runs/settlements. Claims are always attributable (no orphan claims). |
| Settleable predicate | orders.seller_id=<seller> AND settlement_id IS NULL AND status IN ('paid','partially_refunded') — identical at snapshot, claim, and validate (settle_impl.rs:16,225,303,598) |
| Claim protocol | Uncommitted claims are orders.settlement_id='run:<run_id>'; the record batch atomically retags run:* → settlement.id (020 claim-tag contract, settle_impl.rs:23-28,369-372). run:* tags with no live run row are zombies released by the sweeper (settle_impl.rs:683-709). |
| Gross | gross = Σ (amount_krw − COALESCE(refunded_krw,0)) over claimed orders still settleable at validate time (settle_impl.rs:303,313) |
| Fee snapshot | pg_fee_bp = round(seller_settings.pg_fee_rate × 10000), platform_fee_bp = round(platform_fee_rate × 10000) — f64 rate snapped to integer bps at run creation and stored on the run and the settlement (settle_impl.rs:566-589,618-623,373-379). rules_version = 'settle_rules/2026-11-w4a-v1' (settle_impl.rs:14). |
| Fee formula | pg_fee = floor((gross × pg_fee_bp + 5000) / 10000); platform_fee = floor((gross × platform_fee_bp + 5000) / 10000); fee = pg_fee + platform_fee; net = gross − fee — integer math, round-half-up (the +5000 term), settle_impl.rs:314-317. Confirmed by oracle-independent reimplementation in settle-recovery.test.mjs:151-152. |
| Amount hard gate | pg_bp<0 OR pf_bp<0 OR fee<0 OR fee>gross OR net<0 → NEEDS_REVIEW, never committed (settle_impl.rs:321-332); config-side validation rate≥0 finite and pg_rate+pf_rate<1.0 rejects earlier with 409 (settle_impl.rs:577-587) |
| Run counts | settlement_runs.claimed_count = orders claimed; order_count = orders in committed set; run gross_krw/fee_krw/net_krw recorded at VALIDATING (settle_impl.rs:281-288,334-341) |
| Post-commit check | COUNT(*) == order_count AND Σ(amount_krw − refunded_krw) == gross over orders.settlement_id=set_id re-queried after commit; drift → NEEDS_REVIEW (settle_impl.rs:414-429) |
| Detection | recon settlement_consistency: (a) orders.settlement_id not run:* and no settlements row → auto-fix release to NULL (checks.rs:399-411,431-437); (b) per-settlement recompute — Σ(amount_krw − refunded_krw) == gross_krw AND net == gross − pg_fee − platform_fee (s2-02 e6a05cf); finding types emitted: settlement_consistency, settlement_membership, post_settlement_refund, settlement_fee_mismatch, settlement_run_mismatch |
RESOLVED (s2-02) | Was NOT_VERIFIED at d910a68: recon check (b) summed raw orders.amount_krw while the pipeline stores gross = Σ(amount − refunded_krw). Oracle Phase D pinned it as a real false positive; s2-02 (e6a05cf) corrected the check to the pipeline's net-of-refund authority and added post_settlement_refund so post-commit member refunds surface instead of tripping arithmetic drift. |
| Tolerated exceptions | run:* claims under a live run are excluded from the orphan-claim check by design (checks.rs:428-434); zombie run:* release belongs to the settle sweeper, not recon. |
| Gaps (s2-02 update) | settlement_run_mismatch, settlement_fee_mismatch, settlement_membership (s2-02). Remaining: none structural recorded at 940fd75; pre-020 rows without bp snapshots are skipped by the fee re-derivation (legacy-scope exception). |
INV-PAYOUT — settlement created vs external paid evidence
| Field | Specification |
|---|---|
| Claim | settlements.status='pending' means computed, not paid. status='paid' is asserted only with external payout evidence (payout_ref) recorded by an admin; the transition is idempotent per payout_ref. |
| Transition | UPDATE settlements SET status='paid', paid_at=now, payout_ref=? WHERE id=? AND paid_at IS NULL AND status IN ('pending','paid') — CAS; same payout_ref replay → already_paid, different ref → PAYOUT_REF_CONFLICT (settle_impl.rs:839-881) |
| Evidence | payout_ref required non-empty, ≤200 chars; settlement_payout money-debit ledger row (amount = net_krw, idem_key='payout-<set_id>', ref_id=payout_ref) written in the same batch (settle_impl.rs:817-856) |
| Entry point | POST /api/v1/admin/settlements/:id/mark-paid — admin only (finops_impl.rs:751-772) |
| Tolerated exceptions | Pre-020 rows default status='paid' with paid_at NULL — legacy rows are closable by supplying a payout_ref; paid_at NULL + status='paid' is therefore ambiguous between "legacy" and "missing evidence" and cannot be distinguished by schema (020 comment, settle_impl.rs:814-815) |
| Detection | NONE — gap for a recon check that status='paid' ⇒ paid_at+payout_ref present and a settlement_payout ledger row exists. Test coverage: SREC-07 (settle-recovery.test.mjs:403-415) asserts CAS, idempotent re-send, and payout ledger idem_key. |
INV-ENTITLE — payment/cancel/refund/revoke ↔ entitlement state
| Field | Specification |
|---|---|
| Claim | An active license/subscription exists iff the payment state entitles it: paid/partially_refunded orders keep entitlement; refunded orders must have license revoked; non-capture-state orders must not hold an active license. |
| Input set | orders, licenses (order_id join), subscriptions, products.license_json |
| Rules | (a) orders.status ∈ {paid,partially_refunded} + product license_json.enabled=1 + type<>'donation' ⇒ orders.license_id exists (checks.rs:79-85). (b) Exactly one license per order (checks.rs:89-92). (c) licenses.status='active' ⇒ owning order ∈ {paid,partially_refunded} (checks.rs:103-107). (d) orders.status='refunded' ⇒ no active license (checks.rs:110-114). (e) subscriptions.status='expired' ⇒ no paid renewal order on it (checks.rs:123-128). |
| Write-path enforcement | checkout/finalize license issuance (checkout_impl.rs:242-248, toss_impl.rs:420-429); full-refund revocation (refund_impl.rs:760-783); sub_event transitions (events_impl.rs:157-175) |
| Detection | recon entitlement — finding codes paid_no_entitlement, duplicate_issuance_per_payment, unpaid_but_entitled, refunded_but_valid_entitlement, subscription_expired_but_renewed (checks.rs:32-131) |
| Tolerated exceptions | Donation products and license_json.enabled≠1 products never require a license. suspended/expired license states are not drift-checked against order status (only active is) — a suspended license on a refunded order is not currently a finding; NOT_VERIFIED whether intentional. |
| Gaps | No check that orders.subscription_id rows exist or that subscription orders carry paid consistency beyond (e) — NONE — gap (partial). License expires_at vs subscription period-end consistency is unchecked — NONE — gap. |
INV-AUDIT — cause/actor/before-after traceability for financial changes
| Field | Specification |
|---|---|
| Claim | Every money-affecting commit writes a hash-chained audit_events row; commit-bound domain evidence is sealed into audit_events_v2/audit_evidence (HMAC-SHA256 chain); approval-gated operations record actor, approver, before/after snapshots, and receipts. |
| v1 chain | integrity_hash = audit_hash(prev, "{actor}|{action}|{entity}|{entity_id}|{detail}") — non-standard HMAC variant keyed by NOUGAT_AUDIT_HMAC_KEY when present (checkout_impl.rs:12-29); verified by GET /api/v1/audit/verify recomputation (verify_impl.rs:129-158). prev is the last row by created_at,rowid and its read is fail-closed (audit_prev_strict, checkout_impl.rs:65-74). |
| v2 chain | RFC-2104 HMAC-SHA256 over canonical preimage {audit_version, sequence, key_id, prev_sequence, prev_hash, event_type, actor_id, correlation_id, operation_id, payload, occurred_at}; sequence via counters('audit_v2_sequence') CAS (audit.rs:167-261). Evidence payload is denylist-redacted (audit.rs:137-159) and sha256-fingerprinted (audit.rs:266-303). Verified by verify_chain (audit.rs:331-408) and daily audit_checkpoints root-hash folds (audit.rs:416-446). |
| Sealed evidence events | payment.capture, refund.attempt, refund.apply, license.revoke, settlement.commit, recovery.execute, recovery.verify, alert:recon_failures, migration.apply, payment_key_takeover (v1) — emit sites: checkout_impl.rs:275, toss_impl.rs:442, refund_impl.rs:234,798,806, settle_impl.rs:407 |
| Approval traceability | financial_operations + financial_operation_approvals: money-affecting ops require actor ≠ approver (SELF_APPROVAL_DENIED), CAS-guarded execute/verify, stored before_evidence_json/after_evidence_json/receipt_json/verification_json (022, finops_impl.rs, docs financial-integrity.md) |
| Key gate | prod-config without NOUGAT_AUDIT_HMAC_KEY → 500 AUDIT_KEY_MISSING at write-entry preflight (checkout, refund, settle) — fail closed (audit.rs:103-119). Non-prod: emit skipped with warn, never an unkeyed row. |
| Gaps | (a) v1 rows store actor hardcoded 'dev'/'toss' — the real caller identity is not recorded in v1 rows; actor_role is the only identity signal — NONE — gap (v2 actor_id is also passed as literal 'dev'/'system' at current emit sites). (b) emit_logged is best-effort post-commit — a failed emit leaves a chain gap detectable by verify but not atomically coupled to the money write (audit.rs:305-319). (c) No check enforces "every money ledger row has a corresponding audit event" — NONE — gap. (d) before/after snapshots exist only for recovery ops, not for checkout/refund/settle effects — NONE — gap (evidence payload carries amounts but not before/after state). |
2. Oracle contract (S2-02 deliverable)
The oracle is an independent reimplementation of these invariants in the test-harness language (Node .mjs under be-cloudflare/tests/), consumed by a new run-*.sh suite following the existing pattern.
MUST requirements
- Independence: the oracle MUST NOT import, copy, or call any application function (
src/**), nor delegate to the app's own reconciliation checks or/api/v1/admin/reconciliation/*endpoints for its expected values. Expected amounts are computed by oracle-owned SQL/arithmetic written from this spec. (The recon engine's output may be compared to the oracle's as a detector, but the oracle's expectation must be computed independently.) - Environment: local loopback only —
wrangler dev --local+ local D1 at.wrangler/state/v3/d1; the suite script resets D1 state and appliesmigrations/*.sql+ seed +tests/fixtures.sqlat start, as existingrun-*.shfiles do. Never run against staging/production. - Access: state inspection via
npx wrangler d1 execute DB --local(existingd1()/d1file()helpers pattern); drives state through the HTTP API surface (checkout,refund,settlements,webhooks/toss, admin recon/ops endpoints) withDEV_AUTH=1dev identities. - Failure semantics: a DB read failure inside the oracle is an
ERRORoutcome, never a pass — mirror the fail-closed convention.
Fixture shapes the oracle consumes
| Fixture | Shape | Notes |
|---|---|---|
order | {id, order_no, product_id, plan_id?, amount_krw, status, payment_id?, license_id?, subscription_id?, seller_id, settlement_id?, refunded_krw=0, idempotency_key} | statuses per §0 |
payment | {id, order_id, provider: mock|toss, status, amount_krw, payment_key?, purpose} | purpose set: PRODUCT_PURCHASE, DONATION, SUBSCRIPTION, GAME_ITEM_PURCHASE, PAID_FEEDBACK |
refund_attempt | {id, order_id, payment_id, provider, amount_krw, status, provider_ref?, idem_key?, request_hash?} | status machine per §0 |
ledger_row | {id, event_type, ledger_kind, direction, asset, entity, entity_id, amount_krw, ref_id?, idem_key?} | event vocabulary per §0 |
settlement / settlement_run | per §0 schema incl. pg_fee_bp, platform_fee_bp, rules_version | run claim tag 'run:<run_id>' |
license / subscription | {id, order_id, status, …} | status vocab per §0 |
inbox_event | {event_id, payload_sha256, status} | |
product | {id, seller_id, type, status, price_krw, license_json, plans_json} | license_json.enabled, type='donation' gate entitlement rules |
Outputs the oracle produces
Per scenario, per invariant:
{
"scenario": "s2-partial-refund-settle",
"invariant": "INV-SETTLE",
"expected": {"gross_krw": 600, "pg_fee_krw": 19, "platform_fee_krw": 30, "net_krw": 551, "claim_count": 1, "run_status": "COMMITTED"},
"observed": {"gross_krw": 600, "...": "..."},
"verdict": "PASS | FAIL | ERROR",
"diff": "human-readable field-level diff on FAIL"
}2
3
4
5
6
7
8
expectedmust be computed before or independent of the app's stored values (e.g., expected settlement fee computed by oracle mathfloor((gross*bp + 5000)/10000)in JSBigInt/integer arithmetic — JSMath.floor((g*b+5000)/10000)is acceptable for KRW-scale values but the oracle must document its integer-precision bound).- Minimum scenario coverage: clean paid order; partial refund (single + cumulative-to-full); refund attempt in each non-terminal state; duplicate webhook redelivery; duplicate refund
idem_key(same + different fingerprint); settlement including apartially_refundedorder (this also exercises theNOT_VERIFIEDrecon-check discrepancy in INV-SETTLE); settlement fee at rounding boundaries (gross*bp % 10000∈ {0, 4999, 5000, 9999}); payout mark-paid replay (same/differentpayout_ref); entitlement transitions across full refund; audit-chain verification after each money commit.
3. Coverage map
| Invariant | Existing enforcement (code) | Existing detection (check/suite) | Residual gap → S2-02+ |
|---|---|---|---|
| INV-CAPTURE | toss_impl.rs:384-405 guarded transition; atomic batches; deterministic ids | recon capture_consistency, ledger_uniqueness, reference_integrity; ledger/verify captured_sum; tests FI-2/FI-6, PAY-01/02 | payments.amount_krw vs orders.amount_krw unchecked; no periodic provider↔internal diff |
| INV-REFUND | refund_impl.rs cap/single-flight/state machine; 019 unique indexes | recon refund_consistency, refund_attempt_liveness; tests RS-01..RS-16, PAY-04/05, FI-1 | no scheduled provider↔internal refund diff |
| INV-NET | refund effect batch atomicity | recon net_amount; ledger/verify net; test FI-1 | none structural — exact-match only |
| INV-IDEM | unique constraints (001, 008:16, 019, 022), inbox dedup, run gate, payout CAS, deterministic ids + OR IGNORE | recon ledger_uniqueness, event_processing; tests PAY-02, RS-02/14/15/16, SREC-06/07, FI-7 | no unique index on payments.payment_key; no dup audit/outbox detection |
| INV-SETTLE | run state machine + lease fencing + record batch atomicity + post-commit re-query (settle_impl.rs) | recon settlement_consistency (+ settlement_membership/post_settlement_refund/settlement_fee_mismatch/settlement_run_mismatch, s2-02 e6a05cf); tests SREC-01..08, recon2 | amount_krw FP; run↔settlement x-check absent; membership unchecked |
| INV-PAYOUT | mark_settlement_paid guards + CAS + payout ledger row | test SREC-07 only | NONE — no recon check that paid ⇒ paid_at+payout_ref+settlement_payout row; legacy paid_at NULL ambiguity |
| INV-ENTITLE | issuance/revocation in capture & refund batches | recon entitlement (5 violation types); tests LIC/PAY/REC-03, RS-01 | suspended/expired license vs order state unchecked; subscription consistency partial |
| INV-AUDIT | v1 hash chain + v2 HMAC chain + evidence + ops approvals; preflight fail-closed | /api/v1/audit/verify, verify_chain (+ checkpoint_comparison/evidence_coverage/key_ids/truncated/link_breaks/sequence_gaps fields, s2-05 637654a), checkpoints; tests audit-evidence suite, audit2 + audit-v2-verifier.mjs, FI-1/RS-13 hash recompute | v1/v2 actor is literal 'dev'/'system' not caller identity; post-commit emit gaps — narrowed by s2-10 preflight+evidence expansion and alert:evidence_gaps residue surfacing, still not atomic; no ledger↔audit presence check; no before/after for non-op writes |
4. Conventions this contract relies on
- Fail-closed reads: any DB error inside a verification/recon/oracle path must surface as
ERROR/5xx, never be coerced to "clean" or "empty". The codebase marks theseFAILCLOSEDcomments; the oracle MUST adopt the same rule. - Recon check ids used above are
reconciliation_checks.check_namevalues registered inchecks.rs:16-26(execution order is persisted order). - Auto-fix policy: the engine auto-fixes only state-surface reversals (stale outbox claim, stale inbox processing, orphan settlement claim); money or entitlement changes stay
needs_review(mod.rs:29-33). NOT_VERIFIEDmarkers in this document are explicit unknowns carried to S2-02 — they are not waived; the oracle must either pin the behavior or the PM assigns the owning part to fix/clarify.
Related runbooks
- financial-integrity — admin operations surface
- reconciliation-runbook — findings → exceptions
- refund-recovery — refund attempt lifecycle
- settlement-recovery — settlement run recovery
- audit-evidence — audit v2 + evidence chain