CR-EDG-017 · EXCEPTION & EDGE-CASE HANDLING

Exception & Edge-Case Handling

How the platform behaves at the edges — with state diagrams, decision tables and live test evidence.

ConfidentialVersion: v1Date: 07 Jun 2026

Purpose & Scope

This document specifies how Engagement & Loyalty Platform behaves at its boundaries: reversals, refunds (full and partial), point clawbacks that would drive a balance negative, disputed redemptions, account-status enforcement, card closure, settlement anomalies, and the cross-cutting idempotency model. Each scenario is documented as: scenario → expected behaviour → how the system handles it → live evidence → decision table / state diagram.

Unless explicitly marked policy-recommended, every behaviour below was verified live against the running system on 07 Jun 2026. Where a behaviour is a recommendation rather than implemented code, this is called out honestly.

Companion reading: the happy-path flows are in CR-FLW-016; the accrual/offer grant engine and ledger model are in CR-AOG-018; the database schema (ledger, balance, clawback_pending) is in CR-DBS-013.

Full Reversal / Refund

Scenario. A posted purchase is fully refunded by the merchant or cancelled; the points it earned must be removed.

Expected. The accrual is unwound exactly once: the earned points are debited from available and from lifetime_earned, the transaction is marked reversed, and replays do nothing.

How the system handles it. POST /api/v1/transactions/{ref}/reverse posts a REVERSAL ledger debit under a reversal idempotency key, decrements available and lifetime_earned, and sets cr.transaction.txn_status='reversed' and accrual_status='reversed'. The reversal idempotency key makes a replay a strict no-op — no second debit, the original result is returned.

Live evidence

# First reversal — posts the REVERSAL debit
curl -sX POST https://api.chegrewards.local/api/v1/transactions/TXN-DINE-0001/reverse \
  -H "Idempotency-Key: rev-TXN-DINE-0001"
# → HTTP 200
{"reversed":true,"pointsDebited":1200,"txnStatus":"reversed","accrualStatus":"reversed"}

# Replay the same reversal — idempotent no-op, original result returned
curl -sX POST https://api.chegrewards.local/api/v1/transactions/TXN-DINE-0001/reverse \
  -H "Idempotency-Key: rev-TXN-DINE-0001"
# → HTTP 200 (no second debit)
{"reversed":true,"pointsDebited":1200,"txnStatus":"reversed","accrualStatus":"reversed","replayed":true}
FieldBeforeAfter full reverse
txn_statuspostedreversed
accrual_statusaccruedreversed
available+1,200−1,200 (net 0 for this txn)
lifetime_earned+1,200−1,200

Partial Refund

Scenario. Only part of a purchase is refunded (e.g. one line item returned). The points earned must be clawed back pro-rata, but the transaction itself remains a valid posted purchase.

Expected. The clawback is proportional to the refunded fraction; the original transaction stays posted; the operation is idempotent under a per-amount key.

How the system handles it. POST /api/v1/transactions/{ref}/reverse with a body {"refundAmountMinor": N} where N < originalAmount claws back:

clawbackPoints = floor(accruedPoints × refundAmount / originalAmount)

with reason_code = 'partial_refund'. Because the purchase was only partially refunded, txn_status stays posted. Each distinct partial-refund amount uses its own idempotency key, so multiple partial refunds against the same transaction are each applied exactly once.

Live evidence

A ₹10,000 dining purchase earned 1,200 pts. A 40% partial refund (refundAmountMinor=400000 of 1000000) clawed back exactly 480 pts (40% of 1,200); the transaction remained posted.

curl -sX POST https://api.chegrewards.local/api/v1/transactions/TXN-DINE-0002/reverse \
  -H "Idempotency-Key: prefund-TXN-DINE-0002-400000" \
  -H "Content-Type: application/json" \
  -d '{"refundAmountMinor":400000}'
# → HTTP 200 — txn stays 'posted'
{"refundType":"partial","pointsDebited":480,"recoveredFromAvailable":480,"clawbackShortfall":0}
InputOriginalRefundClawbackTxn status
Amount (minor)1,000,000400,000 (40%)—posted (unchanged)
Points1,200—480 = floor(1200 × 400000 / 1000000)
Full vs partial. Omitting refundAmountMinor (or sending the full amount) is a full reversal → txn_status='reversed'. Supplying a smaller amount is a partial refund → txn_status stays posted. The same endpoint serves both; the body decides.

Going-Negative: Clawback & Recovery

This is the most important edge case in the platform. It was a real, reproduced bug — now fixed. Both states (before and after the fix) are documented from live observation.

The problem (reproduced live, before the fix)

