stable-diffusion.cpp/examples/server/routes_models.cpp
Claude abbec1a7f3
feat: track device health and halt the server when nothing can run
The engine keeps, for the whole process, a record of how each device,
the RAM and the disk are doing (src/core/device_health.*). A component
under strain offers less of its capacity, one step per level (85%, 70%,
55%); an excluded one offers nothing and is never computed on. A level
rises by one for a compute that fails, a backend that does not start,
the memory guard that cannot reach its threshold or a read of the
weights that fails (events less than 10 s apart count once), and comes
down one step after each quiet period of 300 s. Outside watchers report
signals with a source and a duration; a signal reaches the other
listings of the same card, a failure of one backend does not.

- C API, additions only: sd_device_health_t, sd_get_device_health(),
  sd_report_device_pressure() and sd_resume_device_health().
- The layer split gives each device its share of capacity, the run plan
  and the multi-GPU planner their share of memory, and an excluded
  device is never the default one. When the record changes, the next
  generation releases the cached models and places them again.
- The engine refuses to compute on an excluded device (a backend error
  at the start of the segment), computes on the CPU with 25% fewer
  threads per level and does not fall back to an excluded CPU. The RAM
  is never cut below the share of level 3; with the disk excluded,
  weights that would be read from it during the run are refused as out
  of memory.
- sd-server: the context keeper skips excluded devices and does not
  climb back to them. A guardian (examples/server/guardian.*) stops all
  work when a component is reported critical or every compute device is
  excluded: the generation in progress ends with the code halted, new
  work is refused with 503 halted and Retry-After, queued jobs wait, and
  /sdcpp/v1/health reports the guardian and every component. It resumes
  when the cause ends, or with POST /sdcpp/v1/guardian/resume; while it
  is halted the keeper neither loads the model again nor steps down.
  --guardian on|off, on by default.
- POST /sdcpp/v1/devices/{device}/pressure takes the reports of outside
  watchers, and termico.py osserva --segnala sends the temperature band
  of an NVIDIA GPU as the level of its device.

The values are provisional. This is a layer of the software, not a
safety system, and the docs say so: examples/server/api.md (Device
health and the guardian), the server README, the README of
scripts/diagnostica_termica, docs/agenti_indipendenti.md (section 9)
and the fork history.

test: device_health_test and server_guardian_test are new, and the
recovery, layer split, planner and termico tests cover the new rules.
server_guardian_e2e.py runs the guardian against a real sd-server: 59
checks, three runs in a row, with a synthetic SD 1.5 model. Every
program of test/ passes, the server tests under ThreadSanitizer too,
and broken versions of the registry, guardian, keeper and termico code
make them fail. Not tried: real GPUs, a layer split between two
devices, Windows.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-11-25 13:16:02 +01:00

157 lines
6.9 KiB
C++

