Reload cached application settings before updating them

What does this MR do and why?

A setting an admin saves can be undone by a background job. When the job updates one setting, it writes back the whole group of settings stored beside it, from a copy it read up to a minute earlier, so anything saved in between goes back to its old value.

On self-managed, Search with advanced search saved shortly before the first index setup resumed indexing was turned off again by the resume step. Zero-downtime reindexing turns it off the same way when it finalizes the task. This is not the documented delay before setting changes show: the old value is written to the row and stays after the cache expires.

  • Gitlab::CurrentSettings.update! updated the record from ApplicationSetting.cached, which each process keeps for up to application_settings_cache_seconds (60 by default).
  • A jsonb settings column is written whole, so the write puts every other key in that column back to its cached value. The pause flag and elasticsearch_search share the elasticsearch column.
  • This MR reloads a persisted record before it applies the attributes, so every caller of update! gets the current row, read from the primary. SecretsManagement::InstanceEnrollmentService#update_settings already does this before its own write (!257869 (merged)).
  • The reload also covers a copy that already holds the requested value, which dirty tracking would otherwise skip as no change. A record that is not persisted yet, as with in-memory settings, is saved as before.
  • The six calls that hand Gitlab::CurrentSettings.writable_application_settings to ApplicationSettings::UpdateService write a jsonb column whole from the same copy (elasticsearch, and zoekt_settings for the zoekt call), so they take a fresh one as well: four in Search::RakeTaskExecutorService, one in Search::Elastic::TriggerIndexingWorker#initiate and one in Search::Zoekt::IndexingSettingsService. They reload in place, so later reads in the same job see the write.

Gitlab::CurrentSettings.update without the bang reloads the same way. Four of its callers each write only the boolean license_usage_data_exported column, so no other value is at stake, but dirty tracking skips the write when a stale copy already holds the requested value, which would leave a newer saved value in place.

Seven more writers held the same copy, each now with a spec that saves a different value after the settings were cached. The first is covered by the new update without a change of its own; the other six are changed here:

  • Licenses::DestroyService clears future_subscriptions through Gitlab::CurrentSettings.update.
  • GitlabSubscriptions::UpdateLicenseDependenciesService writes future_subscriptions and seat_control through Gitlab::CurrentSettings.update!.
  • Ai::DuoSettings::UpdateService takes a reloaded copy before it writes the instance-level AI settings, and only when such a setting is in the request. It still reads saved_changes for the audit event off the same object, which the in-place reload keeps.
  • Gitlab::Database::Reindexing.update_reindexing_setting! takes a reloaded copy before it merges its key into the database_reindexing jsonb column.
  • Ai::AmazonQ::BaseService memoizes the settings it hands to ApplicationSettings::UpdateService with duo_availability, so it takes a reloaded copy.
  • ApplicationController#disable_usage_stats takes a reloaded copy before it turns usage ping off at the first admin sign-in.
  • License#update_trial_setting reads ApplicationSetting.current_without_cache, because its guard on the saved trial date reads a copy that a write in another process does not expire.

The other writers to the row are not changed, each for one reason: a with_lock or lock! reloads the row, the admin controller, the settings API and a few rake tasks read current_without_cache, a token reset writes a new random value, a dev setup task and the install seed each run in a process with no concurrent writer, whose own saves expire its cache, and the rest write another table.

No feature flag: the change adds one primary-key read before a write that already happens.

Where the write races the cache

sequenceDiagram
    participant Admin as Admin::ApplicationSettingsController (Puma)
    participant Worker as Search::Elastic::TriggerIndexingWorker (Sidekiq)
    participant Cache as ApplicationSetting.cached (Sidekiq process, up to 60 s)
    participant Row as application_settings.elasticsearch (jsonb)
    Worker->>Row: update! pause flag true
    Note over Worker: re-enqueues itself 2 minutes out
    Cache->>Row: a job reads the settings (search off)
    Admin->>Row: save elasticsearch_search true
    Note over Admin,Cache: expires the cache in Puma only
    Worker->>Cache: second run reads the settings (search off)
    Worker->>Row: update! pause flag false
    Note over Row: before: whole column from the copy, search off<br/>after: reloaded first, search stays on

References

Screenshots or screen recordings

No UI change. The table shows Search with advanced search after the resume, as the API and the application_settings row read it. Admin > Settings > Search reads the same row.

Before After
On 19.4.1, saved 22 seconds before the resume, it reads cleared after it Saved 26 and 50 seconds before the resume, it stays selected
On a 19.5 nightly build, saved about 117 seconds after the pause line, it reads cleared after the resume all three times. Saved while zero-downtime reindexing runs, it reads cleared once the task finalizes Saved about 117 or 100 seconds after the pause line, it stays selected all three times, and it stays selected through zero-downtime reindexing

On a current master build, with a settings copy read before another process saved the setting, each of these writes cleared it before this change and keeps it after:

Write Before After
Search::RakeTaskExecutorService#resume_advanced_search_indexing after a save turned search on search off search on
The same resume after a save turned search off search on search off
Gitlab::CurrentSettings.update!(elasticsearch_requeue_workers: true) after a save turned search on search off search on
The same resume with the save made before the copy was read search on search on

