Fix #301: remap/reset tolerate negative-qty/value holdings
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
>= 0validation for ordinary edits, and changing how the trade form resolves a ticker to a security record (the cause of the duplicate records).
What changed
| File | Change |
|---|---|
app/models/holding.rb | remap_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.yml | Adds the two failed strings. |
test/models/holding_test.rb | Six tests (below). |
test/controllers/holdings_controller_test.rb | Four 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
BigDecimaland 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 withprovider_security_idset.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, andreset_security_to_provider! bumps updated_at on the holdings it moves back: each sets every holding'supdated_attwo 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, thenmaterialize_balancesraises. Asserts the error is reported, the alert, no newSecurity, 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 failsnew_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 in7adabddfail: the threeupdated_attests (timestamp unchanged), the re-materialise rollback test (a newSecuritypersisted and the holding moved), and the unsaveable-security test (422, not a redirect). The reset rollback test passes onc942f83too, becausereset_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:Mutation Result Controller: drop the transaction around save, remap and materialise 1 failure: remap_security rolls the remap back when re-materialising failsDrop updated_atfrom the merge write1 failure: bumps updated_at on the row it merges intoDrop updated_atfrom the plain move1 failure: bumps updated_at on a moved holdingDrop updated_atfrom the reset write1 failure: reset ... bumps updated_at on the holdings it moves backRestore 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 testsDrop both Rails.error.reportcalls (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 on7adabdd, 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'sANTHROPIC_BASE_URL; with it unset they pass. One isProvider::OpenaiTest"extra_headers stringifies nested values Ruby-style", which expects Ruby 3.4'sHash#inspectformat (the repo pins 3.4.9). CI runs the pinned Ruby. -
bin/rubocopon the changed Ruby files: no offenses. -
bin/brakeman --no-pager: 0 warnings. -
erb_lint: no ERB changed. -
CI on
7adabddwas all green; CI on463c492is running.
Risks, blockers, and follow-up
reset_securitydoes not re-materialize, which is unchanged. Bumpingupdated_aton the reset rows is what moves the cached series key for it.- The chosen
Securityrow 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 toupdate!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.