stable-diffusion.cpp/examples/server/async_jobs.h
Claude eeec4916a5
feat(server): stop a job that is generating
POST /sdcpp/v1/jobs/{id}/cancel used to answer 409 for a job that had
started. It now tells the library to stop and waits for the job to end:
200 with the cancelled job as soon as it has ended, or 202 with the job and
"cancel_requested": true when it is still stopping after ?wait= seconds
(0 to 60, default 10; 0 answers at once). Repeating the call is harmless,
and GET /sdcpp/v1/jobs/{id} shows the pending request. /capabilities now
reports cancel_generating as true.

The request belongs to the job: ContextKeeper::run() takes a CancelToken
and registers it, with the context, only while that job's attempt is
executing. A stop for one job can therefore never reach another request
(including a synchronous /sdapi one), a job cancelled before it reaches the
context generates nothing, and the context can be released or rebuilt
without cancel() ever touching a context that is gone.

The library forgets a stop request when a generation begins, so a request
that arrives a moment earlier would be lost. The route repeats it every
100 ms until the job ends.

A cancelled run is neither a failure nor a reason to step down: it does not
reload the model, does not touch last_error, and has its own counter,
counters.cancelled in /health. When a stop and a recoverable failure meet,
the stop wins and the model is not reloaded for a request nobody waits for.

Checked on a real sd-server with a CPU build and a synthetic model: stop of
a running job, repeated stop, queued job, job already finished, unknown id,
wait=0, invalid wait, and the next job on the same context. Tests and
documentation follow in separate commits.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-14 16:35:58 +02:00

94 lines
3.3 KiB
C++

#pragma once
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "recovery.h"
#include "runtime.h"
enum class AsyncJobKind {
ImgGen,
VidGen,
};
enum class AsyncJobStatus {
Queued,
Generating,
Completed,
Failed,
Cancelled,
};
const char* async_job_kind_name(AsyncJobKind kind);
const char* async_job_status_name(AsyncJobStatus status);
struct AsyncGenerationJob {
std::string id;
AsyncJobKind kind = AsyncJobKind::ImgGen;
AsyncJobStatus status = AsyncJobStatus::Queued;
int64_t created_at = unix_timestamp_now();
int64_t started_at = 0;
int64_t completed_at = 0;
ImgGenJobRequest img_gen;
VidGenJobRequest vid_gen;
std::vector<std::string> result_images_b64;
std::string result_media_b64;
std::string result_media_mime_type;
int result_frame_count = 0;
int result_fps = 0;
std::string error_code;
std::string error_message;
// Set when a client asked to stop the job while it was generating.
CancelToken cancel;
mutable std::mutex preview_mutex;
std::string preview_b64;
int preview_pass = 0;
int preview_step = 0;
int preview_total_steps = 0;
};
struct AsyncJobManager {
std::mutex mutex;
std::condition_variable cv;
// Notified, with mutex held, whenever a job that was generating reaches a final state.
std::condition_variable finished_cv;
std::unordered_map<std::string, std::shared_ptr<AsyncGenerationJob>> jobs;
std::unordered_map<std::string, int64_t> expired_jobs;
std::deque<std::string> queue;
uint64_t next_id = 0;
bool stop = false;
size_t max_pending_jobs = 64;
int64_t completed_ttl_seconds = 600;
int64_t failed_ttl_seconds = 600;
};
void purge_expired_jobs(AsyncJobManager& manager);
size_t count_pending_jobs(const AsyncJobManager& manager);
std::string make_async_job_id(AsyncJobManager& manager);
bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job);
// Asks the generating job to stop and waits, at most for the given time, until it has ended. The request is
// repeated while waiting, because the library forgets a stop request that arrives before the generation has
// begun. Returns true when the job has reached a final state. Call it without holding manager.mutex.
bool cancel_generating_job(ServerRuntime& runtime,
const std::shared_ptr<AsyncGenerationJob>& job,
std::chrono::milliseconds wait);
json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job);
bool execute_img_gen_job(ServerRuntime& runtime,
AsyncGenerationJob& job,
std::vector<std::string>& output_images,
GenerationFailure& failure);
bool execute_vid_gen_job(ServerRuntime& runtime,
AsyncGenerationJob& job,
std::string& output_media_b64,
std::string& output_media_mime_type,
int& output_frame_count,
int& output_fps,
GenerationFailure& failure);
void async_job_worker(ServerRuntime& runtime);