-
Notifications
You must be signed in to change notification settings - Fork 369
Recover stuck service operations after transient DB failures #5011
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
johha
merged 15 commits into
cloudfoundry:main
from
sap-contributions:fix/recover-failed-delayed-jobs
Jun 3, 2026
+457
−2
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
3c060d7
feat: add DelayedJobsRecover scheduled job to re-enqueue stuck servic…
serdarozerr b8da6a7
fix: comment is fixed
serdarozerr 0ec67e4
feat: new sheduling jobs test is added
serdarozerr df047e3
fix: replace N+1 lookup with single join query in DelayedJobsRecover
serdarozerr f37a14c
fix: warn added to mock logger
serdarozerr 655a7db
fix: removed the state condition, since it doesn't add any valued to …
serdarozerr f5a1881
fix: instead of reenqueuing the job we started orphan migration opera…
serdarozerr 9539cce
fix: resolve stuck in-progress create operations left by permanently …
serdarozerr 6a18d44
fix: removed test file in main folder
serdarozerr d497a38
fix: config param added
serdarozerr d16821b
fix: delayed job recovery remainings are removed
serdarozerr 304ca98
fix: func args namings were fixed
serdarozerr 901150f
fix: index check logic simplified
serdarozerr 87742e0
fix: fix wording
serdarozerr b3375c2
fix: test logic simplified
serdarozerr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
117 changes: 117 additions & 0 deletions
117
app/jobs/runtime/service_operations_create_in_progress_cleanup.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| module VCAP::CloudController | ||
| module Jobs | ||
| module Runtime | ||
| class ServiceOperationsCreateInProgressCleanup < VCAP::CloudController::Jobs::CCJob | ||
| BATCH_SIZE = 10 | ||
|
|
||
| def perform | ||
| logger.info("Cleaning up service 'create' operations stuck in 'in progress'") | ||
| cleanup_operations(ServiceInstanceOperation, ServiceInstance, :service_instance_id, 'service_instance.create', :cleanup_failed_provision) | ||
|
johha marked this conversation as resolved.
|
||
| cleanup_operations(ServiceBindingOperation, ServiceBinding, :service_binding_id, 'service_bindings.create', :cleanup_failed_bind) | ||
| cleanup_operations(ServiceKeyOperation, ServiceKey, :service_key_id, 'service_keys.create', :cleanup_failed_key) | ||
| end | ||
|
|
||
| def max_attempts | ||
| 1 | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def cleanup_operations(operation_model, instance_model, foreign_key, jobs_operation, orphan_mitigator_method) | ||
| # The explanation below uses service_instance_operations as the concrete example; | ||
| # the same logic applies to service_binding_operations and service_key_operations | ||
| # when invoked with their respective arguments. | ||
| # | ||
| # Find stuck service instance 'in progress' operations where the broker is still working | ||
| # but CC's polling job has permanently failed due to a transient error (e.g. brief db connection flip). | ||
| # Join path: service_instance_operations → service_instances → jobs → delayed_jobs. | ||
| # | ||
| # Filters: | ||
| # - service_instance_operations.state='in progress': the broker has not yet reported a final state | ||
| # (succeeded or failed) that CC could successfully persist; if CC had received and saved a final | ||
| # state from the broker, this column would already be 'succeeded' or 'failed' — not 'in progress' | ||
| # - service_instance_operations.type='create': scope to create operations only | ||
| # - service_instance_operations.created_at > CURRENT_TIMESTAMP - max_duration: operations beyond the max async polling window | ||
| # are intentionally excluded — the broker has given up on them too, so they are out of scope for this cleanup | ||
| # - jobs.state IN (POLLING, FAILED): the pollable job has not reached COMPLETE (a successful job | ||
| # would already be done and is out of scope); POLLING covers the case where the failure hook | ||
| # itself couldn't write FAILED due to the DB flip | ||
| # - jobs.operation='service_instance.create': prevents matching update/delete jobs for the same | ||
| # service instance that happen to share the same resource_guid | ||
| # - delayed_jobs.failed_at IS NOT NULL: the delayed job permanently failed (exhausted max_attempts); | ||
| # jobs still alive or locked have failed_at=NULL and must not be touched | ||
| operation_table = operation_model.table_name | ||
| instance_table = instance_model.table_name | ||
|
|
||
| stuck = operation_model. | ||
| join(instance_table, id: Sequel[operation_table][foreign_key]). | ||
| join(:jobs, resource_guid: Sequel[instance_table][:guid]). | ||
| join(:delayed_jobs, guid: Sequel[:jobs][:delayed_job_guid]). | ||
| where(Sequel[operation_table][:state] => 'in progress'). | ||
| where(Sequel[operation_table][:type] => 'create'). | ||
| where(Sequel.lit("#{operation_table}.created_at > CURRENT_TIMESTAMP - INTERVAL '?' SECOND", default_maximum_duration_seconds.to_i)). | ||
| where(Sequel[:jobs][:state] => [PollableJobModel::POLLING_STATE, PollableJobModel::FAILED_STATE]). | ||
| where(Sequel[:jobs][:operation] => jobs_operation). | ||
| exclude(Sequel[:delayed_jobs][:failed_at] => nil). | ||
| select( | ||
| Sequel[:jobs][:guid].as(:pollable_guid), | ||
| Sequel[operation_table][:id].as(:op_id), | ||
| Sequel[operation_table][foreign_key].as(:resource_id) | ||
| ). | ||
| order(Sequel[operation_table][:created_at]). | ||
| limit(BATCH_SIZE) | ||
|
|
||
| stuck.each do |row| | ||
| mitigate_orphan(operation_model, instance_model, orphan_mitigator_method, | ||
| row[:op_id], row[:resource_id], row[:pollable_guid]) | ||
| end | ||
| end | ||
|
|
||
| def mitigate_orphan(operation_model, instance_model, orphan_mitigator_method, op_id, resource_id, pollable_guid) | ||
| # Mark the stuck create operation as failed, mark its pollable job as failed, | ||
| # and trigger broker-side orphan deprovisioning to clean up any resource the | ||
| # broker may have created. | ||
| operation_model.db.transaction do | ||
| operation = operation_model.where(id: op_id, state: 'in progress').for_update.skip_locked.first | ||
| return unless operation | ||
|
|
||
| instance = instance_model.first(id: resource_id) | ||
| return unless instance | ||
|
|
||
| instance_type = instance_model.to_s.split('::').last | ||
|
|
||
| logger.info( | ||
| "#{instance_type} #{instance.guid} create operation is stuck in 'in progress'. " \ | ||
| "Setting operation's state to 'failed' and pollable job's state to 'FAILED'.", | ||
| instance_type: instance_type, | ||
| instance_guid: instance.guid, | ||
| operation_id: op_id, | ||
| pollable_job_guid: pollable_guid | ||
| ) | ||
|
|
||
| operation.update(state: 'failed', | ||
| description: "Operation was stuck in 'in progress' state. Set to 'failed' by cleanup job; orphan mitigation triggered.") | ||
| PollableJobModel.where(guid: pollable_guid).update(state: PollableJobModel::FAILED_STATE) | ||
| orphan_mitigator.send(orphan_mitigator_method, instance) | ||
| end | ||
| end | ||
|
|
||
| def orphan_mitigator | ||
| @orphan_mitigator ||= VCAP::Services::ServiceBrokers::V2::OrphanMitigator.new | ||
| end | ||
|
|
||
| def default_maximum_duration_seconds | ||
| Config.config.get(:broker_client_max_async_poll_duration_minutes).minutes | ||
| end | ||
|
|
||
| def logger | ||
| @logger ||= Steno.logger('cc.background.service-operations-create-in-progress-cleanup') | ||
|
johha marked this conversation as resolved.
|
||
| end | ||
|
|
||
| def job_name_in_configuration | ||
| :service_operations_create_in_progress_cleanup | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
db/migrations/20260505071445_add_jobs_operation_state_index.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| Sequel.migration do | ||
| no_transaction # required for concurrently option on postgres | ||
|
|
||
| up do | ||
| if database_type == :postgres | ||
| VCAP::Migration.with_concurrent_timeout(self) do | ||
| add_index :jobs, %i[operation state], | ||
| name: :jobs_operation_state_index, | ||
| where: "state IN ('POLLING', 'FAILED')", | ||
| if_not_exists: true, | ||
| concurrently: true | ||
| end | ||
| elsif database_type == :mysql | ||
| alter_table(:jobs) do | ||
| # rubocop:disable Sequel/ConcurrentIndex -- MySQL does not support concurrent index operations | ||
| add_index %i[operation state], name: :jobs_operation_state_index unless @db.indexes(:jobs).key?(:jobs_operation_state_index) | ||
| # rubocop:enable Sequel/ConcurrentIndex | ||
| end | ||
| end | ||
| end | ||
|
|
||
| down do | ||
| if database_type == :postgres | ||
| VCAP::Migration.with_concurrent_timeout(self) do | ||
| drop_index :jobs, %i[operation state], | ||
| name: :jobs_operation_state_index, | ||
| if_exists: true, | ||
| concurrently: true | ||
| end | ||
| elsif database_type == :mysql | ||
| alter_table(:jobs) do | ||
| # rubocop:disable Sequel/ConcurrentIndex | ||
| drop_index %i[operation state], name: :jobs_operation_state_index if @db.indexes(:jobs).key?(:jobs_operation_state_index) | ||
| # rubocop:enable Sequel/ConcurrentIndex | ||
| end | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
spec/migrations/20260505071445_add_jobs_operation_state_index_spec.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| require 'spec_helper' | ||
| require 'migrations/helpers/migration_shared_context' | ||
|
|
||
| RSpec.describe 'migration to add operation_state_index on jobs table', isolation: :truncation, type: :migration do | ||
| include_context 'migration' do | ||
| let(:migration_filename) { '20260505071445_add_jobs_operation_state_index.rb' } | ||
| end | ||
|
|
||
| def operation_state_index_present? | ||
| if db.database_type == :postgres | ||
| db.fetch("SELECT 1 FROM pg_indexes WHERE tablename = 'jobs' AND indexname = 'jobs_operation_state_index'").any? | ||
| else | ||
| db.indexes(:jobs).key?(:jobs_operation_state_index) | ||
| end | ||
| end | ||
|
|
||
| describe 'jobs table' do | ||
| it 'adds index and handles idempotency gracefully' do | ||
| # Test up migration | ||
| expect(operation_state_index_present?).to be_falsey | ||
| expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error | ||
| expect(operation_state_index_present?).to be_truthy | ||
|
|
||
| # Test up migration idempotency | ||
| expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error | ||
| expect(operation_state_index_present?).to be_truthy | ||
|
|
||
| # Test down migration | ||
| expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error | ||
| expect(operation_state_index_present?).to be_falsey | ||
|
|
||
| # Test down migration idempotency | ||
| expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error | ||
| expect(operation_state_index_present?).to be_falsey | ||
| end | ||
| end | ||
| end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.