mirror of
https://github.com/we-promise/sure.git
synced 2026-12-03 10:49:07 +08:00
Make conflict decisions durable and serialize downstream work
Four findings from the alpha review of 3b3ece1, each reproduced before
changing anything and each covered by a test that fails without its fix.
**Balance decisions did not survive a replay.** The observation conflict
was looked up by open status on the lineage, so `keep_sure` dismissed one
capture rather than settling the disagreement, and a distinct observation
on the same lineage could not raise its own conflict. The lookup now
matches the observation identity carried in `details`, the same way a
source transaction's decision is matched. `retry_after_repair` now
releases the declined observation: it is immutable, so the replayed money
would disagree again after the repair and the conflict would just reopen.
Every other observation on the lineage is untouched, and the canonical
balance still only moves when a newer booked value lands.
**Overlapping downstream workers both fanned out.** Two instances can
snapshot the same incomplete ids before either runs — a per-upload job
and the periodic sweep overlap exactly this way — and nothing rechecked
before repeating account syncs, transfer matching and rule application.
Work is now claimed per publisher with `pg_try_advisory_lock`, matching
the keying the other advisory-locked jobs use, and the pending ids are
re-read inside the claim. A worker that cannot claim leaves the batches
for the holder and the sweep.
**Tombstones ignored the remaining-open-conflicts rule.** The settled
branch reset `review_required` unconditionally, so a tombstone cleared
review while a `protected_tombstone` conflict was still open. It now
derives review state the same way resolution and upserts do.
**Completion metadata committed in two steps.** Batch completion landed
before publisher health, so a failure between them left completed batches
with stale health that the recovery sweep then skipped, because it only
looks for incomplete batches. Both writes now commit together, after the
scheduling, so nothing is enqueued from inside the transaction.
Reported by jjmata on #3678.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
class Financekit::Downstream
|
||||
ADVISORY_LOCK_SCOPE = "financekit_downstream".freeze
|
||||
|
||||
# Takes a scope rather than loaded records and keeps only the ids. A pending
|
||||
# batch carries its payload — up to Financekit::MAX_BYTES, retained for seven
|
||||
# days — and an applied batch no longer counts against the inbox cap, so a
|
||||
# backlog awaiting downstream work has no ceiling of its own. Snapshotting the
|
||||
# ids up front also stops a capture applied concurrently from being marked
|
||||
# done without a fan-out of its own.
|
||||
# backlog awaiting downstream work has no ceiling of its own.
|
||||
def initialize(item, scope)
|
||||
@item = item
|
||||
@batch_ids = scope.where(downstream_completed_at: nil).pluck(:id)
|
||||
@@ -13,22 +13,61 @@ class Financekit::Downstream
|
||||
def perform!
|
||||
return if @batch_ids.empty?
|
||||
|
||||
# Account syncs, transfer matching and rule application all cost the same
|
||||
# whether one capture or fifty just landed, so a drain pays for them once
|
||||
# rather than once per capture.
|
||||
@item.selected_accounts.includes(financekit_account_lineage: :account).find_each do |mapping|
|
||||
mapping.account&.sync_later
|
||||
with_publisher_claim do
|
||||
# Re-read inside the claim. Two workers can snapshot the same ids before
|
||||
# either runs — a per-upload job and the periodic sweep overlap this way —
|
||||
# and without this the second one repeats the whole family fan-out.
|
||||
pending = FinancekitBatch.where(id: @batch_ids, downstream_completed_at: nil).pluck(:id)
|
||||
next if pending.empty?
|
||||
|
||||
# Account syncs, transfer matching and rule application all cost the same
|
||||
# whether one capture or fifty just landed, so a drain pays for them once
|
||||
# rather than once per capture.
|
||||
@item.selected_accounts.includes(financekit_account_lineage: :account).find_each do |mapping|
|
||||
mapping.account&.sync_later
|
||||
end
|
||||
@item.family.auto_match_transfers!
|
||||
@item.family.rules.where(active: true).find_each(&:apply_later)
|
||||
|
||||
# Both writes together, and after the scheduling above so nothing is
|
||||
# enqueued from inside the transaction. Committing them separately left
|
||||
# batches complete alongside stale publisher health, which the recovery
|
||||
# sweep then skipped because it only looks for incomplete batches.
|
||||
completed_at = Time.current
|
||||
FinancekitBatch.transaction do
|
||||
FinancekitBatch.where(id: pending)
|
||||
.update_all(downstream_completed_at: completed_at, updated_at: completed_at)
|
||||
@item.update!(last_downstream_at: completed_at)
|
||||
end
|
||||
end
|
||||
@item.family.auto_match_transfers!
|
||||
@item.family.rules.where(active: true).find_each(&:apply_later)
|
||||
completed_at = Time.current
|
||||
FinancekitBatch.where(id: @batch_ids)
|
||||
.update_all(downstream_completed_at: completed_at, updated_at: completed_at)
|
||||
@item.update!(last_downstream_at: completed_at)
|
||||
rescue StandardError
|
||||
DebugLogEntry.capture(category: "provider_sync", level: "error",
|
||||
message: "FinanceKit downstream scheduling failed", source: self.class.name,
|
||||
provider_key: "financekit", family: @item.family,
|
||||
metadata: { financekit_item_id: @item.id, batches: @batch_ids.size })
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def with_publisher_claim
|
||||
acquired = ActiveRecord::Base.connection.select_value(
|
||||
ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", advisory_lock_key ])
|
||||
)
|
||||
# Another worker holds this publisher's downstream work. It completes the
|
||||
# batches it claimed, and the sweep picks up anything left behind.
|
||||
return unless acquired
|
||||
|
||||
begin
|
||||
yield
|
||||
ensure
|
||||
ActiveRecord::Base.connection.execute(
|
||||
ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", advisory_lock_key ])
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
def advisory_lock_key
|
||||
# Matches the keying used by the other advisory-locked jobs in this app.
|
||||
@advisory_lock_key ||= Digest::MD5.hexdigest("#{ADVISORY_LOCK_SCOPE}:#{@item.id}").to_i(16) % (2**62)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -116,8 +116,7 @@ class Financekit::Processor
|
||||
# for the family and carry on with the rest of the capture.
|
||||
if observation.amount != amount || observation.currency != money["currency"] ||
|
||||
observation.direction != money["direction"]
|
||||
create_observation_conflict!(mapping, record)
|
||||
counts["review_required"] += 1
|
||||
counts[create_observation_conflict!(mapping, record) ? "review_required" : "settled"] += 1
|
||||
return
|
||||
end
|
||||
counts["balances"] += 1 if observation.previously_new_record?
|
||||
@@ -216,7 +215,9 @@ class Financekit::Processor
|
||||
# The family already chose to keep Sure's entry for this identity. The
|
||||
# tombstone is still recorded so the source cannot resurrect it, but the
|
||||
# protected entry stays and the answered conflict is not reopened.
|
||||
identity.review_required = false
|
||||
# Review state follows the same rule as resolution and upserts: it is
|
||||
# open while any conflict about this record still is.
|
||||
identity.review_required = identity.financekit_conflicts.open.exists?
|
||||
counts["settled"] += 1
|
||||
elsif entry
|
||||
Entry.transaction do
|
||||
@@ -311,15 +312,28 @@ class Financekit::Processor
|
||||
end
|
||||
|
||||
# Balance observations have no source transaction, so the conflict hangs off
|
||||
# the lineage alone and one open row covers the lineage until it is answered.
|
||||
# the lineage and carries the observation identity in its details. Returns
|
||||
# whether the record still needs review.
|
||||
#
|
||||
# Matching on that identity rather than the lineage alone is what makes
|
||||
# "keep Sure" durable here, the same way it is for a source transaction: the
|
||||
# publisher re-sends the same disagreement on every capture that covers it,
|
||||
# so keying the lookup on open rows made the decision last one capture. A
|
||||
# different observation still opens its own conflict.
|
||||
def create_observation_conflict!(mapping, record)
|
||||
@item.financekit_conflicts.find_or_create_by!(financekit_transaction: nil,
|
||||
details = { "source_id" => record["source_id"], "kind" => record["kind"],
|
||||
"observed_at" => record["observed_at"] }
|
||||
history = @item.financekit_conflicts
|
||||
.where(kind: "balance_observation_conflict",
|
||||
financekit_account_lineage_id: mapping.financekit_account_lineage_id)
|
||||
.where("details @> ?::jsonb", details.to_json)
|
||||
return false if history.exists?(resolution: "keep_sure")
|
||||
return true if history.open.exists?
|
||||
|
||||
@item.financekit_conflicts.create!(family: @item.family,
|
||||
financekit_account_lineage: mapping.financekit_account_lineage,
|
||||
kind: "balance_observation_conflict", status: "open") do |conflict|
|
||||
conflict.family = @item.family
|
||||
conflict.details = { "source_id" => record["source_id"], "kind" => record["kind"],
|
||||
"observed_at" => record["observed_at"] }
|
||||
end
|
||||
kind: "balance_observation_conflict", status: "open", details: details)
|
||||
true
|
||||
end
|
||||
|
||||
def create_conflict!(mapping, identity, kind)
|
||||
|
||||
@@ -21,6 +21,7 @@ class FinancekitConflict < ApplicationRecord
|
||||
financekit_transaction.update!(review_required: financekit_transaction.financekit_conflicts.open.exists?)
|
||||
end
|
||||
when "retry_after_repair"
|
||||
release_conflicting_observation!
|
||||
financekit_item.mark_repair!("conflict_retry_requested")
|
||||
if financekit_transaction
|
||||
financekit_transaction.update!(review_required: financekit_transaction.financekit_conflicts.open.exists?)
|
||||
@@ -28,4 +29,21 @@ class FinancekitConflict < ApplicationRecord
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Asking the publisher to retry only means something if the stored
|
||||
# observation stops blocking the replay. Observations are immutable, so the
|
||||
# same money would disagree again after the repair and the conflict would
|
||||
# simply reopen. Dropping the one the family declined lets the new
|
||||
# generation supply the value they chose to accept; every other observation
|
||||
# on the lineage is untouched, and the canonical balance still only moves
|
||||
# when a newer booked value lands.
|
||||
def release_conflicting_observation!
|
||||
return unless kind == "balance_observation_conflict" && financekit_account_lineage
|
||||
|
||||
financekit_account_lineage.financekit_balance_observations
|
||||
.where(source_id: details["source_id"], kind: details["kind"],
|
||||
observed_at: details["observed_at"]).delete_all
|
||||
end
|
||||
end
|
||||
|
||||
@@ -227,6 +227,34 @@ class Financekit::InboxTest < ActiveSupport::TestCase
|
||||
assert_not_nil second.reload.downstream_completed_at
|
||||
end
|
||||
|
||||
test "overlapping downstream workers fan out once" do
|
||||
batch, = accept_batch
|
||||
assert Financekit::Processor.new(@item).apply_next!.present?
|
||||
# Both snapshot the same incomplete ids before either performs, which is how
|
||||
# a per-upload job and the periodic sweep overlap in production.
|
||||
first = Financekit::Downstream.new(@item, FinancekitBatch.where(id: batch.id))
|
||||
second = Financekit::Downstream.new(@item, FinancekitBatch.where(id: batch.id))
|
||||
Family.any_instance.expects(:auto_match_transfers!).once.returns(nil)
|
||||
|
||||
first.perform!
|
||||
second.perform!
|
||||
|
||||
assert_not_nil batch.reload.downstream_completed_at
|
||||
end
|
||||
|
||||
test "a failure writing publisher health leaves the batches for recovery" do
|
||||
batch, = accept_batch
|
||||
assert Financekit::Processor.new(@item).apply_next!.present?
|
||||
FinancekitItem.any_instance.stubs(:update!).raises(ActiveRecord::StatementInvalid.new("health write failed"))
|
||||
|
||||
Financekit::Downstream.new(@item, FinancekitBatch.where(id: batch.id)).perform!
|
||||
|
||||
# Completing the batch without the health write would hide it from the
|
||||
# recovery sweep, which only looks for incomplete batches.
|
||||
assert_nil batch.reload.downstream_completed_at
|
||||
assert_nil FinancekitItem.find(@item.id).last_downstream_at
|
||||
end
|
||||
|
||||
test "the sweep recovers a backlog without materializing batch rows" do
|
||||
first = accept_and_apply
|
||||
second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
|
||||
|
||||
@@ -220,6 +220,88 @@ class Financekit::MappingTest < ActiveSupport::TestCase
|
||||
assert_equal "active", @item.reload.status
|
||||
end
|
||||
|
||||
test "a balance decision the family keeps is not reopened by an identical replay" do
|
||||
first = accept_and_apply
|
||||
disagreement = financekit_events.find { |record| record["kind"] == "balance_upsert" }
|
||||
disagreement["balance"]["money"] = money("999.00", "credit")
|
||||
second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
|
||||
events: [ disagreement ]))
|
||||
@item.financekit_conflicts.open.sole.resolve!(user: @user, resolution: "keep_sure")
|
||||
|
||||
third = accept_and_apply(financekit_payload(sequence: 3, predecessor_digest: second.payload_digest,
|
||||
events: [ disagreement ]))
|
||||
|
||||
assert_empty @item.financekit_conflicts.open
|
||||
assert_equal 1, @item.financekit_conflicts.count
|
||||
assert_equal 1, third.counts.fetch("settled")
|
||||
assert_equal BigDecimal("112.66"), @source.account.reload.balance
|
||||
end
|
||||
|
||||
test "a settled balance decision does not suppress a different disagreement" do
|
||||
first = accept_and_apply
|
||||
disagreement = financekit_events.find { |record| record["kind"] == "balance_upsert" }
|
||||
disagreement["balance"]["money"] = money("999.00", "credit")
|
||||
second = accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
|
||||
events: [ disagreement ]))
|
||||
@item.financekit_conflicts.open.sole.resolve!(user: @user, resolution: "keep_sure")
|
||||
|
||||
other = financekit_events.find { |record| record["kind"] == "balance_upsert" }
|
||||
other["balance"]["observed_at"] = 1.minute.from_now.iso8601
|
||||
other["balance"]["money"] = money("222.00", "credit")
|
||||
accept_and_apply(financekit_payload(sequence: 3, predecessor_digest: second.payload_digest,
|
||||
events: [ other ], captured_at: 1.minute.from_now.iso8601))
|
||||
accept_and_apply(financekit_payload(sequence: 4, predecessor_digest: FinancekitBatch.order(:sequence).last.payload_digest,
|
||||
events: [ other.deep_dup.tap { |event| event["balance"]["money"] = money("333.00", "credit") } ],
|
||||
captured_at: 1.minute.from_now.iso8601))
|
||||
|
||||
assert_equal 1, @item.financekit_conflicts.open.count
|
||||
end
|
||||
|
||||
test "retry after repair releases the observation blocking the replay" do
|
||||
first = accept_and_apply
|
||||
disagreement = financekit_events.find { |record| record["kind"] == "balance_upsert" }
|
||||
disagreement["balance"]["money"] = money("999.00", "credit")
|
||||
accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest,
|
||||
events: [ disagreement ]))
|
||||
|
||||
# An immutable observation would disagree again after the repair, so the
|
||||
# retry only means something once the declined one is out of the way.
|
||||
@item.financekit_conflicts.open.sole.resolve!(user: @user, resolution: "retry_after_repair")
|
||||
|
||||
assert_equal "repair_required", @item.reload.status
|
||||
assert_empty @source.financekit_balance_observations.where(source_id: @balance_id, kind: "booked")
|
||||
end
|
||||
|
||||
test "a tombstone leaves review open while another conflict is unresolved" do
|
||||
accept_and_apply
|
||||
entry = @source.account.entries.sole
|
||||
entry.update!(locked_attributes: { "name" => Time.current.iso8601 })
|
||||
identity = @source.financekit_transactions.sole
|
||||
tombstone = {
|
||||
"kind" => "transaction_tombstone",
|
||||
"tombstone" => {
|
||||
"source_id" => @transaction_id,
|
||||
"source_account_id" => @source_id,
|
||||
"lineage_id" => @source.financekit_account_lineage_id,
|
||||
"mapping_version" => @source.mapping_version
|
||||
}
|
||||
}
|
||||
upsert = accept_and_apply(financekit_payload(sequence: 2,
|
||||
predecessor_digest: FinancekitBatch.order(:sequence).last.payload_digest,
|
||||
events: [ financekit_events.last ]))
|
||||
retraction = accept_and_apply(financekit_payload(sequence: 3, predecessor_digest: upsert.payload_digest,
|
||||
events: [ tombstone ]))
|
||||
identity.financekit_conflicts.open.find_by!(kind: "protected_entry")
|
||||
.resolve!(user: @user, resolution: "keep_sure")
|
||||
|
||||
accept_and_apply(financekit_payload(sequence: 4, predecessor_digest: retraction.payload_digest,
|
||||
events: [ tombstone ]))
|
||||
|
||||
assert_equal [ "protected_tombstone" ], identity.financekit_conflicts.open.pluck(:kind)
|
||||
assert identity.reload.review_required, "review must stay open while a conflict about the record is"
|
||||
assert_equal 1, @source.account.entries.reload.count
|
||||
end
|
||||
|
||||
test "a source identifier outside the v1-v5 range is accepted" do
|
||||
uuidv7 = "01890a5d-ac96-774b-bcce-b302099a8057"
|
||||
event = financekit_events.last
|
||||
|
||||
Reference in New Issue
Block a user