An account accrued 12,000 pts, then redeemed 3,000 (available = 9,040 after a separate small accrual). Reversing the original purchase tried to claw back the full 12,000 pts — but only 9,040 were available. The clawback drove the balance to −2,960, violating CHECK(available >= 0). The endpoint returned HTTP 500 and leaked the raw Postgres constraint name:

# BEFORE FIX — full reverse when available < clawback
curl -sX POST https://api.chegrewards.local/api/v1/transactions/TXN-BIG-0007/reverse
# → HTTP 500
{"code":"INTERNAL_ERROR",
 "message":"new row for relation \"point_balance\" violates check constraint \"point_balance_available_check\""}
Two defects in one: (1) a value-mutating operation could fail and leave the caller unable to reverse a transaction; (2) an internal database constraint name was leaked to the API consumer. Both are resolved below.

The fix (migration 009)

A new column clawback_pending BIGINT was added (migration 009). On reversal the system now recovers what it can from available, clamps available at zero, and carries the unrecoverable remainder as recoverable debt:

recoveredFromAvailable = min(available, clawbackPoints)
available              = available − recoveredFromAvailable      # clamped at 0
clawback_pending      += clawbackPoints − recoveredFromAvailable  # the shortfall

The core invariant is preserved at all times:

(available − clawback_pending) == net ledger position

Recovery on the next accrual

The next accrual pays down clawback_pending first, then credits the remainder to available. The UPDATE uses GREATEST/LEAST so both SET expressions read the pre-update value of the columns (no read-after-write skew within one statement):

UPDATE cr.point_balance SET
  clawback_pending = GREATEST(0, clawback_pending - :accrual),
  available        = available + GREATEST(0, :accrual - clawback_pending)
WHERE account_id = :acct;

Live evidence (after fix)

# Full reverse of the 12,000 accrual when only 9,040 was available
curl -sX POST https://api.chegrewards.local/api/v1/transactions/TXN-BIG-0007/reverse \
  -H "Idempotency-Key: rev-TXN-BIG-0007"
# → HTTP 200 (no more 500)
{"reversed":true,"pointsDebited":12000,"recoveredFromAvailable":9040,"clawbackShortfall":2960}
# balance now: available = 0, clawback_pending = 2960

# Next accrual of 5,040 pts — clears the debt first, then credits remainder
curl -sX POST https://api.chegrewards.local/api/v1/transactions/TXN-NEXT-0008/accrue \
  -H "Idempotency-Key: acc-TXN-NEXT-0008"
# → HTTP 200
{"accrued":5040,"clawbackCleared":2960,"creditedToAvailable":2080}
# balance now: available = 2080, clawback_pending = 0
StepΔ pointsavailableclawback_pending(avail − pending)
Start (post-redeem)—9,04009,040
Full reverse −12,000−12,00002,960−2,960
Accrue +5,040+5,0402,08002,080

Balance state diagram

stateDiagram-v2
    [*] --> Positive
    Positive --> Positive: accrual / partial reverse within available
    Positive --> Debt: full reversal > available
    Debt --> Debt: accrual < clawback_pending
    Debt --> Positive: accrual >= clawback_pending
    note right of Positive
      available >= 0
      clawback_pending = 0
    end note
    note right of Debt
      available = 0
      clawback_pending > 0
      (recoverable debt)
    end note

Reversal outcome decision table

ConditionrecoveredFromAvailableavailable afterclawback_pending afterHTTP
available ≥ clawbackPoints= clawbackPointsavailable − clawbackPoints (≥ 0)unchanged (0)200
available < clawbackPoints= available (all of it)0 (clamped)+ (clawbackPoints − available)200
The reconciler now checks (available − clawback_pending) == ledger net for every account. Existing accounts have clawback_pending = 0, so the prior invariant available == ledger net still holds for them — the migration is backward-compatible and the reconciler ties out across both old and new accounts.

Disputed / Customer-Claimed Redemptions

Scenario. A customer claims they did not receive a redeemed reward, or submits a duplicate redemption request. The platform must never double-debit, and must be able to credit points back when fulfilment failed.

Expected. Redemption is idempotent under an Idempotency-Key; a duplicate claim returns the original redemption with replayed=true and no second debit. A genuine non-receipt is resolved by reversing the redemption, which credits the points back (also idempotent).

Live evidence

# Duplicate redemption claim — returns the original, no double debit
curl -sX POST https://api.chegrewards.local/api/v1/redemptions \
  -H "Idempotency-Key: redeem-cust-44-voucher-amzn-500" \
  -d '{"accountRef":"ACC-44","sku":"AMZN-500","points":5000}'
# → HTTP 200
{"redemptionId":"RDM-9001","status":"fulfilled","pointsDebited":5000,"replayed":true}

