Decide pending in SQL the way Transaction#pending? does

Merged
JA
3mo ago
+488-78

Addresses #137. The triage plan and blast radius are in the issue comments. The follow-ups named there stay open, so this PR does not auto-close the issue.

What was wrong

Transaction#pending? casts each provider's flag with ActiveModel::Type::Boolean. Every SQL filter for the same question cast it with ::boolean instead. Checked against the test database:

stored flagPostgreSQL ::booleanActiveModel::Type::Boolean
"no", "n", "False", "Off", "fa", " false"falsetrue
"maybe"raises PG::InvalidTextRepresentationtrue

The raise aborts the whole query, not one row. That query can be the income statement, goal pace, the withdrawal detector, the status filter, or the balance calculators behind a sync.

The change

One definition on Transaction, and it never casts:

Transaction.pending_sql(table_alias = "transactions")
# COALESCE(<alias>.extra -> '<provider>' ->> 'pending', '') NOT IN ('0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF', '')
# OR'd across PENDING_PROVIDERS
Transaction.not_pending_sql(table_alias = "transactions")  # NOT (pending_sql)
  • Where the false values come from. They are derived from ActiveModel::Type::Boolean::FALSE_VALUES, plus "", so SQL cannot drift from the Ruby predicate.
  • Why NOT (...) is exact. COALESCE maps an absent flag or JSON null to "", so no provider's term is ever NULL.

Built from it:

  • PENDING_CHECK_SQL, scope :pending, scope :excluding_pending and pending_providers_sql. pending_providers_sql keeps its signature and its leading AND, which Goal::WithdrawalDetector strips.
  • The inline copies of the same predicate: Entry.pending, Entry.reconcile_pending_duplicates, Transaction#pending_duplicate_candidates, and PendingDuplicateMergesController#find_eligible_posted_entry. Leaving any of these on the cast would make SQL disagree with SQL.

Blast radius

The full caller table is in the triage comment and its addendum on #137. In short:

  • Every account balance sync: Entry.excluding_pending via PENDING_CHECK_SQL.
  • Both status filters.
  • Income statement: totals, FamilyStats and CategoryStats.
  • Goals: InvestmentFlowStatement, Family#savings_inflow_velocity, Goal.pace_for, the funding breakdown and Goal::WithdrawalDetector.
  • Pending merges: the manual merge flow and SimpleFIN's pending reconciliation and stale-pending auto-exclude. The auto-exclude is the only caller that writes on the answer.

Classification changes only for non-boolean strings. Every provider writes a JSON boolean or omits the flag:

  • SimpleFIN writes true/false, and Plaid copies Plaid's boolean.
  • Lunchflow casts first, and Enable Banking writes only true.
  • Akahu, Up, Mercury and Redbark write Ruby comparisons.

->> renders those as 'true'/'false'/NULL, which both rules classify identically. No expression index uses the old cast; transactions has only a GIN index on extra, which serves neither form.

Deliberately unchanged, and still casting:

  • Account::ProviderImportAdapter's three hardcoded eight-provider lists. Upstream already replaced them with PENDING_LOOKUP_SQL, so editing them here would conflict on the next sync.
  • The single-provider reads in the Akahu and Up processors, the SimpleFIN/Plaid pair in SimplefinItem::Importer, and simplefin_pending_cleanup.rake.
  • Portfolio::FlowClassifier.pending_sql on #133 should delegate to Transaction.pending_sql once both are on main.

Known residual divergence, documented in the code; no provider writes it: a JSON number 0.0 is pending in SQL but not to #pending?, because 0.0 == 0.

Fixed after review: a provider key holding a non-object (for example {"simplefin" => "bad", "plaid" => {"pending" => true}}) used to make #pending? raise inside Hash#dig and rescue the whole row to false, while SQL still saw plaid's flag. #pending? now skips a non-object provider value, the way SQL does.

  • Test: TransactionTest "malformed metadata under one provider does not hide another provider's flag". It was committed alone (bc112177c) and observed to fail: pending? should see plaid's flag past simplefin => "bad".
  • Blast radius: only rows with a non-object under a provider key change. The callers of Transaction#pending? are the Pending badges (transactions/_transaction, _header, show), PendingDuplicateMergesController#set_transaction, merge_with_duplicate! and pending_duplicate_candidates, RecurringTransaction::Matcher, and ProviderImportAdapter's posted-match guard. Every provider writes an object there.

Evidence

