The personal finance app for everyone (by everyone)
Ruby
fix(goals): stop two goals from each claiming the same account in full (#3160)
buzzromain7a86ee47c50f
diff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rbindex 684b5ce0a9..7e193e4603 100644--- a/app/controllers/goals_controller.rb+++ b/app/controllers/goals_controller.rb@@ -46,6 +46,7 @@ class GoalsController < ApplicationControllercurrency: Current.family.primary_currency_code)@linkable_accounts = linkable_accounts_for_new+ @currently_linked_account_ids = []@breadcrumbs = plan_breadcrumb_prefix + [[ t("goals.index.title"), goals_path ],[ t("goals.new.heading"), nil ]@@ -72,6 +73,12 @@ class GoalsController < ApplicationControllerendrescue ActiveRecord::RecordInvalid@linkable_accounts = linkable_accounts_for_new+ # From the in-memory links, not `pluck`: nothing is persisted on a failed+ # create, so a query would come back empty and every box the user ticked+ # would render unchecked. The amounts survived — the form reads those off+ # the same built records — so the user was left staring at an error telling+ # them to enter an amount, on a form whose accounts had silently cleared.+ @currently_linked_account_ids = @goal.goal_accounts.map { |ga| ga.account_id.to_s }render :new, status: :unprocessable_entityenddiff --git a/app/models/goal.rb b/app/models/goal.rbindex 8d43946014..edee4c41bb 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -4,6 +4,16 @@ class Goal < ApplicationRecordCOLORS = Category::COLORSICONS = Category.icon_codes+ # States in which a goal has let go of its money: `Goal.pooled_allocations_for`+ # leaves it out of the backing math, so its links reserve nothing and the+ # account it pointed at is free again.+ #+ # Read by three places that must agree — the shared pool, GoalAccount's+ # exclusivity check, and the restore guard below. Keeping them on one constant+ # is what stops the double-counting hole from reopening the day this set+ # grows: adding a state here makes every one of them release together.+ RELEASED_STATES = %w[archived].freeze+validates :icon, inclusion: { in: ICONS, allow_nil: true }validates :color, format: { with: /\A#[0-9A-Fa-f]{6}\z/ }, allow_nil: true@@ -30,6 +40,14 @@ class Goal < ApplicationRecordvalidate :linked_accounts_must_match_goal_currencyvalidate :linked_accounts_must_belong_to_familyvalidate :currency_locked_once_linked+ validate :restore_must_not_recreate_whole_account_conflict++ # Autosave validates each link separately, so each would otherwise take its+ # own account lock in association order. Two goals saving links on the same+ # two accounts in opposite orders would then hold one lock each and wait on+ # the other. Taking the whole set here, sorted, before any child validates,+ # is what makes the order the same for everyone.+ before_validation :lock_whole_account_claims_in_ordermonetize :target_amount@@ -53,7 +71,7 @@ class Goal < ApplicationRecorddef self.pooled_allocations_for(family)GoalAccount.joins(:goal).where(goals: { family_id: family.id })- .where.not(goals: { state: "archived" })+ .where.not(goals: { state: RELEASED_STATES }).pluck(:account_id, :goal_id, :allocated_amount).group_by(&:first).transform_values do |triples|@@ -61,6 +79,69 @@ class Goal < ApplicationRecordendend+ # Whole-account links held by OTHER goals of this family on any of+ # `account_ids` — the links that would double-count the balance if this goal+ # claimed one of those accounts in full too.+ #+ # Shared by GoalAccount's exclusivity validation (which asks about the one+ # account being written) and by the restore guard (which asks about every+ # account this goal claims in full). One query, one scope: the two cannot+ # drift into disagreeing about what "already claimed" means.+ # `excluding_link_id` is the row being written, when there is one. Excluding+ # by goal alone is not enough for a link that is CHANGING goals: its persisted+ # row still carries the old goal_id, so the query hands it back and the link+ # conflicts with itself.+ # A whole-account claim is exclusive per account, and the check that enforces+ # it is a read. Callers take this first so the read and the write that+ # follows are one step as far as any other request is concerned.+ def self.lock_whole_account_claims!(account_id)+ # Bound rather than interpolated. The key is a digest of an id and could+ # not carry a payload, but a hand-built SQL string in a model is the shape+ # a reader has to stop and verify — and Brakeman flags it, correctly.+ # Projected through a subquery so the result set is an integer, not the+ # `void` the lock function returns — which the adapter cannot type and+ # logs a warning about on every acquisition.+ connection.exec_query(+ "SELECT 1 FROM (SELECT pg_advisory_xact_lock($1)) locked",+ "Goal Whole-Account Claim Lock",+ [ ActiveRecord::Relation::QueryAttribute.new(+ "key", whole_account_claim_lock_key(account_id), ActiveRecord::Type::BigInteger.new+ ) ]+ )+ end++ def self.whole_account_claim_lock_key(account_id)+ Digest::SHA1.hexdigest("goal_accounts:whole_account:#{account_id}").to_i(16) % (2**63)+ end++ def whole_account_conflicts_on(account_ids, excluding_link_id: nil)+ ids = Array(account_ids).compact+ return GoalAccount.none if ids.empty?++ # Serialised before the read, because what follows is a check-then-write:+ # two requests can both find no conflict and both commit a whole-account+ # claim, recreating exactly the double-count this exists to prevent. A+ # transaction-scoped advisory lock rather than a row lock — the conflicting+ # write may be an INSERT, so there is no row to lock — and it is released+ # when the enclosing transaction ends, whichever way it ends.+ #+ # Locked in id order so two goals claiming the same pair of accounts in+ # opposite orders cannot deadlock against each other. Saving a goal takes+ # the whole set up front (see `lock_whole_account_claims_in_order`); this+ # covers a link saved on its own, and re-taking a lock the transaction+ # already holds costs nothing.+ ids.sort.each { |account_id| self.class.lock_whole_account_claims!(account_id) }++ scope = GoalAccount.joins(:goal)+ .where(account_id: ids, allocated_amount: nil)+ .where(goals: { family_id: family_id })+ .where.not(goals: { state: RELEASED_STATES })++ scope = scope.where.not(goal_id: id) if persisted?+ scope = scope.where.not(id: excluding_link_id) if excluding_link_id+ scope+ end+attr_writer :pooled_allocations# Family-wide map of cumulative market gain/loss per account_id (sum of@@ -767,4 +848,48 @@ class Goal < ApplicationRecorderrors.add(:currency, :locked_after_linked)end++ # Archiving a goal frees the accounts it claimed in full, so another goal+ # can legitimately claim one of them while it is away. Restoring it would+ # then put two whole-account links back on the same account and reopen the+ # double-counting `GoalAccount#whole_account_link_must_be_exclusive` closes+ # — that check only fires when a link is written, and a state change writes+ # none.+ #+ # A validation rather than an AASM guard: `may_fire_event?` stays true, the+ # save fails, and GoalsController#perform_transition! already surfaces+ # `errors.full_messages`. The user reads which goal holds the account+ # instead of a generic "can't do that in this state".+ def restore_must_not_recreate_whole_account_conflict+ return unless will_save_change_to_state?++ previous_state, next_state = state_change_to_be_saved+ return unless previous_state.in?(RELEASED_STATES)+ return if next_state.in?(RELEASED_STATES)++ conflict = whole_account_conflicts_on(own_whole_account_ids).first+ return if conflict.nil?++ errors.add(+ :base,+ :whole_account_conflict_on_restore,+ goal_name: conflict.goal.name,+ account_name: conflict.account.name+ )+ end++ # Accounts this goal claims in full. Read from the loaded association so it+ # is correct for a goal whose links were built but not yet saved.+ def lock_whole_account_claims_in_order+ ids = own_whole_account_ids+ ids |= goal_accounts.filter_map { |ga| ga.account_id if ga.will_save_change_to_allocated_amount? }+ ids.compact.uniq.sort.each { |account_id| self.class.lock_whole_account_claims!(account_id) }+ end++ def own_whole_account_ids+ goal_accounts+ .reject(&:marked_for_destruction?)+ .select(&:whole_account?)+ .filter_map(&:account_id)+ endenddiff --git a/app/models/goal_account.rb b/app/models/goal_account.rbindex 57f906db6e..2c38626353 100644--- a/app/models/goal_account.rb+++ b/app/models/goal_account.rb@@ -7,6 +7,8 @@ class GoalAccount < ApplicationRecordnumericality: { greater_than_or_equal_to: 0 },allow_nil: true+ validate :whole_account_link_must_be_exclusive+# nil allocated_amount means "dedicate the whole account balance" (the v1# default). A set amount earmarks a fixed slice of the account toward this# goal. The share that actually counts toward the goal — after sibling@@ -15,4 +17,43 @@ class GoalAccount < ApplicationRecorddef whole_account?allocated_amount.nil?end++ private+ # A whole-account link claims the account's ENTIRE balance, so two of them+ # on one account double-count it. Goal#backing_share_for's pro-rata haircut+ # can't catch this: it only scales FIXED earmarks, and an unallocated link+ # contributes nil.to_d — zero — to `others_fixed`, so the two links never+ # see each other. Both then read the full balance and both show 100%.+ # The invariant "shares never sum past the balance" is therefore enforced+ # at the door instead of in the math.+ #+ # The conflict lookup itself lives on Goal (`whole_account_conflicts_on`),+ # scoped to Goal::RELEASED_STATES — exactly the set+ # Goal.pooled_allocations_for feeds into the backing math. Sharing one+ # method with the restore guard is what keeps this door and that one from+ # disagreeing about which goals still hold their money.+ def whole_account_link_must_be_exclusive+ return unless whole_account?+ return if account_id.nil? || goal.nil?+ # Only guard what is being written now. Rows that predate this+ # validation stay readable and editable: autosave revalidates every+ # loaded goal_account on goal.save, and blocking there would make a+ # goal that merely holds a legacy overlap impossible to rename.+ #+ # "Written now" has to include moving the link, not just re-pricing it.+ # A whole-account row whose account_id or goal_id changes is neither new+ # nor allocation-dirty, so on those two predicates alone it would land on+ # an account nobody checked — the same hole as a restore, through a+ # different door. Widening the bound rather than dropping it: the reason+ # above still holds for every row that is merely along for the ride.+ return unless new_record? ||+ will_save_change_to_allocated_amount? ||+ will_save_change_to_account_id? ||+ will_save_change_to_goal_id?++ other = goal.whole_account_conflicts_on(account_id, excluding_link_id: id).first+ return if other.nil?++ errors.add(:base, :account_already_fully_earmarked, goal_name: other.goal.name)+ endenddiff --git a/app/views/goals/_form.html.erb b/app/views/goals/_form.html.erbindex 6b53c230d8..c87d96a6a3 100644--- a/app/views/goals/_form.html.erb+++ b/app/views/goals/_form.html.erb@@ -85,6 +85,13 @@<% end %></div><p class="<%= "hidden" unless goal.errors[:base].any? %> mt-1.5 text-xs text-destructive" data-goal-form-target="accountsError"><%= t("goals.form.errors.accounts_required") %></p>+ <%# Server-side only: GoalAccount refuses a second whole-balance link on an+ account another goal already claims in full. There is no client-side+ equivalent to mirror, so this renders straight from the record rather+ than through a goal-form target (the controller is already at 10). %>+ <% goal.errors.where(:"goal_accounts.base").each do |error| %>+ <p class="mt-1.5 text-xs text-destructive"><%= error.message %></p>+ <% end %></div><%= f.text_area :notes,diff --git a/app/views/goals/new.html.erb b/app/views/goals/new.html.erbindex 40bd104b93..758727244e 100644--- a/app/views/goals/new.html.erb+++ b/app/views/goals/new.html.erb@@ -13,7 +13,7 @@</div><% end %><% dialog.with_body do %>- <%= render "form", goal: @goal, linkable_accounts: @linkable_accounts %>+ <%= render "form", goal: @goal, linkable_accounts: @linkable_accounts, currently_linked_account_ids: @currently_linked_account_ids %><% end %><% end %><% else %>@@ -25,6 +25,6 @@<p class="text-sm text-secondary mt-0.5"><%= t(".subtitle") %></p></div></header>- <%= render "form", goal: @goal, linkable_accounts: @linkable_accounts %>+ <%= render "form", goal: @goal, linkable_accounts: @linkable_accounts, currently_linked_account_ids: @currently_linked_account_ids %></div><% end %>diff --git a/config/locales/models/goal/en.yml b/config/locales/models/goal/en.ymlindex cbe2b28a94..f4a1a5a552 100644--- a/config/locales/models/goal/en.yml+++ b/config/locales/models/goal/en.yml@@ -17,6 +17,7 @@ en:attributes:base:at_least_one_linked_account_required: Pick at least one account to fund this goal.+ whole_account_conflict_on_restore: "Can't restore this goal: “%{account_name}” is now fully earmarked for “%{goal_name}”. Enter an amount on one of them first."linked_accounts:must_be_fundable: All linked accounts must be cash or investment accounts.currency_mismatch: All linked accounts must share the same currency.diff --git a/config/locales/models/goal/fr.yml b/config/locales/models/goal/fr.ymlindex 64cb7aa1dd..0a08fe66a6 100644--- a/config/locales/models/goal/fr.yml+++ b/config/locales/models/goal/fr.yml@@ -17,6 +17,7 @@ fr:attributes:base:at_least_one_linked_account_required: Sélectionnez au moins un compte pour financer cet objectif.+ whole_account_conflict_on_restore: "Impossible de restaurer cet objectif : « %{account_name} » est désormais entièrement affecté à « %{goal_name} ». Indiquez d'abord un montant sur l'un des deux."currency:locked_after_linked: Impossible de modifier la devise après que l'objectif a été lié à des comptes.linked_accounts:diff --git a/config/locales/models/goal_account/en.yml b/config/locales/models/goal_account/en.ymlnew file mode 100644index 0000000000..9747754974--- /dev/null+++ b/config/locales/models/goal_account/en.yml@@ -0,0 +1,9 @@+---+en:+ activerecord:+ errors:+ models:+ goal_account:+ attributes:+ base:+ account_already_fully_earmarked: This account is already fully earmarked for “%{goal_name}”. Enter an amount to split it.diff --git a/config/locales/models/goal_account/fr.yml b/config/locales/models/goal_account/fr.ymlnew file mode 100644index 0000000000..95c241b9bc--- /dev/null+++ b/config/locales/models/goal_account/fr.yml@@ -0,0 +1,9 @@+---+fr:+ activerecord:+ errors:+ models:+ goal_account:+ attributes:+ base:+ account_already_fully_earmarked: Ce compte est déjà entièrement affecté à l'objectif « %{goal_name} ». Indiquez un montant pour le partager.diff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rbindex cd2023d62f..30b9a0b4d4 100644--- a/test/controllers/goals_controller_test.rb+++ b/test/controllers/goals_controller_test.rb@@ -45,6 +45,13 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestendtest "create persists a goal with linked accounts" do+ # Fresh accounts: the goal fixtures already claim @depository and+ # @connected in full, and GoalAccount refuses a second whole-balance+ # link on a contested account. Blank allocations here keep this test on+ # the default "dedicate the whole balance" path.+ first = unclaimed_account("Holiday Pot")+ second = unclaimed_account("House Pot")+assert_difference -> { Goal.count } => 1,-> { GoalAccount.count } => 2 dopost goals_url, params: {@@ -53,7 +60,7 @@ class GoalsControllerTest < ActionDispatch::IntegrationTesttarget_amount: "1000",target_date: 3.months.from_now.to_date.iso8601,color: "#4da568",- account_ids: [ @depository.id, @connected.id ]+ account_ids: [ first.id, second.id ]}}end@@ -235,13 +242,14 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest# not the stale (empty) set already on the record.test "an orphaned goal can be repaired by re-linking an account" doorphan = orphaned_goal+ rescue_account = unclaimed_account("Rescue Pot")patch goal_url(orphan), params: {- goal: { name: orphan.name, target_amount: orphan.target_amount, account_ids: [ @depository.id ] }+ goal: { name: orphan.name, target_amount: orphan.target_amount, account_ids: [ rescue_account.id ] }}assert_redirected_to goal_path(orphan)- assert_equal [ @depository.id ], orphan.reload.goal_accounts.pluck(:account_id)+ assert_equal [ rescue_account.id ], orphan.reload.goal_accounts.pluck(:account_id)assert orphan.valid?end@@ -324,7 +332,44 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_match(/without a deadline/i, response.body)end+ # The form reads its ticks from a separate local, not from the built links,+ # so a failed create rendered every account unchecked while the amounts the+ # user typed survived — an error telling them to enter an amount, on a form+ # whose accounts had silently cleared.+ test "a rejected creation keeps the accounts the user ticked" do+ account = Account.create!(+ family: @user.family, accountable: Depository.new,+ name: "Contested Pot", currency: @user.family.currency, balance: 3_000+ )+ holder = @user.family.goals.create!(name: "Holder", target_amount: 5_000, currency: @user.family.currency) do |g|+ g.goal_accounts.build(account: account)+ end+ assert holder.persisted?++ post goals_url, params: {+ goal: {+ name: "Second claim", target_amount: 5_000,+ account_ids: [ account.id ], allocations: { account.id.to_s => "" }+ }+ }++ assert_response :unprocessable_entity+ assert_select "input[type=checkbox][name='goal[account_ids][]'][value=?][checked]", account.id+ end+private+ # A fundable account no goal fixture claims. The fixtures link+ # @depository and @connected as whole-balance earmarks, and GoalAccount+ # refuses a second whole-balance link on an account already claimed in+ # full — so any test that wants the default "dedicate the whole balance"+ # link needs an account of its own.+ def unclaimed_account(name)+ Account.create!(+ family: @user.family, accountable: Depository.new,+ name: name, currency: "USD", balance: 1_000+ )+ end+# A goal in the state account deletion leaves behind: still present, zero# linked accounts, failing its own validations.def orphaned_goal@@ -342,9 +387,19 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestgoalend+ # Each goal gets its own funding account, mirroring @depository's balance.+ # These goals used to share @depository as a whole-balance link, which+ # GoalAccount now refuses — and which was the double count in the first+ # place: every goal read the same 5,000 as if it were its own. One account+ # each keeps every goal's current_balance identical to what it was, without+ # the overlap.def build_goal(family, name, target_amount: 1_000_000, target_date: nil)+ funding = Account.create!(+ family: family, accountable: Depository.new,+ name: "#{name} Funding", currency: "USD", balance: @depository.balance+ )g = family.goals.new(name: name, target_amount: target_amount, target_date: target_date, currency: "USD")- g.goal_accounts.build(account: @depository)+ g.goal_accounts.build(account: funding)g.save!gend@@ -363,7 +418,7 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestcurrency: "USD",state: "archived",family_id: other_family.id,- account_ids: [ @depository.id ]+ account_ids: [ unclaimed_account("Hijack Pot").id ]}}enddiff --git a/test/fixtures/goal_accounts.yml b/test/fixtures/goal_accounts.ymlindex a9d1a47b37..a1c857398e 100644--- a/test/fixtures/goal_accounts.yml+++ b/test/fixtures/goal_accounts.yml@@ -6,10 +6,16 @@ vacation_italy_connected:goal: vacation_italyaccount: connected+# Fixed slices, not whole-account links: three goals each claiming the whole of+# `depository` is the very state GoalAccount#whole_account_link_must_be_exclusive+# forbids, and it left the reference data unable to survive an archive/restore+# round trip. Only `vacation_italy` claims the account in full.emergency_fund_depository:goal: emergency_fundaccount: depository+ allocated_amount: 1000car_paydown_depository:goal: car_paydownaccount: depository+ allocated_amount: 1000diff --git a/test/models/assistant/function/create_goal_test.rb b/test/models/assistant/function/create_goal_test.rbindex 0631a64879..32ecd68531 100644--- a/test/models/assistant/function/create_goal_test.rb+++ b/test/models/assistant/function/create_goal_test.rb@@ -19,13 +19,21 @@ class Assistant::Function::CreateGoalTest < ActiveSupport::TestCaseendtest "creates a goal with linked accounts" do+ # A fresh account, not one the goal fixtures already claim in full:+ # GoalAccount refuses a second whole-balance link on a contested account,+ # and this function has no way to pass an earmark.+ unclaimed = Account.create!(+ family: @family, accountable: Depository.new,+ name: "Vacation Savings", currency: "USD", balance: 2_000+ )+assert_difference -> { Goal.count } => 1,-> { GoalAccount.count } => 1 doresult = @fn.call("name" => "Vacation","target_amount" => 1500,"target_date" => 3.months.from_now.to_date.iso8601,- "linked_account_names" => [ @depository.name ]+ "linked_account_names" => [ unclaimed.name ])assert result[:success]diff --git a/test/models/goal_account_test.rb b/test/models/goal_account_test.rbindex c0c8b96096..bb6725afb7 100644--- a/test/models/goal_account_test.rb+++ b/test/models/goal_account_test.rb@@ -29,4 +29,214 @@ class GoalAccountTest < ActiveSupport::TestCaseassert_not ga.valid?assert_includes ga.errors[:allocated_amount], "must be greater than or equal to 0"end++ # --- whole-account exclusivity (see GoalAccount#whole_account_link_must_be_exclusive) ---++ test "a second whole-account link on an already fully-earmarked account is rejected" do+ goals(:vacation_italy).goal_accounts.create!(account: @account)++ ga = GoalAccount.new(goal: @goal, account: @account, allocated_amount: nil)++ assert_not ga.valid?+ assert_includes ga.errors[:base].first, "Vacation in Italy"+ end++ test "a fixed earmark is always allowed on an account another goal claims whole" do+ goals(:vacation_italy).goal_accounts.create!(account: @account)++ ga = GoalAccount.new(goal: @goal, account: @account, allocated_amount: 250)++ assert ga.valid?, ga.errors.full_messages.to_sentence+ end++ test "a whole-account link is allowed when the other goal earmarks a fixed slice" do+ goals(:vacation_italy).goal_accounts.create!(account: @account, allocated_amount: 250)++ ga = GoalAccount.new(goal: @goal, account: @account, allocated_amount: nil)++ assert ga.valid?, ga.errors.full_messages.to_sentence+ end++ # The guard tracks Goal.pooled_allocations_for, which excludes archived goals+ # from the backing math. Money held by an archived goal is not claimed, so it+ # must not block a live one.+ test "an archived goal's whole-account link does not block a new one" do+ other = goals(:vacation_italy)+ other.goal_accounts.create!(account: @account)+ other.archive!++ ga = GoalAccount.new(goal: @goal, account: @account, allocated_amount: nil)++ assert ga.valid?, ga.errors.full_messages.to_sentence+ end++ # A completed goal still holds its money and still feeds the pool, so unlike+ # an archived one it does claim the balance.+ test "a completed goal's whole-account link still blocks a new one" do+ other = goals(:vacation_italy)+ other.goal_accounts.create!(account: @account)+ other.complete!++ ga = GoalAccount.new(goal: @goal, account: @account, allocated_amount: nil)++ assert_not ga.valid?+ end++ test "another family's whole-account link on its own account is irrelevant" do+ foreign_family = families(:empty)+ foreign_account = Account.create!(+ family: foreign_family, accountable: Depository.new,+ name: "Their Checking", currency: "USD", balance: 1_000+ )+ foreign_family.goals.create!(+ name: "Theirs", target_amount: 500, currency: "USD",+ goal_accounts: [ GoalAccount.new(account: foreign_account) ]+ )++ ga = GoalAccount.new(goal: @goal, account: @account, allocated_amount: nil)++ assert ga.valid?, ga.errors.full_messages.to_sentence+ end++ test "re-saving an existing whole-account link does not trip on itself" do+ ga = @goal.goal_accounts.create!(account: @account)++ assert ga.valid?, ga.errors.full_messages.to_sentence+ assert ga.reload.update(updated_at: Time.current)+ end++ # Autosave revalidates every loaded goal_account on goal.save. A goal that+ # merely holds an overlap written before this guard existed must stay+ # editable — otherwise renaming it becomes impossible.+ test "a legacy overlap does not block an unrelated edit to the goal holding it" do+ other = goals(:vacation_italy)+ other.goal_accounts.create!(account: @account)+ legacy = @goal.goal_accounts.create!(account: @account, allocated_amount: 1)+ legacy.update_column(:allocated_amount, nil)++ @goal.reload.name = "Renamed"++ assert @goal.save, @goal.errors.full_messages.to_sentence+ end++ # ...but deliberately clearing an amount on a contested account is a new+ # claim on the whole balance, so it is refused.+ test "clearing a fixed earmark onto a contested account is refused" do+ goals(:vacation_italy).goal_accounts.create!(account: @account)+ ga = @goal.goal_accounts.create!(account: @account, allocated_amount: 250)++ ga.allocated_amount = nil++ assert_not ga.valid?+ end++ # Moving a whole-account link is a fresh claim on wherever it lands. It is+ # neither new nor allocation-dirty, so the two original predicates let it+ # through onto an account nobody had checked.+ test "moving a whole-account link onto a contested account is refused" do+ contested = Account.create!(+ family: families(:dylan_family), accountable: Depository.new,+ name: "Contested", currency: "USD", balance: 4_000+ )+ goals(:vacation_italy).goal_accounts.create!(account: contested)+ mine = @goal.goal_accounts.create!(account: @account, allocated_amount: nil)++ mine.account = contested++ assert_not mine.valid?+ assert_includes mine.errors.full_messages.to_sentence, goals(:vacation_italy).name+ end++ test "moving a whole-account link onto a free account is allowed" do+ free = Account.create!(+ family: families(:dylan_family), accountable: Depository.new,+ name: "Free", currency: "USD", balance: 4_000+ )+ mine = @goal.goal_accounts.create!(account: @account, allocated_amount: nil)++ mine.account = free++ assert mine.valid?, mine.errors.full_messages.to_sentence+ end++ # The bound still has to let a row that is merely along for the ride pass:+ # autosave revalidates every loaded child on goal.save.+ test "a legacy overlap still does not block an unrelated edit after the widening" do+ other = goals(:vacation_italy)+ other.goal_accounts.create!(account: @account)+ legacy = @goal.goal_accounts.create!(account: @account, allocated_amount: 1)+ legacy.update_column(:allocated_amount, nil)++ @goal.reload.name = "Renamed again"++ assert @goal.save, @goal.errors.full_messages.to_sentence+ end++ # A link changing owner still carries its OLD goal_id in the database, so+ # excluding by goal alone handed the moving row back as its own conflict.+ test "moving a whole-account link to another goal is not blocked by itself" do+ destination_goal = goals(:emergency_fund) == @goal ? goals(:vacation_italy) : goals(:emergency_fund)+ solo = Account.create!(+ family: families(:dylan_family), accountable: Depository.new,+ name: "Solo #{SecureRandom.hex(4)}", currency: "USD", balance: 2_000+ )+ link = @goal.goal_accounts.create!(account: solo, allocated_amount: nil)++ link.goal = destination_goal++ assert link.valid?, link.errors.full_messages.to_sentence+ end++ # The exclusivity validation is a read followed by a write, so on its own two+ # requests can both find no conflict and both commit a whole-account claim —+ # the double-count the validation exists to prevent, recreated by timing.+ #+ # This asserts the lock is taken before the read, and taken in id order so+ # two goals claiming the same pair of accounts in opposite orders cannot+ # deadlock. That the lock then serialises is PostgreSQL's guarantee, not+ # something a transactional test on one connection can demonstrate.+ test "the account is claimed before the conflict check reads it" do+ goal = goals(:vacation_italy)+ ids = [ accounts(:credit_card).id, accounts(:depository).id ]++ Goal.expects(:lock_whole_account_claims!).with(ids.min).once+ Goal.expects(:lock_whole_account_claims!).with(ids.max).once++ goal.whole_account_conflicts_on(ids.sort.reverse).to_a+ end++ test "no account is claimed when there is nothing to check" do+ Goal.expects(:lock_whole_account_claims!).never++ goals(:vacation_italy).whole_account_conflicts_on([]).to_a+ end++ # Autosave validates each link separately, so without a set-wide lock each+ # would take its own in association order — and two goals saving links on the+ # same two accounts in opposite orders would hold one lock each and wait on+ # the other.+ test "saving a goal claims every account it touches, in id order" do+ family = families(:dylan_family)+ # Ids fixed rather than generated: the whole assertion is about ordering,+ # and random UUIDs would make it pass half the time on association order+ # alone.+ low = Account.create!(id: "00000000-0000-4000-8000-000000000001", family: family,+ accountable: Depository.new, name: "Pot A",+ currency: family.currency, balance: 1_000)+ high = Account.create!(id: "ffffffff-0000-4000-8000-000000000002", family: family,+ accountable: Depository.new, name: "Pot B",+ currency: family.currency, balance: 1_000)++ seen = []+ Goal.stubs(:lock_whole_account_claims!).with { |id| seen << id; true }++ # Built high-id first, so association order and id order disagree.+ family.goals.create!(name: "Two pots", target_amount: 2_000, currency: family.currency) do |g|+ g.goal_accounts.build(account: high)+ g.goal_accounts.build(account: low)+ end++ assert_equal [ low.id, high.id ], seen.uniq,+ "locked in association order rather than id order"+ endenddiff --git a/test/models/goal_test.rb b/test/models/goal_test.rbindex d4efc1aa82..f0d5619e18 100644--- a/test/models/goal_test.rb+++ b/test/models/goal_test.rb@@ -14,6 +14,40 @@ class GoalTest < ActiveSupport::TestCaseassert @goal.valid?end+ # Two whole-account links on ONE account each claim the entire balance, so+ # the account is counted twice. The pro-rata haircut in backing_share_for+ # only scales FIXED earmarks: `others_fixed` sums allocated_amount, and an+ # unallocated link contributes nil.to_d == 0, so the two links never see+ # each other. GoalAccount now refuses to create this state (see+ # GoalAccountTest), but rows that predate the guard still read this way —+ # this test pins the behaviour those rows get, and is the reason the guard+ # exists.+ test "two grandfathered whole-account links each claim the full balance" do+ livret = Account.create!(+ family: @family, accountable: Depository.new,+ name: "Livret A", currency: "USD", balance: 6_000+ )+ precaution = @family.goals.create!(+ name: "Precaution", target_amount: 5_000, currency: "USD",+ goal_accounts: [ GoalAccount.new(account: livret) ]+ )+ # Built with a fixed earmark so the new guard lets it through, then+ # forced to NULL behind the validation's back — exactly the shape of a+ # row written before the guard shipped.+ vacances = @family.goals.create!(+ name: "Vacances", target_amount: 5_000, currency: "USD",+ goal_accounts: [ GoalAccount.new(account: livret, allocated_amount: 1) ]+ )+ vacances.goal_accounts.first.update_column(:allocated_amount, nil)++ assert_equal 6_000, precaution.reload.current_balance.to_i+ assert_equal 6_000, vacances.reload.current_balance.to_i+ assert_equal 12_000, precaution.current_balance.to_i + vacances.current_balance.to_i,+ "6 000 of balance backing 12 000 of goals — the double count B7 guards against"+ assert_equal 100, precaution.progress_percent.to_i+ assert_equal 100, vacances.progress_percent.to_i+ end+# The confirm dialog assigns `body` to innerHTML, so an unescaped goal name# would execute when a family member opens the delete confirmation.test "deletion_confirm escapes the goal name in the dialog body" do@@ -166,8 +200,19 @@ class GoalTest < ActiveSupport::TestCaseassert_includes @goal.errors[:currency], "Can't change the currency after the goal is linked to accounts."end- test "current_balance sums linked account balances" do- expected = @goal.linked_accounts.sum(&:balance).to_d+ # A whole-account link takes what is LEFT of the balance once other goals'+ # fixed earmarks are set aside — not the gross balance. This used to assert+ # the gross figure, which only held because the fixtures had three goals+ # claiming `depository` in full at once: the very state the exclusivity rule+ # forbids, and one where the same money was counted three times.+ test "current_balance sums linked account balances net of other goals' earmarks" do+ account_ids = @goal.linked_accounts.map(&:id)+ others_fixed = GoalAccount.where(account_id: account_ids)+ .where.not(goal_id: @goal.id)+ .sum(:allocated_amount)+ expected = @goal.linked_accounts.sum(&:balance).to_d - others_fixed++ assert_operator others_fixed, :>, 0, "fixtures should exercise the netting"assert_equal expected, @goal.current_balance.to_dend@@ -536,4 +581,85 @@ class GoalTest < ActiveSupport::TestCaseassert_equal 1, summary[:behind_count]assert_kind_of Money, summary[:saved_money]end++ # --- Restoring a goal must not recreate a whole-account overlap ---+ #+ # The door-side tests — writing a link onto a contested account — live in+ # goal_account_test.rb. These cover the other way in: a state change, which+ # writes no link at all and so slips past that validation entirely.++ test "restoring an archived goal is refused when its account was claimed meanwhile" do+ account = standoff_account+ away = whole_account_goal("Away", account)+ away.archive!++ # Legitimate while `away` holds nothing: an archived goal releases its+ # accounts, so this claim is exactly what the pool expects.+ whole_account_goal("Claimer", account)++ away.reload+ assert_not away.unarchive!, "expected the restore to be refused"+ assert_equal "archived", away.reload.state+ assert_match "Claimer", away.errors.full_messages.to_sentence+ end++ test "restoring is allowed once the other goal earmarks a fixed slice instead" do+ account = standoff_account+ away = whole_account_goal("Away", account)+ away.archive!+ claimer = whole_account_goal("Claimer", account)++ claimer.goal_accounts.first.update!(allocated_amount: 2_000)++ away.reload+ assert away.unarchive!, away.errors.full_messages.to_sentence+ assert_equal "active", away.reload.state+ end++ test "restoring an archived goal whose account is still free is untouched" do+ account = standoff_account+ away = whole_account_goal("Away", account)+ away.archive!++ away.reload+ assert away.unarchive!, away.errors.full_messages.to_sentence+ assert_equal "active", away.reload.state+ end++ # `paused` is not a released state: a paused goal never let go of its+ # accounts, so nothing can legitimately have claimed one meanwhile. The guard+ # that restricts this check to restores from a released state is what keeps a+ # user holding a LEGACY overlap — data the rule predates — from being+ # stranded on a goal they merely shelved. Built through update_column, since+ # the overlap is exactly what the door now refuses to write.+ test "resuming a paused goal is never blocked, even on a legacy overlap" do+ account = standoff_account+ goal = whole_account_goal("Shelved", account)+ squatter = @family.goals.create!(name: "Squatter", target_amount: 5_000, currency: "USD") do |g|+ g.goal_accounts.build(account: account, allocated_amount: 1)+ end+ squatter.goal_accounts.first.update_column(:allocated_amount, nil)++ goal.pause!++ assert goal.reload.resume!, goal.errors.full_messages.to_sentence+ assert_equal "active", goal.reload.state+ end++ private+ # A fresh account: the fixtures deliberately carry three goals holding+ # whole-account links on `depository`, a legacy overlap the exclusivity+ # rule tolerates but which would muddy every assertion here.+ def standoff_account+ Account.create!(+ family: @family, accountable: Depository.new,+ name: "Standoff Savings #{SecureRandom.hex(4)}", currency: "USD", balance: 6_000+ )+ end++ def whole_account_goal(name, account)+ @family.goals.create!(name: name, target_amount: 5_000, currency: "USD") do |goal|+ goal.goal_accounts.build(account: account)+ end+ endend