Classify every investment cash movement in one place

Closed
JA
2mo ago
+1813-86

Pre-flight for the upstream PR we-promise/sure#3617, which is part of the upstream coordination issue we-promise/sure#3494.

Same branch, same commits. The upstream PR is opened from this branch (up/portfolio-flow-classifier), so there is no cherry-pick and no divergence to reconcile. This is the fork-side gate: its CI and Gatekeeper history is the review evidence that can't be seen from upstream.

Why this exists at all

Raised on 2026-09-25 because #3617 had no pre-flight. That breaches the fork's own cross-link rule: an upstream PR's description must name its fork pre-flight, and #3617 named none because none existed. The point of the rule is that a maintainer looking at an upstream PR can find where its CI, Gatekeeper and CodeRabbit history lives. For #3617 that was nowhere.

#3557 has the same gap in the other direction. Its pre-flight does exist (#146, merged on 2026-09-16), and #3557's body does name it, but the link is buried in a Verification bullet rather than in a dedicated cross-link line as #3617 has. That is the softer form of the failure the rule warns about: read only one direction of the link and the PR looks correctly linked. I have not edited #3557 here; it is flagged as a separate item.

What the change is

balances.cash_inflows cannot tell an external deposit from a dividend landing in cash, and those belong on opposite sides of a return: a deposit goes in the denominator, a dividend in the numerator. Counting one as the other misstates the figure in opposite directions, so a time-weighted return cannot be read off balances as they stand.

Portfolio::FlowClassifier answers that for one entry, or for a set of entry ids in one query, with the same rules either way. There are five classes: external_inflow, external_outflow, income, fee and internal. The class is decided by three things:

  • the activity label on the Trade or Transaction;
  • the transfer's counterpart;
  • whether that counterpart is inside the scope being measured.

Model only, no callers. Nothing reads it yet; the return series that does follows as its own PR.

The design choice worth arguing about

Scope decides what "internal" means. A position journalled between two accounts you own is internal and moves nothing. The same journal to an account outside the measured scope is external: from that scope's point of view, the money left. So the classifier takes scope_account_ids and answers relative to it, rather than holding one global answer per entry.

A label added to Transaction::ACTIVITY_LABELS without a rule in LABEL_RULES fails the test that compares the two, so a new label cannot silently fall into whatever the else-branch happens to be.

Reading the diff

It carries #3557's commits, exactly as the upstream PR does. This branch is cut from up/pending-sql-parity because the classifier's SQL path calls Transaction.pending_sql, which #3557 introduces. The alternative was inlining a second copy of the pending expression, which is precisely the inconsistency #3557 exists to remove.

Against mirror/upstream-main that shows as 31 files, +1723/−84. The three files this PR is actually asking about are:

  • app/models/portfolio/flow_classifier.rb
  • test/models/portfolio/flow_classifier_test.rb
  • test/support/portfolio_flow_test_helper.rb

Stack status, re-checked on 2026-09-26.

  • The mirror was merged into this branch (2f12dbe) to clear a conflict in test/models/account/provider_import_adapter_test.rb, where both sides had appended tests. Both sets were kept. db/ is byte-identical to the mirror.
  • #3557's own branch (up/pending-sql-parity) had the same conflict. It was resolved the same way on 2026-09-26 (merge commit, new head bb9e832), which also updated #3557 upstream.
  • Every #3557-owned file on that branch is now byte-identical to its copy here, across all 28 files.
  • This branch's copies of #3557's commits are replays with different SHAs, but the content matches.

