Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Stop chunked NDJSON import memory from growing with the file (#5274)

Francisco R. Santosc036bf1cfd2e
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index 247a862f31..6988b0d11f 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -111,8 +111,8 @@ class Family::DataImporter
account_targets.each { |source_id, account| @id_mappings[:accounts][source_id] = account.id }
@security_cache = {}
@pending_replacements = {}
- @created_accounts = []
- @created_entries = []
+ @created_account_ids = []
+ @created_entry_ids = []
@summary = Hash.new { |hash, key| hash[key] = empty_summary_bucket }
end
@@ -148,7 +148,7 @@ class Family::DataImporter
import_rules(records["Rule"] || [])
end
- { accounts: @created_accounts, entries: @created_entries, summary: compact_summary }
+ { account_ids: @created_account_ids, entry_ids: @created_entry_ids, summary: compact_summary }
end
private
@@ -194,11 +194,21 @@ class Family::DataImporter
return unless @import_session
source_type = MAPPING_TYPES.fetch(mapping_key)
- mapping = @import_session.source_mappings.find_or_initialize_by(
- family: @family,
+ # The session outlives every chunk, so nothing here may append the mapping
+ # (and, through its target, the imported record) to one of its
+ # associations, or memory grows with the file. That rules out building
+ # through @import_session.source_mappings, and also assigning
+ # `import_session:`/`family:` objects, which only avoids it while the
+ # belongs_to has no inverse_of. Ids plus association(...).target= never
+ # inverse, and keep the loaded owners so validations don't reload them.
+ mapping = ImportSourceMapping.find_or_initialize_by(
+ import_session_id: @import_session.id,
+ family_id: @family.id,
source_type: source_type,
source_id: source_id
)
+ mapping.association(:import_session).target = @import_session
+ mapping.association(:family).target = @family
mapping.target = target
mapping.save!
end
@@ -383,7 +393,7 @@ class Family::DataImporter
end
map_source!(:accounts, old_id, account)
- @created_accounts << account if created
+ @created_account_ids << account.id if created
increment_summary("Account", created ? :created : :updated)
end
end
@@ -1008,7 +1018,7 @@ class Family::DataImporter
split_rows = importable_split_rows(data)
if split_rows.any?
- @created_entries << entry if created
+ @created_entry_ids << entry.id if created
import_split_lines!(entry, split_rows, fallback_tag_ids: new_tag_ids)
else
transaction.taggings.destroy_all unless created
@@ -1016,7 +1026,7 @@ class Family::DataImporter
transaction.taggings.create!(tag_id: tag_id)
end
- @created_entries << entry if created
+ @created_entry_ids << entry.id if created
end
increment_summary("Transaction", created ? :created : :updated)
@@ -1082,7 +1092,7 @@ class Family::DataImporter
end
map_source!(:transactions, row[:old_id], transaction) if row[:old_id].present?
- @created_entries << child_entry
+ @created_entry_ids << child_entry.id
end
end
@@ -1208,7 +1218,7 @@ class Family::DataImporter
end
entry.save!
- @created_entries << entry if created
+ @created_entry_ids << entry.id if created
increment_summary("Trade", created ? :created : :updated)
end
end
@@ -1295,7 +1305,7 @@ class Family::DataImporter
end
entry.save!
- @created_entries << entry if created
+ @created_entry_ids << entry.id if created
increment_summary("Valuation", created ? :created : :updated)
end
end
diff --git a/app/models/monarch_import.rb b/app/models/monarch_import.rb
index c9004897e8..49524f2fd8 100644
--- a/app/models/monarch_import.rb
+++ b/app/models/monarch_import.rb
@@ -252,8 +252,8 @@ class MonarchImport < Import
targets = included_target_mappings.to_h { |mapping| [ MonarchImport::Converter.source_id(mapping.key), mapping.target ] }
imported = Family::DataImporter.new(family, ndjson(result.records), import: self, account_targets: targets).import!
- Account.where(id: imported[:accounts].map(&:id)).update_all(import_id: id)
- Entry.where(id: imported[:entries].map(&:id)).update_all(import_id: id)
+ Account.where(id: imported[:account_ids]).update_all(import_id: id)
+ Entry.where(id: imported[:entry_ids]).update_all(import_id: id)
update!(summary: summary.merge("records" => imported[:summary]))
end
end
diff --git a/app/models/sure_import.rb b/app/models/sure_import.rb
index 334bd9b8cb..a3038e7470 100644
--- a/app/models/sure_import.rb
+++ b/app/models/sure_import.rb
@@ -4,6 +4,8 @@ class SureImport < Import
DEFAULT_MAX_NDJSON_SIZE_MB = 10
DEFAULT_MAX_ROW_COUNT = 100_000
+ # Ids per UPDATE batch when linking created records to the import.
+ LINK_BATCH_SIZE = 1_000
IMPORTABLE_NDJSON_TYPES = {
"Account" => :accounts,
"Balance" => :balances,
@@ -134,17 +136,21 @@ class SureImport < Import
importer = Family::DataImporter.new(family, ndjson_blob_string, import_session: import_session, import: self)
result = importer.import!
+ # DataImporter doesn't set import_id, so link the records it created here.
+ # Done by hand instead of `accounts.concat` / `entries.concat`: those load
+ # the association and need every record in memory at once, while this holds
+ # at most one batch of records at a time. Don't replace it with update_all,
+ # which would skip callbacks.
Import.transaction do
- result[:accounts].each { |account| account.save! if account.new_record? }
- result[:entries].each { |entry| entry.save! if entry.new_record? }
-
- account_ids = result[:accounts].filter_map(&:id)
- entry_ids = result[:entries].filter_map(&:id)
- existing_account_ids = accounts.where(id: account_ids).pluck(:id)
- existing_entry_ids = entries.where(id: entry_ids).pluck(:id)
-
- accounts.concat(result[:accounts].reject { |account| existing_account_ids.include?(account.id) })
- entries.concat(result[:entries].reject { |entry| existing_entry_ids.include?(entry.id) })
+ # IS DISTINCT FROM, not `!=`: a NULL import_id must match too.
+ result[:account_ids].each_slice(LINK_BATCH_SIZE) do |ids|
+ family.accounts.where(id: ids).where("accounts.import_id IS DISTINCT FROM ?", id)
+ .find_each { |account| account.update!(import_id: id) }
+ end
+ result[:entry_ids].each_slice(LINK_BATCH_SIZE) do |ids|
+ family.entries.where(id: ids).where("entries.import_id IS DISTINCT FROM ?", id)
+ .find_each { |entry| entry.update!(import_id: id) }
+ end
update!(summary: result[:summary]) if has_attribute?(:summary)
end
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index f2fd5b3b95..77e0b11d32 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -23,8 +23,8 @@ class Family::DataImporterTest < ActiveSupport::TestCase
importer = Family::DataImporter.new(@family, ndjson)
result = importer.import!
- assert_equal 1, result[:accounts].count
- account = result[:accounts].first
+ assert_equal 1, result[:account_ids].count
+ account = Account.find(result[:account_ids].first)
assert_equal "Test Checking", account.name
assert_equal 1500.0, account.balance.to_f
assert_equal "USD", account.currency
@@ -163,7 +163,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
result = Family::DataImporter.new(@family, ndjson, account_targets: { "old-account" => account }).import!
- assert_empty result[:accounts]
+ assert_empty result[:account_ids]
assert_equal [ "Grocer" ], account.entries.pluck(:name)
end
@@ -199,7 +199,8 @@ class Family::DataImporterTest < ActiveSupport::TestCase
}
])
- account = Family::DataImporter.new(@family, ndjson).import![:accounts].first
+ account_id = Family::DataImporter.new(@family, ndjson).import![:account_ids].first
+ account = Account.find(account_id)
assert account.reload.logo_brandfetch?
assert_not account.logo_auto_fetchable?
@@ -221,7 +222,8 @@ class Family::DataImporterTest < ActiveSupport::TestCase
}
])
- account = Family::DataImporter.new(@family, ndjson).import![:accounts].first
+ account_id = Family::DataImporter.new(@family, ndjson).import![:account_ids].first
+ account = Account.find(account_id)
assert account.reload.logo_automatic?
end
@@ -244,7 +246,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
importer = Family::DataImporter.new(@family, ndjson)
result = importer.import!
- account = result[:accounts].first
+ account = Account.find(result[:account_ids].first)
assert_equal "Closed Checking", account.name
assert_equal "disabled", account.status
end
@@ -267,7 +269,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
importer = Family::DataImporter.new(@family, ndjson)
result = importer.import!
- account = result[:accounts].first
+ account = Account.find(result[:account_ids].first)
assert_equal "Pending Delete Checking", account.name
assert_equal "active", account.status
end
@@ -990,7 +992,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
importer = Family::DataImporter.new(@family, ndjson)
result = importer.import!
- assert_equal 1, result[:entries].count
+ assert_equal 1, result[:entry_ids].count
transaction = @family.transactions.first
assert_not_nil transaction
@@ -1095,8 +1097,8 @@ class Family::DataImporterTest < ActiveSupport::TestCase
parent_entry = @family.entries.find_by!(name: "ATM withdrawal plus fee")
assert parent_entry.split_parent?
assert_equal true, parent_entry.excluded
- assert_equal 4, result[:entries].count
- assert_includes result[:entries].map(&:id), parent_entry.id
+ assert_equal 4, result[:entry_ids].count
+ assert_includes result[:entry_ids], parent_entry.id
transfer_child = parent_entry.child_entries.find_by!(name: "Cash movement")
fee_child = parent_entry.child_entries.find_by!(name: "ATM fee")
@@ -1302,7 +1304,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
result = importer.import!
# Account + Opening balance + Trade entry
- assert_equal 1, result[:entries].count
+ assert_equal 1, result[:entry_ids].count
trade = @family.trades.first
assert_not_nil trade
@@ -1766,7 +1768,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
importer = Family::DataImporter.new(@family, ndjson)
result = importer.import!
- assert_equal 1, result[:entries].count
+ assert_equal 1, result[:entry_ids].count
account = @family.accounts.find_by(name: "Property")
valuation = account.valuations.joins(:entry).find_by(entries: { name: "Updated valuation" })
@@ -3161,8 +3163,31 @@ class Family::DataImporterTest < ActiveSupport::TestCase
importer = Family::DataImporter.new(@family, ndjson)
result = importer.import!
- assert_equal 1, result[:accounts].count
- assert_equal "Valid Account", result[:accounts].first.name
+ assert_equal 1, result[:account_ids].count
+ account_id = result[:account_ids].first
+ assert_equal "Valid Account", Account.find(account_id).name
+ end
+
+ test "session import persists source mappings without retaining them on the session" do
+ session = @family.import_sessions.create!(expected_chunks: 1)
+ ndjson = [
+ { type: "Account", data: {
+ id: "acct-1", name: "Mapped Account", balance: "100.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "Transaction", data: {
+ id: "txn-1", account_id: "acct-1", date: "2024-01-15", amount: "-25.00",
+ name: "Coffee", currency: "USD"
+ } }
+ ].map(&:to_json).join("\n")
+
+ Family::DataImporter.new(@family, ndjson, import_session: session).import!
+
+ # The session lives for every chunk of a publish run; anything built onto
+ # its association stays in memory until the whole run ends.
+ assert_empty session.source_mappings.target
+ assert_empty @family.import_source_mappings.target
+ assert_equal %w[Account Transaction], ImportSourceMapping.where(import_session_id: session.id).pluck(:source_type).sort
end
test "skips unsupported record types" do
@@ -3186,7 +3211,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
importer = Family::DataImporter.new(@family, ndjson)
result = importer.import!
- assert_equal 1, result[:accounts].count
+ assert_equal 1, result[:account_ids].count
end
test "full import scenario with all entity types" do
@@ -3305,7 +3330,7 @@ class Family::DataImporterTest < ActiveSupport::TestCase
result = importer.import!
# Verify all entities were created
- assert_equal 1, result[:accounts].count
+ assert_equal 1, result[:account_ids].count
assert_equal 1, @family.categories.count
assert_equal 1, @family.tags.count
assert_equal 1, @family.merchants.count
diff --git a/test/models/import_session_test.rb b/test/models/import_session_test.rb
index 45525aaa88..af8f1dfaf5 100644
--- a/test/models/import_session_test.rb
+++ b/test/models/import_session_test.rb
@@ -139,8 +139,8 @@ class ImportSessionTest < ActiveSupport::TestCase
Object.new.tap do |importer|
importer.define_singleton_method(:import!) do
{
- accounts: [],
- entries: [],
+ account_ids: [],
+ entry_ids: [],
summary: { "transactions" => { "created" => 1 } }
}
end
diff --git a/test/models/sure_import_test.rb b/test/models/sure_import_test.rb
index 9753dd883f..fbc0fdc921 100644
--- a/test/models/sure_import_test.rb
+++ b/test/models/sure_import_test.rb
@@ -250,6 +250,57 @@ class SureImportTest < ActiveSupport::TestCase
assert_equal({ "categories" => 1, "budgets" => 1, "budget_categories" => 1 }, @import.readback_verification["reused_record_counts"])
end
+ test "import links created accounts and entries without loading them" do
+ attach_ndjson(build_ndjson([
+ { type: "Account", data: {
+ id: "acct-1", name: "Linked Account", balance: "100.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "Transaction", data: {
+ id: "txn-1", account_id: "acct-1", date: "2024-01-15", amount: "-25.00",
+ name: "Coffee", currency: "USD"
+ } }
+ ]))
+
+ result = @import.import!
+
+ assert_equal 1, result[:account_ids].size
+ assert_equal 1, result[:entry_ids].size
+ assert_equal @import.id, Account.find(result[:account_ids].first).import_id
+ assert_equal @import.id, Entry.find(result[:entry_ids].first).import_id
+ assert_not @import.accounts.loaded?
+ assert_not @import.entries.loaded?
+ assert @import.data_committed?
+ end
+
+ test "an import links only the records it created, never another import's unlinked ones" do
+ other = @family.imports.create!(type: "SureImport")
+ other_account = accounts(:depository)
+ other_entry = entries(:transaction)
+ # Records another import committed but hasn't linked yet.
+ other_account.update_columns(import_id: nil)
+ other_entry.update_columns(import_id: nil)
+
+ attach_ndjson(import_payload("first"))
+ result = @import.import!
+
+ assert_nil other_account.reload.import_id
+ assert_nil other_entry.reload.import_id
+ assert_equal result[:account_ids].sort, @import.accounts.pluck(:id).sort
+ assert_equal result[:entry_ids].sort, @import.entries.pluck(:id).sort
+
+ other.ndjson_file.attach(io: StringIO.new(import_payload("second")), filename: "second.ndjson", content_type: "application/x-ndjson")
+ other.sync_ndjson_rows_count!
+ other_result = other.import!
+
+ assert_empty result[:account_ids] & other_result[:account_ids]
+ assert_empty result[:entry_ids] & other_result[:entry_ids]
+ assert_equal result[:account_ids].sort, @import.accounts.reload.pluck(:id).sort
+ assert_equal result[:entry_ids].sort, @import.entries.reload.pluck(:id).sort
+ assert_equal other_result[:account_ids].sort, other.accounts.pluck(:id).sort
+ assert_equal other_result[:entry_ids].sort, other.entries.pluck(:id).sort
+ end
+
test "publishes import successfully" do
attach_ndjson(build_ndjson([
{ type: "Account", data: {
@@ -1153,6 +1204,19 @@ class SureImportTest < ActiveSupport::TestCase
])
end
+ def import_payload(label)
+ build_ndjson([
+ { type: "Account", data: {
+ id: "acct-#{label}", name: "#{label} account", balance: "100.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "Transaction", data: {
+ id: "txn-#{label}", account_id: "acct-#{label}", date: "2024-01-15", amount: "-25.00",
+ name: "#{label} coffee", currency: "USD"
+ } }
+ ])
+ end
+
def build_ndjson(records)
records.map(&:to_json).join("\n")
end