Skip to content

feat: Azure Batch eagerly terminates jobs after all tasks have been submitted #6159

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright 2025, Seqera
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package nextflow.cloud.azure.batch

import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import nextflow.Session
import nextflow.processor.TaskProcessor
import nextflow.trace.TraceObserver

/**
* Observer that handles process termination events for Azure Batch executor.
* When a process terminates (all tasks have been submitted), this observer
* will eagerly set the corresponding Azure Batch job to auto-terminate when
* all tasks complete.
*
* @author Adam Talbot <[email protected]>
*/
@Slf4j
@CompileStatic
class AzBatchProcessObserver implements TraceObserver {

AzBatchProcessObserver(Session session) {
// Session not needed, but required by factory interface
}

/**
* Called when a process terminates (all tasks have been submitted).
* Sets Azure Batch jobs to auto-terminate when all tasks complete.
*/
@Override
void onProcessTerminate(TaskProcessor processor) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why using an observer instead of having this logic in the task hander?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a task, it's a job!

In Azure, job = queue.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See comment here: #3927 (comment)

Basically, it needs to wait until the last task of a process has been submitted to Az Batch, then make the job terminate after completion.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair, but I still don't see a big value using the trace observer. Would not make more sense to keep this in the cleanup logic here

https://github.com/nextflow-io/nextflow/blob/5839_azure_batch_jobs_terminate_upon_completion/plugins/nf-azure/src/main/nextflow/cloud/azure/batch/AzBatchService.groovy#L1065-L1080

all related metadata should be accessible in the AzBatchService object

Copy link
Collaborator Author

@adamrtalbot adamrtalbot Jun 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is how it currently works, see terminateJobsOnCompletion and deleteJobsOnCompletion. However it's causing us problems. If Nextflow dies, all jobs are left in active state which consumes a very limited quota. For some context, I had to argue with Azure support a lot to get 1000 active jobs as a quota, and with 1 process equaling 1 job you can use this up in a matter of days. Once you have done this, the only way to run Nextflow again is to go into your Azure Batch account and manually remove some jobs.

By aggressively going and setting jobs to automatically terminate, we can reduce the number of active jobs to all but the ones with running tasks when a Nextflow process dies. This is reducing the pressure on active jobs as much as possible. Between this and the 30 day cooldown, we should be at effectively zero active jobs for normal running which is what we should aim for.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then not sure how much this approach will improve, most of times processes termination on pipeline completion, so if the execution is killed abruptly the behaviour will be more or less the same.

I wonder instead if it could be a problem with the cleanup execution. Are you able to replicate the problem? do you have any execution logs for effected pipelines ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

most of times processes termination on pipeline completion

Arrgghh that's frustrating.

do you have any execution logs for effected pipelines ?

Attached one from last night.

nf-5ZBk4BU4tGxbqU.log

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It sounds like the earliest point at which we could safely terminate the azure job is right after all tasks for the corresponding process have been submitted to azure batch.

The TaskProcessor can signal when all tasks are "pending" (submitted to nextflow but not to azure) and when all tasks have completed, but not when all tasks are submitted to azure. I think the trace observer is the only way to do this, because it needs to watch the task submissions to figure out when all tasks have been submitted.

In fact, as I write this, even that isn't enough because you could have task retries. If I submit all the tasks, terminate the job, then a task fails and I need to retry it, I assume that wouldn't work if the job was already terminated? Therefore we actually do have to wait until all tasks are completed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Damn, you're right. Back to the drawing board.

// Check if this process uses the Azure Batch executor
if( !(processor.executor instanceof AzBatchExecutor) ) {
return
}

final executor = processor.executor as AzBatchExecutor
final batchService = executor.batchService

// Check if auto-termination is enabled
if( !batchService?.config?.batch()?.terminateJobsOnCompletion ) {
log.trace "Azure Batch job auto-termination is disabled, skipping eager termination for process: ${processor.name}"
return
}

// Find and set auto-termination for all jobs associated with this processor
batchService.allJobIds.findAll { key, jobId ->
key.processor == processor
}.values().each { jobId ->
Comment on lines +52 to +64
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels a bit convoluted to me...is there an easier way?

log.debug "Setting Azure Batch job ${jobId} to auto-terminate for completed process: ${processor.name}"
try {
batchService.setJobAutoTermination(jobId)
}
catch( Exception e ) {
log.warn "Failed to set auto-termination for Azure Batch job ${jobId} associated with process '${processor.name}' - ${e.message ?: e}"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2025, Seqera
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package nextflow.cloud.azure.batch

import groovy.transform.CompileStatic
import nextflow.Session
import nextflow.trace.TraceObserver
import nextflow.trace.TraceObserverFactory

/**
* Factory for creating the Azure Batch process observer that enables eager termination
* of Azure Batch jobs when processes complete.
*
* @author Adam Talbot <[email protected]>
*/
@CompileStatic
class AzBatchProcessObserverFactory implements TraceObserverFactory {

@Override
Collection<TraceObserver> create(Session session) {
return [new AzBatchProcessObserver(session)]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -977,30 +977,53 @@ class AzBatchService implements Closeable {
}

/**
* Set all jobs to terminate on completion.
* Set a specific Azure Batch job to terminate when all tasks complete.
* This is called eagerly when a Nextflow process completes (all tasks submitted)
* rather than waiting for the entire pipeline to finish.
*
* @param jobId The Azure Batch job ID to set for auto-termination
*/
protected void terminateJobs() {
for( String jobId : allJobIds.values() ) {
try {
log.trace "Setting Azure job ${jobId} to terminate on completion"
void setJobAutoTermination(String jobId) {
setJobTermination(jobId)
}

final job = apply(() -> client.getJob(jobId))
final poolInfo = job.poolInfo
/**
* Set a job to terminate when all tasks complete.
*
* @param jobId The Azure Batch job ID to set for auto-termination
*/
protected void setJobTermination(String jobId) {
try {
log.trace "Setting Azure job ${jobId} to terminate on completion"

final jobParameter = new BatchJobUpdateContent()
.setOnAllTasksComplete(OnAllBatchTasksComplete.TERMINATE_JOB)
.setPoolInfo(poolInfo)
final job = apply(() -> client.getJob(jobId))
final poolInfo = job.poolInfo

apply(() -> client.updateJob(jobId, jobParameter))
}
catch (HttpResponseException e) {
if (e.response.statusCode == 409) {
log.debug "Azure Batch job ${jobId} already terminated, skipping termination"
} else {
log.warn "Unable to terminate Azure Batch job ${jobId} - Status: ${e.response.statusCode}, Reason: ${e.message ?: e}"
}
final jobParameter = new BatchJobUpdateContent()
.setOnAllTasksComplete(OnAllBatchTasksComplete.TERMINATE_JOB)
.setPoolInfo(poolInfo)

apply(() -> client.updateJob(jobId, jobParameter))
}
catch (HttpResponseException e) {
if (e.response.statusCode == 409) {
log.debug "Azure Batch job ${jobId} already terminated, skipping auto-termination setup"
} else {
log.warn "Unable to set auto-termination for Azure Batch job ${jobId} - Status: ${e.response.statusCode}, Reason: ${e.message ?: e}"
}
}
catch (Exception e) {
log.warn "Unable to set auto-termination for Azure Batch job ${jobId} - Reason: ${e.message ?: e}"
}
}

/**
* Set all jobs to terminate on completion.
*/
protected void terminateJobs() {
for( String jobId : allJobIds.values() ) {
setJobTermination(jobId)
}
}

protected void cleanupJobs() {
Expand Down
1 change: 1 addition & 0 deletions plugins/nf-azure/src/resources/META-INF/extensions.idx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#

nextflow.cloud.azure.batch.AzBatchExecutor
nextflow.cloud.azure.batch.AzBatchProcessObserverFactory
nextflow.cloud.azure.file.AzPathFactory
nextflow.cloud.azure.file.AzPathSerializer
nextflow.cloud.azure.fusion.AzFusionEnv
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright 2025, Seqera
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package nextflow.cloud.azure.batch

import nextflow.Session
import nextflow.cloud.azure.config.AzBatchOpts
import nextflow.cloud.azure.config.AzConfig
import nextflow.executor.Executor
import nextflow.processor.TaskProcessor
import spock.lang.Specification

/**
* Test for AzBatchProcessObserver
*
* @author Adam Talbot <[email protected]>
*/
class AzBatchProcessObserverTest extends Specification {

def 'should only act on Azure Batch executors'() {
given:
def observer = new AzBatchProcessObserver(Mock(Session))
def processor = Mock(TaskProcessor) {
getExecutor() >> Mock(Executor) // Not an AzBatchExecutor
}

when:
observer.onProcessTerminate(processor)

then:
noExceptionThrown()
}

def 'should set job auto-termination when enabled'() {
given:
def observer = new AzBatchProcessObserver(Mock(Session))
def processor = Mock(TaskProcessor) { getName() >> 'test-process' }
def batchService = Mock(AzBatchService) {
getConfig() >> Mock(AzConfig) {
batch() >> Mock(AzBatchOpts) {
terminateJobsOnCompletion >> true
}
}
getAllJobIds() >> [(new AzJobKey(processor, 'pool1')): 'job123']
}
def executor = Mock(AzBatchExecutor) { getBatchService() >> batchService }
processor.getExecutor() >> executor

when:
observer.onProcessTerminate(processor)

then:
1 * batchService.setJobAutoTermination('job123')
}

def 'should skip when termination disabled'() {
given:
def observer = new AzBatchProcessObserver(Mock(Session))
def processor = Mock(TaskProcessor) { getName() >> 'test-process' }
def batchService = Mock(AzBatchService) {
getConfig() >> Mock(AzConfig) {
batch() >> Mock(AzBatchOpts) {
terminateJobsOnCompletion >> false
}
}
}
def executor = Mock(AzBatchExecutor) { getBatchService() >> batchService }
processor.getExecutor() >> executor

when:
observer.onProcessTerminate(processor)

then:
0 * batchService.setJobAutoTermination(_)
}
}
Loading