The personal finance app for everyone (by everyone)
Ruby
fix(trade-republic): import timeline history beyond 50 pages (#4072)
Niels Eulink6b4945c89d6c
diff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rbindex bd9f624e41..1ba03ae246 100644--- a/app/models/provider/trade_republic_client.rb+++ b/app/models/provider/trade_republic_client.rb@@ -24,6 +24,21 @@ class Provider::TradeRepublicClientclass WafRequired < Error; endclass Timeout < Error; endclass MalformedResponse < Error; end+ # The websocket failed during the history backfill. The sync is retried+ # without the backfill, so one bad backfill page cannot block the rest of+ # the import, and the failure counts towards abandoning the backfill.+ # The pages read before the failure and the cursor to resume at are kept.+ class TimelineBackfillInterrupted < TransientProviderError+ attr_reader :topic, :reason, :cursor, :events++ def initialize(message = nil, topic:, reason:, cursor:, events: [])+ @topic = topic+ @reason = reason+ @cursor = cursor+ @events = events+ super(message)+ end+ endERROR_STATUS = {401 => AuthenticationRequired,@@ -82,6 +97,17 @@ class Provider::TradeRepublicClient].freezeSELL_SUBTITLE_MARKERS = %w[sell verkauf verkaufen verkopen].freezeMAX_TIMELINE_PAGES = 50+ TIMELINE_TOPICS = %w[timelineTransactions timelineActivityLog].freeze+ # A history backfill that keeps failing on the same cursor (for example an+ # expired one) is abandoned instead of being retried forever.+ MAX_TIMELINE_BACKFILL_FAILURES = 5+ MAX_TIMELINE_CURSOR_LENGTH = 1_024+ # Stored per topic in trade_republic_items.timeline_cursors:+ # { topic => { "newest_event_id", "backfill_cursor", "backfill_stop_event_id", "backfill_failures" } }+ # A backfill without a stop event reads the history to the end of the topic;+ # one with a stop event fills a gap of new events down to that event.+ TIMELINE_BACKFILL_KEYS = %w[backfill_cursor backfill_stop_event_id backfill_failures].freeze+ private_constant :TIMELINE_BACKFILL_KEYSMAX_TIMELINE_DETAILS = 200# Reserve this many detail fetches for newly discovered trade events each# sync. The remainder drains the oldest stored incomplete events; leftover@@ -110,6 +136,21 @@ class Provider::TradeRepublicClientdef [](key) = data[key]end+ # One walk through a timeline topic. `outcome` is :finished (end of the+ # topic), :caught_up (reached the stop event), :budget_exhausted (`cursor`+ # is where to continue), :stalled (pagination broke off at `cursor`) or+ # :failed (the page at `cursor` raised `error`).+ TimelinePass = Data.define(:events, :newest_event_id, :warnings, :outcome, :cursor, :error) do+ def initialize(error: nil, **attributes) = super+ end+ # One topic's events this sync and its state for the next sync.+ # `head_complete` is false when the newest pages stalled.+ TopicSync = Data.define(:events, :newest_event_id, :warnings, :head_complete, :state)+ # `cursors` holds the next per-topic state: the newest event id the head+ # pass stops at, and the history backfill position. `topic_event_ids` lists+ # the ids of the events each topic fetched.+ TimelineSync = Data.define(:events, :newest_event_id, :warnings, :pagination_complete, :detail_backfill_count, :cursors, :topic_event_ids)+attr_reader :phone_number, :pindef initialize(phone_number:, pin: nil)@@ -290,22 +331,28 @@ class Provider::TradeRepublicClientendend- def sync(session_txt:, known_newest_event_id: nil, timeline_max_pages: MAX_TIMELINE_PAGES, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {})+ def sync(session_txt:, known_newest_event_id: nil, timeline_cursors: {}, timeline_max_pages: MAX_TIMELINE_PAGES, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {})raise ConfigurationError, "session_txt is required" if session_txt.blank?+ interrupted_backfills = {}with_retry dosync_once(session_txt: session_txt,known_newest_event_id: known_newest_event_id,+ timeline_cursors: timeline_cursors,timeline_max_pages: timeline_max_pages,enrich_events: enrich_events,symbol_lookup_isins: symbol_lookup_isins,- known_instrument_symbols: known_instrument_symbols+ known_instrument_symbols: known_instrument_symbols,+ interrupted_backfills: interrupted_backfills)+ rescue TimelineBackfillInterrupted => e+ interrupted_backfills = interrupted_backfills.merge(e.topic => { reason: e.reason, cursor: e.cursor, events: e.events })+ raiseendend- def sync_once(session_txt:, known_newest_event_id:, timeline_max_pages:, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {})+ def sync_once(session_txt:, known_newest_event_id:, timeline_max_pages:, timeline_cursors: {}, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {}, interrupted_backfills: {})session = new_session(session_blob: session_txt)account_response = session.get("/api/v2/auth/account")return Result.new(data: { "status" => "session_expired" }) if [ 401, 403 ].include?(account_response.code.to_i)@@ -363,29 +410,28 @@ class Provider::TradeRepublicClientinstrument_symbols = known_symbols.dupunresolved_symbol_isins = []- events = []- newest_event_id = nil- timeline_warnings = []- timeline_complete = false- detail_backfill_count = 0+ timeline = nilbegin- events, newest_event_id, timeline_warnings, timeline_complete, detail_backfill_count = collect_all_timeline(+ timeline = collect_all_timeline(websocket,known_newest_event_id: known_newest_event_id,max_pages: timeline_max_pages.to_i,- enrich_events: enrich_events+ enrich_events: enrich_events,+ timeline_cursors: timeline_cursors,+ interrupted_backfills: interrupted_backfills)instrument_symbols = enrich_trade_instrument_symbols(websocket,- events,+ timeline.events,known_symbols: known_symbols,extra_isins: symbol_lookup_isins,unresolved: unresolved_symbol_isins)- warnings.concat(timeline_warnings)- # Timeline domain reflects list pagination only. Detail backlog drains- # across later syncs and must not freeze newest_event_id.- domain_statuses["timeline"] = timeline_complete ? "success" : "partial"+ warnings.concat(timeline.warnings)+ # Timeline domain reflects the newest pages only. The history backfill+ # and detail backlog drain across later syncs and must not freeze+ # newest_event_id.+ domain_statuses["timeline"] = timeline.pagination_complete ? "success" : "partial"rescue MalformedResponse, ProviderUnavailable => eraise if e.is_a?(TransientProviderError)warnings << "timeline fetch failed: #{e.message}"@@ -401,12 +447,14 @@ class Provider::TradeRepublicClient"currency" => money_currency(cash)}.compact),"positions" => positions,- "events" => events,+ "events" => timeline&.events || [],"instrument_symbols" => instrument_symbols,"unresolved_symbol_isins" => unresolved_symbol_isins,- "newest_event_id" => newest_event_id,- "timeline_pagination_complete" => timeline_complete,- "detail_backfill_count" => detail_backfill_count,+ "newest_event_id" => timeline&.newest_event_id,+ "timeline_pagination_complete" => timeline&.pagination_complete || false,+ "timeline_cursors" => timeline&.cursors,+ "timeline_topic_event_ids" => timeline&.topic_event_ids,+ "detail_backfill_count" => timeline&.detail_backfill_count || 0,"warnings" => warnings,"position_warnings" => position_warnings})@@ -420,6 +468,22 @@ class Provider::TradeRepublicClientclass << selfdef available? = !!defined?(WebSocket::Driver)+ # Stops the given topics' backfills that read further back in history.+ # Gap backfills fetch events newer than anything stored, so they keep+ # running.+ def stop_timeline_history_backfills(timeline_cursors, topics:)+ timeline_cursors.to_h.to_h do |topic, state|+ history_backfill = topics.include?(topic) && state.is_a?(Hash) &&+ state["backfill_cursor"].present? && state["backfill_stop_event_id"].blank?+ [ topic, history_backfill ? state.except(*TIMELINE_BACKFILL_KEYS) : state ]+ end+ end+++ def pending_timeline_backfills(timeline_cursors)+ timeline_cursors.to_h.count { |_topic, state| state.is_a?(Hash) && state["backfill_cursor"].present? }+ end+def requires_trade_detail?(item)return false unless item.is_a?(Hash)@@ -1108,29 +1172,20 @@ class Provider::TradeRepublicClientnilend- def collect_timeline(websocket, known_newest_event_id:, max_pages:)- collect_timeline_topic(- websocket,- topic: "timelineTransactions",- known_newest_event_id: known_newest_event_id,- max_pages: max_pages- )- end-- def collect_all_timeline(websocket, known_newest_event_id:, max_pages:, enrich_events: [])- transaction_events, transaction_newest, transaction_warnings, transaction_complete = collect_timeline_topic(- websocket,- topic: "timelineTransactions",- known_newest_event_id: known_newest_event_id,- max_pages: max_pages- )- activity_events, activity_newest, activity_warnings, activity_complete = collect_timeline_topic(- websocket,- topic: "timelineActivityLog",- known_newest_event_id: known_newest_event_id,- max_pages: max_pages- )- skeleton_events = (transaction_events + activity_events).uniq do |event|+ def collect_all_timeline(websocket, known_newest_event_id:, max_pages:, enrich_events: [], timeline_cursors: {}, interrupted_backfills: {})+ timeline_cursors = (timeline_cursors || {}).to_h.stringify_keys+ topics = TIMELINE_TOPICS.index_with do |topic|+ state = timeline_cursors[topic].is_a?(Hash) ? timeline_cursors[topic].stringify_keys : {}+ sync_timeline_topic(+ websocket,+ topic: topic,+ state: state,+ fallback_newest_event_id: known_newest_event_id,+ max_pages: max_pages,+ interrupted_backfill: interrupted_backfills[topic]+ )+ end.values+ skeleton_events = topics.flat_map(&:events).uniq do |event|event["id"].presence || event.slice("timestamp", "eventType", "title", "subtitle", "detail")endevents, detail_warnings, detail_backfill_count = enrich_timeline_details(@@ -1141,57 +1196,186 @@ class Provider::TradeRepublicClient# Backfilled stored events are older than this sync's pages and must not# pull the list cursor backwards.newest_event = skeleton_events.max_by { |event| event["timestamp"].to_s }- # Pagination completeness only — pending details drain on later syncs.- timeline_complete = transaction_complete != false && activity_complete != false- [- events,- newest_event&.dig("id") || transaction_newest || activity_newest,- transaction_warnings + activity_warnings + detail_warnings,- timeline_complete,- detail_backfill_count- ]- end-- def collect_timeline_topic(websocket, topic:, known_newest_event_id:, max_pages:)+ TimelineSync.new(+ events: events,+ newest_event_id: newest_event&.dig("id") || topics.filter_map(&:newest_event_id).first,+ warnings: topics.flat_map(&:warnings) + detail_warnings,+ # Newest pages only — the history backfill and pending details drain on+ # later syncs.+ pagination_complete: topics.all?(&:head_complete),+ detail_backfill_count: detail_backfill_count,+ cursors: TIMELINE_TOPICS.zip(topics.map(&:state)).to_h.compact_blank,+ topic_event_ids: TIMELINE_TOPICS.zip(topics.map { |topic| topic.events.filter_map { |event| event["id"].presence&.to_s } }).to_h+ )+ end++ # Reads a topic's newest pages down to the event the previous sync stopped+ # at, then continues the history backfill. When more pages remain than the+ # budget allows (a first sync of a long history, or a gap of new events+ # since the last sync) the backfill takes over from where the newest pages+ # ran out, so older events are imported over several syncs.+ #+ # The per-topic newest event is authoritative. The item's single+ # newest_event_id only seeds topics synced before per-topic state existed.+ def sync_timeline_topic(websocket, topic:, state:, fallback_newest_event_id:, max_pages:, interrupted_backfill: nil)+ known_newest_event_id = state["newest_event_id"].presence || fallback_newest_event_id.presence+ head = collect_timeline_topic(websocket, topic: topic, known_newest_event_id: known_newest_event_id, max_pages: max_pages)+ events = head.events+ warnings = head.warnings.dup+ head_complete = head.outcome != :stalled++ if head_complete+ state = state.merge("newest_event_id" => head.newest_event_id || known_newest_event_id).compact+ if head.outcome == :budget_exhausted+ # A gap stops at the previous newest event. A backfill that was still+ # running is replaced, so the new one reads down to its stop event+ # (or to the end of the topic) to cover that range too.+ stop_event_id = state["backfill_cursor"].present? ? state["backfill_stop_event_id"] : known_newest_event_id+ state = start_timeline_backfill(state, topic: topic, cursor: head.cursor, stop_event_id: stop_event_id, warnings: warnings)+ end+ end++ if interrupted_backfill+ # The websocket failed during this topic's backfill, and the sync is+ # now being retried without it. The pages read before the failure are+ # kept and the backfill resumes at the failed page on the next sync.+ # Backfills of other topics still run.+ if state["backfill_cursor"].present?+ events += interrupted_backfill[:events]+ state = timeline_backfill_stopped(state, cursor: interrupted_backfill[:cursor], topic: topic, reason: interrupted_backfill[:reason], warnings: warnings)+ end+ elsif state["backfill_cursor"].present?+ backfill_events, state = continue_timeline_backfill(websocket, topic: topic, state: state, max_pages: max_pages, warnings: warnings)+ events += backfill_events+ end++ TopicSync.new(events: events, newest_event_id: head.newest_event_id, warnings: warnings, head_complete: head_complete, state: state)+ end++ def start_timeline_backfill(state, topic:, cursor:, stop_event_id:, warnings:)+ state = state.except(*TIMELINE_BACKFILL_KEYS)+ return state unless storable_timeline_cursor?(cursor, topic: topic, warnings: warnings)++ state.merge("backfill_cursor" => cursor, "backfill_stop_event_id" => stop_event_id).compact+ end++ # Returns the backfilled events and the topic state for the next sync.+ def continue_timeline_backfill(websocket, topic:, state:, max_pages:, warnings:)+ pass = collect_timeline_topic(+ websocket,+ topic: topic,+ known_newest_event_id: state["backfill_stop_event_id"],+ max_pages: max_pages,+ start_cursor: state["backfill_cursor"]+ )+ warnings.concat(pass.warnings)++ case pass.outcome+ when :finished, :caught_up+ [ pass.events, state.except(*TIMELINE_BACKFILL_KEYS) ]+ when :budget_exhausted+ next_state = start_timeline_backfill(state, topic: topic, cursor: pass.cursor, stop_event_id: state["backfill_stop_event_id"], warnings: warnings)+ [ pass.events, next_state ]+ else+ reason = pass.error&.class&.name&.demodulize || "pagination stalled"+ if pass.error.is_a?(Timeout) || pass.error.is_a?(TransientProviderError)+ raise TimelineBackfillInterrupted.new(+ "Trade Republic timeline backfill for #{topic} was interrupted",+ topic: topic,+ reason: reason,+ cursor: pass.cursor,+ events: pass.events+ )+ end++ [ pass.events, timeline_backfill_stopped(state, cursor: pass.cursor, topic: topic, reason: reason, warnings: warnings) ]+ end+ end++ # Resumes after the last page that was read. Abandoning counts failures+ # in a row at the same position, so a pass that moved forward starts the+ # count again.+ def timeline_backfill_stopped(state, cursor:, topic:, reason:, warnings:)+ return state.except(*TIMELINE_BACKFILL_KEYS) unless storable_timeline_cursor?(cursor, topic: topic, warnings: warnings)++ state = state.except("backfill_failures") if cursor != state["backfill_cursor"]+ timeline_backfill_failed(state.merge("backfill_cursor" => cursor), topic: topic, reason: reason, warnings: warnings)+ end++ # Keeps the cursor so the next sync retries the same page, until the+ # backfill has failed too often in a row.+ def timeline_backfill_failed(state, topic:, reason:, warnings:)+ failures = state["backfill_failures"].to_i + 1+ if failures >= MAX_TIMELINE_BACKFILL_FAILURES+ warnings << "timeline history backfill for #{topic} abandoned after #{failures} failed attempts (#{reason})"+ return state.except(*TIMELINE_BACKFILL_KEYS)+ end++ warnings << "timeline history backfill failed for #{topic} (#{reason})"+ state.merge("backfill_failures" => failures)+ end++ # Cursors come from the provider and are stored, so only short scalars+ # are kept.+ def storable_timeline_cursor?(cursor, topic:, warnings:)+ return true if (cursor.is_a?(String) || cursor.is_a?(Integer)) && cursor.to_s.length <= MAX_TIMELINE_CURSOR_LENGTH++ warnings << "timeline pagination cursor for #{topic} cannot be stored; older history is not imported"+ false+ end++ def collect_timeline_topic(websocket, topic:, known_newest_event_id:, max_pages:, start_cursor: nil)items = []- newest_event_id = nil- cursor = nilwarnings = []+ cursor = start_cursor+ seen_cursors = Set.new([ start_cursor ].compact)+ page_budget = [ max_pages, MAX_TIMELINE_PAGES ].minpages = 0- seen_cursors = Set.new- reached_known_event = false- complete = true- while pages < [ max_pages, MAX_TIMELINE_PAGES ].min+ outcome = :finished+ error = nil+ loop do+ if pages >= page_budget+ outcome = cursor.present? ? :budget_exhausted : :stalled+ break+ endpayload = { type: topic }payload[:after] = cursor if cursor- response = subscribe(websocket, payload)- page_items = response.is_a?(Hash) ? Array(response["items"]) : []- break if page_items.empty?- page_items.each do |item|- id = item["id"].to_s- reached_known_event ||= known_newest_event_id.present? && id == known_newest_event_id.to_s- items << item- newest_event_id ||= id.presence+ begin+ response = subscribe(websocket, payload)+ rescue Timeout, MalformedResponse, ProviderUnavailable => e+ # The newest pages fail as a whole; a backfill keeps what it read.+ raise if start_cursor.nil?++ error = e+ outcome = :failed+ breakend- cursor = response.dig("cursors", "after")- break if cursor.blank?- if reached_known_event+ page_items = response.is_a?(Hash) ? Array(response["items"]) : []+ items.concat(page_items)+ if known_newest_event_id.present? && page_items.any? { |item| item["id"].to_s == known_newest_event_id.to_s }+ outcome = :caught_upbreakend- if seen_cursors.include?(cursor)+ # An empty page only ends the topic when it carries no next cursor.+ next_cursor = response.dig("cursors", "after") if response.is_a?(Hash)+ break if next_cursor.blank?+ if seen_cursors.include?(next_cursor)warnings << "timeline pagination cursor repeated for #{topic}"- complete = false+ outcome = :stalledbreakend- seen_cursors << cursor+ seen_cursors << next_cursor+ cursor = next_cursorpages += 1end- if cursor.present? && !reached_known_event && pages >= [ max_pages, MAX_TIMELINE_PAGES ].min- warnings << "timeline pagination truncated for #{topic}"- complete = false- end- events = items.map { |item| build_skeleton_event(item, warnings: warnings) }- [ events, newest_event_id, warnings, complete ]+ TimelinePass.new(+ events: items.map { |item| build_skeleton_event(item, warnings: warnings) },+ newest_event_id: items.filter_map { |item| item["id"].to_s.presence }.first,+ warnings: warnings,+ outcome: outcome,+ cursor: cursor,+ error: error+ )enddef build_skeleton_event(item, warnings: nil)@@ -1209,7 +1393,8 @@ class Provider::TradeRepublicClient# dividend events, drain oldest stored incomplete / price-backfill trades# next, then spend any leftover on additional new events. Failed attempts# still consume budget so a bad event cannot starve the rest of the queue- # forever within one sync. Stored dividends are not backfilled.+ # forever within one sync. Stored dividends without their detail are+ # backfilled too.def enrich_timeline_details(websocket, events, enrich_events: [])warnings = []events = Array(events)@@ -1218,6 +1403,7 @@ class Provider::TradeRepublicClient(self.class.incomplete_trade_detail_event?(event) || self.class.dividend_detail_missing?(event))endnew_ids = new_candidates.to_set { |event| event["id"].to_s }+ page_ids = events.filter_map { |event| event["id"].presence&.to_s }.to_setbacklog_candidates = Array(enrich_events).select do |event|next false unless event.is_a?(Hash)@@ -1225,8 +1411,11 @@ class Provider::TradeRepublicClientnext false if item["id"].blank?next false if new_ids.include?(item["id"].to_s)+ # A dividend on this sync's pages is handled there: a new one is+ # fetched above, and one that already has its details needs nothing.self.class.incomplete_trade_detail_event?(item) ||- self.class.trade_detail_needs_price_backfill?(item)+ self.class.trade_detail_needs_price_backfill?(item) ||+ (self.class.dividend_detail_missing?(item) && !page_ids.include?(item["id"].to_s))endbudget = MAX_TIMELINE_DETAILSdiff --git a/app/models/trade_republic_item/importer.rb b/app/models/trade_republic_item/importer.rbindex db74cabc6b..6bef6a3a0b 100644--- a/app/models/trade_republic_item/importer.rb+++ b/app/models/trade_republic_item/importer.rb@@ -19,6 +19,7 @@ class TradeRepublicItem::Importerresult = provider.sync(session_txt: trade_republic_item.session_blob,known_newest_event_id: known_newest_event_id,+ timeline_cursors: force_full_timeline_fetch? ? {} : trade_republic_item.timeline_cursors,enrich_events: events_needing_detail_enrichment,symbol_lookup_isins: isins_needing_symbol_lookup,known_instrument_symbols: stored_instrument_symbols@@ -33,25 +34,30 @@ class TradeRepublicItem::Importer"Trade Republic session expired. Re-authentication required."end+ capped_topics = []ActiveRecord::Base.transaction do- upsert_account(data, domain_statuses: domain_statuses)+ capped_topics = upsert_account(data, domain_statuses: domain_statuses)trade_republic_item.update!(status: :good,newest_event_id: timeline_cursor_for(data, domain_statuses),+ timeline_cursors: timeline_cursors_for(data, domain_statuses, capped_topics: capped_topics),session_blob: data["session_txt"].presence || trade_republic_item.session_blob)end- record_provider_warnings(data["warnings"])+ record_provider_warnings(Array(data["warnings"]) + importer_warnings(capped_topics: capped_topics)){success: true,- detail_backfill_count: data["detail_backfill_count"].to_i+ detail_backfill_count: data["detail_backfill_count"].to_i,+ timeline_backfill_count: Provider::TradeRepublicClient.pending_timeline_backfills(trade_republic_item.timeline_cursors)}endprivate+ # Returns the topics whose fetched events the size cap of the stored+ # timeline dropped.def upsert_account(data, domain_statuses:)account_info = data["account"] || {}unless domain_statuses["account_metadata"] == "success"@@ -69,7 +75,7 @@ class TradeRepublicItem::Importertrade_republic_item.family.currencyportfolio_account = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")- upsert_kind(+ portfolio_capped = upsert_kind(kind: "portfolio",external_id: account_id,name: build_account_name(account_id, kind: "portfolio"),@@ -78,6 +84,7 @@ class TradeRepublicItem::Importercash_balance: 0,positions: Array(data["positions"]),events: data["events"],+ topic_event_ids: data["timeline_topic_event_ids"],instrument_symbols: data["instrument_symbols"],unresolved_symbol_isins: data["unresolved_symbol_isins"],warnings: position_warnings(data),@@ -86,7 +93,7 @@ class TradeRepublicItem::Importer# Pass every event into the cash merge, including orderExecution. Filtering# happens after merge so a newly categorized savings-plan event can replace# and remove its older unmapped cash copy.- upsert_kind(+ cash_capped = upsert_kind(kind: "cash",external_id: "cash:#{account_id}",name: build_account_name(account_id, kind: "cash"),@@ -95,11 +102,13 @@ class TradeRepublicItem::Importercash_balance: cash_balance(data),positions: [],events: Array(data["events"]),+ topic_event_ids: data["timeline_topic_event_ids"],instrument_symbols: data["instrument_symbols"],warnings: [],domain_statuses: domain_statuses)upsert_crypto_account(account_id, currency, domain_statuses)+ portfolio_capped | cash_cappedend# Crypto gets its own account because Sure has a Crypto account type.@@ -138,13 +147,14 @@ class TradeRepublicItem::ImporterArray(portfolio&.raw_positions_payload).select { |position| TradeRepublicAccount.crypto_position?(position) }end- def upsert_kind(kind:, external_id:, name:, currency:, current_balance:, cash_balance:, positions:, events:, instrument_symbols:, warnings:, domain_statuses:, unresolved_symbol_isins: [])+ def upsert_kind(kind:, external_id:, name:, currency:, current_balance:, cash_balance:, positions:, events:, instrument_symbols:, warnings:, domain_statuses:, topic_event_ids: nil, unresolved_symbol_isins: [])tr_account = trade_republic_item.trade_republic_accounts.find_by(trade_republic_account_id: external_id) ||trade_republic_item.trade_republic_accounts.find_or_initialize_by(kind: kind)portfolio_status = domain_statuses["portfolio"]cash_status = domain_statuses["cash"]timeline_status = domain_statuses["timeline"]domain_status = kind == "portfolio" ? portfolio_status : cash_status+ capped_topics = []attrs = {trade_republic_account_id: external_id,name: name,@@ -171,11 +181,13 @@ class TradeRepublicItem::Importer# Drop order executions before the size cap so they never crowd out# cash events on the cash account.merged = merged.reject { |event| event_category(event) == "orderExecution" } if kind == "cash"+ capped_topics = capped_timeline_topics(merged, existing: tr_account.raw_timeline_payload, incoming: events, topic_event_ids: topic_event_ids)attrs[:raw_timeline_payload] = merged.last(MAX_TIMELINE_EVENTS)endtr_account.assign_attributes(attrs)tr_account.save!+ capped_topicsenddef normalized_domain_statuses(data)@@ -208,21 +220,26 @@ class TradeRepublicItem::Importerenddef known_newest_event_id- return if trade_republic_item.newest_event_id.blank?+ return if force_full_timeline_fetch?- # A previous implementation could persist the newest cursor while- # dropping the actual event payload. Force one full timeline fetch in- # that state so historical data can be recovered instead of remaining- # permanently invisible.- portfolio_accounts = trade_republic_item.trade_republic_accounts.select(&:portfolio?)- return if portfolio_accounts.any? { |account| Array(account.raw_timeline_payload).blank? }+ trade_republic_item.newest_event_id.presence+ end++ # A previous implementation could persist the newest cursor while+ # dropping the actual event payload. Force one full timeline fetch in+ # that state so historical data can be recovered instead of remaining+ # permanently invisible.+ def force_full_timeline_fetch?+ return false if trade_republic_item.newest_event_id.blank?- trade_republic_item.newest_event_id+ portfolio_accounts = trade_republic_item.trade_republic_accounts.select(&:portfolio?)+ portfolio_accounts.any? { |account| Array(account.raw_timeline_payload).blank? }end- # Incomplete trade-detail events and complete trades still missing a share- # price (stored before execution price/fees were parsed). Oldest first so- # repeated syncs progressively drain historical starvation.+ # Incomplete trade-detail events, complete trades still missing a share+ # price (stored before execution price/fees were parsed) and dividends+ # without their detail. Oldest first so repeated syncs progressively drain+ # historical starvation.def events_needing_detail_enrichmentportfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")return [] unless portfolio@@ -230,7 +247,8 @@ class TradeRepublicItem::ImporterArray(portfolio.raw_timeline_payload).select do |event|Provider::TradeRepublicClient.incomplete_trade_detail_event?(event) ||- Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(event)+ Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(event) ||+ Provider::TradeRepublicClient.dividend_detail_missing?(event)end.sort_by { |event| event_timestamp(event) }.first(Provider::TradeRepublicClient::MAX_TIMELINE_DETAILS)@@ -281,7 +299,9 @@ class TradeRepublicItem::Importerend# Advance the list cursor whenever timeline pagination finished, even when- # a detail backlog remains for later syncs.+ # a detail backlog remains for later syncs. The per-topic newest events in+ # timeline_cursors take precedence; this column seeds topics without+ # their own state and triggers the forced full fetch.def timeline_cursor_for(data, domain_statuses)pagination_complete = if data.key?("timeline_pagination_complete")data["timeline_pagination_complete"]@@ -294,6 +314,61 @@ class TradeRepublicItem::Importerdata["newest_event_id"]end+ # Per-topic newest event and history backfill position for the next+ # sync. Kept as-is when the timeline failed so no progress is lost. Once+ # the stored history is full, a topic whose fetched events were dropped+ # would lose its older pages straight away, so its history backfill stops.+ def timeline_cursors_for(data, domain_statuses, capped_topics:)+ stored = trade_republic_item.timeline_cursors+ return stored if domain_statuses["timeline"] == "failed" || data["timeline_cursors"].nil?++ cursors = data["timeline_cursors"].to_h+ return cursors if capped_topics.empty?++ Provider::TradeRepublicClient.stop_timeline_history_backfills(cursors, topics: capped_topics)+ end++ def importer_warnings(capped_topics:)+ return [] if capped_topics.empty?++ [ "timeline history exceeds #{MAX_TIMELINE_EVENTS} events; older history is not imported" ]+ end++ # The topics whose events, fetched for the first time this sync, the size+ # cap would discard, i.e. whose history reaches further back than can be+ # stored. A dropped event that can't be traced to a topic (no id, or no+ # per-topic ids from the provider) counts against every topic.+ def capped_timeline_topics(merged, existing:, incoming:, topic_event_ids:)+ overflow = merged.size - MAX_TIMELINE_EVENTS+ return [] unless overflow.positive?++ existing_keys = Array(existing).filter_map { |event| timeline_event_key(event) }.to_set+ fetched_keys = Array(incoming).filter_map { |event| timeline_event_key(event) }.reject { |key| existing_keys.include?(key) }.to_set+ topics_by_id = Hash.new { |hash, id| hash[id] = [] }+ topic_event_ids.to_h.each { |topic, ids| Array(ids).each { |id| topics_by_id[id.to_s] << topic } }++ merged.first(overflow).flat_map do |event|+ next [] unless fetched_keys.include?(timeline_event_key(event))++ topics = topics_by_id.fetch(event_id(event).to_s, [])+ topics.presence || Provider::TradeRepublicClient::TIMELINE_TOPICS+ end.uniq+ end++ # Matches how merge_timeline_events collapses events: by id, or by the+ # whole event when it has none.+ def timeline_event_key(event)+ return unless event.is_a?(Hash)++ event_id(event) || event.as_json+ end++ def event_id(event)+ return unless event.is_a?(Hash)++ (event["id"] || event[:id]).presence+ end+def merge_timeline_events(existing, incoming)events_by_id = {}(Array(existing) + Array(incoming)).each do |event|diff --git a/app/models/trade_republic_item/syncer.rb b/app/models/trade_republic_item/syncer.rbindex d440cfb208..d76e785b83 100644--- a/app/models/trade_republic_item/syncer.rb+++ b/app/models/trade_republic_item/syncer.rb@@ -99,7 +99,8 @@ class TradeRepublicItem::Syncer"tr_events" => stats[:events],"tr_unknown_events" => stats[:unknown_events],"tr_pending_trade_details" => stats[:pending_trade_details],- "tr_detail_backfills" => import_result.is_a?(Hash) ? import_result[:detail_backfill_count].to_i : 0+ "tr_detail_backfills" => import_result.is_a?(Hash) ? import_result[:detail_backfill_count].to_i : 0,+ "tr_timeline_backfills" => import_result.is_a?(Hash) ? import_result[:timeline_backfill_count].to_i : 0})enddiff --git a/db/migrate/20261008120000_add_timeline_cursors_to_trade_republic_items.rb b/db/migrate/20261008120000_add_timeline_cursors_to_trade_republic_items.rbnew file mode 100644index 0000000000..b5573292a9--- /dev/null+++ b/db/migrate/20261008120000_add_timeline_cursors_to_trade_republic_items.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddTimelineCursorsToTradeRepublicItems < ActiveRecord::Migration[8.1]+ def change+ add_column :trade_republic_items, :timeline_cursors, :jsonb, default: {}, null: false+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 4f76c9406c..7b597565ae 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_10_08_090000) do+ActiveRecord::Schema[8.1].define(version: 2026_10_08_120000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -2684,6 +2684,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_08_090000) dot.boolean "scheduled_for_deletion", default: false, null: falset.text "session_blob"t.string "status", default: "good", null: false+ t.jsonb "timeline_cursors", default: {}, null: falset.datetime "updated_at", null: falset.index ["family_id", "brokerage_account_id"], name: "index_trade_republic_items_on_family_id_and_brokerage_account", unique: true, where: "((brokerage_account_id IS NOT NULL) AND (scheduled_for_deletion = false))"t.index ["family_id"], name: "index_trade_republic_items_on_family_id"diff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rbindex 9b35f1c1a2..69d6fe1f34 100644--- a/test/models/trade_republic_client_test.rb+++ b/test/models/trade_republic_client_test.rb@@ -84,39 +84,43 @@ class TradeRepublicClientTest < ActiveSupport::TestCasetest "merges transaction and activity timelines without duplicate events" doresponses = {- "timelineTransactions" => [ [ { "id" => "cash-1", "timestamp" => "2026-08-02" } ], "cash-1", [], true ],- "timelineActivityLog" => [ [ { "id" => "cash-1", "timestamp" => "2026-08-02" }, { "id" => "trade-1", "timestamp" => "2026-08-03" } ], "trade-1", [], true ]+ "timelineTransactions" => timeline_pass([ { "id" => "cash-1", "timestamp" => "2026-08-02" } ], "cash-1"),+ "timelineActivityLog" => timeline_pass([ { "id" => "cash-1", "timestamp" => "2026-08-02" }, { "id" => "trade-1", "timestamp" => "2026-08-03" } ], "trade-1")}@client.define_singleton_method(:collect_timeline_topic) do |_websocket, topic:, **_|responses.fetch(topic)end- events, newest_id, warnings = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 2)+ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 2)- assert_equal %w[cash-1 trade-1], events.map { |event| event["id"] }- assert_equal "trade-1", newest_id- assert_empty warnings+ assert_equal %w[cash-1 trade-1], timeline.events.map { |event| event["id"] }+ assert_equal "trade-1", timeline.newest_event_id+ assert_empty timeline.warnings+ assert_equal(+ { "timelineTransactions" => { "newest_event_id" => "cash-1" }, "timelineActivityLog" => { "newest_event_id" => "trade-1" } },+ timeline.cursors+ )endtest "advances the list cursor when only trade details remain pending" do+ responses = {+ "timelineTransactions" => timeline_pass([ {+ "id" => "trade-1",+ "timestamp" => "2026-08-02",+ "eventType" => "TRADING_TRADE_EXECUTED",+ "category" => "orderExecution",+ "detail" => { "amount" => -100.0 }+ } ], "trade-1"),+ "timelineActivityLog" => timeline_pass([], nil)+ }@client.define_singleton_method(:collect_timeline_topic) do |_websocket, topic:, **_|- if topic == "timelineTransactions"- [ [ {- "id" => "trade-1",- "timestamp" => "2026-08-02",- "eventType" => "TRADING_TRADE_EXECUTED",- "category" => "orderExecution",- "detail" => { "amount" => -100.0 }- } ], "trade-1", [], true ]- else- [ [], nil, [], true ]- end+ responses.fetch(topic)end@client.define_singleton_method(:subscribe) do |_websocket, **_|raise Provider::TradeRepublicClient::MalformedResponse, "no budget"end- events, newest_id, warnings, complete, backfill_count = @client.send(+ timeline = @client.send(:collect_all_timeline,Object.new,known_newest_event_id: nil,@@ -124,33 +128,527 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseenrich_events: [])- assert_equal [ "trade-1" ], events.map { |event| event["id"] }- assert_equal "trade-1", newest_id- assert complete- assert_equal 0, backfill_count- assert_includes warnings, "detail fetch failed for event trade-1"+ assert_equal [ "trade-1" ], timeline.events.map { |event| event["id"] }+ assert_equal "trade-1", timeline.newest_event_id+ assert timeline.pagination_complete+ assert_equal 0, timeline.detail_backfill_count+ assert_includes timeline.warnings, "detail fetch failed for event trade-1"end- test "does not mark timeline complete when pagination is truncated" do- @client.define_singleton_method(:collect_timeline_topic) do |_websocket, topic:, **_|- if topic == "timelineTransactions"- [ [ { "id" => "event-1", "timestamp" => "2026-08-02" } ], "event-1", [ "timeline pagination truncated for timelineTransactions" ], false ]+ test "hands a truncated first sync over to the history backfill" do+ stub_timeline_pages(+ nil => [ "tx-1", "2026-08-04", "page-2" ],+ "page-2" => [ "tx-2", "2026-08-03", "page-3" ],+ "page-3" => [ "tx-3", "2026-08-02", "page-4" ],+ "page-4" => [ "tx-4", "2026-08-01", "page-5" ]+ )++ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 2)++ assert_equal %w[tx-1 tx-2 tx-3 tx-4], timeline.events.map { |event| event["id"] }+ assert_equal "tx-1", timeline.newest_event_id+ assert timeline.pagination_complete+ assert_empty timeline.warnings+ assert_equal({ "newest_event_id" => "tx-1", "backfill_cursor" => "page-5" }, timeline.cursors["timelineTransactions"])+ end++ test "fills a gap of new events larger than the page budget down to the previous newest event" do+ stub_timeline_pages(+ nil => [ "tx-5", "2026-08-05", "page-2" ],+ "page-2" => [ "tx-4", "2026-08-04", "page-3" ],+ "page-3" => [ "tx-3", "2026-08-03", "page-4" ],+ "page-4" => [ "tx-2", "2026-08-02", "page-5" ],+ "page-5" => [ "tx-1", "2026-08-01", "page-6" ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-2" } }+ )++ assert_equal %w[tx-5 tx-4 tx-3 tx-2], timeline.events.map { |event| event["id"] }+ assert timeline.pagination_complete+ assert_empty timeline.warnings+ assert_equal({ "newest_event_id" => "tx-5" }, timeline.cursors["timelineTransactions"])+ end++ test "continues the history backfill and finishes at the end of the topic" do+ stub_timeline_pages(+ nil => [ "tx-new", "2026-08-03", "page-2" ],+ "page-2" => [ "tx-known", "2026-08-02", "page-3" ],+ "page-9" => [ "tx-old", "2026-08-01", nil ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9", "backfill_failures" => 2 } }+ )++ assert_equal %w[tx-new tx-known tx-old], timeline.events.map { |event| event["id"] }+ assert_equal "tx-new", timeline.newest_event_id+ assert timeline.pagination_complete+ assert_empty timeline.warnings+ assert_equal({ "newest_event_id" => "tx-new" }, timeline.cursors["timelineTransactions"])+ end++ test "backfills the activity log independently of transactions" do+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ case [ payload[:type], payload[:after] ]+ when [ "timelineActivityLog", nil ]+ { "items" => [ { "id" => "act-known", "timestamp" => "2026-08-02" } ], "cursors" => { "after" => "act-2" } }+ when [ "timelineActivityLog", "act-9" ]+ { "items" => [ { "id" => "act-old", "timestamp" => "2026-07-01" } ], "cursors" => { "after" => "act-10" } }+ when [ "timelineActivityLog", "act-10" ]+ { "items" => [ { "id" => "act-older", "timestamp" => "2026-06-01" } ], "cursors" => {} }else- [ [], nil, [], true ]+ { "items" => [ { "id" => "tx-known", "timestamp" => "2026-08-03" } ], "cursors" => {} }endend- _events, newest_id, warnings, complete, = @client.send(+ timeline = @client.send(:collect_all_timeline,Object.new,known_newest_event_id: nil,max_pages: 2,- enrich_events: []+ timeline_cursors: {+ "timelineTransactions" => { "newest_event_id" => "tx-known" },+ "timelineActivityLog" => { "newest_event_id" => "act-known", "backfill_cursor" => "act-9" }+ }+ )++ assert_equal %w[tx-known act-known act-old act-older], timeline.events.map { |event| event["id"] }+ assert_equal({ "newest_event_id" => "act-known" }, timeline.cursors["timelineActivityLog"])+ assert_equal({ "newest_event_id" => "tx-known" }, timeline.cursors["timelineTransactions"])+ end++ test "reports which topic fetched each event" do+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ case payload[:type]+ when "timelineActivityLog" then { "items" => [ { "id" => "act-1", "timestamp" => "2026-08-02" } ], "cursors" => {} }+ else { "items" => [ { "id" => "tx-1", "timestamp" => "2026-08-03" }, { "timestamp" => "2026-08-01" } ], "cursors" => {} }+ end+ end++ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 2)++ assert_equal({ "timelineTransactions" => [ "tx-1" ], "timelineActivityLog" => [ "act-1" ] }, timeline.topic_event_ids)+ end++ test "stops the history backfill only for the given topics" do+ cursors = {+ "timelineTransactions" => { "newest_event_id" => "tx-1", "backfill_cursor" => "page-9" },+ "timelineActivityLog" => { "newest_event_id" => "act-1", "backfill_cursor" => "act-9" }+ }++ stopped = Provider::TradeRepublicClient.stop_timeline_history_backfills(cursors, topics: [ "timelineTransactions" ])++ assert_equal({ "timelineTransactions" => { "newest_event_id" => "tx-1" }, "timelineActivityLog" => cursors["timelineActivityLog"] }, stopped)+ end++ test "stops each topic at its own newest event" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ requested << [ payload[:type], payload[:after] ]+ id = payload[:type] == "timelineTransactions" ? "tx-known" : "act-known"+ { "items" => [ { "id" => id, "timestamp" => "2026-08-02" } ], "cursors" => { "after" => "more" } }+ end++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: "act-known",+ max_pages: 50,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known" } }+ )++ assert timeline.pagination_complete+ assert_equal [ [ "timelineTransactions", nil ], [ "timelineActivityLog", nil ] ], requested+ end++ test "keeps the backfill cursor when the backfill page fails" do+ stub_failing_backfill_page++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }+ )++ assert timeline.pagination_complete+ assert_includes timeline.warnings, "timeline history backfill failed for timelineTransactions (ProviderUnavailable)"+ assert_equal(+ { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9", "backfill_failures" => 1 },+ timeline.cursors["timelineTransactions"]+ )+ end++ test "keeps the pages read before a backfill page fails and resumes at that page" do+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ next { "items" => [], "cursors" => {} } unless payload[:type] == "timelineTransactions"++ case payload[:after]+ when nil then { "items" => [ { "id" => "tx-known", "timestamp" => "2026-08-03" } ], "cursors" => {} }+ when "page-9" then { "items" => [ { "id" => "tx-old", "timestamp" => "2026-08-02" } ], "cursors" => { "after" => "page-10" } }+ else raise Provider::TradeRepublicClient::ProviderUnavailable, "subscription failed"+ end+ end+ failures = Provider::TradeRepublicClient::MAX_TIMELINE_BACKFILL_FAILURES - 1++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 5,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9", "backfill_failures" => failures } }+ )++ assert_equal %w[tx-known tx-old], timeline.events.map { |event| event["id"] }+ assert_includes timeline.warnings, "timeline history backfill failed for timelineTransactions (ProviderUnavailable)"+ # Moving forward restarts the failure count, so the backfill is not abandoned.+ assert_equal(+ { "newest_event_id" => "tx-known", "backfill_cursor" => "page-10", "backfill_failures" => 1 },+ timeline.cursors["timelineTransactions"]+ )+ end++ test "abandons a backfill that keeps failing" do+ stub_failing_backfill_page+ failures = Provider::TradeRepublicClient::MAX_TIMELINE_BACKFILL_FAILURES - 1++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9", "backfill_failures" => failures } }+ )++ assert_includes timeline.warnings,+ "timeline history backfill for timelineTransactions abandoned after #{failures + 1} failed attempts (ProviderUnavailable)"+ assert_equal({ "newest_event_id" => "tx-known" }, timeline.cursors["timelineTransactions"])+ end++ test "reports a websocket failure in the backfill as an interruption" do+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ raise Provider::TradeRepublicClient::TransientProviderError, "busy" if payload[:after] == "page-9"++ { "items" => [ { "id" => "tx-known", "timestamp" => "2026-08-02" } ], "cursors" => {} }+ end++ error = assert_raises(Provider::TradeRepublicClient::TimelineBackfillInterrupted) do+ @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }+ )+ end+ assert_equal "timelineTransactions", error.topic+ assert_equal "TransientProviderError", error.reason+ assert_equal "page-9", error.cursor+ end++ test "retries the sync without a backfill that times out and counts the failure" do+ stub_sync_session+ @client.stubs(:sleep_for)+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ next { "items" => [], "cursors" => {} } unless payload[:type] == "timelineTransactions"++ requested << payload[:after]+ raise Provider::TradeRepublicClient::Timeout, "timeout" if payload[:after] == "page-9"++ { "items" => [ { "id" => "tx-known", "timestamp" => "2026-08-02" } ], "cursors" => {} }+ end++ result = @client.sync(+ session_txt: "session",+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }+ )++ assert_equal [ nil, "page-9", nil ], requested+ assert_includes result["warnings"], "timeline history backfill failed for timelineTransactions (Timeout)"+ assert_equal(+ { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9", "backfill_failures" => 1 },+ result["timeline_cursors"]["timelineTransactions"]+ )+ end++ test "still runs the other topic's backfill when the sync is retried after an interruption" do+ stub_sync_session+ @client.stubs(:sleep_for)+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ requested << [ payload[:type], payload[:after] ]+ case [ payload[:type], payload[:after] ]+ when [ "timelineTransactions", "page-9" ] then raise Provider::TradeRepublicClient::Timeout, "timeout"+ when [ "timelineActivityLog", "act-page-9" ] then { "items" => [ { "id" => "act-old", "timestamp" => "2026-08-01" } ], "cursors" => {} }+ when [ "timelineTransactions", nil ] then { "items" => [ { "id" => "tx-known", "timestamp" => "2026-08-02" } ], "cursors" => {} }+ when [ "timelineActivityLog", nil ] then { "items" => [ { "id" => "act-known", "timestamp" => "2026-08-02" } ], "cursors" => {} }+ else { "items" => [], "cursors" => {} }+ end+ end++ result = @client.sync(+ session_txt: "session",+ timeline_cursors: {+ "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" },+ "timelineActivityLog" => { "newest_event_id" => "act-known", "backfill_cursor" => "act-page-9" }+ }+ )++ assert_includes requested, [ "timelineActivityLog", "act-page-9" ]+ assert_includes result["events"].map { |event| event["id"] }, "act-old"+ assert_equal({ "newest_event_id" => "act-known" }, result["timeline_cursors"]["timelineActivityLog"])+ assert_equal(+ { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9", "backfill_failures" => 1 },+ result["timeline_cursors"]["timelineTransactions"]+ )+ end++ test "keeps the pages read before the websocket fails in the backfill" do+ stub_sync_session+ @client.stubs(:sleep_for)+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ next { "items" => [], "cursors" => {} } unless payload[:type] == "timelineTransactions"++ requested << payload[:after]+ case payload[:after]+ when nil then { "items" => [ { "id" => "tx-known", "timestamp" => "2026-08-03" } ], "cursors" => {} }+ when "page-9" then { "items" => [ { "id" => "tx-old", "timestamp" => "2026-08-02" } ], "cursors" => { "after" => "page-10" } }+ else raise Provider::TradeRepublicClient::Timeout, "timeout"+ end+ end++ result = @client.sync(+ session_txt: "session",+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }+ )++ assert_equal [ nil, "page-9", "page-10", nil ], requested+ assert_equal %w[tx-known tx-old], result["events"].map { |event| event["id"] }+ assert_equal(+ { "newest_event_id" => "tx-known", "backfill_cursor" => "page-10", "backfill_failures" => 1 },+ result["timeline_cursors"]["timelineTransactions"]+ )+ end++ test "replaces a running history backfill with one that reads to the end of the topic" do+ stub_timeline_pages(+ nil => [ "tx-5", "2026-08-05", "page-2" ],+ "page-2" => [ "tx-4", "2026-08-04", "page-3" ],+ "page-3" => [ "tx-3", "2026-08-03", "page-4" ],+ "page-4" => [ "tx-2", "2026-08-02", "page-5" ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-2", "backfill_cursor" => "page-old" } }+ )++ assert_equal %w[tx-5 tx-4 tx-3 tx-2], timeline.events.map { |event| event["id"] }+ assert_equal({ "newest_event_id" => "tx-5", "backfill_cursor" => "page-5" }, timeline.cursors["timelineTransactions"])+ end++ test "replaces a running gap backfill with one that keeps its stop event" do+ stub_timeline_pages(+ nil => [ "tx-7", "2026-08-07", "page-2" ],+ "page-2" => [ "tx-6", "2026-08-06", "page-3" ],+ "page-3" => [ "tx-5", "2026-08-05", "page-4" ],+ "page-4" => [ "tx-4", "2026-08-04", "page-5" ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 2,+ timeline_cursors: {+ "timelineTransactions" => { "newest_event_id" => "tx-4", "backfill_cursor" => "page-old", "backfill_stop_event_id" => "tx-1" }+ }+ )++ assert_equal %w[tx-7 tx-6 tx-5 tx-4], timeline.events.map { |event| event["id"] }+ assert_equal(+ { "newest_event_id" => "tx-7", "backfill_cursor" => "page-5", "backfill_stop_event_id" => "tx-1" },+ timeline.cursors["timelineTransactions"]+ )+ end++ test "seeds each topic from the item newest event before it has its own" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ requested << [ payload[:type], payload[:after] ]+ { "items" => [ { "id" => "evt-new", "timestamp" => "2026-08-03" }, { "id" => "evt-known", "timestamp" => "2026-08-02" } ], "cursors" => { "after" => "more" } }+ end++ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: "evt-known", max_pages: 50)++ assert_equal [ [ "timelineTransactions", nil ], [ "timelineActivityLog", nil ] ], requested+ assert_equal(+ { "timelineTransactions" => { "newest_event_id" => "evt-new" }, "timelineActivityLog" => { "newest_event_id" => "evt-new" } },+ timeline.cursors+ )+ end++ test "reads nothing and keeps the stored state without a page budget" do+ @client.define_singleton_method(:subscribe) { |*| raise "unexpected subscription" }+ stored = { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }++ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 0, timeline_cursors: stored)++ refute timeline.pagination_complete+ assert_equal stored, timeline.cursors+ end++ test "keeps the backfill position when its pagination stalls" do+ stub_timeline_pages(+ nil => [ "tx-known", "2026-08-03", nil ],+ "page-9" => [ "tx-old", "2026-08-02", "page-10" ],+ "page-10" => [ "tx-older", "2026-08-01", "page-10" ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 5,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }+ )++ assert_equal %w[tx-known tx-old tx-older], timeline.events.map { |event| event["id"] }+ assert_includes timeline.warnings, "timeline pagination cursor repeated for timelineTransactions"+ assert_equal(+ { "newest_event_id" => "tx-known", "backfill_cursor" => "page-10", "backfill_failures" => 1 },+ timeline.cursors["timelineTransactions"]+ )+ end++ test "follows an empty page that still has a next cursor" do+ stub_timeline_pages(+ nil => [ "tx-known", "2026-08-03", nil ],+ "page-9" => [ nil, nil, "page-10" ],+ "page-10" => [ "tx-old", "2026-08-01", nil ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 5,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }+ )++ assert_equal %w[tx-known tx-old], timeline.events.map { |event| event["id"] }+ assert_equal({ "newest_event_id" => "tx-known" }, timeline.cursors["timelineTransactions"])+ end++ test "keeps the stored state when the newest pages stall" do+ stub_timeline_pages(+ nil => [ "tx-2", "2026-08-03", "page-2" ],+ "page-2" => [ "tx-1", "2026-08-02", "page-2" ],+ "page-9" => [ "tx-old", "2026-08-01", nil ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 5,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-0", "backfill_cursor" => "page-9" } }+ )++ refute timeline.pagination_complete+ assert_equal %w[tx-2 tx-1 tx-old], timeline.events.map { |event| event["id"] }+ assert_equal({ "newest_event_id" => "tx-0" }, timeline.cursors["timelineTransactions"])+ end++ test "does not store a cursor that is too long to persist" do+ long_cursor = "x" * (Provider::TradeRepublicClient::MAX_TIMELINE_CURSOR_LENGTH + 1)+ stub_timeline_pages(nil => [ "tx-1", "2026-08-02", long_cursor ])++ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 1)++ assert_includes timeline.warnings, "timeline pagination cursor for timelineTransactions cannot be stored; older history is not imported"+ assert_equal({ "newest_event_id" => "tx-1" }, timeline.cursors["timelineTransactions"])+ end++ test "does not store a cursor that stalls the backfill and is too long to persist" do+ long_cursor = "x" * (Provider::TradeRepublicClient::MAX_TIMELINE_CURSOR_LENGTH + 1)+ stub_timeline_pages(+ nil => [ "tx-known", "2026-08-03", nil ],+ "page-9" => [ "tx-old", "2026-08-02", long_cursor ],+ long_cursor => [ "tx-older", "2026-08-01", long_cursor ]+ )++ timeline = @client.send(+ :collect_all_timeline,+ Object.new,+ known_newest_event_id: nil,+ max_pages: 5,+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } }+ )++ assert_includes timeline.warnings, "timeline pagination cursor for timelineTransactions cannot be stored; older history is not imported"+ assert_equal({ "newest_event_id" => "tx-known" }, timeline.cursors["timelineTransactions"])+ end++ test "stores integer cursors but not structured ones" do+ stub_timeline_pages(nil => [ "tx-1", "2026-08-02", 7 ], 7 => [ "tx-0", "2026-08-01", 8 ])++ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 1)++ assert_equal({ "newest_event_id" => "tx-1", "backfill_cursor" => 8 }, timeline.cursors["timelineTransactions"])++ stub_timeline_pages(nil => [ "tx-1", "2026-08-02", { "offset" => 1 } ])++ timeline = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 1)++ assert_includes timeline.warnings, "timeline pagination cursor for timelineTransactions cannot be stored; older history is not imported"+ assert_equal({ "newest_event_id" => "tx-1" }, timeline.cursors["timelineTransactions"])+ end++ test "sync resumes the stored history backfill" do+ stub_sync_session+ stub_timeline_pages(+ nil => [ "tx-known", "2026-08-03", nil ],+ "page-9" => [ "tx-old", "2026-08-01", nil ]+ )++ result = @client.sync(+ session_txt: "session",+ timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "tx-known", "backfill_cursor" => "page-9" } })- assert_equal "event-1", newest_id- refute complete- assert_includes warnings, "timeline pagination truncated for timelineTransactions"+ assert_equal %w[tx-known tx-old], result["events"].map { |event| event["id"] }+ assert_equal({ "timelineTransactions" => { "newest_event_id" => "tx-known" } }, result["timeline_cursors"])+ end++ test "sync returns the timeline cursors for the importer" do+ stub_sync_session+ stub_timeline_pages(+ nil => [ "tx-1", "2026-08-02", "page-2" ],+ "page-2" => [ "tx-0", "2026-08-01", nil ]+ )++ result = @client.sync(session_txt: "session", timeline_max_pages: 1)++ assert_equal "success", result["domain_statuses"]["timeline"]+ assert_equal %w[tx-1 tx-0], result["events"].map { |event| event["id"] }+ assert_equal({ "timelineTransactions" => { "newest_event_id" => "tx-1" } }, result["timeline_cursors"])endtest "recognizes QR login pending state" do@@ -966,8 +1464,9 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseendtest "backfilled stored events do not move the list cursor" do+ empty_pass = timeline_pass([], nil)@client.define_singleton_method(:collect_timeline_topic) do |_websocket, **_|- [ [], nil, [], true ]+ empty_passend@client.define_singleton_method(:subscribe) do |_websocket, **_payload|{@@ -981,7 +1480,7 @@ class TradeRepublicClientTest < ActiveSupport::TestCase}end- events, newest_id, _warnings, complete, backfill_count = @client.send(+ timeline = @client.send(:collect_all_timeline,Object.new,known_newest_event_id: "newest-1",@@ -995,10 +1494,10 @@ class TradeRepublicClientTest < ActiveSupport::TestCase} ])- assert_equal [ "old-1" ], events.map { |event| event["id"] }- assert_equal 1, backfill_count- assert complete- assert_nil newest_id+ assert_equal [ "old-1" ], timeline.events.map { |event| event["id"] }+ assert_equal 1, timeline.detail_backfill_count+ assert timeline.pagination_complete+ assert_nil timeline.newest_event_idendtest "card and cash events do not consume timeline detail requests" do@@ -1087,6 +1586,34 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_empty requestedend+ test "stored dividends without details are fetched from the backlog" do+ requested = []+ @client.define_singleton_method(:subscribe) do |_websocket, **payload|+ requested << payload[:id]+ {+ "sections" => [+ { "title" => "You received €4.30", "type" => "header", "data" => {+ "icon" => { "asset" => "logos/US0378331005/v2", "badge" => nil }+ } },+ { "title" => "Transaction", "data" => [ { "title" => "Shares", "detail" => { "text" => "10.000000" } } ] }+ ]+ }+ end+ stored = {+ "id" => "dividend-1",+ "timestamp" => "2024-12-27T10:00:00Z",+ "eventType" => "SSP_CORPORATE_ACTION_CASH",+ "category" => "DIVIDEND",+ "status" => "EXECUTED",+ "detail" => { "amount" => 4.3, "currency" => "EUR" }+ }++ enriched, = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ stored ])++ assert_equal [ "dividend-1" ], requested+ assert_equal "US0378331005", enriched.find { |event| event["id"] == "dividend-1" }.dig("detail", "isin")+ end+test "trade savings saveback and round-up events request timeline details" dorequested = []@client.define_singleton_method(:subscribe) do |_websocket, **payload|@@ -1213,21 +1740,17 @@ class TradeRepublicClientTest < ActiveSupport::TestCasetest "does not collapse distinct timeline events that have no id" doresponses = {- "timelineTransactions" => [- [- { "timestamp" => "2026-08-02T10:00:00Z", "eventType" => "CARD_TRANSACTION" },- { "timestamp" => "2026-08-02T11:00:00Z", "eventType" => "CARD_TRANSACTION" }- ],- nil,- []- ],- "timelineActivityLog" => [ [], nil, [] ]+ "timelineTransactions" => timeline_pass([+ { "timestamp" => "2026-08-02T10:00:00Z", "eventType" => "CARD_TRANSACTION" },+ { "timestamp" => "2026-08-02T11:00:00Z", "eventType" => "CARD_TRANSACTION" }+ ], nil),+ "timelineActivityLog" => timeline_pass([], nil)}@client.define_singleton_method(:collect_timeline_topic) do |_websocket, topic:, **_|responses.fetch(topic)end- events, = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 1)+ events = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: nil, max_pages: 1).eventsassert_equal 2, events.sizeend@@ -1241,7 +1764,7 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseendend- events, = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: "old", max_pages: 2)+ events = @client.send(:collect_all_timeline, Object.new, known_newest_event_id: "old", max_pages: 2).eventsassert_equal %w[new old], events.map { |event| event["id"] }end@@ -1711,4 +2234,46 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_equal "ABN", symbols.dig("NL0000303709", "symbol")assert_equal "XETR", symbols.dig("NL0000303709", "exchange_slug")end++ private++ def timeline_pass(events, newest_event_id, outcome: :finished)+ Provider::TradeRepublicClient::TimelinePass.new(events: events, newest_event_id: newest_event_id, warnings: [], outcome: outcome, cursor: nil)+ end++ # Serves timelineTransactions pages keyed by their `after` cursor as+ # [event id, timestamp, next cursor]; a nil id is an empty page and the+ # activity log is empty.+ def stub_timeline_pages(pages)+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ next { "items" => [], "cursors" => {} } unless payload[:type] == "timelineTransactions"++ id, timestamp, after = pages.fetch(payload[:after])+ items = id ? [ { "id" => id, "timestamp" => timestamp } ] : []+ { "items" => items, "cursors" => { "after" => after }.compact }+ end+ end++ # Drives the real sync_once against a stubbed account response and an+ # already connected websocket; subscriptions come from the test's stub.+ def stub_sync_session+ account_response = Net::HTTPOK.new("1.1", "200", "OK")+ account_response.stubs(:body).returns({ securitiesAccountNumber: "SEC-1", currency: "EUR" }.to_json)+ session = stub(get: account_response, websocket_headers: {}, cookies_blob: "session")+ @client.stubs(:new_session).returns(session)+ websocket = stub(send_text: nil, receive: "connected", close: nil)+ Provider::TradeRepublicWebsocket.stubs(:new).returns(stub(connect: websocket))+ end++ def stub_failing_backfill_page+ @client.define_singleton_method(:subscribe) do |_websocket, payload|+ raise Provider::TradeRepublicClient::ProviderUnavailable, "subscription failed" if payload[:after] == "page-9"++ if payload[:type] == "timelineTransactions"+ { "items" => [ { "id" => "tx-known", "timestamp" => "2026-08-02" } ], "cursors" => { "after" => "page-2" } }+ else+ { "items" => [], "cursors" => {} }+ end+ end+ endenddiff --git a/test/models/trade_republic_item_importer_test.rb b/test/models/trade_republic_item_importer_test.rbindex 1cc61617a3..d963746181 100644--- a/test/models/trade_republic_item_importer_test.rb+++ b/test/models/trade_republic_item_importer_test.rb@@ -170,6 +170,248 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseassert_equal %w[evt_old evt_recovered], account.reload.raw_timeline_payload.map { |event| event["id"] }end+ test "passes the stored timeline cursors and persists the returned ones" do+ stored = { "timelineTransactions" => { "newest_event_id" => "evt_old", "backfill_cursor" => "page-9" } }+ @item.update!(timeline_cursors: stored)+ returned = { "timelineTransactions" => { "newest_event_id" => "evt_new", "backfill_cursor" => "page-11" } }++ provider = mock("trade_republic_provider")+ provider.expects(:sync).with { |args| args[:timeline_cursors] == stored }.returns(timeline_cursor_result(returned))++ result = TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal returned, @item.reload.timeline_cursors+ assert_equal 1, result[:timeline_backfill_count]+ end++ test "clears the backfill once the client reports it finished" do+ @item.update!(timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "evt_old", "backfill_cursor" => "page-9" } })++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result({}))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal({}, @item.reload.timeline_cursors)+ end++ test "keeps the timeline cursors when the timeline fetch fails" do+ stored = { "timelineTransactions" => { "newest_event_id" => "evt_old", "backfill_cursor" => "page-9" } }+ @item.update!(timeline_cursors: stored)++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result(+ {},+ "domain_statuses" => { "account_metadata" => "success", "cash" => "success", "portfolio" => "success", "timeline" => "failed", "instrument_metadata" => "success" }+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal stored, @item.reload.timeline_cursors+ end++ test "keeps the timeline cursors when the result has none" do+ stored = { "timelineTransactions" => { "newest_event_id" => "evt_old", "backfill_cursor" => "page-9" } }+ @item.update!(timeline_cursors: stored)++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result(nil))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal stored, @item.reload.timeline_cursors+ end++ test "drops the timeline cursors when a full timeline fetch is forced" do+ @item.trade_republic_accounts.create!(kind: "portfolio", name: "Portfolio", trade_republic_account_id: "DE-CURSOR", currency: "EUR")+ @item.update!(newest_event_id: "evt_old", timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "evt_old" } })++ provider = mock("trade_republic_provider")+ provider.expects(:sync).with { |args| args[:known_newest_event_id].nil? && args[:timeline_cursors] == {} }.returns(timeline_cursor_result({}))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal({}, @item.reload.timeline_cursors)+ end++ test "stops the history backfill once the stored timeline is full" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-CURSOR",+ currency: "EUR",+ raw_timeline_payload: [+ { "id" => "evt_2", "timestamp" => "2026-08-02", "category" => "PAYMENT_RECEIVED" },+ { "id" => "evt_3", "timestamp" => "2026-08-03", "category" => "PAYMENT_RECEIVED" }+ ]+ )+ @item.update!(newest_event_id: "evt_3", timeline_cursors: { "timelineTransactions" => { "newest_event_id" => "evt_3", "backfill_cursor" => "page-9" } })+ gap = { "newest_event_id" => "act_9", "backfill_cursor" => "act-page-2", "backfill_stop_event_id" => "act_1" }+ returned = {+ "timelineTransactions" => { "newest_event_id" => "evt_3", "backfill_cursor" => "page-10", "backfill_failures" => 1 },+ "timelineActivityLog" => gap+ }++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result(+ returned,+ "events" => [ { "id" => "evt_1", "timestamp" => "2026-08-01", "category" => "PAYMENT_RECEIVED" } ]+ ))++ with_max_timeline_events(2) do+ DebugLogEntry.expects(:capture).with { |args| args[:message] == "Trade Republic sync warning: timeline history exceeds 2 events; older history is not imported" }+ TradeRepublicItem::Importer.new(@item, provider: provider).import+ end++ # The activity log's gap backfill fetches newer events and keeps running.+ assert_equal({ "timelineTransactions" => { "newest_event_id" => "evt_3" }, "timelineActivityLog" => gap }, @item.reload.timeline_cursors)+ end++ test "stops the history backfill when the cap drops a fetched event without an id" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-CURSOR",+ currency: "EUR",+ raw_timeline_payload: [+ { "id" => "evt_2", "timestamp" => "2026-08-02", "category" => "PAYMENT_RECEIVED" },+ { "id" => "evt_3", "timestamp" => "2026-08-03", "category" => "PAYMENT_RECEIVED" }+ ]+ )+ returned = { "timelineTransactions" => { "newest_event_id" => "evt_3", "backfill_cursor" => "page-10" } }++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result(+ returned,+ "events" => [ { "timestamp" => "2026-08-01", "category" => "PAYMENT_RECEIVED", "title" => "Card" } ]+ ))++ with_max_timeline_events(2) do+ DebugLogEntry.expects(:capture).with { |args| args[:message] == "Trade Republic sync warning: timeline history exceeds 2 events; older history is not imported" }+ TradeRepublicItem::Importer.new(@item, provider: provider).import+ end++ assert_equal({ "timelineTransactions" => { "newest_event_id" => "evt_3" } }, @item.reload.timeline_cursors)+ end++ test "keeps the history backfill when a stored event without an id falls off the cap" do+ stored = { "timestamp" => "2026-08-01", "category" => "PAYMENT_RECEIVED", "title" => "Card" }+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-CURSOR",+ currency: "EUR",+ raw_timeline_payload: [ stored, { "id" => "evt_2", "timestamp" => "2026-08-02", "category" => "PAYMENT_RECEIVED" } ]+ )+ returned = { "timelineTransactions" => { "newest_event_id" => "evt_3", "backfill_cursor" => "page-10" } }++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result(+ returned,+ "events" => [ stored, { "id" => "evt_3", "timestamp" => "2026-08-03", "category" => "PAYMENT_RECEIVED" } ]+ ))++ with_max_timeline_events(2) do+ DebugLogEntry.expects(:capture).never+ TradeRepublicItem::Importer.new(@item, provider: provider).import+ end++ assert_equal returned, @item.reload.timeline_cursors+ end++ test "stops the history backfill only for the topic whose fetched events fall off the cap" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-CURSOR",+ currency: "EUR",+ raw_timeline_payload: [+ { "id" => "evt_2", "timestamp" => "2026-08-02", "category" => "PAYMENT_RECEIVED" },+ { "id" => "evt_3", "timestamp" => "2026-08-03", "category" => "PAYMENT_RECEIVED" }+ ]+ )+ activity = { "newest_event_id" => "act_9", "backfill_cursor" => "act-page-10" }+ returned = {+ "timelineTransactions" => { "newest_event_id" => "evt_3", "backfill_cursor" => "page-10" },+ "timelineActivityLog" => activity+ }++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result(+ returned,+ "events" => [ { "id" => "evt_1", "timestamp" => "2026-08-01", "category" => "PAYMENT_RECEIVED" } ],+ "timeline_topic_event_ids" => { "timelineTransactions" => [ "evt_1" ], "timelineActivityLog" => [] }+ ))++ with_max_timeline_events(2) do+ DebugLogEntry.expects(:capture).with { |args| args[:message] == "Trade Republic sync warning: timeline history exceeds 2 events; older history is not imported" }+ TradeRepublicItem::Importer.new(@item, provider: provider).import+ end++ # The activity log's older events may still fit, so its backfill keeps running.+ assert_equal({ "timelineTransactions" => { "newest_event_id" => "evt_3" }, "timelineActivityLog" => activity }, @item.reload.timeline_cursors)+ end++ test "events needing detail enrichment include dividends without details" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-DIVIDEND",+ currency: "EUR",+ raw_timeline_payload: [+ {+ "id" => "dividend-missing",+ "timestamp" => "2024-12-27T14:58:41Z",+ "eventType" => "SSP_CORPORATE_ACTION_CASH",+ "category" => "DIVIDEND",+ "status" => "EXECUTED",+ "detail" => { "amount" => 4.3, "currency" => "EUR" }+ },+ {+ "id" => "dividend-complete",+ "timestamp" => "2024-12-28T10:00:00Z",+ "eventType" => "SSP_CORPORATE_ACTION_CASH",+ "category" => "DIVIDEND",+ "status" => "EXECUTED",+ "detail" => { "isin" => "US0378331005", "amount" => 4.3, "currency" => "EUR" }+ }+ ]+ )++ enrich_ids = TradeRepublicItem::Importer.new(@item, provider: mock("provider"))+ .send(:events_needing_detail_enrichment)+ .map { |event| event["id"] || event[:id] }++ assert_equal [ "dividend-missing" ], enrich_ids+ end++ test "keeps the history backfill when only stored events fall off the cap" do+ @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Portfolio",+ trade_republic_account_id: "DE-CURSOR",+ currency: "EUR",+ raw_timeline_payload: [+ { "id" => "evt_1", "timestamp" => "2026-08-01", "category" => "PAYMENT_RECEIVED" },+ { "id" => "evt_2", "timestamp" => "2026-08-02", "category" => "PAYMENT_RECEIVED" }+ ]+ )+ returned = { "timelineTransactions" => { "newest_event_id" => "evt_3", "backfill_cursor" => "page-10" } }++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(timeline_cursor_result(+ returned,+ "events" => [ { "id" => "evt_3", "timestamp" => "2026-08-03", "category" => "PAYMENT_RECEIVED" } ]+ ))++ with_max_timeline_events(2) do+ DebugLogEntry.expects(:capture).never+ TradeRepublicItem::Importer.new(@item, provider: provider).import+ end++ assert_equal returned, @item.reload.timeline_cursors+ end+test "session expiry marks item requires_update and preserves stored payloads" do@item.trade_republic_accounts.create!(name: "Existing",@@ -456,14 +698,8 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCase"warnings" => []))- original = TradeRepublicItem::Importer::MAX_TIMELINE_EVENTS- TradeRepublicItem::Importer.send(:remove_const, :MAX_TIMELINE_EVENTS)- TradeRepublicItem::Importer.const_set(:MAX_TIMELINE_EVENTS, 2)- begin+ with_max_timeline_events(2) doTradeRepublicItem::Importer.new(@item, provider: provider).import- ensure- TradeRepublicItem::Importer.send(:remove_const, :MAX_TIMELINE_EVENTS)- TradeRepublicItem::Importer.const_set(:MAX_TIMELINE_EVENTS, original)endcash = @item.trade_republic_accounts.find_by!(kind: "cash")@@ -1037,4 +1273,28 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCasedef client_result(data)Provider::TradeRepublicClient::Result.new(data: data)end++ def timeline_cursor_result(timeline_cursors, overrides = {})+ client_result({+ "status" => "ok",+ "account" => { "brokerage_account_id" => "DE-CURSOR", "currency" => "EUR" },+ "cash" => { "amount" => "1", "currency" => "EUR" },+ "positions" => [],+ "events" => [],+ "newest_event_id" => nil,+ "timeline_pagination_complete" => true,+ "timeline_cursors" => timeline_cursors,+ "warnings" => []+ }.merge(overrides))+ end++ def with_max_timeline_events(limit)+ original = TradeRepublicItem::Importer::MAX_TIMELINE_EVENTS+ TradeRepublicItem::Importer.send(:remove_const, :MAX_TIMELINE_EVENTS)+ TradeRepublicItem::Importer.const_set(:MAX_TIMELINE_EVENTS, limit)+ yield+ ensure+ TradeRepublicItem::Importer.send(:remove_const, :MAX_TIMELINE_EVENTS)+ TradeRepublicItem::Importer.const_set(:MAX_TIMELINE_EVENTS, original)+ endenddiff --git a/test/models/trade_republic_item_syncer_test.rb b/test/models/trade_republic_item_syncer_test.rbindex 45e2f69088..8fa2cb9210 100644--- a/test/models/trade_republic_item_syncer_test.rb+++ b/test/models/trade_republic_item_syncer_test.rb@@ -80,6 +80,15 @@ class TradeRepublicItemSyncerTest < ActiveSupport::TestCaseendend+ test "records the pending timeline backfills" do+ @item.stubs(:import_latest_data).returns({ detail_backfill_count: 0, timeline_backfill_count: 2 })+ sync = Sync.create!(syncable: @item)++ TradeRepublicItem::Syncer.new(@item).perform_sync(sync)++ assert_equal 2, sync.reload.sync_stats["tr_timeline_backfills"]+ end+privatedef client_result(data)