Files
sure/test/controllers
buzzromainandClaude Opus 5 7a86ee47c5 fix(goals): stop two goals from each claiming the same account in full (#3160)
* fix(goals): stop two goals from each claiming the same account in full

A GoalAccount with a NULL `allocated_amount` means "dedicate the whole
balance". Two of them on one account each claimed all of it, so the money
was counted twice:

    Livret A, 6,000        precaution 6,000    vacances 6,000
                           progress: 100%      progress: 100%

`Goal#backing_share_for` cannot catch this. Its pro-rata haircut only
scales FIXED earmarks, and an unallocated link contributes `nil.to_d` —
zero — to `others_fixed`, so the two links never see each other. The
invariant "shares never sum past the balance" held for every earmark
except the one that claims everything.

Enforce it at the door: GoalAccount now refuses a second whole-balance
link on an account another non-archived goal already claims in full, and
asks for an amount instead. The scope matches
`Goal.pooled_allocations_for` — archived goals are excluded from the
backing math, so they do not block; completed goals still hold their
money, so they do.

Rows written before this guard stay readable and editable. Autosave
revalidates every loaded goal_account on `goal.save`, so validating
untouched links would make a goal that merely holds a legacy overlap
impossible to rename. Only a new link, or one whose amount is being
cleared onto a contested account, is checked.

The goal fixtures encoded exactly the forbidden state — three goals
claiming `depository` in full — so tests that built a fourth whole
claim now use accounts of their own. `build_goal` mirrors the old
balance, leaving every KPI figure unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DJ1npaGEHr6t2HW1rYZdt4

* fix(goals): keep a restored goal from re-claiming an account in full

Addresses review feedback on #3160, raised independently on #3165, #3166 and
#3167 — one bug seen four times, because those branches stack.

Archiving a goal releases the accounts it claimed in full, so another goal can
legitimately claim one while it is away. Restoring it then put two
whole-account links back on the same account and reopened the double-counting
`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".

The conflict lookup now lives in one place, `Goal#whole_account_conflicts_on`,
read both by the door (writing a link) and by the restore, so the two cannot
drift into disagreeing about which goals still hold their money. The
`new_record? || will_save_change_to_allocated_amount?` bound stays on the
validation rather than moving into the shared lookup: it exists so a goal
merely holding a legacy overlap can still be renamed.

`Goal::RELEASED_STATES` replaces the repeated "archived" literal. The old
comment already said this scope had to move with the pool's; the constant makes
that true rather than hoped for, and the restore guard will follow the day the
set grows.

Restores from a released state are guarded; `resume` from `paused` is not. A
paused goal never let go of its accounts, so nothing can legitimately have
claimed one meanwhile, and blocking it would strand a user on a goal they
merely shelved.

Two things this surfaced in the test data:

- The fixtures had three goals each claiming `depository` in full — the exact
  state the rule forbids. `test "AASM transitions"` failed on it, a true
  positive. Two of them now take a fixed 1,000 slice.
- `current_balance sums linked account balances` asserted the gross balance,
  which only held because of that overlap. A whole-account link takes what is
  left after other goals' fixed earmarks; the test now says so, and computes it
  from the data rather than a constant.

Each guard was confirmed load-bearing by removing it and watching its test
fail. bin/rails test: 6936 runs, 27911 assertions, 0 failures. RuboCop,
erb_lint and Brakeman clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

* fix(goals): treat moving a whole-account link as the fresh claim it is

Addresses review feedback on #3160.

The exclusivity check was bounded to `new_record? ||
will_save_change_to_allocated_amount?`. A persisted whole-account row whose
`account_id` or `goal_id` changes is neither, so moving one landed it on an
account nobody had checked — the same double-counting hole a restore opened,
through a different door.

The bound is widened rather than dropped. It exists because `Goal has_many
:goal_accounts, autosave: true` revalidates every loaded child on `goal.save`,
so an unguarded check makes a goal that merely holds a legacy overlap
impossible to rename. That reason still holds for every row along for the ride;
it does not hold for a row being moved. A test pins both faces.

bin/rails test: 6939 runs, 27916 assertions, 0 failures. RuboCop and Brakeman
clean. Confirmed load-bearing by narrowing the bound back and watching the move
test fail.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

* fix(goals): stop a link that is changing goals from conflicting with itself

Addresses review feedback on #3160, on the widening that landed in 00894c16.

Guarding ownership changes was right, but the conflict query excluded the
current record by GOAL, not by row. A link changing `goal_id` still carries the
old one in the database, so the query handed the moving row straight back and
the link was refused as its own conflict — the guard blocked the exact case it
had just been widened to cover.

`whole_account_conflicts_on` now takes the row being written and excludes it by
id. The restore guard passes nothing, which is correct: exclusion by goal
already covers every link the goal being restored owns.

Confirmed load-bearing by dropping the id exclusion and watching the new test
fail. bin/rails test: 6940 runs, 27917 assertions, 0 failures. RuboCop and
Brakeman clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

* fix(goals): keep the ticked accounts when a creation is rejected

Addresses review feedback on #3160.

`new.html.erb` rendered the form without `currently_linked_account_ids`, whose
default is `[]`, so a rejected create came back with every account unchecked.
The amounts survived — the form reads those off the same built links — which
made it worse rather than better: the user faced an error telling them to enter
an amount, on a form whose account selection had silently cleared, and a
multi-account selection was gone entirely.

The failed path now derives the ticks from the in-memory links rather than
`pluck`: nothing is persisted on a rejected create, so a query would come back
empty and change nothing.

Confirmed load-bearing by emptying the list again and watching the new
controller test fail. bin/rails test: 6941 runs, 27920 assertions, 0 failures.
RuboCop and erb_lint clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

* fix(goals): hold the account while checking whether it is already claimed

The exclusivity validation is a read followed by a write, so two requests
could both find no conflict and both commit a whole-account claim — the
double-count the validation exists to prevent, recreated by timing alone.

`whole_account_conflicts_on` now takes a transaction-scoped advisory lock
per account before reading. An advisory lock rather than a row lock
because the conflicting write may be an INSERT, so there is no row to
lock; transaction-scoped so it is released whichever way the enclosing
transaction ends. Accounts are locked in id order, so two goals claiming
the same pair in opposite orders cannot deadlock against each other.

Both doors go through this method — the link validation and the restore
guard — so both are covered by the one change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

* fix(goals): bind the advisory lock key instead of interpolating it

Brakeman flagged the hand-built SQL, correctly. The key is a digest of an
id and could not carry a payload, but a raw interpolated string in a model
is the shape a reader has to stop and verify.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

* fix(goals): stop the advisory lock warning on every acquisition

`pg_advisory_xact_lock` returns `void`, which the adapter cannot type, so
each call logged "unknown OID 2278". Projected through a subquery so the
result set is a plain integer.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

* fix(goals): claim every account a goal touches in one deterministic order

Follow-up on the advisory lock: autosave validates each link separately, so
each was taking 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.

The goal takes the whole set up front, sorted, before any child validates.
The per-account lock inside `whole_account_conflicts_on` stays for a link
saved on its own, and re-taking a lock the transaction already holds costs
nothing.

The ordering test fixes the account ids rather than generating them: the
assertion is entirely about order, and random UUIDs would have let it pass
half the time on association order alone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GTNba5qE5NwzaHzbp27ye

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 07:07:39 +02:00
..