Fix #301: remap/reset tolerate negative-qty/value holdings

Merged
JA
2mo ago
+322-21

Requested by Jonathan · project thread

Summary

Fixes #301.

Remapping a holding's security, or resetting it to the provider's security, now works when the holding has a negative quantity or amount. Before, Holding#remap_security! and #reset_security_to_provider! wrote those rows with save!/update!, which ran validates :qty, :price, :amount, numericality: { greater_than_or_equal_to: 0 } (app/models/holding.rb:22). A negative row (for example a full in-kind transfer out, which Holding::Materializer writes through upsert_all without validation) raised ActiveRecord::RecordInvalid, the transaction rolled back, and the user saw nothing change. A failure in either action now reaches the user as a flash alert on the redirect instead of an error response, is reported to the error tracker, and a failed remap changes nothing.

Scope and dependencies

  • Issue: #301 (bug). Its triage plan was approved in the Issue Gatekeeper review on the issue.
  • Parent PR/branch, if stacked: none. Base is main.
  • Intentionally out of scope (as the #301 triage plan states): relaxing the >= 0 validation for ordinary edits, and changing how the trade form resolves a ticker to a security record (the cause of the duplicate records).

What changed

FileChange
app/models/holding.rbremap_security!: the collision merge uses existing.update_columns(merge_attrs) instead of update!; the plain move uses update_columns(security_id:, security_locked: true, provider_security_id:) instead of save!. reset_security_to_provider!: holding.update! becomes update_columns(security_id:, security_locked: false, provider_security_id: nil). Only the columns the remap or reset owns are written, plus updated_at, which update_columns would otherwise leave alone and InvestmentStatement#holdings_version keys cached series on.
app/controllers/holdings_controller.rb#remap_security saves the chosen security, remaps and re-materializes inside one ActiveRecord::Base.transaction, wrapped in rescue StandardError, which logs a warning, calls Rails.error.report(e, handled: true) and redirects with holdings.remap_security.failed. #reset_security rescues the same way with holdings.reset_security.failed.
config/locales/views/holdings/en.ymlAdds the two failed strings.
test/models/holding_test.rbSix tests (below).
test/controllers/holdings_controller_test.rbFour tests (below).

Blast radius

remap_security! is called only from HoldingsController#remap_security (the "Security" pencil form and the "switch provider" auto-submit form in app/views/holdings/show.html.erb). reset_security_to_provider! is called only from HoldingsController#reset_security. After a remap the controller re-materializes with security_ids: [new_security.id], so the qty and amount the remap writes are transient. Holding has no save callbacks, so update_columns skips nothing beyond validations and the timestamp, which is now set explicitly.

Balance::Materializer#materialize_balances runs its own Balance.transaction, which joins the outer one. A database rollback cannot undo an exchange-rate provider request made while re-materializing; that is a boundary of the rollback, not a new side effect.

Write audit inside the two methods: existing.update! and holding.save! in remap_security!, and holding.update! in reset_security_to_provider!, are changed. holding.destroy! (no validations) and the two account.trades...update_all(security_id:) calls are deliberately unchanged. A grep of update_columns in Holding and HoldingsController finds only the three writes above, all of which set updated_at.

Evidence checklist

  • Each issue in this PR has its own acceptance criteria and no unrelated
    issue work is included.
  • Contract rows touched by this change name existing tests.
  • Any gate test has an observed failing mutation transcript attached.
  • Fixtures used as evidence assert internal consistency.
  • Financial calculations use BigDecimal and documented rounding points.
  • De-identification uses token-shape allowlists; no personal data is
    included.
  • Files changed, decisions, tests/runtime, risks, and next unblocked issue
    are documented below.

The unticked rows: the change adds no fixtures and no financial calculation.

Tests

Model (test/models/holding_test.rb):

  • remap_security! moves a negative-amount holding onto another security (no collision): a -22 / -3187.80 row moves onto the other record with its qty and amount intact, locked, and with provider_security_id set.
  • remap_security! merges a holding into a negative target without raising (collision): a +15 / 3240 AMZN row merges into a -22 / -4000 target; one row remains with qty -7 and amount -760.
  • reset_security_to_provider! moves a negative-qty holding back without raising.
  • remap_security! bumps updated_at on a moved holding, ... on the row it merges into, and reset_security_to_provider! bumps updated_at on the holdings it moves back: each sets every holding's updated_at two days back first, then asserts the written rows moved past it.

Controller (test/controllers/holdings_controller_test.rb):

  • remap_security on a negative-amount holding redirects with success notice (no stub on the model).
  • remap_security rolls the remap back when re-materialising fails: the real remap runs, then materialize_balances raises. Asserts the error is reported, the alert, no new Security, the holding on its old security and unlocked, and the trades unmoved.
  • remap_security with a security that cannot be saved shows an alert: an unknown price provider fails new_security.save!; asserts a redirect with the alert, not a 422.
  • reset_security rolls the reset back when a holding write fails: the trades move back, then the holding write (expected to be reached) raises. Asserts the error is reported, the alert, and that the trades and holding are still on the remapped security.

Existing remap and reset tests are unchanged.

Validation

Commands and results:

  • Fail first. On c942f83, five of the six tests added in 7adabdd fail: the three updated_at tests (timestamp unchanged), the re-materialise rollback test (a new Security persisted and the holding moved), and the unsaveable-security test (422, not a redirect). The reset rollback test passes on c942f83 too, because reset_security_to_provider! already wrote in one transaction; it answers the Gatekeeper's MINOR finding rather than a defect.

  • Mutation transcript. bin/rails test test/models/holding_test.rb test/controllers/holdings_controller_test.rb, with each change broken in turn:

    MutationResult
    Controller: drop the transaction around save, remap and materialise1 failure: remap_security rolls the remap back when re-materialising fails
    Drop updated_at from the merge write1 failure: bumps updated_at on the row it merges into
    Drop updated_at from the plain move1 failure: bumps updated_at on a moved holding
    Drop updated_at from the reset write1 failure: reset ... bumps updated_at on the holdings it moves back
    Restore save!/update! in remap and reset (the #301 plan's mutation)3 errors (RecordInvalid) in the three negative-row model tests, 2 failures in the negative-remap and reset-rollback controller tests
    Drop both Rails.error.report calls (463c492)2 failures: both controller rollback tests
    Merge ignores the moved row's amount (463c492)2 failures: both collision tests

    Unmutated on 463c492: 60 runs, 199 assertions, 0 failures.

  • bin/rails test (full suite on 7adabdd, locally on Ruby 3.3.6): 11,767 runs, 4 failures, 1 error, 33 skips, none in this change. Four are Anthropic settings and registry tests that read the sandbox's ANTHROPIC_BASE_URL; with it unset they pass. One is Provider::OpenaiTest "extra_headers stringifies nested values Ruby-style", which expects Ruby 3.4's Hash#inspect format (the repo pins 3.4.9). CI runs the pinned Ruby.

  • bin/rubocop on the changed Ruby files: no offenses.

  • bin/brakeman --no-pager: 0 warnings.

  • erb_lint: no ERB changed.

  • CI on 7adabdd was all green; CI on 463c492 is running.

Risks, blockers, and follow-up

  • reset_security does not re-materialize, which is unchanged. Bumping updated_at on the reset rows is what moves the cached series key for it.
  • The chosen Security row is saved inside the remap transaction, so if it already exists its row lock is held through re-materialization, which can wait on an uncached exchange-rate fetch. CodeRabbit rated this low and inferred. It is kept, because the atomic commit is what makes the failure alert true; bounding the exchange-rate wait would be a separate change.
  • The reset rollback test injects its failure through Holding#update_columns, the only write after the trade move, and now expects that call. A revert to update! fails it by name; the reset model test remains the behavioural guard.
  • Follow-up already named in #301: the trade form resolving one ticker to two security records.