Log DataEnrichment only after a successful save (option 1)

Merged
JA
2mo ago
+142-7

Closes #224. Implements option 1, the decision approved in the issue: DataEnrichment rows are written only after a successful save, and only when the record already existed when the call began. At head c201c0d9, a refused save also rolls back everything the call wrote, including association writes.

The defect (from #224)

Enrichable#enrich_attributes wrote its DataEnrichment rows before it knew whether the save would succeed, inside a transaction that committed either way. The code calls save, not save!, so a refused write returns false and nothing raises. The transaction then committed, and the rows stood as a record of a write that never happened.

data_enrichments answers "who set this?". A row saying source: "plaid" for a rate the model refused tells an untrue story about a financial attribute.

There are two shapes (see the #224 comments):

  • First write: a new row appears for a value the record never accepted.
  • Repeat write: log_enrichment is a find_or_create_by on (enrichable, attribute_name, source) that then overwrites value, so a refused write replaces a correct earlier value. The row count does not change, so a count assertion cannot catch this shape.

The fix

was_new = new_record?                                  # captured BEFORE the setter loop

ActiveRecord::Base.transaction(requires_new: true) do  # always a savepoint
  enrichable_attrs.each do |attr, value|
    self.send("#{attr}=", value)
  end

  save_result = save
  raise ActiveRecord::Rollback unless save_result      # a refusal leaves nothing behind

  if save_result && !was_new                           # log AFTER a known-accepted save
    enrichable_attrs.each do |attr, value|
      log_enrichment(attribute_name: attr, attribute_value: value, source: source, metadata: metadata)
    end
  end
  # ... unchanged virtual-attribute / previous_changes logic ...
end

was_new is captured before the setter loop, not re-read after save. After the save, new_record? would be false, so re-reading it would start logging provenance rows for new records that never had them, such as the plaid_account processor's new-record enrichments. The captured value suppresses exactly the cases the old unless self.new_record? guard suppressed.

Refused saves roll back (c201c0d9, from CodeRabbit's review). Some virtual setters write to the database before save runs. On a persisted Transaction, tag_ids= inserts the join rows straight away. Without a rollback, a refused save committed those tags with no provenance row. raise ActiveRecord::Rollback straight after a false save undoes them. The transaction block swallows Rollback, so the method still returns false rather than raising, and the record keeps its errors for the caller.

Why requires_new: true. Several callers already hold a transaction: Account::ProviderImportAdapter wraps its work in Account.transaction do at :44, :410 and :651. A plain transaction block inside another one joins the outer transaction, and there ActiveRecord::Rollback is swallowed silently and undoes nothing. requires_new makes the block a savepoint, so the rollback takes effect whether or not the caller holds a transaction. On an accepted save the savepoint is simply released.

What is preserved

  • save stays save. A refusal still surfaces as false, and the record's errors stay populated. The existing write paths rely on both: #213's live caller cleans up with restore_attributes/errors.clear after a refusal, and it writes a DebugLogEntry only when errors is populated.
  • Accepted, locked and unchanged writes behave as before. An accepted write logs one row per changed attribute. A locked or unchanged write returns false early without saving.

Blast radius

enrich_attributes is reached from 31 call sites in app/: Family::AutoCategorizer, Family::BayesCategorizer, Family::AutoMerchantDetector, the Rule::ActionExecutor::* classes, Account::ProviderImportAdapter, PlaidAccount::Processor and RedbarkAccount::LoanDetailsProcessor.

  • Accepted saves: unchanged, apart from the released savepoint.
  • Refused saves: nothing persists. That covers the provenance rows and any association writes a virtual setter made.
  • A refused save now returns false. Before, it could return true, because the virtual-attribute comparison or a stale previous_changes from an earlier save reported a change that never landed. Three callers read the return value, and all three use it only to count modifications, so their counts no longer include refused writes:
    • Family::AutoCategorizer:81
    • Family::BayesCategorizer:66
    • Family::AutoMerchantDetector:43
  • RedbarkAccount::LoanDetailsProcessor#write (#213, the one live loan caller on main) still sees loan.errors populated and still calls restore_attributes. Its tests pass unchanged.
  • PlaidAccount::Liabilities::LoanTermWriter#write_loan_terms is in PR #222, which is not on main. It inherits this fix when main is merged into it. That was checked with a local, unpushed merge: a refused Plaid rate no longer overwrites the accepted provenance value, and all of #222's tests pass.

Tests

The pre-existing Enrichable tests are the regression guard. They still assert one row per accepted changed attribute and none for locked or unchanged attributes, which pins the side where the fix must not turn into "never log".

New tests:

TestPins
does not log enrichment when save is refusedthe first-write shape: save stubbed to false, assert_no_difference "DataEnrichment.count"
does not log enrichment for a new record that a real save persistscorrection (b), on a real first save: a valid new Account with a Depository. Asserts the call returns true, the record is persisted, the enriched name is stored in the database, and no DataEnrichment row exists for it. Because the save really moves the record from new to persisted, reading new_record? after the save would fail this test.
a refused save keeps the previously accepted provenance valuethe overwrite shape from #224: an accepted write stores "Accepted Name", then a refused write sends "Refused Name". Asserts the row's value is still "Accepted Name", along with the stored attribute. This checks the value, not the count.
a refused save rolls back association writes made by a virtual setterthe rollback: a persisted Transaction, save stubbed to false, tag_ids= adding an untagged tag, run inside a caller-held transaction as the importer does. Asserts the stored tag_ids equal the tags from before the call, the call returns false, and no DataEnrichment row is added.
enriches a virtual attribute (tag_ids) on an Enrichable model and logs after savethe accepted virtual path: a real Transaction and a real Tag, assert_difference +1, the tag is actually attached, and the row has attribute_name == "tag_ids" and source == "rule"

Evidence

Fail-first. Run against main's enrichable.rb, three of the new tests fail for the right reason:

  • refused save: DataEnrichment.count went 0 → 1.
  • association rollback: the row count rose.
  • value preserved: expected "Accepted Name", got "Refused Name".

Two more checks:

  • Against this PR's previous head a7bae9db, the association test failed because the stored tags came back with the extra tag.
  • The new-record test passes on main by design, because main's guard reads new_record? before the save. Its job is the mutation below.

Mutations on the fix, each caught:

MutationTest that fails
requires_new: true removeda refused save rolls back association writes… (the tags leak through the caller's transaction)
raise ActiveRecord::Rollback removeda refused save rolls back association writes…
guard reads !new_record? after the save instead of was_newdoes not log enrichment for a new record that a real save persists

The previous stubbed version of the new-record test did not catch that last mutation: all 11 tests passed. That is why it was rewritten.

Suite.

  • enrichable_test.rb: 13 runs, 0 failures.
  • Neighbouring caller tests (test/models/{redbark_account,rule,account,plaid_account,family} and transaction_test.rb): 577 runs, 0 failures.
  • Full bin/rails test: 10,523 runs, 0 failures apart from 7 local environment-only failures. They come from Ruby 3.3.6 locally against CI's 3.4.9, and the same tests fail on unmerged main: Anthropic ENV/base-URL, OpenAI extra_headers, the ActiveStorage variants test, and the Admin profile-picture test.
  • rubocop: clean on both changed files.
  • CI runs on this head.

Not in this PR

  • No change to the callers themselves. They are unchanged and become correct on refusal.
  • No unlock UI, no Redbark/SimpleFIN follow-ups (#159), no Redbark dated rows (#142/#160). Those are separate work.

Summary by CodeRabbit

  • Bug Fixes
    • Enrichment logs are created only after a successful save and only for records that already existed when enrichment began.
    • Failed saves and newly created records no longer generate enrichment logs.
    • Failed enrichment attempts roll back virtual attribute changes while preserving validation errors.
  • Tests
    • Added coverage for failed saves, new records, and successful enrichment of virtual attributes.