Share one pending predicate, and classify investment cash movements in one place

Merged
JA
2mo ago
+1865-89

Summary

One SQL definition of "pending" that agrees with Transaction#pending? everywhere, and one place that says what a cash movement in an investment account is. The second is built on the first, which is why they are one PR.

Fixes we-promise/sure#3556.

Fork pre-flight: jaysbeekay/sure#258. Same branch (up/pending-sql-parity). #258 was merged into the fork's copy of upstream main at e01ed2f87. The only commit since is 1c89d1159, a merge of upstream main (see Verification). An earlier pre-flight, jaysbeekay/sure#146, covered the first seven pending-SQL commits.

This PR absorbed we-promise/sure#3617 on 2026-09-29. The two were never a stack: their merge base was main, and #3617 carried its own copies of this PR's seven pending-SQL commits under different SHAs. Reviewing them apart meant reading the same 28 files twice, and landing this one first would have left #3617 rebasing one copy of those commits onto another. #3617 is closed; nothing was dropped, and the duplicated commits now appear once. History was linear on main when the two were combined. Since then, one merge of upstream main (1c89d1159, 2026-09-30) has resolved a conflict with #3603.

What changed

One pending predicate

  • Reusable pending and not-pending SQL predicates with ActiveModel boolean semantics, replacing provider-specific casts and duplicated conditions in import, reconciliation, analytics and cleanup queries.
  • The correlated SQL constant is built from fixed provider and boolean constants, so class loading opens no database connection and arbitrary JSON text is never cast to PostgreSQL boolean.
  • One false-value list (PENDING_FLAG_FALSE_VALUES_SQL) shared between the scope builder and the correlated constant, so the two cannot diverge.
  • A malformed provider namespace no longer aborts an import: Transaction.pending_extra? skips a scalar the way pending_sql does, where Hash#dig raised TypeError inside Account.transaction.

One place that classifies investment cash flow

  • Portfolio::FlowClassifier sorts every entry in an investment or crypto account into external_inflow, external_outflow, income, fee or internal, from one rule table, in two forms generated from it: #classify for tests and small sets, #sql_case for the daily queries a series needs. A parity test proves the two agree on every corpus entry, at two scopes.
  • Scope is a required argument, not a default: a transfer between two brokerages is internal to a family portfolio and external to either account alone.
  • Returns, allocation, income and contribution-room figures all need this split and need the same answer. Deriving it per reader is how the same dividend is counted as income in one place and a deposit in another.

Three corrections found in review

  • A security transfer whose opposite leg had a NULL excluded flag was read as excluded, so an internal journal became an external_outflow. Both lookups now use IS NOT TRUE.
  • A Contribution or Withdrawal label outranked an actual linked Transfer. With both legs in scope the movement is internal whatever either leg is labelled; an unlinked Contribution is unchanged.
  • The SimpleFIN importer excluded stale pending entries before counting them for review, and this PR's own work gave both steps the same definition of pending — so the exclusion marked exactly the rows the tracker then looked for. stale_unmatched_pending could not exceed zero, and the sync summary's "N pending transactions need manual review" never rendered. The two now sit behind one caller that counts first.

31 files changed: 1,813 insertions, 86 deletions, across 13 commits.

Demo data

None needed; no demo-facing surface.

Migration notes

No migration.

Verification

On head e01ed2f87, Ruby 3.4.9 and PostgreSQL 16:

  • Full suite: 10,235 runs, 43,351 assertions, 0 failures, 33 skips. The one error is local to this machine: RecurringTransaction::PipelineTest opens its own PG.connect and fails authentication on any branch here.
  • Focused run over test/models/portfolio, transaction_test, test/models/simplefin_item and test/models/account: 316 runs, 1,410 assertions, 0 failures.
  • Every correction above was observed to fail before its fix. The classifier's Ruby and SQL forms were each reverted in turn against the labelled-transfer test and both were caught; swapping the two stale-pending calls back gives Expected: 2, Actual: nil, which is also the proof the counter was dead.
  • bin/rubocop on the changed models, tests and support files: no offenses. No ERB or JavaScript changed.

On head 1c89d1159 (the merge of upstream main at 20352e1a0): every test file this PR changes, plus upstream's test/models/transaction/search_test.rb and test/controllers/transactions_controller_test.rb, which exercise the #3603 code the conflict sat beside. 383 runs, 1,945 assertions, 0 failures. bin/rubocop app/models/transaction.rb: no offenses. CI runs the full suite on this head.

Blast radius

The shared pending predicate reaches provider-import matching, entry reconciliation and status filters, income and goal calculations, and SimpleFIN stale-pending cleanup. The classifier has no application callers yet — it is the model layer the portfolio work is built on — so its blast radius today is its own tests and the parity between its two forms. Tests cover SQL parity and every touched reader.

Rebased onto main (6 Oct)

Rebased onto main at eb34c06f0; the commits carry the same changes under new SHAs, apart from the conflict resolutions below. SHAs elsewhere in this description refer to the commits as they were before.

  • bb2b62d3d → 4c1f70f5e Align provider SQL pending checks with model semantics
  • 1f77fcab9 → 9070485f1 Build correlated pending SQL lazily
  • 74c92d1d5 → e0972cb30 Build pending SQL without a boot-time connection
  • dab7c6949 → ef5248a3a Share one false-value list across pending SQL builders
  • 44b44fc80 → 6de906db2 Decide Monobank's stale pending prune the way Transaction#pending? does
  • 1b3f564a3 → 55ffd2987 Read pending provider metadata through one predicate
  • 380b71f70 → 1b297ddf7 State the leading-AND contract on pending_providers_sql
  • 17f5721d6 → e8de5d1c4 Classify every investment cash movement in one place
  • 03c2be5ff → a6c7a63be Read a NULL excluded flag as live on a security transfer's opposite leg
  • 03fc2b21f → 2cfbb5bca Count stale pending for review before the exclusion hides it
  • 6533077e4 → 705776ab5 State the flow classifier's caller contract: signed sums and family scoping
  • da6ebef3b → 97a3b6940 Drop the contract-gate claim this branch cannot back
  • e01ed2f87 → 7619d7091 Let the link outrank the label on a transfer inside the scope
  • 73bb97331 → 00a1493ef Read SimpleFIN pending flags through Transaction.pending_sql in rake tasks

Conflicts: app/models/transaction.rb: main's new AUTO_CATEGORY_SOURCES kept beside this PR's pending_sql in place of the old PENDING_CHECK_SQL.

bin/rails test on 00a1493ef: 10,633 runs, 45,529 assertions, 0 failures, 0 errors, 33 skips. bin/rubocop on the changed files: no offenses.

Summary by CodeRabbit

  • New Features
    • Investment activity can be classified as income, fees, internal movements, or external inflows and outflows, with transfers assessed across the selected accounts.
  • Bug Fixes
    • Pending transactions with unusual or malformed status values are handled more consistently, reducing errors in transaction matching, cleanup, and financial summaries.
    • Transactions marked as pending are no longer mistakenly treated as posted when determining matches or withdrawal candidates.
    • Pending-status handling now aligns across supported providers, including for values such as “no” and “off.”