The other pause flag writes take the same path, so the same change covers them:

  • Search::Elastic::ClusterReindexingService#initial!, #finalize_reindexing and #abort_reindexing!
  • Elastic::MigrationWorker#preflight_check_successful?, #pause_indexing! and #unpause_indexing!. On master these writes run only against Elasticsearch 6 or for a migration that pauses indexing, and none does.

Database

Each Gitlab::CurrentSettings.update! or Gitlab::CurrentSettings.update call on a persisted record now reads the single application_settings row by primary key before its UPDATE. With max_http_response_size_limit as the attribute, a call went from BEGIN, UPDATE, COMMIT to the SELECT below followed by those three. The reload runs before the transaction opens. The six ApplicationSettings::UpdateService calls, the Duo settings update and the reindexing setting write issue the same read before their own write. Licenses::DestroyService goes through update, so it issues it too. Rails lists every column of the model; the list is shortened here:

SELECT "application_settings"."id", ... FROM "application_settings" WHERE "application_settings"."id" = 1 LIMIT 1

The fourteen production calls to update! are:

  • The advanced search pause and resume writes (eight), run by Search::Elastic::TriggerIndexingWorker, Search::Elastic::ClusterReindexingService and Elastic::MigrationWorker.
  • The Geo rake tasks that enable maintenance mode and silent mode (two).
  • UpdateContainerRegistryInfoService, run by a cron worker and a rake task.
  • GitlabSubscriptions::UpdateLicenseDependenciesService (two), run when a license is activated.
  • The admin button that restores the Web IDE extension host domain, the only one in a controller. It runs once per click.

None sits on a path every request takes. The Amazon Q services, the first admin sign-in, creating a trial license and the Duo settings update with an instance-level setting add the same read, once per call.

Plan taken on Database Lab (gitlab-production-main, warm run), with * in place of the column list:

 Limit  (cost=0.12..3.14 rows=1 width=5445) (actual time=0.025..0.026 rows=1 loops=1)
   Buffers: shared hit=2
   I/O Timings: read=0.000 write=0.000
   ->  Index Scan using application_settings_pkey on public.application_settings  (cost=0.12..3.14 rows=1 width=5445) (actual time=0.024..0.024 rows=1 loops=1)
         Index Cond: (application_settings.id = 1)
         Buffers: shared hit=2
         I/O Timings: read=0.000 write=0.000

The UPDATE is the same statement, now built against the reloaded row.

With database load balancing a read can be served by a replica that has not replayed the last commit, which would hand back the stale row again. A private with_primary method in Gitlab::CurrentSettings runs the reload on the primary, the use_primary pattern of Search::Elastic::IndexBulkCronWorker. The fix sits on writable_application_settings, the accessor !272918 (merged) added for writers: this MR replaces the update and update! methods that !272918 (merged) added with versions that reload first, the reload acts on that record, and the code of current_application_settings is unchanged. Because the reload refreshes that record in place, later reads in the same request see the saved row.

A save that lands between the SELECT and the UPDATE can still be lost. This MR reloads with reset rather than taking a row lock (with_lock). Both forms ran against the same cases. A lock covers that window only against another writer that also locks, and Gitlab::CurrentSettings.update! would be the only one: the admin settings controller saves its own copy without a lock, so a save from it inside the window still loses, or wins, depending on which write commits last.

A lock alone would also need the reload first. After an update! that fails validation in a request or job, the cached copy keeps the rejected value, and with_lock on it raises Locking a record with unpersisted changes. With the reload the rejected value is dropped and the next update! saves; on master it fails validation again.

How to set up and validate locally

  1. In a Rails console, hold a settings copy the way a request does, save another key of the same jsonb column from a separate record, then update:

    Gitlab::SafeRequestStore.ensure_request_store do
      settings = Gitlab::CurrentSettings
      size = settings.max_http_decompressed_size
      limit = settings.max_http_response_size_limit
      ApplicationSetting.current_without_cache.update!(max_http_decompressed_size: size + 1)
      settings.update!(max_http_response_size_limit: limit + 1)
    end
    ApplicationSetting.current_without_cache.max_http_decompressed_size
  2. With this change the last line returns the new value, size + 1. On master it returns size, the value the first read saw.

  3. bundle exec rspec spec/lib/gitlab/current_settings_spec.rb spec/lib/gitlab/database/reindexing_spec.rb ee/spec/services/search/rake_task_executor_service_spec.rb ee/spec/services/search/zoekt/indexing_settings_service_spec.rb ee/spec/workers/search/elastic/trigger_indexing_worker_spec.rb ee/spec/services/licenses/destroy_service_spec.rb ee/spec/services/gitlab_subscriptions/update_license_dependencies_service_spec.rb ee/spec/services/ai/duo_settings/update_service_spec.rb ee/spec/services/ai/amazon_q/update_service_spec.rb spec/controllers/application_controller_spec.rb ee/spec/models/license_spec.rb

MR acceptance checklist

Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.

An AI coding assistant wrote this change. The assistant also checked each claim against the code it cites and ran RuboCop, the commit message linter, the specs listed above and mutation checks on the changed files on a development build of master on a test VM. The assistant also ran each described behavior on a self-managed GitLab 19.4.1 instance, a 19.5 nightly build and a development build of master on test VMs, and took the query plan on Database Lab.

Edited by Andrew Dunn

Merge request reports

Loading
Loading