Observed to fail on main

The tests were committed alone (2b81b8099) and run before the fix (e2a90d3eb) existed: 111 runs, 5 failures, 4 errors, all nine of them new tests.

New testBefore the fix
TransactionTest every SQL pending predicate agrees with pending? on any stored flagTransaction.pending disagrees with pending? on "no"
TransactionTest no SQL pending predicate raises on a flag PostgreSQL cannot castPG::InvalidTextRepresentation … "maybe"
TransactionTest pending_duplicate_candidates offers only transactions pending? calls postedPG::InvalidTextRepresentation … "maybe"
IncomeStatementTest a pending flag PostgreSQL cannot cast neither raises nor countsPG::InvalidTextRepresentation … "maybe"
IncomeStatementTest a "no" pending flag is pending, as Transaction#pending? saysexpected 4 transactions, got 5
Goal::WithdrawalDetectorTest ignores an outflow whose pending flag PostgreSQL cannot castPG::InvalidTextRepresentation … "maybe"
Goal::WithdrawalDetectorTest ignores an outflow whose pending flag is "no"the "no" outflow was offered
EntryTest reconcile_pending_duplicates matches only twins pending? calls postedreconciled 1, expected 0 (the pending entry was excluded against a "no" twin)
PendingDuplicateMergesControllerTest create rejects merge with a transaction whose pending flag is "no"the merge went through (Entry.count changed)

With the fix: the same five files, 111 runs, 0 failures, 0 errors.

Mutations

Each mutation was applied to the committed fix, run against the named tests, and restored from HEAD. The script aborts if the tree is ever dirty.

All eight mutations were caught. The tree was clean after the round.

MutationTests runCaught by
M1: the shared definition restores ::boolean IS TRUEtransaction, income statement, withdrawal detector7 red: both parity tests, candidates, both income statement tests, both detector tests
M2: "" dropped from the false valuestransactionparity on nil/"", and candidates
M3: COALESCE droppedtransactionparity (absent flag gives NULL, so excluding_pending loses the row), and candidates
M4: false values hardcoded as %w[false FALSE] instead of derived from ActiveModeltransactionparity on "0"/"f"/0
M5: find_eligible_posted_entry back on the castmerge controllercreate rejects merge with a "no" transaction
M6: reconcile_pending_duplicates back on the castentryreconcile_pending_duplicates matches only twins pending? calls posted
M7: pending_duplicate_candidates back on the casttransactioncandidates (raises on "maybe")
M8: Entry.pending back on the casttransaction, entryboth parity tests

Each call site that #137 moved onto the shared definition has a test that goes red if that site alone regresses.

Checks

Run locally on e2a90d3eb:

  • Full suite (env -u ANTHROPIC_BASE_URL bin/rails test): 8703 runs, 36091 assertions, 0 failures, 1 error, 30 skips. The error is RecurringTransaction::PipelineTest#test_run_with_lock!_refuses_to_stack_on_a_held_family_lock: its own PG.connect over ::1 fails password authentication on this machine. It is environmental and unrelated to this change; CI runs it.
  • bin/rubocop repo-wide: 2564 files, no offenses.
  • bin/brakeman --no-pager: 0 warnings (9 ignored, unchanged).
  • No ERB changed.

Run again after the review fix to #pending? (head of this PR), on the pending-related files: transaction, income statement, withdrawal detector, entry, merge controller, RecurringTransaction (a #pending? caller) and ProviderImportAdapter (a #pending? caller). Result: 376 runs, 0 failures, 1 error. The error is the same environmental PipelineTest. Rubocop found no offenses.

Upstream

Labelled upstream:candidate on #137.

  • Same code upstream. The four fragments are identical on we-promise/sure main; upstream's PENDING_PROVIDERS also lists monobank.
  • Unaffected by #3408. Upstream's refactor (IncomeStatement::ScopedTransactionsQuery and its test/support/legacy_* copies) calls Transaction.pending_providers_sql(alias), whose signature this keeps.
  • Nothing to duplicate. Searches for InvalidTextRepresentation, pending ::boolean and excluding_pending found no existing upstream issue or PR.
  • The pitch. Hardening plus Ruby/SQL agreement, not a live misclassification.
  • One addition. The upstream PR should also switch ProviderImportAdapter::PENDING_LOOKUP_SQL to the shared definition.

The fork-only CLAUDE.md workflow section does not travel with it.

🤖 Generated with Claude Code