Decide pending in SQL the way Transaction#pending? does
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 flag | PostgreSQL ::boolean | ActiveModel::Type::Boolean |
|---|---|---|
"no", "n", "False", "Off", "fa", " false" | false | true |
"maybe" | raises PG::InvalidTextRepresentation | true |
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.COALESCEmaps an absent flag or JSONnullto"", so no provider's term is ever NULL.
Built from it:
PENDING_CHECK_SQL,scope :pending,scope :excluding_pendingandpending_providers_sql.pending_providers_sqlkeeps its signature and its leadingAND, whichGoal::WithdrawalDetectorstrips.- The inline copies of the same predicate:
Entry.pending,Entry.reconcile_pending_duplicates,Transaction#pending_duplicate_candidates, andPendingDuplicateMergesController#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_pendingviaPENDING_CHECK_SQL. - Both status filters.
- Income statement: totals,
FamilyStatsandCategoryStats. - Goals:
InvestmentFlowStatement,Family#savings_inflow_velocity,Goal.pace_for, the funding breakdown andGoal::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 withPENDING_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, andsimplefin_pending_cleanup.rake. Portfolio::FlowClassifier.pending_sqlon #133 should delegate toTransaction.pending_sqlonce both are onmain.
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!andpending_duplicate_candidates,RecurringTransaction::Matcher, andProviderImportAdapter'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 test | Before the fix |
|---|---|
TransactionTest every SQL pending predicate agrees with pending? on any stored flag | Transaction.pending disagrees with pending? on "no" |
TransactionTest no SQL pending predicate raises on a flag PostgreSQL cannot cast | PG::InvalidTextRepresentation … "maybe" |
TransactionTest pending_duplicate_candidates offers only transactions pending? calls posted | PG::InvalidTextRepresentation … "maybe" |
IncomeStatementTest a pending flag PostgreSQL cannot cast neither raises nor counts | PG::InvalidTextRepresentation … "maybe" |
IncomeStatementTest a "no" pending flag is pending, as Transaction#pending? says | expected 4 transactions, got 5 |
Goal::WithdrawalDetectorTest ignores an outflow whose pending flag PostgreSQL cannot cast | PG::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 posted | reconciled 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.
| Mutation | Tests run | Caught by |
|---|---|---|
M1: the shared definition restores ::boolean IS TRUE | transaction, income statement, withdrawal detector | 7 red: both parity tests, candidates, both income statement tests, both detector tests |
M2: "" dropped from the false values | transaction | parity on nil/"", and candidates |
M3: COALESCE dropped | transaction | parity (absent flag gives NULL, so excluding_pending loses the row), and candidates |
M4: false values hardcoded as %w[false FALSE] instead of derived from ActiveModel | transaction | parity on "0"/"f"/0 |
M5: find_eligible_posted_entry back on the cast | merge controller | create rejects merge with a "no" transaction |
M6: reconcile_pending_duplicates back on the cast | entry | reconcile_pending_duplicates matches only twins pending? calls posted |
M7: pending_duplicate_candidates back on the cast | transaction | candidates (raises on "maybe") |
M8: Entry.pending back on the cast | transaction, entry | both 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 isRecurringTransaction::PipelineTest#test_run_with_lock!_refuses_to_stack_on_a_held_family_lock: its ownPG.connectover::1fails password authentication on this machine. It is environmental and unrelated to this change; CI runs it. bin/rubocoprepo-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/suremain; upstream'sPENDING_PROVIDERSalso listsmonobank. - Unaffected by #3408. Upstream's refactor (
IncomeStatement::ScopedTransactionsQueryand itstest/support/legacy_*copies) callsTransaction.pending_providers_sql(alias), whose signature this keeps. - Nothing to duplicate. Searches for
InvalidTextRepresentation, pending::booleanandexcluding_pendingfound 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_SQLto the shared definition.
The fork-only CLAUDE.md workflow section does not travel with it.
🤖 Generated with Claude Code