Skip to content

Commit 82c19c8

Browse files
authored
feat(server): support cancelling DGL jobs (#2420)
1 parent f296cb0 commit 82c19c8

3 files changed

Lines changed: 41 additions & 4 deletions

File tree

‎examples/server/api.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1839,6 +1839,7 @@ the working directory's ./dgl directory unless --dgl-dir is set.
18391839
| POST /sdcpp/v1/dgl/script | Saves UTF-8 source with the given name. Pass previous_source to update an existing script. A conflict returns HTTP 409. |
18401840
| POST /sdcpp/v1/dgl/jobs | Queues the source string and returns a job ID with HTTP 202 |
18411841
| GET /sdcpp/v1/dgl/jobs/{id} | Returns the job status, error or result with tensor descriptions and inline encoded media |
1842+
| POST /sdcpp/v1/dgl/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job. Send `Content-Type: application/json`. |
18421843
| GET /sdcpp/v1/dgl/jobs/{id}/outputs/{index}?frame=0 | Returns a PNG of an image output or a video frame. Output and frame indexes start at zero. |
18431844

18441845
Failed jobs report `error.code` and `error.message`. When execution reports
@@ -1849,6 +1850,12 @@ Scripts share the component cache and execution settings used for generation.
18491850
Model reads are restricted to the configured model directories. Script writes
18501851
are restricted to output/ in the server's working directory.
18511852

1853+
Cancellation returns the current job status with HTTP 200. A queued job
1854+
becomes `cancelled` immediately. A running job sets the `cancel_requested`
1855+
flag. Poll the status endpoint until it reports `cancelled`. Execution stops
1856+
at a DGL cancellation check, so an operation currently running may have to
1857+
finish first. A terminal job returns its current status.
1858+
18521859
### Encoded DGL results
18531860

18541861
The existing job result has `type`, `outputs` and `media`. `outputs` retains

‎examples/server/async_jobs.cpp‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <sstream>
1111
#include <string_view>
1212
#include <thread>
13+
#include <utility>
1314

1415
#include "common/log.h"
1516
#include "common/media_io.h"
@@ -25,18 +26,24 @@ class JobCancellationMonitor {
2526
public:
2627
// The caller holds sd_ctx_mutex until this monitor has joined, keeping the
2728
// context alive and preventing cancellation from reaching another request.
28-
JobCancellationMonitor(sd_ctx_t* ctx, const AsyncGenerationJob& job)
29-
: thread_([this, ctx, &job]() {
29+
template <typename Cancel>
30+
JobCancellationMonitor(const AsyncGenerationJob& job, Cancel cancel)
31+
: thread_([this, &job, cancel = std::move(cancel)]() {
3032
std::unique_lock<std::mutex> lock(mutex_);
3133
while (!done_) {
3234
if (job.cancel_requested.load()) {
33-
// Each generation pass resets the library flag, including ADetailer.
34-
sd_cancel_generation(ctx, SD_CANCEL_ALL);
35+
cancel();
3536
}
3637
cv_.wait_for(lock, std::chrono::milliseconds(10), [this]() { return done_; });
3738
}
3839
}) {}
3940

41+
JobCancellationMonitor(sd_ctx_t* ctx, const AsyncGenerationJob& job)
42+
: JobCancellationMonitor(job, [ctx]() {
43+
// Each generation pass resets the library flag, including ADetailer.
44+
sd_cancel_generation(ctx, SD_CANCEL_ALL);
45+
}) {}
46+
4047
~JobCancellationMonitor() {
4148
{
4249
std::lock_guard<std::mutex> lock(mutex_);
@@ -233,6 +240,7 @@ bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job) {
233240
manager.queue.erase(new_end, manager.queue.end());
234241
job.model.reset();
235242
job.request_body = nullptr;
243+
job.dgl_source.clear();
236244
job.cancel_requested.store(true);
237245
job.status = AsyncJobStatus::Cancelled;
238246
job.completed_at = unix_timestamp_now_ms();
@@ -689,6 +697,11 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime,
689697
sd_dgl_result_t* raw_result = nullptr;
690698
{
691699
std::lock_guard<std::mutex> lock(*runtime.sd_ctx_mutex);
700+
if (job.cancel_requested.load())
701+
return false;
702+
JobCancellationMonitor cancellation(job, [ctx = runtime.sd_ctx]() {
703+
sd_dgl_ctx_cancel(sd_ctx_get_dgl_ctx(ctx));
704+
});
692705
update_job_progress(job, "executing", "dgl");
693706
const auto status = sd_dgl_run(sd_ctx_get_dgl_ctx(runtime.sd_ctx), source.c_str(), nullptr, 0, &raw_result);
694707
if (status != SD_STATUS_OK) {

‎examples/server/routes_dgl.cpp‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,23 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
259259
send_json(res, 200, make_async_job_json(manager, *job));
260260
}));
261261

262+
svr.Post(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/cancel)", local_dgl_route([&runtime](const Request& req, Response& res) {
263+
auto& manager = *runtime.async_job_manager;
264+
std::lock_guard<std::mutex> lock(manager.mutex);
265+
auto job = find_dgl_job(manager, req.matches[1].str(), res);
266+
if (!job)
267+
return;
268+
if (job->status == AsyncJobStatus::Queued) {
269+
if (!cancel_queued_job(manager, *job)) {
270+
send_error(res, 409, "Job queue state changed before cancellation");
271+
return;
272+
}
273+
} else if (job->status == AsyncJobStatus::Generating) {
274+
job->cancel_requested.store(true);
275+
}
276+
send_json(res, 200, make_async_job_json(manager, *job));
277+
}));
278+
262279
svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/outputs/([0-9]+))", local_dgl_route([&runtime](const Request& req, Response& res) {
263280
auto& manager = *runtime.async_job_manager;
264281
std::shared_ptr<sd_dgl_result_t> result;

0 commit comments

Comments
 (0)