# Disputed / failed fulfilment — reverse the redemption, points returned
curl -sX POST http://fulfilment:3005/redemptions/RDM-9001/reverse \
  -H "Idempotency-Key: rev-RDM-9001"
# → HTTP 200
{"reversed":true,"pointsCredited":5000,"alreadyReversed":false}

# Replay the reversal — idempotent
# → {"reversed":true,"pointsCredited":5000,"alreadyReversed":true}

Dispute workflow

sequenceDiagram
    actor Cust as Customer
    participant Sup as Support
    participant Core as Core-API
    participant Ful as Fulfilment :3005
    Cust->>Sup: Claims non-receipt of reward
    Sup->>Ful: Verify fulfilment_ref / voucher state
    alt Fulfilment confirmed delivered
        Ful-->>Sup: Voucher redeemed by customer
        Sup-->>Cust: Evidence shared, dispute closed
    else Fulfilment failed or unverifiable
        Sup->>Ful: POST /redemptions/{id}/reverse
        Ful->>Core: Credit points back (idempotent)
        Core-->>Ful: available += points
        Ful-->>Sup: reversed=true
        Sup-->>Cust: Points returned + comms sent
    end

Account Status Enforcement

Scenario. Operations are attempted against accounts that are not in a normal state.

cr.loyalty_account.status ∈ {active, dormant, blocked, closed}. Redemption requires status='active'; any other status raises ApiError ACCOUNT_NOT_ACTIVE (HTTP 422). Catalogue and balance edges return their own 422s.

Capability decision table

StatusCan accrue?Can redeem?Notes
activeYesYesNormal operating state.
dormantYesNo 422Reactivates to active on qualifying activity; redemption blocked while dormant.
blockedYes gapNo 422Redemption correctly blocked. Accrual is NOT currently gated — see gap note.
closedYes gapNo 422Redemption blocked. Accrual should be excluded but is not yet gated.
Honest gap. Only redemption enforces status='active' today. Accrual does not check status, so a blocked or closed account could still earn points. Recommendation: gate accrual to exclude blocked and closed (and decide policy for dormant — typically allowed, since activity reactivates the account). This is policy-recommended, not yet implemented.

Other redemption-time 422s

ConditionError codeHTTP
Account not activeACCOUNT_NOT_ACTIVE422
Catalogue SKU inactiveSKU_INACTIVE422
Not enough pointsINSUFFICIENT_BALANCE422

Card Closure Edge Cases

Scenario. A card / account is closed (status='closed') while it may still hold points or carry clawback_pending debt.

Implemented today: redemption is blocked on closed (ACCOUNT_NOT_ACTIVE, 422); the ledger is immutable and retained for audit.

Recommended closure runbook policy-recommended — most of the orchestration below is policy, not yet automated:

  1. Settle or forfeit remaining available points per the closure policy (forfeit, or transfer/redeem before closure).
  2. Resolve any clawback_pending — write it off, or recover from the customer's final card statement.
  3. Close open campaign enrolments so no further offer grants accrue.
  4. Retain the ledger immutably for audit; closure never deletes ledger history.

Closure decision

flowchart TD
    A[Account closure requested] --> B[Block redemptions]
    B --> C{available > 0?}
    C -->|Yes| D{Policy: forfeit or transfer}
    C -->|No| F
    D -->|Forfeit| E[Zero out available, ledger entry]
    D -->|Transfer| T[Redeem/transfer before close]
    E --> F{clawback_pending > 0?}
    T --> F
    F -->|Yes| G{Write-off or recover}
    F -->|No| K[Close enrolments]
    G -->|Write-off| H[Adjust ledger, zero pending]
    G -->|Recover| R[Bill to final statement]
    H --> K
    R --> K
    K --> L[Retain ledger for audit]
    L --> M[Account closed]
Implemented vs recommended. Implemented: redemption block on closed, immutable ledger retention. Recommended (not yet automated): forfeit/transfer of residual points, clawback_pending resolution, campaign-enrolment teardown. The closure runbook should be wired into the account-lifecycle service before go-live.

Settlement & Billing Anomalies

Scenario. Merchant attribution rows arrive after a settlement file was generated, creating a variance between the settlement and the ledger.

Late-arriving attribution

When merchant_txn_map rows are inserted after a period settlement was produced, the settlement understates the period and a variance appears. Resolution: regenerate the period settlement.

Observed live. Three merchant_txn_map rows were created after a settlement was generated, producing a 6,500 variance that exactly equalled the sum of those three rows. The authoritative ledger ↔ map leg tied to 0 — i.e. the ledger was always correct; only the snapshotted settlement was stale. Regenerating the period reconciled it.

