Respect user locks when Plaid writes loan terms

Closed
JA
1mo ago
+359-2

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 sends rate_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 without interest_rate.percentage erases the stored rate. A student loan missing either date erases term_months.
  • No provenance. No DataEnrichment row 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!:

  • compact drops the fields the payload omitted. Only nil counts as "not said": a rate of exactly 0 is still written.
  • Enrichable#enrich_attributes(..., source: "plaid") writes the rest. It skips locked attributes and records a DataEnrichment per attribute. RedbarkAccount::LoanDetailsProcessor#write already uses the same path.
  • A refused save is rolled back inside transaction(requires_new: true). Enrichable writes the DataEnrichment before it saves, so without the rollback a rejected value would be recorded as Plaid's. requires_new keeps the rollback effective if a caller ever opens a transaction around the processor.
  • A refusal is logged with DebugLogEntry.capture (category provider_sync, provider plaid, with the account). enrich_attributes uses save, so a refusal no longer raises into PlaidAccount::Processor#process_liabilities's rescue; without the log it would be silent. Only populated errors count as a refusal, because Enrichable also returns false when every attribute was locked or unchanged.
  • The in-memory loan is put back. After a refusal, restore_attributes and errors.clear remove 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::LoanDetailsProcessor already writes through Enrichable, with the same rollback and cleanup. This change brings Plaid in line with it.
  • PlaidAccount::Liabilities::CreditProcessor writes credit-card apr and minimum_payment through Account::ProviderImportAdapter#update_accountable_attributes, which also uses update!. 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, and Expected 120 for 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 NoMethodError on 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):

#MutationTests that fail
M1back to loan.update!(present)11: every lock, provenance and refusal test
M2compact removedthe 3 omitted-field tests
M3a filter that treats 0 as absenta rate of exactly zero is written
M4source "redbark" instead of "plaid"...Plaid is recorded as the source, both provenance-on-refusal tests
M5raise ActiveRecord::Rollback removedboth provenance-on-refusal tests
M6requires_new: true removeda refused value inside a caller's transaction leaves the earlier provenance in place
M7DebugLogEntry.capture removeda value the model refuses is logged rather than raised, a refusal leaves no errors behind...
M8errors.clear removeda refusal leaves no errors behind for a locked write to report
M9restore_attributes removeda 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_account and test/models/loan_test.rb give 163 runs, 0 failures.
  • bin/rubocop on 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.capture with provider and account context;
    • commit subject is under 72 characters.

Since review

  • 5e7147989: the refusal DebugLogEntry now carries account_provider, so /settings/debug can 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 through process_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.