Leave a clamped position's basis unknown, and read lot costs back

Merged
JA
1mo ago
+153-23

Part of jaysbeekay/sure#551. This is PR 3b of the stack (PR 3 #582 ← PR 3b ← 4 ← 5; owner decision 15). It is stacked on #582, so its base is feat/551-lot-basis-pr3-lot-editor and the diff shows only this slice. It is retargeted to main when #582 merges.

Problem

  1. A clamped position still reports a figure. When the provider holds fewer units than the imported trades bought, 1b records a clamp (decision 9), but the figure is unchanged: the trades' average is applied to units the provider says aren't there. On the fixture, 10 bought at $100 and $150 against 3 held still reads $125, and no data-quality entry says anything is wrong.
  2. A linked account's current row ignores lot costs (#582's open point). Where the provider gives no cost, Holding#avg_cost falls back to the trades. That fallback, and its batched preload, refuse any position with a transfer-in, even after the user has costed that transfer-in's lot.

What this changes

  • The reverse calculator reports a clamped position's basis as unknown on every date, and marks it unknown, so the materializer clears a figure stored on an earlier run.
  • The avg-cost fallback, in both paths: Holding#calculate_avg_cost (Ruby) and Holding.preload_avg_costs (SQL) each answer nil for a clamped position. Each now counts a trade whose lot the user has costed at that cost, a transfer-in included. Both paths stay within their existing query budgets: two trades queries for the Ruby path, and one for the preload.
  • A data-quality kind, quantity_mismatch ("Fewer units than the trades"). It replaces "Missing cost basis" for such a position, with a "Review position" link, since setting a cost won't fix it. The preload already works out the clamp, so it hands it to the holding (Holding#quantity_mismatch?) with no extra query.

Not in this PR, and why:

  • Unclamping. The next reverse sync already unclamps a position the provider brings back above its trades (1b), and the figure returns with it.
  • The preload checks only the Transfer label, while the Ruby fallback checks every internal-movement label. This predates the lot work and is unchanged here.

Screenshots

The portfolio's data-quality section, with a position of 10 bought against 5 held and its clamp recorded. The before shots are from #582's head: the trades' $100 stands in, and nothing is flagged. The after shots are from this PR. Both were rendered headless by a throwaway system test on the test containers, with fixture data.

BeforeAfter
Desktop (1400px)beforeafter
Phone (390px)before phoneafter phone

Blast radius

Who else hits these lines, and what do they pass?

  • The fallback is reached from Holding#avg_cost, and in batch from InvestmentStatement#holdings_with_avg_costs and Portfolio::RealizedGains. Both paths change together, and the query-count tests on each still pass (the fallback reads the trades in two queries, data_quality_issues issues a bounded number of queries).
  • A clamped position's sales now read an unknown basis (:missing_cost_basis), from the snapshot and from fifo disposals alike. A clamped position is out of partition, so HoldingLotDisposal.readable_by_sale already falls back to the snapshot.

What else reads what changed (siblings):

  • clamped, read via grep -rn clamped app: the reverse calculator (writes it), the materializer (stores it), and now the two fallbacks. Nothing else reads it.
  • The partition guard (decision 12) is deliberately not applied to the clamp. A clamped position is out of partition by definition: its trades exceed the holding. The read only ever makes a figure unknown.

Tests

test/models/holding_lot_test.rb; the bracket says what each assertion catches.

  • provider quantity below trade-derived quantity makes the position unknown [nil, where the trades give $125; the control keeps $102.50].
  • an unclamped position that the provider drops below its trades is clamped, extended [$102.50 stored, then cleared once the provider drops below].
  • the avg-cost fallback and its batched preload answer nil for a clamped position [nil from both; the control is unchanged and equal in both].
  • a clamped position raises its own data-quality entry, in place of a missing cost basis [quantity_mismatch and not missing_cost_basis; the control is not flagged; the copy exists].
  • the avg-cost fallback counts a user-set lot cost, so a linked position resolves [the provider row is nil, then $15.20 with the transfer-in costed, then $13.20 with the buy costed, in both paths].

Changed tests:

  • 1b's provider quantity below trade-derived quantity clamps the opening lot and records it no longer pins the $125 figure, which this slice changes by design (decision 15). The new test above owns it.
  • Two ReverseCalculatorTest cases bought 15 against a provider holding fixed at 10, so they were clamped positions without meaning to be. They now pass held: 15. The helper's default stays 10, because a split test relies on it.

Evidence

Fail first. On #582's head (d00ca826f), the four new tests fail for the expected reasons: $125 where nil is expected (twice), no quantity_mismatch entry, and nil where $15.20 is expected.

Mutations (9, all caught):

#MutationCaught by
C1the reverse calculator keeps the figuremakes-unknown test
C2the clamp not marked unknowndrop-below test (stored figure not cleared)
C3no clamp check in the Ruby fallbackfallback/preload test
C4no clamp check in the preloadfallback/preload test, data-quality test
C5the Ruby fallback ignores lot costslinked-position test
C6the preload ignores lot costslinked-position test
C7the kind is always missing_cost_basisdata-quality test
C8the preload still refuses a costed transfer-inlinked-position test
C9the Ruby fallback still refuses a costed transfer-inlinked-position test

Full suite at 1e3d515b1: 14397 runs, 66878 assertions, 0 failures, 0 errors, 38 skips. bin/rubocop, erb_lint and bin/brakeman (0 warnings) are clean.

AGENTS.md

I checked the change against the current we-promise/sure AGENTS.md:

  • Code placement: models only.
  • Performance: no new queries on the batched paths.
  • Copy: every string through t() (portfolios.data_quality.kinds.quantity_mismatch.*, review_position).
  • Comments: intent only.
  • Migrations, API: none.
  • Screenshots: included above.
  • Commit: the subject is ≤72 characters.

Summary by CodeRabbit

  • Bug Fixes

    • Manually entered lot costs are now included when calculating a holding’s cost basis.
    • Positions where reported units are fewer than imported trades no longer show a potentially misleading cost basis.
  • New Features

    • Quantity mismatches are identified as a data-quality issue, with a “Review position” option for writable accounts. Read-only accounts continue to show a read-only label.