stable-diffusion.cpp/examples/server/runtime.h
Claude 6a01873d73
feat: keep sd-server serving when a request runs out of memory
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
2026-10-11 10:40:29 +02:00

112 lines
3.5 KiB
C++

#pragma once
#include <algorithm>
#include <cstdint>
#include <filesystem>
#include <mutex>
#include <string>
#include <vector>
#include <json.hpp>
#include "common/common.h"
#include "common/resource_owners.hpp"
#include "stable-diffusion.h"
using json = nlohmann::json;
struct ArgOptions;
struct SDContextParams;
struct AsyncJobManager;
class ContextKeeper;
struct SDSvrParams {
std::string listen_ip = "127.0.0.1";
int listen_port = 1234;
std::string serve_html_path;
std::string api_key; // empty = no authentication
std::string cors_origins; // comma-separated allowlist; empty = reflect any origin
bool disable_degradation = false;
int degradation_cooldown = 300; // seconds before the server tries a heavier profile again; 0 = never
bool normal_exit = false;
sd_log_level_t log_level = SD_LOG_INFO;
bool color = false;
ArgOptions get_options();
bool validate();
bool resolve_and_validate();
std::string to_string() const;
};
struct LoraEntry {
std::string name;
std::string path;
std::string fullpath;
};
struct UpscalerEntry {
std::string name;
std::string path;
std::string fullpath;
std::string model_name;
int scale = 4;
int image_upscale_factor = 0;
uintmax_t file_size = 0;
std::filesystem::file_time_type last_modified;
};
struct ServerRuntime {
ContextKeeper* keeper;
const SDSvrParams* svr_params;
const SDContextParams* ctx_params;
const SDGenerationParams* default_gen_params;
std::vector<LoraEntry>* lora_cache;
std::mutex* lora_mutex;
std::vector<UpscalerEntry>* upscaler_cache;
std::mutex* upscaler_mutex;
AsyncJobManager* async_job_manager;
};
struct ImgGenJobRequest {
SDGenerationParams gen_params;
std::string output_format = "png";
int output_compression = 100;
std::string preview_mode = "none";
int preview_interval = 1;
sd_img_gen_params_t to_sd_img_gen_params_t() {
return gen_params.to_sd_img_gen_params_t();
}
};
struct VidGenJobRequest {
SDGenerationParams gen_params;
std::string output_format = "webm";
int output_compression = 100;
std::string preview_mode = "none";
int preview_interval = 1;
sd_vid_gen_params_t to_sd_vid_gen_params_t() {
return gen_params.to_sd_vid_gen_params_t();
}
};
std::string base64_encode(const std::vector<uint8_t>& bytes);
std::string normalize_output_format(std::string output_format);
std::vector<std::string> supported_img_output_formats(bool allow_webp = true);
std::vector<std::string> supported_vid_output_formats();
bool assign_output_options(ImgGenJobRequest& request,
std::string output_format,
int output_compression,
bool allow_webp,
std::string& error_message);
bool assign_output_options(VidGenJobRequest& request,
std::string output_format,
int output_compression,
std::string& error_message);
std::string video_mime_type(const std::string& output_format);
bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode);
std::string unsupported_generation_mode_error(const ServerRuntime& runtime, SDMode mode);
void refresh_lora_cache(ServerRuntime& rt);
std::string get_lora_full_path(ServerRuntime& rt, const std::string& path);
void refresh_upscaler_cache(ServerRuntime& rt);
int64_t unix_timestamp_now();