← Back to Pull requests

Resolve duplicate same-type Enable Banking balances deterministically #4344

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Oct 20, 2026 11:57 UTC
Author

Fixes #3188

Problem

Some banks report the same balance type twice with different amounts, for example two CLBD entries where one includes the arranged overdraft. select_current_balance used index_by, which silently keeps the last entry. Affected current accounts could show a balance inflated by the whole overdraft. That figure then fed net worth, reports and the daily balance anchors.

Behavior after this change

Same-type candidates are resolved in stages, strongest evidence first. Every real tie is logged once in /settings/debug, and logged again only when the candidates or the outcome change:

1. credit_limit (depository): the gap between the candidates equals the account's credit limit, so the lower one wins. This is direct evidence of an included overdraft, so it runs first.
2. last_committed_transaction: the candidates point to different known bookings, so the newer booking wins.
3. anchor (depository): a candidate matches (within 0.01) the previous anchor minus the bookings since then (anchor − Σ amount, outflows positive). This stage only runs when that anchor was verified when it was written and was written while this provider account was linked. It also requires that bookings dated on the anchor day don't change the answer. If several candidates match, the newer last_change_date_time wins (anchor_timestamp). With no match, the stage abstains.
4. Fallback: lowest for depository accounts (an included overdraft can only raise the figure), otherwise first in response order.

The same amount reported twice is not treated as a tie. When a fresher balance (XPCD/CLAV/ITAV) replaces an outdated OPBD/PRCD, the freshness check runs first. Duplicates of the fresher type on its newest date go through the same tiebreak. A duplicated OPBD that gets replaced anyway is neither resolved nor logged.

This works together with the available-first order for credit cards from #4277. For credit cards with a real tie, only the booking-reference stage applies. Otherwise they keep the first entry of the preferred type.

How

  • One migration adds two booleans to enable_banking_accounts (default false, reversible, no data conversion):

  • - The importer writes balance_evidence_verified together with current_balance. It is true when the balance was chosen without a tiebreak or by an evidence stage (credit_limit, last_committed_transaction, anchor).
    - balance_verified describes the current anchor. Only the processor sets it, right after set_current_balance succeeds, by copying the evidence flag. A sync that stops earlier never vouches for an older anchor, because a failed import makes the syncer skip processing. If processing fails, the processor clears the flag.
  • The balance refresh now runs after the transaction fetch, so the anchor stage sees this sync's bookings. It runs in its own rescue, so a failure in one step never skips the other or stops the import loop.

  • The anchor stage uses the same pending filters as the rest of the importer (PDNG, _pending, unidentified card holds) and the same date fallback as EnableBankingEntry::Processor#date (booking_date, then value_date, then transaction_date). If an amount can't be parsed, the stage abstains.

  • If several balances have unknown types, the first entry wins and counts as a heuristic pick, not as evidence.
  • Known limits

  • Balances already stored with the overdraft included stay in history. Only new syncs are corrected.

  • Banks that always report duplicates and don't send a credit limit or distinct booking references never get a verified anchor. For them, the lowest fallback decides.

  • If the stored bookings don't cover everything since the anchor, the anchor stage finds no match and abstains.

  • Credit cards and loans with real duplicates and no distinct booking references now keep the first entry instead of the last.

  • The processor still clears balance_verified when processing fails, even if the rolled-back transaction left the old anchor untouched. This is stricter than needed, but it fails safe.
  • Validation

  • Wrote a failing test reproducing #3188 first (it picked 5834.56 instead of 1234.56). Importer and processor tests then cover every stage, the sign convention (anchor 1000 with a DBIT of 50 gives 950, not 1050), anchor-day abstention, the value_date fallback, card holds, relinked accounts, log deduplication and both verification flags. Each review follow-up test fails on the code before its fix.

  • bin/rails test: 12469 runs, 0 failures, 0 errors.

  • bin/rubocop and bin/brakeman: no offenses, no warnings. There are no ERB, JS or UI changes, so ERB lint, Biome, system tests and screenshots don't apply.
  • <!-- This is an auto-generated comment: release notes by coderabbit.ai -->
    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

  • New Features

  • - Added balance verification tracking for connected bank accounts.
    - Improved balance selection using transaction, credit-limit, anchor, currency, freshness, and value evidence.
    - Account updates now reflect whether the selected balance is verified.
    - Transaction synchronization can continue when balance retrieval fails.
    - Improved transaction date handling across supported date and timestamp formats.

  • Bug Fixes

  • - Balance verification is cleared after processing failures or unverified balance updates.
    - Added clearer diagnostics for ambiguous or unsupported balance data.

  • Tests

  • - Expanded coverage for verification, tie-breaking, currency handling, refresh failures, and malformed balance responses.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jjmata Review duration: 971m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #4344"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%