#include "routes.h"
#include "async_jobs.h"
#include "guardian.h"
#include "model_catalog.h"
class SynchronousContextJob {
AsyncJobManager& manager_;
const SDSvrParams& params_;
public:
explicit SynchronousContextJob(const ServerRuntime& runtime)
: manager_(*runtime.async_job_manager), params_(*runtime.svr_params) {
std::lock_guard<std::mutex> lock(manager_.mutex);
++manager_.synchronous_jobs;
}
SynchronousContextJob(const SynchronousContextJob&) = delete;
SynchronousContextJob& operator=(const SynchronousContextJob&) = delete;
~SynchronousContextJob() {
{
std::lock_guard<std::mutex> lock(manager_.mutex);
--manager_.synchronous_jobs;
manager_.record_context_job_completion(params_);
}
manager_.cv.notify_one();
}
};
static void model_error(httplib::Response& res, int status, const std::string& code, const std::string& message) {
res.status = status;
res.set_content(safe_json_dump(json({{"error", message}, {"code", code}})), "application/json");
}
httplib::Server::Handler RuntimeRoutes::protect(httplib::Server::Handler handler) {
ServerRuntime* runtime = &runtime_;
return [runtime, handler](const httplib::Request& req, httplib::Response& res) {
const bool generation = req.path == "/sdapi/v1/txt2img" || req.path == "/sdapi/v1/img2img" ||
req.path == "/v1/images/generations" || req.path == "/v1/images/edits";
if (generation) {
if (refuse_while_halted(runtime->guardian, res)) {
return;
}
SynchronousContextJob job(*runtime);
std::lock_guard<std::mutex> lock(*runtime->sd_ctx_mutex);
if (!runtime->keeper->has_model()) {
model_error(res, 503, "model_not_loaded", "No model is loaded");
return;
}
handler(req, res);
// A generation that the guardian stopped is answered with the halt while it lasts.
if (res.status >= 400) {
refuse_while_halted(runtime->guardian, res);
}
} else {
handler(req, res);
}
};
}
void RuntimeRoutes::get(const std::string& pattern, httplib::Server::Handler handler) {
if (pattern.find("/sdcpp/v1/jobs/") != std::string::npos) {
server_.Get(pattern, handler);
return;
}
ServerModels* models = runtime_.models;
server_.Get(pattern, [models, handler](const httplib::Request& req, httplib::Response& res) {
std::shared_lock<std::shared_mutex> lock(models->model_mutex);
handler(req, res);
});
}
void RuntimeRoutes::post(const std::string& pattern, httplib::Server::Handler handler) {
server_.Post(pattern, pattern.find("/sdcpp/v1/jobs/") != std::string::npos ? handler : protect(handler));
}
// Loads the model of a recipe ahead of the requests that use it, or unloads the current one. Generation jobs
// pick their model themselves; these routes are for programs that want the model ready, or the memory back.
static void change_model(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, bool unload) {
// Unloading gives memory back, which a halted machine may need; loading is work.
if (!unload && refuse_while_halted(runtime.guardian, res)) {
return;
}
auto& models = *runtime.models;
{
std::lock_guard<std::mutex> jobs_lock(runtime.async_job_manager->mutex);
if (count_pending_jobs(*runtime.async_job_manager) != 0) {
model_error(res, 409, "model_busy", "Finish or cancel pending generation jobs before switching models");
return;
}
}
std::unique_lock<std::mutex> context_lock(*runtime.sd_ctx_mutex, std::try_to_lock);
if (!context_lock.owns_lock()) {
model_error(res, 409, "model_busy", "Model is in use or another model operation is running");
return;
}
if (unload) {
std::unique_lock<std::shared_mutex> lock(models.model_mutex);
runtime.keeper->unload();
*runtime.ctx_params = models.base_context;
*runtime.default_gen_params = models.base_defaults;
models.current_recipe = nullptr;
models.current_files = json::object();
++models.revision;
} else {
ServerModelSelection selection;
try {
selection = resolve_model_selection(runtime, json::parse(req.body), IMG_GEN);
} catch (const std::exception& e) {
model_error(res, 400, "invalid_model_config", e.what());
return;
}
std::string error_message;
if (!switch_current_model(runtime, std::move(selection), error_message)) {
model_error(res, 422, "model_load_failed", error_message);
return;
}
}
std::shared_lock<std::shared_mutex> lock(models.model_mutex);
res.set_content(safe_json_dump(model_status(runtime)), "application/json");
}
void register_model_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
svr.Get("/sdcpp/v1/recipes", [&runtime](const httplib::Request&, httplib::Response& res) {
auto& models = *runtime.models;
std::lock_guard<std::mutex> lock(models.catalog_mutex);
json items = json::array();
for (const auto& entry : models.recipes)
items.push_back(entry.second);
res.set_content(json({{"recipes", items}, {"errors", models.catalog_errors}}).dump(), "application/json");
});
svr.Get("/sdcpp/v1/model-files", [&runtime](const httplib::Request&, httplib::Response& res) {
auto& models = *runtime.models;
std::lock_guard<std::mutex> lock(models.catalog_mutex);
json items = json::array();
for (const auto& entry : models.files) {
items.push_back({{"id", entry.first}, {"name", entry.second.name}, {"category", entry.second.category}, {"root", entry.second.root.id}, {"relative_path", entry.second.relative_path}});
}
res.set_content(json({{"files", items}, {"errors", models.catalog_errors}}).dump(), "application/json");
});
svr.Post("/sdcpp/v1/models/refresh", [&runtime](const httplib::Request&, httplib::Response& res) {
refresh_model_catalog(runtime);
std::lock_guard<std::mutex> lock(runtime.models->catalog_mutex);
res.set_content(json({{"errors", runtime.models->catalog_errors}}).dump(), "application/json");
});
svr.Get("/sdcpp/v1/models/status", [&runtime](const httplib::Request&, httplib::Response& res) {
std::shared_lock<std::shared_mutex> lock(runtime.models->model_mutex);
res.set_content(safe_json_dump(model_status(runtime)), "application/json");
});
svr.Post("/sdcpp/v1/models/load", [&runtime](const httplib::Request& req, httplib::Response& res) {
change_model(runtime, req, res, false);
});
svr.Post("/sdcpp/v1/models/unload", [&runtime](const httplib::Request& req, httplib::Response& res) {
change_model(runtime, req, res, true);
});
}