Duplicate-attribution & invoice guards

RiskGuardEffect
Same offer attributed twice to one ledger entryUNIQUE(offer_id, ledger_entry_id)Second attribution rejected; no double-count.
Duplicate fulfilment-partner invoice for a periodUNIQUE(fp_id, period)One invoice per partner per period; reruns are idempotent.
Stale settlement after late map rowsRegenerate period settlementVariance clears; ledger was always authoritative.

Engagement: Events, Triggers & Scratch Cards

Scenario. The event-trigger + milestone + scratch-card layer introduces its own edge cases around replay, expiry, window boundaries and reward budgets. All of them resolve deterministically — the prize is fixed at issue time and every write is idempotent.

Edge caseTriggerBehaviour
Duplicate event replaySame eventRef posted again to POST /api/v1/events.Deduped on bank_event.event_ref (UNIQUE). Returns the original response with duplicate:true; no second evaluation, no second scratch card, no second ledger credit.
Scratch after expiryPOST /scratch-cards/:id/scratch on a card past expires_at.Card is terminal EXPIRED; returns 409. No prize revealed, no ledger credit. The loyalty-scheduler sweep sets ISSUED→EXPIRED at expires_at; a scratch attempt on an ISSUED-but-overdue card is also rejected 409.
Re-scratch (reveal replay)/scratch called again on a SCRATCHED card.Idempotent: returns the same prize and same ledgerEntryId. The POINTS credit used key scr:{scratchCardId}, so the second reveal never double-credits.
Milestone window rolloverProgress accrued in one weekly/monthly window carries into the next.Progress is keyed by UNIQUE(account_id, milestone_code, window_start). A new window opens a fresh row starting at 0; the prior window's progress does not leak forward. One reward per account per window.
First-occurrence raceTwo events of a first_occurrence type arrive near-simultaneously.Only one card is issued — the per-event/per-rule scratch_card.idempotency_key (evt:{eventRef}:{triggerId}) plus the first-occurrence check ensure the second event finds an existing match and does not issue again.
Prize draw when limits hitmax_per_window cap reached (e.g. SALARY_CREDIT max 1/month) or trigger paused/retired.Rule does not match; event is recorded but evaluations[].matched=false and no card is issued. If a campaign/trigger budget is exhausted, the reward is skipped and an ops signal is raised — the event still ingests successfully (200/201).
VOUCHER prize revealScratched card whose drawn prize is a VOUCHER.Voucher label/value recorded on the card; no ledger credit (fulfilment via the redemption stack). ledgerEntryId is null; balance unchanged.
Invariant. Because the prize is drawn and stored hidden at issue time, scratching is purely presentational — expiry, replay and budget edges can only affect whether a card is issued or revealed, never which prize a revealed card shows. See the sequence in CR-FLW-016.

Idempotency & Exactly-Once

Every value-mutating POST carries an idempotency key. Ledger entries enforce UNIQUE(idempotency_key), so a replay returns the original result with no re-execution — no double accrual, debit, claw-back, or credit. This is the single mechanism behind the idempotent behaviour seen in every section above.

OperationEndpointIdempotency keyReplay behaviour
AccrualPOST /transactions/{ref}/accrueper-transaction accrual keyReturns original accrual; no second credit.
Full reversalPOST /transactions/{ref}/reversereversal keyNo-op; original result with replayed=true.
Partial refundPOST /transactions/{ref}/reverse + refundAmountMinordistinct key per partial amountEach partial applied once; replay returns its result.
RedemptionPOST /redemptionsIdempotency-Key headerReturns original redemption; replayed=true.
Redemption reversalPOST :3005/redemptions/{id}/reversereversal keyCredits once; replay sets alreadyReversed=true.

Exception Catalogue

CodeHTTPMeaningCaller action
ACCRUAL_NOT_FOUND404No accrual exists for the referenced transaction.Verify the transaction ref; do not retry blindly.
ACCOUNT_NOT_ACTIVE422Account status is not active (dormant/blocked/closed).Resolve account status before redeeming; surface to support.
SKU_INACTIVE422Catalogue SKU is not currently redeemable.Pick an active SKU; refresh catalogue.
INSUFFICIENT_BALANCE422Available points are below the redemption cost.Reduce points requested or wait for next accrual.
INTERNAL_ERROR / point_balance_available_check500Fixed. Previously leaked when a clawback drove the balance negative.No longer reachable — clamp + clawback_pending handles the shortfall and returns 200.
For the end-to-end happy-path flows that these exceptions branch from, see CR-FLW-016. For the accrual / offer-grant engine, the ledger model and the clawback_pending recovery logic in context, see CR-AOG-018.