mirror of
https://github.com/leejet/stable-diffusion.cpp.git
synced 2026-11-28 19:16:33 +00:00
A request that ran the machine out of memory ended in a 500 and left the
server on the configuration that had just failed, so every later request
of that size failed the same way. The context now belongs to a
ContextKeeper (examples/server/recovery.*) and every generation of the
OpenAI, sdapi and sdcpp endpoints goes through ContextKeeper::run().
On out_of_memory or backend (the codes of sd_get_last_error()) it frees
the model, loads it again with the next lighter profile of
max > balanced > lite > lite-disk > lite-cpu and runs the same request
again. Steps that would load the same configuration are skipped, a
device failure jumps to lite-cpu, and from lite on the VAE is decoded in
tiles whatever the request asked. --profile sets the top of the ladder.
After --degradation-cooldown seconds (300; 0 = never) the server climbs
back one profile at the start of the next request. A climb that fails
on its first use is undone and doubles the wait, up to an hour. If the
model cannot be loaded again, requests get 503 "unavailable" and the
load is retried no more than every 15 seconds. --disable-degradation
keeps the old behavior of answering with the error.
Failures are answered with 503 and Retry-After (out of memory, no
context), 400 (invalid_argument) or 500, with a body of
{"error", "code", "retry_after_seconds"}. Async jobs report the same
code in error.code, 429 carries Retry-After, and std::bad_alloc in a
handler becomes a 503. New endpoints: GET /sdcpp/v1/health (status,
profile, counters, last error, queue; it never waits for a running
generation) and GET /sdcpp/v1/resources (system memory and devices).
sd-server now exits with code 1 and a message when it cannot listen or
create its HTTP threads; the second used to end in std::terminate and
the first in a silent exit 0. The lite-disk profile clears --eager-load,
which read every weight into memory and so saved nothing.
test/server_recovery_test.cpp checks the ladder, the step downs, the
climb back, the reload after a failure, the HTTP answers and use from
several threads with a scripted library and clock (114 checks, also
under ASan/UBSan and TSan). Checked with a synthetic SD 1.5 model on
the CPU under address-space limits: a 384x384 request at 2400 MiB steps
down to lite-disk and succeeds, below 2200 MiB it answers 503 and the
server stays up, the climb back and a failed climb behave as described,
and nine parallel requests of the three kinds are all served. The server
and the whole engine built with ASan/UBSan went through the ladder, the
CPU memory-guard scenarios and injected read errors without a report.
Not checked: Windows, GPUs, real models.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
468 lines
17 KiB
C++
468 lines
17 KiB
C++
// Extracted from main.cpp during server refactor.
|
|
|
|
#include "async_jobs.h"
|
|
|
|
#include <algorithm>
|
|
#include <iomanip>
|
|
#include <sstream>
|
|
|
|
#include "common/log.h"
|
|
#include "common/media_io.h"
|
|
#include "common/resource_owners.hpp"
|
|
|
|
static void preview_callback(int step, int frame_count, sd_image_t* frames, bool is_noisy, void* data) {
|
|
(void)is_noisy;
|
|
if (frame_count <= 0 || frames == nullptr || frames[0].data == nullptr) {
|
|
return;
|
|
}
|
|
|
|
AsyncGenerationJob* job = static_cast<AsyncGenerationJob*>(data);
|
|
const sd_image_t& frame = frames[0];
|
|
const sd_preview_info_t info = sd_get_preview_info();
|
|
|
|
auto image_bytes = encode_image_to_vector(EncodedImageFormat::PNG,
|
|
frame.data,
|
|
frame.width,
|
|
frame.height,
|
|
frame.channel,
|
|
"",
|
|
80);
|
|
if (image_bytes.empty()) {
|
|
return;
|
|
}
|
|
|
|
std::string b64 = base64_encode(image_bytes);
|
|
std::lock_guard<std::mutex> lock(job->preview_mutex);
|
|
job->preview_b64 = std::move(b64);
|
|
job->preview_step = step < 0 ? -step : step;
|
|
job->preview_pass = info.sample_pass;
|
|
job->preview_total_steps = info.total_steps;
|
|
}
|
|
|
|
static void clear_preview_callback() {
|
|
sd_set_preview_callback(nullptr, PREVIEW_NONE, 1, false, false, nullptr);
|
|
}
|
|
|
|
static void set_preview_callback(AsyncGenerationJob& job) {
|
|
preview_t mode = str_to_preview(job.kind == AsyncJobKind::ImgGen
|
|
? job.img_gen.preview_mode.c_str()
|
|
: job.vid_gen.preview_mode.c_str());
|
|
if (mode == PREVIEW_COUNT || mode == PREVIEW_NONE) {
|
|
return;
|
|
}
|
|
int interval = job.kind == AsyncJobKind::ImgGen
|
|
? job.img_gen.preview_interval
|
|
: job.vid_gen.preview_interval;
|
|
if (interval <= 0) {
|
|
interval = 1;
|
|
}
|
|
sd_set_preview_callback(preview_callback, mode, interval, true, false, &job);
|
|
}
|
|
|
|
const char* async_job_kind_name(AsyncJobKind kind) {
|
|
switch (kind) {
|
|
case AsyncJobKind::ImgGen:
|
|
return "img_gen";
|
|
case AsyncJobKind::VidGen:
|
|
return "vid_gen";
|
|
default:
|
|
return "img_gen";
|
|
}
|
|
}
|
|
|
|
const char* async_job_status_name(AsyncJobStatus status) {
|
|
switch (status) {
|
|
case AsyncJobStatus::Queued:
|
|
return "queued";
|
|
case AsyncJobStatus::Generating:
|
|
return "generating";
|
|
case AsyncJobStatus::Completed:
|
|
return "completed";
|
|
case AsyncJobStatus::Failed:
|
|
return "failed";
|
|
case AsyncJobStatus::Cancelled:
|
|
return "cancelled";
|
|
default:
|
|
return "failed";
|
|
}
|
|
}
|
|
|
|
void purge_expired_jobs(AsyncJobManager& manager) {
|
|
const int64_t now = unix_timestamp_now();
|
|
|
|
for (auto it = manager.expired_jobs.begin(); it != manager.expired_jobs.end();) {
|
|
if (it->second <= now) {
|
|
it = manager.expired_jobs.erase(it);
|
|
} else {
|
|
++it;
|
|
}
|
|
}
|
|
|
|
for (auto it = manager.jobs.begin(); it != manager.jobs.end();) {
|
|
const auto& job = it->second;
|
|
if (job->completed_at == 0) {
|
|
++it;
|
|
continue;
|
|
}
|
|
|
|
int64_t ttl_seconds = job->status == AsyncJobStatus::Completed
|
|
? manager.completed_ttl_seconds
|
|
: manager.failed_ttl_seconds;
|
|
if (now - job->completed_at >= ttl_seconds) {
|
|
manager.expired_jobs[job->id] = now + std::max<int64_t>(ttl_seconds, 60);
|
|
it = manager.jobs.erase(it);
|
|
} else {
|
|
++it;
|
|
}
|
|
}
|
|
}
|
|
|
|
size_t count_pending_jobs(const AsyncJobManager& manager) {
|
|
size_t pending = 0;
|
|
for (const auto& entry : manager.jobs) {
|
|
if (entry.second->status == AsyncJobStatus::Queued ||
|
|
entry.second->status == AsyncJobStatus::Generating) {
|
|
++pending;
|
|
}
|
|
}
|
|
return pending;
|
|
}
|
|
|
|
std::string make_async_job_id(AsyncJobManager& manager) {
|
|
std::ostringstream oss;
|
|
oss << "job_" << std::hex << unix_timestamp_now() << "_" << std::setw(8)
|
|
<< std::setfill('0') << manager.next_id++;
|
|
return oss.str();
|
|
}
|
|
|
|
bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job) {
|
|
auto new_end = std::remove(manager.queue.begin(), manager.queue.end(), job.id);
|
|
if (new_end == manager.queue.end()) {
|
|
return false;
|
|
}
|
|
|
|
manager.queue.erase(new_end, manager.queue.end());
|
|
job.status = AsyncJobStatus::Cancelled;
|
|
job.completed_at = unix_timestamp_now();
|
|
job.result_images_b64.clear();
|
|
job.result_media_b64.clear();
|
|
job.result_media_mime_type.clear();
|
|
job.result_frame_count = 0;
|
|
job.result_fps = 0;
|
|
job.error_code = "cancelled";
|
|
job.error_message = "job cancelled by client";
|
|
return true;
|
|
}
|
|
|
|
json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job) {
|
|
json result;
|
|
result["id"] = job.id;
|
|
result["kind"] = async_job_kind_name(job.kind);
|
|
result["status"] = async_job_status_name(job.status);
|
|
result["created"] = job.created_at;
|
|
result["started"] = job.started_at == 0 ? json(nullptr) : json(job.started_at);
|
|
result["completed"] = job.completed_at == 0 ? json(nullptr) : json(job.completed_at);
|
|
result["queue_position"] = 0;
|
|
|
|
if (job.status == AsyncJobStatus::Queued) {
|
|
size_t position = 1;
|
|
for (const auto& queued_id : manager.queue) {
|
|
if (queued_id == job.id) {
|
|
result["queue_position"] = position;
|
|
break;
|
|
}
|
|
++position;
|
|
}
|
|
}
|
|
|
|
if (job.status == AsyncJobStatus::Completed) {
|
|
if (job.kind == AsyncJobKind::VidGen) {
|
|
result["result"] = {
|
|
{"output_format", job.vid_gen.output_format},
|
|
{"mime_type", job.result_media_mime_type},
|
|
{"fps", job.result_fps},
|
|
{"frame_count", job.result_frame_count},
|
|
{"b64_json", job.result_media_b64},
|
|
};
|
|
} else {
|
|
json images = json::array();
|
|
for (size_t i = 0; i < job.result_images_b64.size(); ++i) {
|
|
images.push_back({{"index", i}, {"b64_json", job.result_images_b64[i]}});
|
|
}
|
|
result["result"] = {
|
|
{"output_format", job.img_gen.output_format},
|
|
{"images", images},
|
|
};
|
|
}
|
|
result["error"] = nullptr;
|
|
} else if (job.status == AsyncJobStatus::Failed ||
|
|
job.status == AsyncJobStatus::Cancelled) {
|
|
result["result"] = nullptr;
|
|
result["error"] = {
|
|
{"code",
|
|
job.error_code.empty()
|
|
? (job.status == AsyncJobStatus::Cancelled ? "cancelled" : "generation_failed")
|
|
: job.error_code},
|
|
{"message", job.error_message},
|
|
};
|
|
} else {
|
|
result["result"] = nullptr;
|
|
result["error"] = nullptr;
|
|
}
|
|
|
|
if (job.status == AsyncJobStatus::Generating) {
|
|
std::lock_guard<std::mutex> lock(job.preview_mutex);
|
|
if (!job.preview_b64.empty()) {
|
|
result["preview"] = {
|
|
{"pass", job.preview_pass},
|
|
{"step", job.preview_step},
|
|
{"total_steps", job.preview_total_steps},
|
|
{"b64_json", job.preview_b64},
|
|
};
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
static bool fail_with(GenerationFailure& failure, const char* message) {
|
|
failure = GenerationFailure();
|
|
failure.code = SD_ERROR_UNKNOWN;
|
|
failure.message = message;
|
|
return false;
|
|
}
|
|
|
|
bool execute_img_gen_job(ServerRuntime& runtime,
|
|
AsyncGenerationJob& job,
|
|
std::vector<std::string>& output_images,
|
|
GenerationFailure& failure) {
|
|
const sd_img_gen_params_t params = job.img_gen.to_sd_img_gen_params_t();
|
|
|
|
SDImageVec results;
|
|
const bool generated = runtime.keeper->run(
|
|
[&](const ContextKeeper::ContextView& view) {
|
|
sd_img_gen_params_t attempt_params = params;
|
|
if (view.force_vae_tiling) {
|
|
attempt_params.vae_tiling_params.enabled = true;
|
|
}
|
|
set_preview_callback(job);
|
|
sd_image_t* raw_results = nullptr;
|
|
int num_results = 0;
|
|
const bool ok = generate_image(view.ctx, &attempt_params, &raw_results, &num_results);
|
|
clear_preview_callback();
|
|
if (!ok) {
|
|
return false;
|
|
}
|
|
results.adopt(raw_results, num_results);
|
|
return true;
|
|
},
|
|
failure);
|
|
if (!generated) {
|
|
return false;
|
|
}
|
|
|
|
const int num_results = results.count();
|
|
if (num_results <= 0) {
|
|
return fail_with(failure, "generate_image returned no results");
|
|
}
|
|
|
|
EncodedImageFormat encoded_format = EncodedImageFormat::PNG;
|
|
if (job.img_gen.output_format == "jpeg") {
|
|
encoded_format = EncodedImageFormat::JPEG;
|
|
} else if (job.img_gen.output_format == "webp") {
|
|
encoded_format = EncodedImageFormat::WEBP;
|
|
}
|
|
|
|
int batch_count = job.img_gen.gen_params.batch_count;
|
|
int images_per_batch = batch_count > 0 ? std::max(1, num_results / batch_count) : 1;
|
|
for (int i = 0; i < num_results; ++i) {
|
|
if (results[i].data == nullptr) {
|
|
continue;
|
|
}
|
|
|
|
const std::string metadata = job.img_gen.gen_params.embed_image_metadata
|
|
? get_image_params(*runtime.ctx_params,
|
|
job.img_gen.gen_params,
|
|
job.img_gen.gen_params.seed + i / images_per_batch)
|
|
: "";
|
|
auto image_bytes = encode_image_to_vector(encoded_format,
|
|
results[i].data,
|
|
results[i].width,
|
|
results[i].height,
|
|
results[i].channel,
|
|
metadata,
|
|
job.img_gen.output_compression);
|
|
if (image_bytes.empty()) {
|
|
continue;
|
|
}
|
|
output_images.push_back(base64_encode(image_bytes));
|
|
}
|
|
|
|
if (output_images.empty()) {
|
|
return fail_with(failure, "generate_image returned empty encoded outputs");
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
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) {
|
|
const sd_vid_gen_params_t params = job.vid_gen.to_sd_vid_gen_params_t();
|
|
std::string str_params = job.vid_gen.gen_params.embed_image_metadata
|
|
? get_image_params(*runtime.ctx_params, job.vid_gen.gen_params, job.vid_gen.gen_params.seed, VID_GEN)
|
|
: "";
|
|
|
|
SDImageVec results;
|
|
int num_results = 0;
|
|
sd_audio_t* generated_audio = nullptr;
|
|
|
|
const bool generated = runtime.keeper->run(
|
|
[&](const ContextKeeper::ContextView& view) {
|
|
sd_vid_gen_params_t attempt_params = params;
|
|
if (view.force_vae_tiling) {
|
|
attempt_params.vae_tiling_params.enabled = true;
|
|
}
|
|
set_preview_callback(job);
|
|
sd_image_t* raw_results = nullptr;
|
|
int frame_count = 0;
|
|
sd_audio_t* audio = nullptr;
|
|
int fps = 0;
|
|
const bool ok = generate_video(view.ctx, &attempt_params, &raw_results, &frame_count, &audio, &fps);
|
|
clear_preview_callback();
|
|
if (!ok) {
|
|
return false;
|
|
}
|
|
results.adopt(raw_results, frame_count);
|
|
generated_audio = audio;
|
|
output_fps = fps;
|
|
return true;
|
|
},
|
|
failure);
|
|
if (!generated) {
|
|
return false;
|
|
}
|
|
|
|
num_results = results.count();
|
|
if (num_results <= 0) {
|
|
free_sd_audio(generated_audio);
|
|
return fail_with(failure, "generate_video returned no results");
|
|
}
|
|
|
|
std::vector<uint8_t> video_bytes = create_video_from_sd_images_to_vector(job.vid_gen.output_format,
|
|
results.data(),
|
|
num_results,
|
|
output_fps,
|
|
job.vid_gen.output_compression,
|
|
generated_audio,
|
|
str_params);
|
|
free_sd_audio(generated_audio);
|
|
if (video_bytes.empty()) {
|
|
return fail_with(failure, "failed to encode generated video container");
|
|
}
|
|
|
|
output_media_b64 = base64_encode(video_bytes);
|
|
output_media_mime_type = video_mime_type(job.vid_gen.output_format);
|
|
output_frame_count = num_results;
|
|
return true;
|
|
}
|
|
|
|
void async_job_worker(ServerRuntime& runtime) {
|
|
AsyncJobManager& manager = *runtime.async_job_manager;
|
|
|
|
while (true) {
|
|
std::shared_ptr<AsyncGenerationJob> job;
|
|
{
|
|
std::unique_lock<std::mutex> lock(manager.mutex);
|
|
manager.cv.wait(lock, [&]() { return manager.stop || !manager.queue.empty(); });
|
|
|
|
if (manager.stop && manager.queue.empty()) {
|
|
break;
|
|
}
|
|
|
|
purge_expired_jobs(manager);
|
|
if (manager.queue.empty()) {
|
|
continue;
|
|
}
|
|
|
|
const std::string job_id = manager.queue.front();
|
|
manager.queue.pop_front();
|
|
|
|
auto it = manager.jobs.find(job_id);
|
|
if (it == manager.jobs.end()) {
|
|
continue;
|
|
}
|
|
|
|
job = it->second;
|
|
job->status = AsyncJobStatus::Generating;
|
|
job->started_at = unix_timestamp_now();
|
|
}
|
|
|
|
std::vector<std::string> output_images;
|
|
std::string output_media_b64;
|
|
std::string output_media_mime_type;
|
|
int output_frame_count = 0;
|
|
int output_fps = 0;
|
|
GenerationFailure failure;
|
|
bool ok = false;
|
|
|
|
try {
|
|
if (job->kind == AsyncJobKind::ImgGen) {
|
|
ok = execute_img_gen_job(runtime, *job, output_images, failure);
|
|
} else if (job->kind == AsyncJobKind::VidGen) {
|
|
ok = execute_vid_gen_job(runtime,
|
|
*job,
|
|
output_media_b64,
|
|
output_media_mime_type,
|
|
output_frame_count,
|
|
output_fps,
|
|
failure);
|
|
} else {
|
|
fail_with(failure, "unsupported job kind");
|
|
}
|
|
} catch (const std::exception& error) {
|
|
// An exception must not end the only thread that serves the queue.
|
|
ok = false;
|
|
failure = failure_from_exception(error);
|
|
LOG_ERROR("job %s stopped by an exception: %s", job->id.c_str(), error.what());
|
|
} catch (...) {
|
|
ok = false;
|
|
fail_with(failure, "unexpected error while generating");
|
|
}
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(manager.mutex);
|
|
auto it = manager.jobs.find(job->id);
|
|
if (it == manager.jobs.end()) {
|
|
continue;
|
|
}
|
|
|
|
job->completed_at = unix_timestamp_now();
|
|
if (ok) {
|
|
job->status = AsyncJobStatus::Completed;
|
|
job->result_images_b64 = std::move(output_images);
|
|
job->result_media_b64 = std::move(output_media_b64);
|
|
job->result_media_mime_type = std::move(output_media_mime_type);
|
|
job->result_frame_count = output_frame_count;
|
|
job->result_fps = output_fps;
|
|
job->error_code.clear();
|
|
job->error_message.clear();
|
|
} else {
|
|
job->status = AsyncJobStatus::Failed;
|
|
job->error_code = failure_code_name(failure);
|
|
job->error_message = failure.message.empty() ? "unknown generation error" : failure.message;
|
|
job->result_images_b64.clear();
|
|
job->result_media_b64.clear();
|
|
job->result_media_mime_type.clear();
|
|
job->result_frame_count = 0;
|
|
job->result_fps = 0;
|
|
}
|
|
|
|
purge_expired_jobs(manager);
|
|
}
|
|
}
|
|
}
|