Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix: security price sync reliability (TwelveData errors, offline resolver, health checker, missing names) (#3098)

GFRfd733529177e
diff --git a/.env.example b/.env.example
index 2ee40d1ec2..d33be15f85 100644
--- a/.env.example
+++ b/.env.example
@@ -144,6 +144,17 @@ TWELVE_DATA_API_KEY=
EXCHANGE_RATE_PROVIDER=yahoo_finance
SECURITIES_PROVIDER=yahoo_finance
+# Optional: daily market data (security price) import. These only set the
+# defaults; once you change the import on the Self-Hosting settings page, the
+# saved value wins. The job runs Monday to Friday at the given local time
+# (default 22:00 UTC, about an hour after the New York close). Set the time
+# shortly after your main exchange closes, or set ENABLED to 0 to turn the
+# import off. Only "1" counts as enabled. The timezone accepts IANA names such as
+# Europe/Berlin; an unknown name falls back to UTC.
+# MARKET_DATA_SYNC_ENABLED=1
+# MARKET_DATA_SYNC_TIME=22:00
+# MARKET_DATA_SYNC_TIMEZONE=UTC
+
# Brandfetch to grab logos for banks and merchants
BRAND_FETCH_CLIENT_ID=
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index 2c407f2050..86fefe2d23 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -182,6 +182,29 @@ class Settings::HostingsController < ApplicationController
sync_auto_sync_scheduler!
end
+ market_data_sync_settings_changed = false
+
+ if hosting_params.key?(:market_data_sync_enabled)
+ Setting.market_data_sync_enabled = hosting_params[:market_data_sync_enabled] == "1"
+ market_data_sync_settings_changed = true
+ end
+
+ if hosting_params.key?(:market_data_sync_time)
+ time_value = hosting_params[:market_data_sync_time]
+ unless Setting.valid_auto_sync_time?(time_value)
+ flash[:alert] = t(".invalid_sync_time")
+ return redirect_to settings_hosting_path
+ end
+
+ Setting.market_data_sync_time = time_value
+ Setting.market_data_sync_timezone = current_user_timezone
+ market_data_sync_settings_changed = true
+ end
+
+ if market_data_sync_settings_changed
+ sync_market_data_scheduler!
+ end
+
update_encrypted_setting(:openai_access_token)
# Validate OpenAI configuration before updating
@@ -334,7 +357,7 @@ class Settings::HostingsController < ApplicationController
# Strong parameters for the self-hosting settings form.
def hosting_params
return ActionController::Parameters.new unless params.key?(:setting)
- params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :demo_family_refresh_enabled, :demo_family_refresh_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :chimnie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :ai_health_probe_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])
+ params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :demo_family_refresh_enabled, :demo_family_refresh_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :chimnie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :ai_health_probe_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :market_data_sync_enabled, :market_data_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])
end
def load_external_assistant_models
@@ -509,6 +532,15 @@ class Settings::HostingsController < ApplicationController
flash[:alert] = t(".scheduler_sync_failed")
end
+ def sync_market_data_scheduler!
+ MarketDataScheduler.sync!
+ rescue StandardError => error
+ Rails.logger.error("[MarketDataScheduler] Failed to sync scheduler: #{error.message}")
+ Rails.logger.error(error.backtrace.join("\n"))
+ MarketDataScheduler.capture_sync_failure(error, source: self.class.name, user: Current.user)
+ flash[:alert] = t(".scheduler_sync_failed")
+ end
+
def update_encrypted_setting(param_key)
return unless hosting_params.key?(param_key)
value = hosting_params[param_key].to_s.strip
diff --git a/app/models/provider/twelve_data.rb b/app/models/provider/twelve_data.rb
index 468fce5feb..ce9bd2c779 100644
--- a/app/models/provider/twelve_data.rb
+++ b/app/models/provider/twelve_data.rb
@@ -341,7 +341,21 @@ class Provider::TwelveData < Provider
when Faraday::TooManyRequestsError
RateLimitError.new("TwelveData rate limit exceeded", details: error.response&.dig(:body))
when Faraday::Error
- self.class::Error.new(error.message, details: error.response&.dig(:body))
+ body = error.response&.dig(:body)
+ # Faraday's `raise_error` middleware raises before our own
+ # `JSON.parse(response.body); check_api_error!(parsed)` code runs, so
+ # for any 4xx/5xx we'd otherwise only ever see Faraday's generic
+ # "the server responded with status ..." message — never TwelveData's
+ # actual JSON error body (which is what plan_upgrade_required? needs
+ # to detect plan-tier restrictions). Parse it here instead.
+ parsed_body = begin
+ body.is_a?(String) ? JSON.parse(body) : body
+ rescue JSON::ParserError
+ nil
+ end
+ api_message = parsed_body.is_a?(Hash) ? parsed_body["message"] : nil
+
+ self.class::Error.new(api_message.presence || error.message, details: body)
else
self.class::Error.new(error.message)
end
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rb
index d867943dc3..9093ce0707 100644
--- a/app/models/provider/yahoo_finance.rb
+++ b/app/models/provider/yahoo_finance.rb
@@ -909,6 +909,15 @@ class Provider::YahooFinance < Provider
results.sort_by(&:date)
rescue Faraday::Error, JSON::ParserError => e
+ Rails.logger.warn("#{self.class.name}: fetch_chart_data failed for #{symbol}: #{e.class}: #{e.message}")
+ DebugLogEntry.capture(
+ category: "provider_chart_fetch",
+ level: "warn",
+ message: "Yahoo Finance fetch_chart_data failed",
+ source: self.class.name,
+ provider_key: "yahoo_finance",
+ metadata: { symbol: symbol, exception_class: e.class.name, exception_message: e.message }
+ )
nil
end
end
@@ -920,7 +929,7 @@ class Provider::YahooFinance < Provider
interval: retry_interval,
interval_randomness: 0.5,
backoff_factor: 2,
- retry_statuses: [ 429 ],
+ retry_statuses: [ 429, 500, 502, 503, 504 ],
exceptions: [ Faraday::ConnectionFailed, Faraday::TimeoutError ]
})
@@ -1084,7 +1093,7 @@ class Provider::YahooFinance < Provider
interval: retry_interval,
interval_randomness: 0.5,
backoff_factor: 2,
- retry_statuses: [ 429 ],
+ retry_statuses: [ 429, 500, 502, 503, 504 ],
exceptions: [ Faraday::ConnectionFailed, Faraday::TimeoutError ]
})
diff --git a/app/models/security/health_checker.rb b/app/models/security/health_checker.rb
index c24428c462..0b76084787 100644
--- a/app/models/security/health_checker.rb
+++ b/app/models/security/health_checker.rb
@@ -5,7 +5,9 @@
# Each security goes through some basic health checks. If failed, this class is responsible for:
# - Marking failed attempts and incrementing the failed attempts counter
# - Marking the security offline if enough consecutive failed checks occur
-# - When we move a security "offline", delete all prices for that security as we assume they are bad data
+# - When we move a security "offline", delete its prices ONLY if it never had a
+# successfully-fetched price — an established history isn't suddenly "bad data"
+# just because the provider can't currently be reached
#
# The health checker is run daily through SecurityHealthCheckJob (see config/schedule.yml), but not all
# securities will be checked every day (we run in batches)
@@ -49,6 +51,15 @@ class Security::HealthChecker
def run_check
Rails.logger.info("Running health check for #{security.ticker}")
+ # Nothing to check — either no provider is assigned, or the assigned
+ # provider is currently disabled/unavailable (Setting.enabled_securities_providers).
+ # This is NOT a fetch failure: counting it as one would eventually overwrite
+ # a more specific offline_reason (e.g. "provider_disabled", set explicitly
+ # when an admin disables a provider) with the generic "health_check_failed",
+ # which then makes the bulk reactivation-on-re-enable in
+ # Settings::HostingsController#update stop finding this security.
+ return if provider.blank?
+
if latest_provider_price
handle_success
else
@@ -113,11 +124,27 @@ class Security::HealthChecker
failed_fetch_count: new_failure_count,
failed_fetch_at: new_failure_at
)
+
+ DebugLogEntry.capture(
+ category: "security_health_check",
+ level: "warn",
+ message: "Security health check failed (#{new_failure_count}/#{MAX_CONSECUTIVE_FAILURES})",
+ source: self.class.name,
+ provider: provider,
+ metadata: {
+ security_id: security.id,
+ ticker: security.ticker,
+ exchange_operating_mic: security.exchange_operating_mic,
+ failed_fetch_count: new_failure_count
+ }
+ )
end
end
# The "offline" state tells our MarketDataImporter (daily cron) to skip this security when fetching prices
def convert_to_offline_security!
+ had_price_history = security.prices.exists?
+
Security.transaction do
security.update!(
offline: true,
@@ -125,7 +152,27 @@ class Security::HealthChecker
failed_fetch_count: MAX_CONSECUTIVE_FAILURES + 1,
failed_fetch_at: Time.current
)
- security.prices.delete_all
+ # Only delete prices when the security never had a successfully-fetched
+ # one — five failed *new* fetches say nothing about the correctness of
+ # *existing* history. Deleting a track record just because the provider
+ # is temporarily unreachable would be a silent, hard-to-notice data loss.
+ security.prices.delete_all unless had_price_history
end
+
+ DebugLogEntry.capture(
+ category: "security_health_check",
+ level: "error",
+ message: had_price_history ?
+ "Security marked offline after #{MAX_CONSECUTIVE_FAILURES} consecutive health check failures; existing price history preserved" :
+ "Security marked offline after #{MAX_CONSECUTIVE_FAILURES} consecutive health check failures; no prior price history to preserve",
+ source: self.class.name,
+ provider: provider,
+ metadata: {
+ security_id: security.id,
+ ticker: security.ticker,
+ exchange_operating_mic: security.exchange_operating_mic,
+ had_price_history: had_price_history
+ }
+ )
end
end
diff --git a/app/models/security/provided.rb b/app/models/security/provided.rb
index 74eb955c6d..efe273792d 100644
--- a/app/models/security/provided.rb
+++ b/app/models/security/provided.rb
@@ -37,7 +37,15 @@ module Security::Provided
# Per-provider timeout so one slow provider can't stall the entire search
PROVIDER_SEARCH_TIMEOUT = 8.seconds
- def search_provider(symbol, country_code: nil, exchange_operating_mic: nil)
+ # technical_failure is an optional callable invoked once per provider that
+ # errored/timed out (as opposed to answering with zero results). Callers
+ # that need to distinguish "provider search technically failed" from
+ # "provider search succeeded, nothing found" — e.g. Security::Resolver,
+ # which must not treat a rate-limited/timed-out search as a confirmed
+ # "no such security" — can pass a callback here instead of us changing
+ # the return type for all callers (e.g. SecuritiesController just wants
+ # the plain result array).
+ def search_provider(symbol, country_code: nil, exchange_operating_mic: nil, technical_failure: nil)
return [] if symbol.blank?
active_providers = providers.compact
@@ -70,7 +78,10 @@ module Security::Provided
seen_keys = Set.new
results_array.each_with_index do |provider_results, idx|
- next if provider_results.nil?
+ if provider_results.nil?
+ technical_failure&.call(active_providers[idx])
+ next
+ end
provider_key = provider_key_for(active_providers[idx])
@@ -196,14 +207,18 @@ module Security::Provided
return nil if offline?
# Make sure we have a data provider before fetching
- return nil unless price_data_provider.present?
- response = price_data_provider.fetch_security_price(
+ provider = price_data_provider
+ return nil unless provider.present?
+ response = provider.fetch_security_price(
symbol: ticker,
exchange_operating_mic: exchange_operating_mic,
date: date
)
- return nil unless response.success? # Provider error
+ unless response.success? # Provider error
+ log_failed_price_fetch(response.error, provider)
+ return nil
+ end
price = response.data
Security::Price.find_or_create_by!(
@@ -214,6 +229,24 @@ module Security::Provided
price
end
+ # Throttled so a page with many holdings missing today's price doesn't
+ # flood the debug log with one entry per request — at most one per
+ # security per day.
+ def log_failed_price_fetch(error, provider = price_data_provider)
+ cache_key = "security_price_fetch_log:#{id}:#{Date.current}"
+ return unless Rails.cache.write(cache_key, true, expires_in: 24.hours, unless_exist: true)
+
+ DebugLogEntry.capture(
+ category: "security_price_fetch",
+ level: "warn",
+ message: "find_or_fetch_price failed",
+ source: self.class.name,
+ provider: provider,
+ metadata: { security_id: id, ticker: ticker, provider_error: error&.message }
+ )
+ end
+ private :log_failed_price_fetch
+
def import_provider_details(clear_cache: false)
unless price_data_provider.present?
Rails.logger.warn("No provider configured for Security.import_provider_details")
diff --git a/app/models/security/resolver.rb b/app/models/security/resolver.rb
index ddd340c08f..b40b2c83aa 100644
--- a/app/models/security/resolver.rb
+++ b/app/models/security/resolver.rb
@@ -17,7 +17,7 @@ class Security::Resolver
exact_match_from_db ||
exact_match_from_provider ||
close_match_from_provider ||
- offline_security
+ offline_security(reason: provider_search_technical_failure? ? "resolution_pending" : nil)
end
private
@@ -37,7 +37,14 @@ class Security::Resolver
value.to_s
end
- def offline_security
+ # reason: nil means "provider search ran successfully and genuinely found
+ # no match" — the pre-existing, generic offline fallback. A non-nil reason
+ # (currently only "resolution_pending", see provider_search_technical_failure?)
+ # means the search itself failed technically (rate limit/timeout/error),
+ # so we don't yet know whether the security exists — a future retry
+ # (e.g. the next daily import run) should attempt resolution again rather
+ # than treating this as a confirmed non-match.
+ def offline_security(reason: nil)
security = Security.find_or_initialize_by_ticker_and_exchange(
ticker: symbol,
exchange_operating_mic: exchange_operating_mic
@@ -47,9 +54,36 @@ class Security::Resolver
country_code: country_code,
offline: true # This tells us that we shouldn't try to fetch prices later
)
+ # Don't clobber a more specific existing reason (e.g. "provider_disabled",
+ # "health_check_failed") with "resolution_pending" — only write a new
+ # reason when the record doesn't already have a more specific one.
+ # A successful search without a match settles an earlier
+ # "resolution_pending", so later resolves use the DB fast path again.
+ if reason.present?
+ security.offline_reason = reason if security.offline_reason.blank?
+ elsif security.offline_reason == "resolution_pending"
+ security.offline_reason = nil
+ end
security.save!
+ if reason == "resolution_pending"
+ DebugLogEntry.capture(
+ category: "security_resolution",
+ level: "warn",
+ message: "Could not resolve security: provider search failed technically (not a confirmed no-match)",
+ source: self.class.name,
+ provider_key: provider_search_technical_failure_keys.first,
+ metadata: {
+ security_id: security.id,
+ ticker: symbol,
+ exchange_operating_mic: exchange_operating_mic,
+ country_code: country_code,
+ failed_providers: provider_search_technical_failure_keys
+ }
+ )
+ end
+
security
end
@@ -62,6 +96,13 @@ class Security::Resolver
return nil unless security
+ # A "resolution_pending" record means the last provider search failed
+ # technically (rate limit/timeout), not that the security is a
+ # confirmed no-match. Skip the DB fast path so this resolution attempt
+ # actually retries the provider instead of returning the same stale
+ # offline record forever.
+ return nil if security.offline? && security.offline_reason == "resolution_pending"
+
# When the caller provides an explicit provider (e.g. user selected from
# search results), honor that choice. Automated syncs (Plaid, SimpleFIN)
# pass price_provider: nil and will not overwrite.
@@ -136,6 +177,17 @@ class Security::Resolver
security.country_code = match.country_code
+ # Backfill the name straight from the search result — it's already
+ # available here and doesn't depend on a later, separate
+ # fetch_security_info/profile call succeeding. Some providers (e.g.
+ # TwelveData on lower plan tiers) gate /profile entirely regardless of
+ # symbol, so without this the name would never populate at all. Only
+ # fills a blank name — never overwrites an existing (possibly
+ # user-edited) one. Deliberately does NOT copy logo_url: that stays
+ # sourced from fetch_security_info/Brandfetch so existing coverage for
+ # those paths is unaffected.
+ security.name = match.name if match.name.present? && security.name.blank?
+
# Set provider when explicitly provided (user selection) or when the
# record is new / has no provider yet. Automated syncs pass nil and
# will not overwrite an existing choice.
@@ -153,12 +205,21 @@ class Security::Resolver
security
end
- # If a security was marked offline (e.g. its provider was temporarily
- # removed in settings) but now has a valid, enabled provider, bring it
- # back online so the MarketDataImporter picks it up again.
+ # If a security was marked offline, bring it back online whenever we have
+ # a good reason to trust it can now be priced: either its provider was
+ # temporarily disabled and is available again ("provider_disabled"), or
+ # a provider search just found it again after a prior technical failure
+ # ("resolution_pending"), or the caller explicitly passed a price_provider
+ # — meaning the user picked this exact security+provider combination from
+ # search results, which we trust the same way
+ # HoldingsController#remap_security already does unconditionally.
+ # Automated syncs (Plaid, SimpleFIN, imports) pass price_provider: nil and
+ # won't trigger the explicit-selection path, so a security that went
+ # offline for other reasons (e.g. "health_check_failed") stays offline
+ # until a human explicitly re-confirms it.
def reactivate_if_provider_available!(security)
return unless security.offline?
- return unless security.offline_reason == "provider_disabled"
+ return unless price_provider.present? || %w[provider_disabled resolution_pending].include?(security.offline_reason)
return unless security.price_data_provider.present?
security.update!(offline: false, offline_reason: nil, failed_fetch_count: 0, failed_fetch_at: nil)
@@ -185,7 +246,23 @@ class Security::Resolver
country_code: country_code
}.compact_blank
- @provider_search_result ||= Security.search_provider(symbol, **params)
+ @provider_search_result ||= Security.search_provider(
+ symbol,
+ technical_failure: ->(provider) { (@provider_search_technical_failure_keys ||= []) << provider.class.name.demodulize.underscore },
+ **params
+ )
+ end
+
+ # True when at least one enabled provider's search request errored/timed
+ # out rather than answering with zero results. Only meaningful after
+ # provider_search_result has run (close_match_from_provider always calls
+ # it before resolve reaches the offline_security fallback).
+ def provider_search_technical_failure?
+ provider_search_technical_failure_keys.any?
+ end
+
+ def provider_search_technical_failure_keys
+ @provider_search_technical_failure_keys || []
end
# Non-exhaustive list of common country codes for help in choosing "close" matches
diff --git a/app/models/setting.rb b/app/models/setting.rb
index c587829472..7357b54af1 100644
--- a/app/models/setting.rb
+++ b/app/models/setting.rb
@@ -189,6 +189,14 @@ class Setting < RailsSettings::Base
field :auto_sync_time, type: :string, default: ENV.fetch("AUTO_SYNC_TIME", "02:22")
field :auto_sync_timezone, type: :string, default: ENV.fetch("AUTO_SYNC_TIMEZONE", "UTC")
+ # Daily market data (security price) import — mirrors auto_sync_* above.
+ # Default time intentionally unchanged from the previous hardcoded
+ # config/schedule.yml entry (22:00 UTC, ~1h after NYSE close) so existing
+ # installations see no behavior change unless they actively reconfigure it.
+ field :market_data_sync_enabled, type: :boolean, default: ENV.fetch("MARKET_DATA_SYNC_ENABLED", "1") == "1"
+ field :market_data_sync_time, type: :string, default: ENV.fetch("MARKET_DATA_SYNC_TIME", "22:00")
+ field :market_data_sync_timezone, type: :string, default: ENV.fetch("MARKET_DATA_SYNC_TIMEZONE", "UTC")
+
AUTO_SYNC_TIME_FORMAT = /\A([01]?\d|2[0-3]):([0-5]\d)\z/
def self.valid_auto_sync_time?(time_str)
diff --git a/app/services/auto_sync_scheduler.rb b/app/services/auto_sync_scheduler.rb
index 10121a1c63..eaf23f269a 100644
--- a/app/services/auto_sync_scheduler.rb
+++ b/app/services/auto_sync_scheduler.rb
@@ -1,51 +1,31 @@
-class AutoSyncScheduler
+class AutoSyncScheduler < CronScheduler
JOB_NAME = "sync_all_accounts"
- def self.sync!
- Rails.logger.info("[AutoSyncScheduler] auto_sync_enabled=#{Setting.auto_sync_enabled}, time=#{Setting.auto_sync_time}")
- if Setting.auto_sync_enabled?
- upsert_job
- else
- remove_job
- end
- end
-
- # Schedule the configured local wall-clock time in its IANA zone so DST resolves per occurrence.
- def self.upsert_job
- time_str = Setting.auto_sync_time || "02:22"
- timezone_str = Setting.auto_sync_timezone || "UTC"
-
- unless Setting.valid_auto_sync_time?(time_str)
- Rails.logger.error("[AutoSyncScheduler] Invalid time format: #{time_str}, using default 02:22")
- time_str = "02:22"
- end
-
- hour, minute = time_str.split(":").map(&:to_i)
- timezone = ActiveSupport::TimeZone[timezone_str] || ActiveSupport::TimeZone["UTC"]
- cron = "#{minute} #{hour} * * * #{timezone.tzinfo.name}"
-
- job = Sidekiq::Cron::Job.create(
- name: JOB_NAME,
- cron: cron,
- class: "SyncAllJob",
- active_job: true, # see config/schedule.yml
- queue: "scheduled",
- description: "Syncs all accounts for all families"
- )
-
- if job.nil? || (job.respond_to?(:valid?) && !job.valid?)
- error_msg = job.respond_to?(:errors) ? job.errors.to_a.join(", ") : "unknown error"
- Rails.logger.error("[AutoSyncScheduler] Failed to create cron job: #{error_msg}")
- raise StandardError, "Failed to create sync schedule: #{error_msg}"
- end
-
- Rails.logger.info("[AutoSyncScheduler] Created cron job with schedule: #{cron} (#{time_str} #{timezone_str})")
- job
- end
-
- def self.remove_job
- if (job = Sidekiq::Cron::Job.find(JOB_NAME))
- job.destroy
- end
+ class << self
+ private
+ def job_name = JOB_NAME
+ def enabled? = Setting.auto_sync_enabled?
+ def enabled_log_label = "auto_sync_enabled"
+ def time_setting = Setting.auto_sync_time
+ def timezone_setting = Setting.auto_sync_timezone
+ def default_time = "02:22"
+ def schedule_label = "sync"
+
+ def job_attributes(cron)
+ {
+ name: JOB_NAME,
+ cron: cron,
+ class: "SyncAllJob",
+ active_job: true, # see config/schedule.yml
+ queue: "scheduled",
+ description: "Syncs all accounts for all families"
+ }
+ end
+
+ # Embeds the IANA timezone in the cron string, like MarketDataScheduler,
+ # so the job keeps the configured local time across daylight saving.
+ def build_cron(hour:, minute:, timezone:)
+ "#{minute} #{hour} * * * #{timezone.tzinfo.name}"
+ end
end
end
diff --git a/app/services/cron_scheduler.rb b/app/services/cron_scheduler.rb
new file mode 100644
index 0000000000..e53cba7729
--- /dev/null
+++ b/app/services/cron_scheduler.rb
@@ -0,0 +1,84 @@
+# Base class for the Settings-driven Sidekiq::Cron jobs (see AutoSyncScheduler,
+# MarketDataScheduler). Handles the shared upsert/remove/error-handling
+# boilerplate; subclasses only supply job identity, the relevant Settings,
+# and their own local-time -> cron-string strategy via `build_cron`.
+class CronScheduler
+ class << self
+ def sync!
+ Rails.logger.info("[#{name}] #{enabled_log_label}=#{enabled?}, time=#{time_setting}")
+ if enabled?
+ upsert_job
+ else
+ remove_job
+ end
+ end
+
+ def upsert_job
+ time_str = time_setting || default_time
+ timezone_str = timezone_setting || "UTC"
+
+ unless Setting.valid_auto_sync_time?(time_str)
+ Rails.logger.error("[#{name}] Invalid time format: #{time_str}, using default #{default_time}")
+ time_str = default_time
+ end
+
+ hour, minute = time_str.split(":").map(&:to_i)
+ timezone = ActiveSupport::TimeZone[timezone_str] || ActiveSupport::TimeZone["UTC"]
+ cron = build_cron(hour: hour, minute: minute, timezone: timezone)
+
+ job = Sidekiq::Cron::Job.create(**job_attributes(cron))
+
+ if job.nil? || (job.respond_to?(:valid?) && !job.valid?)
+ error_msg = job.respond_to?(:errors) ? job.errors.to_a.join(", ") : "unknown error"
+ Rails.logger.error("[#{name}] Failed to create cron job: #{error_msg}")
+ raise StandardError, "Failed to create #{schedule_label} schedule: #{error_msg}"
+ end
+
+ Rails.logger.info("[#{name}] Created cron job with schedule: #{cron}")
+ job
+ end
+
+ def remove_job
+ Sidekiq::Cron::Job.find(job_name)&.destroy
+ end
+
+ private
+ # Subclasses must implement all of the below.
+
+ def job_name
+ raise NotImplementedError
+ end
+
+ def enabled?
+ raise NotImplementedError
+ end
+
+ def enabled_log_label
+ raise NotImplementedError
+ end
+
+ def time_setting
+ raise NotImplementedError
+ end
+
+ def timezone_setting
+ raise NotImplementedError
+ end
+
+ def default_time
+ raise NotImplementedError
+ end
+
+ def schedule_label
+ raise NotImplementedError
+ end
+
+ def job_attributes(cron)
+ raise NotImplementedError
+ end
+
+ def build_cron(hour:, minute:, timezone:)
+ raise NotImplementedError
+ end
+ end
+end
diff --git a/app/services/market_data_scheduler.rb b/app/services/market_data_scheduler.rb
new file mode 100644
index 0000000000..8668b8c242
--- /dev/null
+++ b/app/services/market_data_scheduler.rb
@@ -0,0 +1,62 @@
+class MarketDataScheduler < CronScheduler
+ JOB_NAME = "import_market_data"
+
+ class << self
+ # Writes a failed schedule sync to the debug log (/settings/debug), so an
+ # admin can see why daily price imports stopped without server log access.
+ # Never raises: it runs inside rescue blocks (incl. Sidekiq startup), and
+ # reading the settings can fail for the same reason the sync failed.
+ def capture_sync_failure(error, source:, user: nil)
+ DebugLogEntry.capture(
+ category: "market_data_schedule",
+ level: "error",
+ message: "Market data schedule could not be applied",
+ source: source,
+ user: user,
+ metadata: {
+ job_name: JOB_NAME,
+ time: Setting.market_data_sync_time,
+ timezone: Setting.market_data_sync_timezone,
+ exception_class: error.class.name,
+ exception_message: error.message
+ }
+ )
+ rescue StandardError => e
+ Rails.logger.error("[MarketDataScheduler] Failed to write debug log entry: #{e.class}: #{e.message}")
+ nil
+ end
+
+ private
+ def job_name = JOB_NAME
+ def enabled? = Setting.market_data_sync_enabled?
+ def enabled_log_label = "market_data_sync_enabled"
+ def time_setting = Setting.market_data_sync_time
+ def timezone_setting = Setting.market_data_sync_timezone
+ def default_time = "22:00"
+ def schedule_label = "market data sync"
+
+ def job_attributes(cron)
+ {
+ name: JOB_NAME,
+ cron: cron,
+ class: "ImportMarketDataJob",
+ active_job: true, # see config/schedule.yml
+ queue: "scheduled",
+ args: { mode: "full", clear_cache: false },
+ description: "Imports market data daily (Mon-Fri) at the configured time"
+ }
+ end
+
+ # Markets are closed on weekends, matching the previous static
+ # config/schedule.yml entry ("0 22 * * 1-5"). The IANA timezone is
+ # embedded directly in the cron string (sidekiq-cron/fugit syntax)
+ # instead of converting to a fixed UTC offset, so the job keeps firing
+ # at the configured local time/weekday across daylight-saving
+ # transitions rather than drifting by an hour or landing on the wrong
+ # local day near the UTC date boundary.
+ def build_cron(hour:, minute:, timezone:)
+ iana_timezone = timezone.tzinfo.name
+ "#{minute} #{hour} * * 1-5 #{iana_timezone}"
+ end
+ end
+end
diff --git a/app/views/settings/hostings/_sync_settings.html.erb b/app/views/settings/hostings/_sync_settings.html.erb
index 44abd18cbb..b34026e8d1 100644
--- a/app/views/settings/hostings/_sync_settings.html.erb
+++ b/app/views/settings/hostings/_sync_settings.html.erb
@@ -51,6 +51,41 @@
<% end %>
</div>
+ <div class="flex items-center justify-between">
+ <div class="space-y-1">
+ <p class="text-sm"><%= t(".market_data_sync_label") %></p>
+ <p class="text-secondary text-sm"><%= t(".market_data_sync_description") %></p>
+ </div>
+
+ <%= styled_form_with model: Setting.new,
+ url: settings_hosting_path,
+ method: :patch,
+ data: { controller: "auto-submit-form", auto_submit_form_trigger_event_value: "change" } do |form| %>
+ <%= form.toggle :market_data_sync_enabled,
+ checked: Setting.market_data_sync_enabled,
+ data: { auto_submit_form_target: "auto" } %>
+ <% end %>
+ </div>
+
+ <div class="flex items-center justify-between">
+ <div class="space-y-1">
+ <p class="text-sm"><%= t(".market_data_sync_time_label") %></p>
+ <p class="text-secondary text-sm"><%= t(".market_data_sync_time_description") %></p>
+ </div>
+
+ <%= form_with model: Setting.new,
+ url: settings_hosting_path,
+ method: :patch,
+ data: { controller: "auto-submit-form", auto_submit_form_trigger_event_value: "change" } do |form| %>
+ <%= form.label :market_data_sync_time, t(".market_data_sync_time_label"), class: "sr-only" %>
+ <%= form.time_field :market_data_sync_time,
+ value: Setting.market_data_sync_time,
+ disabled: !Setting.market_data_sync_enabled,
+ class: "rounded-lg border border-primary px-3 py-2 text-sm bg-container text-primary w-full",
+ data: { auto_submit_form_target: "auto" } %>
+ <% end %>
+ </div>
+
<% if env_configured %>
<%= render DS::Alert.new(message: t(".env_configured_message"), variant: :warning) %>
<% end %>
diff --git a/config/initializers/sidekiq.rb b/config/initializers/sidekiq.rb
index b8292c651c..d4a824bba1 100644
--- a/config/initializers/sidekiq.rb
+++ b/config/initializers/sidekiq.rb
@@ -70,6 +70,15 @@ Sidekiq.configure_server do |config|
rescue => e
Rails.logger.error("[AutoSyncScheduler] Failed to initialize: #{e.message}")
end
+
+ # Initialize market data (security price) import scheduler when Sidekiq server starts
+ config.on(:startup) do
+ MarketDataScheduler.sync!
+ Rails.logger.info("[MarketDataScheduler] Initialized import_market_data cron job")
+ rescue => e
+ Rails.logger.error("[MarketDataScheduler] Failed to initialize: #{e.message}")
+ MarketDataScheduler.capture_sync_failure(e, source: "Sidekiq startup")
+ end
end
Sidekiq.configure_client do |config|
diff --git a/config/locales/views/settings/hostings/de.yml b/config/locales/views/settings/hostings/de.yml
index 63a3bacbc6..39433beafd 100644
--- a/config/locales/views/settings/hostings/de.yml
+++ b/config/locales/views/settings/hostings/de.yml
@@ -153,6 +153,10 @@ de:
auto_sync_description: Wenn aktiviert, werden alle Konten täglich zur angegebenen Zeit automatisch synchronisiert.
auto_sync_time_label: Synchronisierungszeit (HH:MM)
auto_sync_time_description: Lege die Tageszeit fest, zu der die automatische Synchronisierung erfolgen soll.
+ market_data_sync_label: Täglichen Kursdatenimport aktivieren
+ market_data_sync_description: Wenn aktiviert, werden Wertpapierkurse einmal täglich (Montag bis Freitag) zur angegebenen Zeit automatisch importiert.
+ market_data_sync_time_label: Zeit für den Kursdatenimport (HH:MM)
+ market_data_sync_time_description: Lege die Tageszeit fest, zu der der tägliche Kursimport laufen soll, z. B. kurz nach Handelsschluss deiner wichtigsten Börse.
include_pending_label: Ausstehende Transaktionen einbeziehen
include_pending_description: Wenn aktiviert, werden ausstehende (noch nicht gebuchte) Transaktionen importiert und bei Buchung automatisch abgeglichen. Deaktivieren, wenn deine Bank unzuverlässige Ausstehend-Daten liefert.
env_configured_message: Diese Einstellung ist deaktiviert, weil eine Anbieter-Umgebungsvariable (SIMPLEFIN_INCLUDE_PENDING oder PLAID_INCLUDE_PENDING) gesetzt ist. Entferne sie, um diese Einstellung zu aktivieren.
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index 381b6b32f0..3bc6b04956 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -344,6 +344,10 @@ en:
auto_sync_description: When enabled, all accounts will be automatically synced daily at the specified time.
auto_sync_time_label: Sync time (HH:MM)
auto_sync_time_description: Specify the time of day when automatic sync should occur.
+ market_data_sync_label: Enable daily market data import
+ market_data_sync_description: When enabled, security prices are imported automatically once a day (Monday-Friday) at the specified time.
+ market_data_sync_time_label: Market data import time (HH:MM)
+ market_data_sync_time_description: Specify the time of day when the daily security price import should run — e.g. shortly after your primary exchange closes.
include_pending_label: Include pending transactions
include_pending_description: When enabled, pending (uncleared) transactions will be imported and automatically reconciled when they post. Disable if your bank provides unreliable pending data.
env_configured_message: This setting is disabled because a provider environment variable (SIMPLEFIN_INCLUDE_PENDING or PLAID_INCLUDE_PENDING) is set. Remove it to enable this setting.
diff --git a/config/schedule.yml b/config/schedule.yml
index 7ff15d08a8..5d76d1c5d3 100644
--- a/config/schedule.yml
+++ b/config/schedule.yml
@@ -2,17 +2,8 @@
# `active_job: true`. Without it sidekiq-cron falls back to a raw Sidekiq::Job
# payload whenever the enqueuing process can't resolve the class constant, and
# the worker then fails with `undefined method 'jid='` (we-promise/sure#1442).
+# import_market_data is scheduled dynamically by MarketDataScheduler.
-import_market_data:
- cron: "0 22 * * 1-5" # 5:00 PM EST / 6:00 PM EDT (NY time) Monday through Friday
- class: "ImportMarketDataJob"
- active_job: true
- queue: "scheduled"
- description: "Imports market data daily at 5:00 PM EST (1 hour after market close)"
- args:
- mode: "full"
- clear_cache: false
-
clean_syncs:
cron: "0 * * * *" # every hour
class: "SyncCleanerJob"
diff --git a/docs/hosting/docker.md b/docs/hosting/docker.md
index 7e0a31614a..8d82e18b2c 100644
--- a/docs/hosting/docker.md
+++ b/docs/hosting/docker.md
@@ -418,6 +418,20 @@ If you want to load sample/demo data on a small host:
2. Apply the change with a **fresh deploy/restart of the worker**. Note for Render specifically: plan changes only take effect on the next deploy - they do **not** apply on a plain restart.
3. Load the sample data, then optionally drop the worker back to the small plan with another fresh deploy.
+## Daily market data import
+
+Sure imports security prices once a day, Monday to Friday. By default the import runs at 22:00 UTC, about an hour after the New York close. To change the time or turn the import off, open **Settings > Self-Hosting** and use the market data import options under the sync settings. The time you save there is interpreted in your browser's timezone.
+
+You can also set the defaults in your `.env` file. A value saved on the settings page always takes precedence over these variables:
+
+```txt
+MARKET_DATA_SYNC_ENABLED=1 # 1 = on, anything else = off
+MARKET_DATA_SYNC_TIME=22:00 # HH:MM, 24-hour clock
+MARKET_DATA_SYNC_TIMEZONE=UTC # IANA name such as Europe/Berlin; unknown names fall back to UTC
+```
+
+**Upgrading from an earlier version:** the import used to be a fixed entry in `config/schedule.yml`. It is now created by the worker when it starts, from the settings above. Without any change on your side it keeps running at 22:00 UTC, Monday to Friday. If prices stop updating after an upgrade, open `/sidekiq` (see [Inspecting background jobs](#inspecting-background-jobs-sidekiq)), check that the **Cron** tab lists `import_market_data`, and look for `[MarketDataScheduler]` lines in the worker log (`docker compose logs worker`). Saving the import time once on the settings page recreates the job.
+
## How to update your app
The mechanism that updates your self-hosted Sure app is the GHCR (Github Container Registry) Docker image that you see in the `compose.yml` file:
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index 0c97ea3b42..7b9314ebae 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -32,7 +32,8 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
teardown do
# These tests persist global Setting.* values; reset them so state can't
# leak into later (order-dependent) tests.
- %i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout ai_health_probe_timeout external_assistant_url external_assistant_token external_assistant_model external_assistant_agent_id rentcast_api_key realie_api_key chimnie_api_key demo_family_refresh_enabled demo_family_refresh_family_id].each do |key|
+ %i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout ai_health_probe_timeout external_assistant_url external_assistant_token external_assistant_model external_assistant_agent_id rentcast_api_key realie_api_key chimnie_api_key demo_family_refresh_enabled demo_family_refresh_family_id
+ market_data_sync_enabled market_data_sync_time market_data_sync_timezone].each do |key|
Setting.public_send("#{key}=", nil)
end
end
@@ -1402,6 +1403,74 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
Setting.tinkoff_invest_api_key = nil
end
+ test "can update market data sync settings when self hosting is enabled" do
+ with_self_hosting do
+ patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "1", market_data_sync_time: "18:30" } }
+
+ assert_redirected_to settings_hosting_url
+ assert Setting.market_data_sync_enabled
+ assert_equal "18:30", Setting.market_data_sync_time
+
+ job = Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)
+ assert job, "Expected the market data cron job to be (re)created"
+ assert_equal "ImportMarketDataJob", job.klass
+ end
+ ensure
+ Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)&.destroy
+ end
+
+ test "disabling market data sync removes its cron job" do
+ with_self_hosting do
+ patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "1" } }
+ assert Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)
+
+ patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "0" } }
+ refute Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)
+ end
+ ensure
+ Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)&.destroy
+ end
+
+ test "rejects an invalid market data sync time" do
+ with_self_hosting do
+ original_time = Setting.market_data_sync_time
+
+ patch settings_hosting_url, params: { setting: { market_data_sync_time: "not-a-time" } }
+
+ assert_redirected_to settings_hosting_path
+ assert_equal original_time, Setting.market_data_sync_time
+ end
+ end
+
+ test "still applies market_data_sync_enabled when market_data_sync_time in the same request is invalid" do
+ with_self_hosting do
+ Setting.market_data_sync_enabled = false
+
+ patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "1", market_data_sync_time: "not-a-time" } }
+
+ assert_redirected_to settings_hosting_path
+ assert Setting.market_data_sync_enabled, "enabled flag from the same submission should not be dropped by the invalid time"
+ end
+ ensure
+ Sidekiq::Cron::Job.find(MarketDataScheduler::JOB_NAME)&.destroy
+ end
+
+ test "logs a failed market data schedule sync to the debug log" do
+ with_self_hosting do
+ MarketDataScheduler.stubs(:sync!).raises(StandardError, "cron create failed")
+
+ assert_difference -> { DebugLogEntry.where(category: "market_data_schedule").count }, 1 do
+ patch settings_hosting_url, params: { setting: { market_data_sync_enabled: "1" } }
+ end
+
+ assert_redirected_to settings_hosting_url
+ entry = DebugLogEntry.where(category: "market_data_schedule").last
+ assert_equal "Settings::HostingsController", entry.source
+ assert_equal users(:family_admin), entry.user
+ assert_equal "cron create failed", entry.metadata["exception_message"]
+ end
+ end
+
private
def enable_preview_features!
@user = users(:family_admin)
diff --git a/test/models/provider/twelve_data_test.rb b/test/models/provider/twelve_data_test.rb
index 48ecb53c37..f0984edc4b 100644
--- a/test/models/provider/twelve_data_test.rb
+++ b/test/models/provider/twelve_data_test.rb
@@ -116,6 +116,32 @@ class Provider::TwelveDataTest < ActiveSupport::TestCase
assert_instance_of Provider::TwelveData::Error, result.error
end
+ test "default_error_transformer surfaces the real API message from a raised HTTP error body" do
+ body = {
+ "code" => 404,
+ "message" => "This endpoint is not available for this symbol/exchange combination, available starting with Grow plan",
+ "status" => "error"
+ }.to_json
+ error = Faraday::ResourceNotFound.new("the server responded with status 404 for GET https://api.twelvedata.com/time_series", { status: 404, body: body })
+
+ result = @provider.send(:with_provider_response) { raise error }
+
+ assert_not result.success?
+ assert_instance_of Provider::TwelveData::Error, result.error
+ assert_includes result.error.message, "available starting with Grow plan"
+ assert Provider::TwelveData.plan_upgrade_required?(result.error.message)
+ assert_equal "Grow", Provider::TwelveData.extract_required_plan(result.error.message)
+ end
+
+ test "default_error_transformer falls back to the generic Faraday message when the body isn't JSON" do
+ error = Faraday::ResourceNotFound.new("the server responded with status 404 for GET https://api.twelvedata.com/time_series", { status: 404, body: "<html>Not Found</html>" })
+
+ result = @provider.send(:with_provider_response) { raise error }
+
+ assert_not result.success?
+ assert_equal error.message, result.error.message
+ end
+
# ================================
# Crypto Filter Tests
# ================================
diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rb
index a3b65395b8..93106a0d7f 100644
--- a/test/models/provider/yahoo_finance_test.rb
+++ b/test/models/provider/yahoo_finance_test.rb
@@ -828,6 +828,32 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert_equal 0.5, @provider.send(:min_request_interval)
end
+ test "client retries on 5xx statuses in addition to 429" do
+ retry_statuses = retry_middleware_options(@provider.send(:client)).retry_statuses
+ assert_equal [ 429, 500, 502, 503, 504 ], retry_statuses
+ end
+
+ test "authenticated_client retries on 5xx statuses in addition to 429" do
+ retry_statuses = retry_middleware_options(@provider.send(:authenticated_client, "cookie")).retry_statuses
+ assert_equal [ 429, 500, 502, 503, 504 ], retry_statuses
+ end
+
+ test "fetch_chart_data logs (rather than silently swallows) a Faraday error" do
+ @provider.stubs(:throttle_request)
+ @provider.stubs(:fetch_authenticated_chart).raises(Faraday::ConnectionFailed, "connection failed")
+
+ Rails.logger.expects(:warn).with(regexp_matches(/fetch_chart_data failed for EURUSD=X/))
+ DebugLogEntry.expects(:capture).with do |attributes|
+ attributes[:provider_key] == "yahoo_finance" &&
+ attributes[:metadata][:symbol] == "EURUSD=X" &&
+ attributes[:metadata][:exception_class] == "Faraday::ConnectionFailed"
+ end
+
+ result = @provider.send(:fetch_chart_data, "EURUSD=X", Date.current - 5.days, Date.current) { |ts, close| close }
+
+ assert_nil result
+ end
+
# ================================
# Cookie/Crumb Authentication Tests
# ================================
@@ -1096,6 +1122,11 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
private
+ def retry_middleware_options(faraday_connection)
+ handler = faraday_connection.builder.handlers.find { |h| h.klass.to_s.include?("Retry") }
+ handler.build.instance_variable_get(:@options)
+ end
+
def stub_successful_health_authentication(provider: @provider, count: 1)
responses = count.times.flat_map do |index|
[
diff --git a/test/models/security/health_checker_test.rb b/test/models/security/health_checker_test.rb
index aef6a6c7a7..f1c4081dba 100644
--- a/test/models/security/health_checker_test.rb
+++ b/test/models/security/health_checker_test.rb
@@ -83,7 +83,7 @@ class Security::HealthCheckerTest < ActiveSupport::TestCase
assert @new_offline_security.offline?
end
- test "after enough consecutive health check failures, security goes offline and prices are deleted" do
+ test "after enough consecutive health check failures, security with existing price history goes offline but keeps its prices" do
# Create one test price
Security::Price.create!(
security: @due_for_check_security,
@@ -110,10 +110,90 @@ class Security::HealthCheckerTest < ActiveSupport::TestCase
refute @due_for_check_security.offline?
assert_equal 1, @due_for_check_security.prices.count
- # We've now exceeded the max consecutive failures, so the security should be marked offline
- hc.run_check
+ # We've now exceeded the max consecutive failures, so the security should be marked offline —
+ # but since it had a real, previously-fetched price, five failed *new* fetches don't make that
+ # existing history untrustworthy, so it must be preserved.
+ assert_difference "DebugLogEntry.count", 1 do
+ hc.run_check
+ end
+ assert @due_for_check_security.offline?
+ assert_equal "health_check_failed", @due_for_check_security.offline_reason
+ assert_equal 1, @due_for_check_security.prices.count, "Existing price history must be preserved"
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "security_health_check", entry.category
+ assert_equal "error", entry.level
+ assert_equal true, entry.metadata["had_price_history"]
+ end
+
+ test "after enough consecutive health check failures, security with no prior price history goes offline with no prices to preserve" do
+ hc = Security::HealthChecker.new(@due_for_check_security)
+
+ @provider.expects(:fetch_security_price)
+ .with(
+ symbol: @due_for_check_security.ticker,
+ exchange_operating_mic: @due_for_check_security.exchange_operating_mic,
+ date: Date.current
+ )
+ .returns(provider_error_response(StandardError.new("No prices found")))
+ .times(Security::HealthChecker::MAX_CONSECUTIVE_FAILURES + 1)
+
+ Security::HealthChecker::MAX_CONSECUTIVE_FAILURES.times { hc.run_check }
+
+ assert_difference "DebugLogEntry.count", 1 do
+ hc.run_check
+ end
assert @due_for_check_security.offline?
assert_equal 0, @due_for_check_security.prices.count
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "security_health_check", entry.category
+ assert_equal "error", entry.level
+ assert_equal false, entry.metadata["had_price_history"]
+ end
+
+ test "an intermediate (non-terminal) health check failure logs a warn-level debug entry" do
+ hc = Security::HealthChecker.new(@due_for_check_security)
+
+ @provider.expects(:fetch_security_price)
+ .with(
+ symbol: @due_for_check_security.ticker,
+ exchange_operating_mic: @due_for_check_security.exchange_operating_mic,
+ date: Date.current
+ )
+ .returns(provider_error_response(StandardError.new("No prices found")))
+ .once
+
+ assert_difference "DebugLogEntry.count", 1 do
+ hc.run_check
+ end
+
+ refute @due_for_check_security.offline?
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "security_health_check", entry.category
+ assert_equal "warn", entry.level
+ assert_equal 1, entry.metadata["failed_fetch_count"]
+ end
+
+ test "run_check does not count a missing/unavailable provider as a fetch failure" do
+ # e.g. the security's assigned provider was disabled in settings —
+ # offline_reason: "provider_disabled" is more specific than the generic
+ # health-check failure path and must not be overwritten by it.
+ @due_for_check_security.update!(offline: true, offline_reason: "provider_disabled", price_provider: "twelve_data")
+ @due_for_check_security.stubs(:price_data_provider).returns(nil)
+
+ hc = Security::HealthChecker.new(@due_for_check_security)
+
+ @provider.expects(:fetch_security_price).never
+
+ assert_no_difference "DebugLogEntry.count" do
+ hc.run_check
+ end
+
+ assert @due_for_check_security.offline?
+ assert_equal "provider_disabled", @due_for_check_security.offline_reason
+ assert_equal 0, @due_for_check_security.failed_fetch_count
+ assert_not_nil @due_for_check_security.reload.last_health_check_at, "Skipped checks still update last_health_check_at so they aren't re-queued daily"
end
test "failure incrementor increases for each health check failure" do
diff --git a/test/models/security/provided_test.rb b/test/models/security/provided_test.rb
index 0b06d8d79c..cb74587541 100644
--- a/test/models/security/provided_test.rb
+++ b/test/models/security/provided_test.rb
@@ -125,6 +125,34 @@ class Security::ProvidedTest < ActiveSupport::TestCase
assert_equal "GOOG", results.first.ticker
end
+ test "search_provider invokes technical_failure for a provider that errors" do
+ bad_provider = mock("bad_provider")
+ bad_provider.stubs(:class).returns(Provider::YahooFinance)
+ bad_provider.expects(:search_securities).with("XMAW").raises(StandardError, "rate limited")
+
+ Security.stubs(:providers).returns([ bad_provider ])
+
+ failed_providers = []
+ results = Security.search_provider("XMAW", technical_failure: ->(provider) { failed_providers << provider })
+
+ assert_equal [], results
+ assert_equal [ bad_provider ], failed_providers
+ end
+
+ test "search_provider does not invoke technical_failure when a provider genuinely finds nothing" do
+ provider = mock("provider")
+ provider.stubs(:class).returns(Provider::TwelveData)
+ provider.expects(:search_securities).with("NOPE").returns(provider_success_response([]))
+
+ Security.stubs(:providers).returns([ provider ])
+
+ failure_called = false
+ results = Security.search_provider("NOPE", technical_failure: ->(_provider) { failure_called = true })
+
+ assert_equal [], results
+ refute failure_called
+ end
+
# --- price_data_provider ---
test "price_data_provider returns assigned provider" do
@@ -177,6 +205,49 @@ class Security::ProvidedTest < ActiveSupport::TestCase
assert_equal "twelve_data", entry.provider_key
end
+ # --- find_or_fetch_price ---
+
+ test "find_or_fetch_price logs a debug entry when the provider fetch fails" do
+ provider = mock("provider")
+ provider.stubs(:fetch_security_price).returns(
+ provider_error_response(Provider::Error.new("the server responded with status 404"))
+ )
+ @security.stubs(:price_data_provider).returns(provider)
+
+ result = nil
+ assert_difference "DebugLogEntry.count", 1 do
+ result = @security.find_or_fetch_price(date: 5.days.ago.to_date)
+ end
+
+ assert_nil result
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "security_price_fetch", entry.category
+ assert_equal "warn", entry.level
+ assert_equal @security.id, entry.metadata["security_id"]
+ assert_equal "the server responded with status 404", entry.metadata["provider_error"]
+ end
+
+ test "find_or_fetch_price only logs once per security per day (deduped)" do
+ # Test env runs with a null cache store, which would make the dedupe a
+ # no-op and let this test pass vacuously — swap in a real one just for
+ # this test so the dedupe logic is actually exercised.
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ provider = mock("provider")
+ provider.stubs(:fetch_security_price).returns(
+ provider_error_response(Provider::Error.new("boom"))
+ ).twice
+ @security.stubs(:price_data_provider).returns(provider)
+
+ assert_difference "DebugLogEntry.count", 1 do
+ @security.find_or_fetch_price(date: 5.days.ago.to_date)
+ @security.find_or_fetch_price(date: 6.days.ago.to_date)
+ end
+ ensure
+ Rails.cache = original_cache
+ end
+
# --- provider_status ---
test "provider_status returns provider_unavailable when assigned provider disabled" do
diff --git a/test/models/security/resolver_test.rb b/test/models/security/resolver_test.rb
index 02f4b342ba..075cd77bdb 100644
--- a/test/models/security/resolver_test.rb
+++ b/test/models/security/resolver_test.rb
@@ -1,4 +1,5 @@
require "test_helper"
+require "ostruct"
class Security::ResolverTest < ActiveSupport::TestCase
test "resolves DB security" do
@@ -19,7 +20,7 @@ class Security::ResolverTest < ActiveSupport::TestCase
near_miss = Security.new(ticker: "NVDA", exchange_operating_mic: "XNYS", country_code: "US")
Security.expects(:search_provider)
- .with("NVDA", exchange_operating_mic: "XNAS", country_code: "US")
+ .with("NVDA", exchange_operating_mic: "XNAS", country_code: "US", technical_failure: anything)
.returns([ near_miss, exact_match ])
assert_difference "Security.count", 1 do
@@ -40,7 +41,7 @@ class Security::ResolverTest < ActiveSupport::TestCase
# Return in reverse-priority order to prove the sorter works
Security.expects(:search_provider)
- .with("TEST", exchange_operating_mic: "XNAS")
+ .with("TEST", exchange_operating_mic: "XNAS", technical_failure: anything)
.returns([ other, preferred ])
assert_difference "Security.count", 1 do
@@ -92,7 +93,7 @@ class Security::ResolverTest < ActiveSupport::TestCase
match = Security.new(ticker: "VWCE", exchange_operating_mic: "XETR", country_code: "DE", price_provider: "eodhd")
Security.expects(:search_provider)
- .with("VWCE", exchange_operating_mic: "XETR")
+ .with("VWCE", exchange_operating_mic: "XETR", technical_failure: anything)
.returns([ match ])
Setting.stubs(:enabled_securities_providers).returns([ "eodhd" ])
@@ -138,7 +139,7 @@ class Security::ResolverTest < ActiveSupport::TestCase
)
Security.expects(:search_provider)
- .with("BTCUSD", exchange_operating_mic: "BNCX", country_code: "US")
+ .with("BTCUSD", exchange_operating_mic: "BNCX", country_code: "US", technical_failure: anything)
.returns([ binance_match ])
Setting.stubs(:enabled_securities_providers).returns([ "binance_public" ])
@@ -157,14 +158,13 @@ class Security::ResolverTest < ActiveSupport::TestCase
assert_equal "binance_public", resolved.price_provider
end
- test "resolved provider match is persisted with nil name/logo_url" do
- # Documents that find_or_create_provider_match! intentionally copies only
- # ticker, MIC, country_code, and price_provider from the match — not name
- # or logo_url. This means Security#import_provider_details always has
- # blank metadata on first resolution and runs fetch_security_info +
- # probe_brandfetch_crypto_coverage! as expected. Regression guard: if
- # someone adds name/logo copying to the resolver, the Brandfetch
- # coverage probe would be bypassed on first sync.
+ test "resolved provider match copies name but not logo_url from the search result" do
+ # Name is backfilled directly from the search match (it's already known
+ # at resolve time and some providers, e.g. TwelveData on lower plan
+ # tiers, gate /profile entirely — without this the name would never
+ # populate). logo_url deliberately stays untouched: it's sourced from
+ # fetch_security_info/Brandfetch instead, so those paths still run
+ # exactly as before on first sync.
match = Security.new(
ticker: "BTCUSD",
exchange_operating_mic: "BNCX",
@@ -175,7 +175,7 @@ class Security::ResolverTest < ActiveSupport::TestCase
)
Security.expects(:search_provider)
- .with("BTCUSD", exchange_operating_mic: "BNCX", country_code: "US")
+ .with("BTCUSD", exchange_operating_mic: "BNCX", country_code: "US", technical_failure: anything)
.returns([ match ])
Setting.stubs(:enabled_securities_providers).returns([ "binance_public" ])
@@ -187,8 +187,189 @@ class Security::ResolverTest < ActiveSupport::TestCase
price_provider: "binance_public"
).resolve
- assert_nil resolved.reload.name, "Resolver must not copy name from the search match"
- assert_nil resolved.logo_url, "Resolver must not copy logo_url from the search match"
+ assert_equal "BTC", resolved.reload.name, "Resolver should copy name from the search match"
+ assert_nil resolved.logo_url, "Resolver must not copy logo_url from the search match"
+ end
+
+ test "does not overwrite an existing (e.g. user-edited) name on re-resolve" do
+ # country_code intentionally mismatches the resolver call below, so
+ # exact_match_from_db (which requires an exact country match) misses and
+ # falls through to the provider-match path — which finds the same
+ # ticker+MIC record via find_or_create_provider_match! and must not
+ # clobber its existing name.
+ db_security = Security.create!(ticker: "CSPX3", exchange_operating_mic: "XLON", country_code: "US", name: "Custom Name")
+ match = Security.new(ticker: "CSPX3", exchange_operating_mic: "XLON", country_code: "GB", name: "iShares Core S&P 500", price_provider: "tiingo")
+
+ Security.expects(:search_provider)
+ .with("CSPX3", exchange_operating_mic: "XLON", country_code: "GB", technical_failure: anything)
+ .returns([ match ])
+ Setting.stubs(:enabled_securities_providers).returns([ "tiingo" ])
+
+ resolved = Security::Resolver.new("CSPX3", exchange_operating_mic: "XLON", country_code: "GB", price_provider: "tiingo").resolve
+
+ assert_equal db_security, resolved
+ assert_equal "Custom Name", resolved.reload.name
+ end
+
+ test "marks security resolution_pending (not a generic offline fallback) when provider search fails technically" do
+ bad_provider = mock("bad_provider")
+ bad_provider.stubs(:class).returns(Provider::YahooFinance)
+ bad_provider.expects(:search_securities).with("XMAW").raises(StandardError, "rate limited")
+
+ Security.stubs(:providers).returns([ bad_provider ])
+ Security.stubs(:enabled_securities_providers).returns([ "yahoo_finance" ])
+
+ assert_difference "Security.count", 1 do
+ resolved = Security::Resolver.new("XMAW").resolve
+
+ assert resolved.persisted?
+ assert resolved.offline?
+ assert_equal "resolution_pending", resolved.offline_reason
+ end
+ end
+
+ test "genuine no-match from a successful provider search still uses the generic offline fallback" do
+ Security.expects(:search_provider).returns([])
+
+ resolved = Security::Resolver.new("FOO2").resolve
+
+ assert resolved.offline?
+ assert_nil resolved.offline_reason
+ end
+
+ test "reactivates an offline security when the user explicitly re-selects a valid provider, regardless of offline_reason" do
+ db_security = Security.create!(
+ ticker: "DIS2",
+ exchange_operating_mic: "XNYS",
+ country_code: "US",
+ price_provider: "twelve_data",
+ offline: true,
+ offline_reason: nil, # e.g. left blank by an old offline_security fallback, or health_check_failed
+ failed_fetch_count: 3
+ )
+
+ Security.expects(:search_provider).never
+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])
+ Security.stubs(:provider_for).with("twelve_data").returns(mock("twelve_data_provider"))
+
+ resolved = Security::Resolver.new(
+ "DIS2",
+ exchange_operating_mic: "XNYS",
+ country_code: "US",
+ price_provider: "twelve_data"
+ ).resolve
+
+ assert_equal db_security, resolved
+ resolved.reload
+ refute resolved.offline?, "Explicit re-selection of a valid provider must bring the security back online"
+ assert_nil resolved.offline_reason
+ assert_equal 0, resolved.failed_fetch_count
+ end
+
+ test "does not reactivate an offline security during an automated sync (no explicit price_provider)" do
+ db_security = Security.create!(
+ ticker: "DIS3",
+ exchange_operating_mic: "XNYS",
+ country_code: "US",
+ price_provider: "twelve_data",
+ offline: true,
+ offline_reason: "health_check_failed",
+ failed_fetch_count: 6
+ )
+
+ Security.expects(:search_provider).never
+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])
+ Security.stubs(:provider_for).with("twelve_data").returns(mock("twelve_data_provider"))
+
+ resolved = Security::Resolver.new(
+ "DIS3",
+ exchange_operating_mic: "XNYS",
+ country_code: "US"
+ ).resolve
+
+ assert_equal db_security, resolved
+ resolved.reload
+ assert resolved.offline?, "Automated syncs must not silently bring a failed security back online"
+ assert_equal "health_check_failed", resolved.offline_reason
+ end
+
+ test "offline_security does not overwrite an existing, more specific offline_reason with resolution_pending" do
+ db_security = Security.create!(
+ ticker: "XMAW3",
+ exchange_operating_mic: "XNAS",
+ country_code: "US",
+ offline: true,
+ offline_reason: "health_check_failed"
+ )
+
+ bad_provider = mock("bad_provider")
+ bad_provider.stubs(:class).returns(Provider::YahooFinance)
+ bad_provider.expects(:search_securities).with("XMAW3", exchange_operating_mic: "XNAS", country_code: "GB").raises(StandardError, "rate limited")
+
+ Security.stubs(:providers).returns([ bad_provider ])
+ Security.stubs(:enabled_securities_providers).returns([ "yahoo_finance" ])
+
+ # A different country_code this time so the exact DB lookup (which
+ # filters by country_code when present) misses the existing "US" record
+ # and falls through to a (failing) provider search.
+ resolved = Security::Resolver.new("XMAW3", exchange_operating_mic: "XNAS", country_code: "GB").resolve
+
+ assert_equal db_security, resolved
+ resolved.reload
+ assert resolved.offline?
+ assert_equal "health_check_failed", resolved.offline_reason
+ end
+
+ test "bypasses the DB fast path and retries the provider for a resolution_pending security" do
+ db_security = Security.create!(
+ ticker: "XMAW4",
+ exchange_operating_mic: "XNAS",
+ country_code: "US",
+ offline: true,
+ offline_reason: "resolution_pending",
+ failed_fetch_count: 2
+ )
+
+ good_provider = mock("good_provider")
+ good_provider.stubs(:class).returns(Provider::YahooFinance)
+ good_provider.expects(:search_securities).with("XMAW4", exchange_operating_mic: "XNAS", country_code: "US").returns(
+ Provider::Response.new(
+ success?: true,
+ data: [ OpenStruct.new(symbol: "XMAW4", name: "Test Co", exchange_operating_mic: "XNAS", country_code: "US", logo_url: nil) ],
+ error: nil
+ )
+ )
+
+ Security.stubs(:providers).returns([ good_provider ])
+ Security.stubs(:enabled_securities_providers).returns([ "yahoo_finance" ])
+ Security.stubs(:provider_for).with("yahoo_finance").returns(good_provider)
+
+ resolved = Security::Resolver.new("XMAW4", exchange_operating_mic: "XNAS", country_code: "US").resolve
+
+ assert_equal db_security, resolved
+ resolved.reload
+ refute resolved.offline?, "A resolution_pending security must come back online once the provider search succeeds again"
+ assert_nil resolved.offline_reason
+ assert_equal 0, resolved.failed_fetch_count
+ end
+
+ test "clears resolution_pending once a successful provider search confirms there is no match" do
+ db_security = Security.create!(
+ ticker: "XMAW5",
+ exchange_operating_mic: "XNAS",
+ country_code: "US",
+ offline: true,
+ offline_reason: "resolution_pending"
+ )
+
+ Security.expects(:search_provider).returns([])
+
+ resolved = Security::Resolver.new("XMAW5", exchange_operating_mic: "XNAS", country_code: "US").resolve
+
+ assert_equal db_security, resolved
+ resolved.reload
+ assert resolved.offline?
+ assert_nil resolved.offline_reason, "A confirmed no-match must stop the DB fast-path bypass on later resolves"
end
test "rejects disabled price_provider" do
@@ -224,7 +405,7 @@ class Security::ResolverTest < ActiveSupport::TestCase
match = Security.new(ticker: "KTY", exchange_operating_mic: "XWAR", country_code: "PL", price_provider: "eodhd")
Security.expects(:search_provider)
- .with("KTY", exchange_operating_mic: "XWAR", country_code: "PL")
+ .with("KTY", exchange_operating_mic: "XWAR", country_code: "PL", technical_failure: anything)
.returns([ match ])
Setting.stubs(:enabled_securities_providers).returns([ "eodhd" ])
diff --git a/test/services/auto_sync_scheduler_test.rb b/test/services/auto_sync_scheduler_test.rb
index a2703a54ff..5c6b235917 100644
--- a/test/services/auto_sync_scheduler_test.rb
+++ b/test/services/auto_sync_scheduler_test.rb
@@ -2,6 +2,50 @@ require "test_helper"
require "ostruct"
class AutoSyncSchedulerTest < ActiveSupport::TestCase
+ # Stubbed instead of hitting real Sidekiq::Cron (Redis): the JOB_NAME key
+ # is global, so parallel test workers sharing the same Redis instance can
+ # race and destroy each other's job mid-test (flaky NoMethodError on nil).
+ setup do
+ @job = OpenStruct.new(valid?: true)
+ end
+
+ test "sync! creates a cron job in the configured timezone when enabled" do
+ Setting.stubs(:auto_sync_enabled?).returns(true)
+ Setting.stubs(:auto_sync_time).returns("02:22")
+ Setting.stubs(:auto_sync_timezone).returns("UTC")
+
+ Sidekiq::Cron::Job.expects(:create).with(
+ name: AutoSyncScheduler::JOB_NAME,
+ cron: "22 2 * * * Etc/UTC",
+ class: "SyncAllJob",
+ active_job: true,
+ queue: "scheduled",
+ description: "Syncs all accounts for all families"
+ ).returns(@job)
+
+ AutoSyncScheduler.sync!
+ end
+
+ test "sync! removes the cron job when disabled" do
+ Setting.stubs(:auto_sync_enabled?).returns(false)
+ Setting.stubs(:auto_sync_time).returns("02:22")
+ Sidekiq::Cron::Job.expects(:find).with(AutoSyncScheduler::JOB_NAME).returns(@job)
+ @job.expects(:destroy)
+
+ AutoSyncScheduler.sync!
+ end
+
+ test "upsert_job falls back to the default time on an invalid time format" do
+ Setting.stubs(:auto_sync_time).returns("not-a-time")
+ Setting.stubs(:auto_sync_timezone).returns("UTC")
+
+ Sidekiq::Cron::Job.expects(:create).with(
+ has_entries(cron: "22 2 * * * Etc/UTC")
+ ).returns(@job)
+
+ AutoSyncScheduler.upsert_job
+ end
+
test "keeps the configured local sync time across daylight saving changes" do
Setting.stubs(:auto_sync_time).returns("06:30")
Setting.stubs(:auto_sync_timezone).returns("Europe/London")
diff --git a/test/services/market_data_scheduler_test.rb b/test/services/market_data_scheduler_test.rb
new file mode 100644
index 0000000000..092c98b45a
--- /dev/null
+++ b/test/services/market_data_scheduler_test.rb
@@ -0,0 +1,117 @@
+require "test_helper"
+
+class MarketDataSchedulerTest < ActiveSupport::TestCase
+ # Stubbed instead of hitting real Sidekiq::Cron (Redis): the JOB_NAME key
+ # is global, so parallel test workers sharing the same Redis instance can
+ # race and destroy each other's job mid-test (flaky NoMethodError on nil).
+ setup do
+ @job = OpenStruct.new(valid?: true)
+ end
+
+ test "sync! creates a cron job with the correct UTC cron string when enabled" do
+ Setting.stubs(:market_data_sync_enabled?).returns(true)
+ Setting.stubs(:market_data_sync_enabled).returns(true)
+ Setting.stubs(:market_data_sync_time).returns("18:00")
+ Setting.stubs(:market_data_sync_timezone).returns("UTC")
+
+ Sidekiq::Cron::Job.expects(:create).with(
+ name: MarketDataScheduler::JOB_NAME,
+ cron: "0 18 * * 1-5 Etc/UTC",
+ class: "ImportMarketDataJob",
+ active_job: true,
+ queue: "scheduled",
+ args: { mode: "full", clear_cache: false },
+ description: "Imports market data daily (Mon-Fri) at the configured time"
+ ).returns(@job)
+
+ MarketDataScheduler.sync!
+ end
+
+ test "upsert_job embeds the configured IANA timezone instead of converting to UTC" do
+ Setting.stubs(:market_data_sync_time).returns("22:00")
+ Setting.stubs(:market_data_sync_timezone).returns("Pacific Time (US & Canada)")
+
+ # The local hour/weekday are preserved verbatim (no UTC conversion), so
+ # the job always fires at 22:00 local time regardless of daylight-saving
+ # transitions or how far the local date is from the UTC date boundary.
+ Sidekiq::Cron::Job.expects(:create).with(
+ has_entries(cron: "0 22 * * 1-5 America/Los_Angeles")
+ ).returns(@job)
+
+ MarketDataScheduler.upsert_job
+ end
+
+ test "sync! removes the cron job when disabled" do
+ Setting.stubs(:market_data_sync_enabled?).returns(false)
+ Setting.stubs(:market_data_sync_enabled).returns(false)
+ Setting.stubs(:market_data_sync_time).returns("18:00")
+ Sidekiq::Cron::Job.expects(:find).with(MarketDataScheduler::JOB_NAME).returns(@job)
+ @job.expects(:destroy)
+
+ MarketDataScheduler.sync!
+ end
+
+ test "upsert_job falls back to the default time on an invalid time format" do
+ Setting.stubs(:market_data_sync_time).returns("not-a-time")
+ Setting.stubs(:market_data_sync_timezone).returns("UTC")
+
+ Sidekiq::Cron::Job.expects(:create).with(
+ has_entries(cron: "0 22 * * 1-5 Etc/UTC")
+ ).returns(@job)
+
+ MarketDataScheduler.upsert_job
+ end
+
+ test "the timezone-suffixed cron formats MarketDataScheduler emits are accepted by the installed Sidekiq::Cron parser" do
+ # Unlike the tests above, this hits real Sidekiq::Cron (Redis) to confirm
+ # the installed sidekiq-cron/fugit version actually parses and persists a
+ # cron string with a trailing IANA timezone. Mocking Job.create everywhere
+ # would let a parser/version regression slip through unnoticed. Covers
+ # both a UTC alias and a non-UTC zone, since MarketDataScheduler emits
+ # both. Uses random job names (not JOB_NAME) so this can't race with
+ # other tests/workers touching MarketDataScheduler's job.
+ [ "0 18 * * 1-5 Etc/UTC", "0 22 * * 1-5 America/Los_Angeles" ].each do |cron|
+ job_name = "market_data_scheduler_cron_contract_test_#{SecureRandom.hex(8)}"
+
+ begin
+ created = Sidekiq::Cron::Job.create(
+ name: job_name,
+ cron: cron,
+ class: "ImportMarketDataJob"
+ )
+ assert created, "Expected Sidekiq::Cron to accept cron string: #{cron}"
+
+ job = Sidekiq::Cron::Job.find(job_name)
+ assert job, "Expected the cron job to be persisted for: #{cron}"
+ assert job.valid?, job.errors.to_a.join(", ")
+ assert_equal cron, job.cron
+ ensure
+ Sidekiq::Cron::Job.find(job_name)&.destroy
+ end
+ end
+ end
+
+ test "capture_sync_failure writes an error entry to the debug log" do
+ Setting.stubs(:market_data_sync_time).returns("18:30")
+ Setting.stubs(:market_data_sync_timezone).returns("Europe/Berlin")
+
+ assert_difference -> { DebugLogEntry.where(category: "market_data_schedule").count }, 1 do
+ MarketDataScheduler.capture_sync_failure(StandardError.new("redis down"), source: "Sidekiq startup")
+ end
+
+ entry = DebugLogEntry.where(category: "market_data_schedule").last
+ assert_equal "error", entry.level
+ assert_equal "Sidekiq startup", entry.source
+ assert_equal "redis down", entry.metadata["exception_message"]
+ assert_equal "18:30", entry.metadata["time"]
+ assert_equal "Europe/Berlin", entry.metadata["timezone"]
+ end
+
+ test "capture_sync_failure never raises when the settings cannot be read" do
+ Setting.stubs(:market_data_sync_time).raises(ActiveRecord::ConnectionNotEstablished)
+
+ assert_no_difference -> { DebugLogEntry.count } do
+ assert_nil MarketDataScheduler.capture_sync_failure(StandardError.new("boom"), source: "Sidekiq startup")
+ end
+ end
+end