Single-copy divergence (#118, duty 3)

dab9694 fixes a real finding from cubic. A security transfer whose opposite leg has a NULL excluded flag was treated as excluded, which made an internal journal read as external_outflow. Both the Ruby and the SQL opposite-leg lookups now use IS NOT TRUE, and a new test covers the NULL, false and true cases. It failed first on the unfixed code, and four deliberate breaks were each caught.

This means app/models/portfolio/flow_classifier.rb and test/models/portfolio/flow_classifier_test.rb currently differ from fork main. #237 ports the identical commit to fork main; it is green on CI and restores byte-identity across all three files. The divergence closes when #237 merges. test/support/portfolio_flow_test_helper.rb is unchanged and still identical.

Verification status

  • CI is green on head dab9694: test_unit, test_system, lint, lint_js, scan_ruby, scan_js and Codacy.
  • Local run on dab9694 (Ruby 3.3.6): test/models/portfolio/, the investment statement, entry and trade tests, and every file this PR touches. 378 runs, 0 failures. Rubocop is clean.
  • Gatekeeper: the last draft-gate APPROVE was at 2ec83e3e. A fresh review is needed at dab9694.
  • CodeRabbit does not apply on this base. The base is mirror/upstream-main, and CodeRabbit does not review a non-default base. That gate cannot close here, and its absence is not an outstanding request. The CodeRabbit review that matters is the upstream PR's own (we-promise/sure#3617).
  • Both cubic threads are now answered and resolved at ae94ba5fe; see the 2026-09-29 round below. Each was previously held as an owner decision, and each decision is stated there so it can be reversed.

Review follow-up

Pushed on 2026-09-29 with the owner's go-ahead: 4c0f3a404 on top of 9815218d. This branch is the head of we-promise/sure#3617, so that PR carries the same commit (same branch, same commit).

Finding (source)Status
Income and fee ignore the amount's sign (PRR non-blocking 1, MEDIUM)Fixed in 4c0f3a404 by stating the contract. The class comment now says callers sum signed amounts per class. That matches the one real caller, fork main's Portfolio::DailyReturns, which sums -entries.amount for income. New test: "income and fee are decided by label, not by the sign of the amount". It covers a positive-amount Interest transaction, a positive-amount Interest trade and a negative-amount Fee, in both #classify and #classify_ids, and checks each sign precondition first. It pins behaviour that already exists, so it passed before the change. Four sign-aware mutations were each caught: the Ruby transaction income rule, the Ruby transaction fee rule, the SQL income rule and the Ruby trade income rule.
Family scoping is left to the caller and not documented (PRR 3, MEDIUM)Fixed in 4c0f3a404. The class comment and #classify_ids now say that neither form filters by family, and that the caller passes only ids and accounts it has already scoped.
A linked-transfer counterpart's excluded flag is not checked (PRR 2, MEDIUM)OWNER DECISION. See the options below.
Scan for non-boolean pending flags before deploying layer (B) (PRR 4, MUST VERIFY 1)OWNER DECISION. This is a deploy-time data check. It cannot be done from the repository.
Comments cite files that exist only on the fork: the model's lines 19 and 50/75-77, and the test header (PRR 5 and SHOULD IMPROVE 1; cubic thread flow_classifier_test.rb:3)OWNER DECISION, carried over. Rewording the upstream copy breaks single-copy with fork main.
Pre-existing: stale-pending auto-exclusion runs with no match check (PRR 6, SHOULD IMPROVE 2)OWNER DECISION. It needs an upstream issue, and this sweep does not act on we-promise/sure.
cubic simplefin_item/importer_test.rb:131: the exclusion step runs before the counterOWNER DECISION, carried over. The code is #3557's and was already on the mirror.
Gatekeeper (2026-09-28): the "Single-copy divergence" section is staleAlready addressed at 9815218d: all three files matched fork main. 4c0f3a404 reopens the divergence for flow_classifier.rb and flow_classifier_test.rb. The same commit still needs porting to fork main, as #237 did: a follow-up for the owner.
Gatekeeper (2026-09-28): the branch is behind the mirrorAlready addressed by 9815218d, which merges mirror/upstream-main 1052443a, the current mirror head. None of the three classifier files changed.
cubic threads for rake_task_test_helper.rb:29, transaction.rb:160 and the NULL excluded legAlready resolved at dab9694b.

Verification at 4c0f3a404 (Ruby 3.3.6, locally). Ran test/models/portfolio, transaction_test, provider_import_adapter_test, investment_statement_test, entry_test, trade_test and simplefin_item/importer_test: 217 runs, 0 failures. Rubocop is clean.

Review follow-up — 2026-09-29

Two commits on top of 4c0f3a404, both answering cubic threads that earlier rounds had held open for the owner. The branch is the head of we-promise/sure#3617, so that PR carries them too.

ThreadDecision takenCommit
importer_test.rb:131 — the exclusion runs before the counter, so the asserted count is unreachable during a syncTaken, not deferred. The finding is larger than the test. This PR gave exclude_and_track_stale_pending and track_stale_unmatched_pending the same definition of pending (Transaction.pending_sql), so the exclusion now marks exactly the rows the tracker looks for, and stale_unmatched_pending cannot exceed zero in a real sync — the sync summary's "N pending transactions need manual review" never renders. The two steps now sit behind review_and_exclude_stale_pending, which counts first and excludes second.8d2492901
flow_classifier_test.rb:3 — the header claims a methodology document and a contract-coverage gate that this checkout has not gotTaken. docs/portfolio/methodology.md, config/portfolio_contract_tests.yml and portfolio:verify_contract_coverage are all fork-side; this branch is cut from upstream main and carries none of them. Removed the claim from all three places that made it — the classifier's own header (contract rows P1-P16), the test header and the flow test helper.ae94ba5fe

Evidence for 8d2492901. SimplefinItem::ImporterTest#test_stale_pending_review_counts_every_provider's_flag_before_the_exclusion_hides_it drives review_and_exclude_stale_pending rather than either step alone, and asserts stale_unmatched_pending, stale_pending_excluded, no reconciliation error, and which entry is left unexcluded. Observed to fail under the old order: swapping the two calls back gives Expected: 2, Actual: nil — which is also the proof that the stat was dead before this commit. ImporterStaleUnmatchedPendingTest still calls the tracker directly; those four cover the predicate itself, and its header now points at the ordering test.

Single-copy (#118, duty 3). ae94ba5fe's wording is true on the fork as well — the gate binds test names through config/portfolio_contract_tests.yml, not through the comment — so it ports to fork main unchanged, the way #237 ported dab9694. 8d2492901 touches app/models/simplefin_item/importer.rb, which fork main also holds; it needs the same port. Both are follow-ups for the owner.

Verification at ae94ba5fe. Full suite, Ruby 3.4.9, private Postgres and Redis: 10,096 runs, 42,828 assertions, 0 failures, 1 error and 33 skips. The error is the known environmental one — RecurringTransaction::PipelineTest opens its own PG.connect as the OS user and fails password auth. Rubocop clean on all six changed files.