Respect user locks when Plaid writes loan terms
Closes #4392
Fork pre-flight: jaysbeekay/sure#527, from the same branch.
Ported from jaysbeekay/sure#222 (fork issue jaysbeekay/sure#158), adapted to upstream main.
Problem
PlaidAccount::Liabilities::MortgageProcessor and StudentLoanProcessor write the liabilities payload onto the loan with account.loan.update!(...). That one call causes three problems:
- Locked values are overwritten. Saving the loan form locks the changed attributes (
Account#lock_saved_attributes!→accountable.lock_saved_attributes!).update!ignores the locks, so the next sync reverts the user's correction. The student-loan processor always sendsrate_type: "fixed", so a student loan the user marked variable goes back to fixed on every sync. - Omitted fields blank stored ones. A field missing from the payload arrives as
nil. A mortgage withoutinterest_rate.percentageerases the stored rate. A student loan missing either date erasesterm_months. - No provenance. No
DataEnrichmentrow records that Plaid supplied the value.
Change
A new concern, PlaidAccount::Liabilities::LoanTermWriter (write_loan_terms), is included by both processors and replaces the update!:
compactdrops the fields the payload omitted. Onlynilcounts as "not said": a rate of exactly0is still written.Enrichable#enrich_attributes(..., source: "plaid")writes the rest. It skips locked attributes and records aDataEnrichmentper attribute.RedbarkAccount::LoanDetailsProcessor#writealready uses the same path.- A refused save is rolled back inside
transaction(requires_new: true). Enrichable writes theDataEnrichmentbefore it saves, so without the rollback a rejected value would be recorded as Plaid's.requires_newkeeps the rollback effective if a caller ever opens a transaction around the processor. - A refusal is logged with
DebugLogEntry.capture(categoryprovider_sync, providerplaid, with the account).enrich_attributesusessave, so a refusal no longer raises intoPlaidAccount::Processor#process_liabilities's rescue; without the log it would be silent. Only populatederrorscount as a refusal, because Enrichable also returnsfalsewhen every attribute was locked or unchanged. - The in-memory loan is put back. After a refusal,
restore_attributesanderrors.clearremove the rejected values and stale errors. Otherwise a later write in the same sync would be refused because of them, or would report them again.
Blast radius. write_loan_terms has two callers, the two processors. Each processor has one production caller, PlaidAccount::Processor#process_liabilities. For an unlocked loan with a complete payload, the result is the same values as before, plus DataEnrichment rows. The student loan's existing start_date rule (keep a recorded date, skip a future one) is unchanged; it now goes through the same writer.
Siblings checked.
RedbarkAccount::LoanDetailsProcessoralready writes through Enrichable, with the same rollback and cleanup. This change brings Plaid in line with it.PlaidAccount::Liabilities::CreditProcessorwrites credit-cardaprandminimum_paymentthroughAccount::ProviderImportAdapter#update_accountable_attributes, which also usesupdate!. It is a different accountable and a shared adapter used by SimpleFIN too, so it is left for a separate change.- No other code calls
loan.update!from a provider.
Left out. A variable loan's rate change still replaces the base rate. Dating it as a variable_rate_schedule row is a separate change, stacked on this branch.
Tests
In test/models/plaid_account/liabilities/: 11 new tests in mortgage_processor_test.rb and 4 in student_loan_processor_test.rb. The refusal tests use one of Loan's own validations: a loan that turns variable cannot carry a rate change dated before its start date.
Fail-first against upstream main (3ae36a6), tests only: 29 runs, 9 failures, 4 errors.
- Lock tests fail with the overwritten value, e.g.
Plaid overwrote a rate the user had locked. Expected: 4.5, Actual: 5.2. - Omitted-field tests fail with
Expected: 4.5, Actual: 0.0, andExpected 120for the term. - Provenance tests fail with
didn't change by 2, but by 0. - The refusal test errors with
ActiveRecord::RecordInvalid: ... A rate change cannot take effect before the loan originated. - The three tests that drive the writer directly error with
NoMethodErroron main, because the writer does not exist there. The mutations below show each one fails for its own reason. - a rate of exactly zero is written passes on main, as expected:
update!writes everything. It guards the boundary the fix introduces, and mutation M3 confirms that.
Mutations (each applied alone to the committed fix; the liabilities tests were re-run and the mutation reverted):
| # | Mutation | Tests that fail |
|---|---|---|
| M1 | back to loan.update!(present) | 11: every lock, provenance and refusal test |
| M2 | compact removed | the 3 omitted-field tests |
| M3 | a filter that treats 0 as absent | a rate of exactly zero is written |
| M4 | source "redbark" instead of "plaid" | ...Plaid is recorded as the source, both provenance-on-refusal tests |
| M5 | raise ActiveRecord::Rollback removed | both provenance-on-refusal tests |
| M6 | requires_new: true removed | a refused value inside a caller's transaction leaves the earlier provenance in place |
| M7 | DebugLogEntry.capture removed | a value the model refuses is logged rather than raised, a refusal leaves no errors behind... |
| M8 | errors.clear removed | a refusal leaves no errors behind for a locked write to report |
| M9 | restore_attributes removed | a refused value does not cost the next write its change |
Every mutation is caught.
Validation
- Full suite:
12661 runs, 58489 assertions, 0 failures, 0 errors, 36 skips. - Targeted:
test/models/plaid_account,test/models/redbark_accountandtest/models/loan_test.rbgive 163 runs, 0 failures. bin/rubocopon the changed files: no offenses.bin/brakeman: 0 warnings. No ERB, JavaScript, migrations or user-facing strings changed.- Checked against
AGENTS.md:- logic is in a model concern;
- tests are Minitest and fixtures;
- provider diagnostics go through
DebugLogEntry.capturewith provider and account context; - commit subject is under 72 characters.
Since review
5e7147989: the refusalDebugLogEntrynow carriesaccount_provider, so/settings/debugcan filter it by connection. A refusal is also sent to Sentry as a warning-level message, tagged with the Plaid account. Before this PR it reached Sentry throughprocess_liabilities's rescue. A write that locks or unchanged values turn into a no-op is not reported. Three new tests; full suite 12,664 runs, 0 failures.
Summary by CodeRabbit
-
Bug Fixes
- Improved mortgage and student-loan term updates while preserving locked attributes.
- Kept existing values when incoming data omits a field, while retaining explicitly supplied zero values.
- Prevented rejected updates from leaving partial changes or stale validation errors.
- Preserved accurate source information for successfully updated loan terms.
-
Tests
- Added coverage for partial data, locked fields, rejected updates, rollback behavior, and source information.