stable-diffusion.cpp/test/api_robustness.cpp
Claude 4d1dad55e8
Merge leejet/stable-diffusion.cpp 3b12781 into fork-pull (sync 4/4, part 2)
Brings in the Diffusion Graph Language runtime (#2396) and the commits
after it: MOSS-Image edit LoRAs (#2203), runtime LoRA counts (#2400),
immediate LoRA merges for INT8 weights (#2403), one server context with
on-demand model loading (#2404), Qwen Image 2.1 prefix caching (#2405)
and idle TTLs for model weights (#2406). The server changes of #2404
and #2406 come in the same merge so that sd-server is ported once.

src/pipeline and src/stable-diffusion.cpp are gone; the fork's
additions move into the graph runtime:
- CPU fallback: ModelRuntime::configure_backends() falls back to the cpu
  backend, with a warning, when a module's backend cannot be
  initialized; disable_backend_fallback (also a DGL context option)
  makes it fail with SD_ERROR_BACKEND instead.
- memory_guard is a DGL context option for the context's ModelManager.
  ModelManager::ResourceHandle, the residency manager the models use,
  forwards the guard hooks and honours the prefetch suspension.
- layer_split_fill is applied when the context is created; multi_gpu is
  checked there. The multi-GPU planner, which upstream no longer calls,
  picks the device of each module when auto-fit is on, more than one
  GPU is present and no backend was given (planned_backend_spec() in
  src/api/generation_program.cpp); the run plan places the weights.
- The SD2 v-parameterization probe reports a failed compute instead of
  aborting.
- sd_ctx_create, sd_ctx_set_model_options*, sd_generate_image and
  sd_generate_video record the error code again; a load failure with no
  deeper cause is model_file.

sd-server keeps the ContextKeeper as the owner of the context:
- requests pick their model as upstream does (recipe and models in the
  body); the switch goes through ContextKeeper::load(), so the profile
  ladder and the recovery cover it too;
- sd_ctx_mutex serializes model switches, generations and DGL scripts;
  a DGL script runs on the keeper's context, or on a temporary one while
  no model is loaded (ContextKeeper::with_context()); the idle TTL
  release does not wait for a running generation (try_with_context());
- every context the keeper creates gets the server's file-access policy
  (create_context_from_params() + apply_server_file_access());
- /sdcpp/v1/models/load and /unload stay, rebuilt on
  resolve_model_selection(), as do /sdcpp/v1/health and /resources;
- /sdcpp/v1/upscale and the server-side ADetailer go, as upstream did:
  both are DGL scripts now.

Tests: memory_guard_engine_test follows the new capacity hook;
server_recovery_test checks with_context() and try_with_context()
(red with both behaviours broken); api_robustness expects a missing
model file at the first generation, where the weights load now;
server_cancel_e2e.py uses 100 steps, the server's maximum.

docs: the C API section of docs/integrazione_progetti.md uses the
opaque options; backend.md says what the multi-GPU planner decides
with DGL; api.md documents the kept load/unload routes.

Verified with a CPU build: the library, sd-cli and sd-server build; all
nine unit-test programs pass, server_recovery_test eight times in a row
and twice under TSan with no warnings; with a synthetic SD 1.5 model
(random weights) sd-cli generates, falls back to the cpu backend for
--backend vulkan0 and fails as backend with --disable-backend-fallback,
and test/server_cancel_e2e.py passes its 35 checks against a real
sd-server. A scratch smoke test of the server (20 checks: no model, DGL
jobs with and without a model, models/load and unload, a job that picks
its model, the idle release) passes too.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-11-24 19:44:43 +01:00

160 lines
8.2 KiB
C++

// Robustness test for the public C API (device enumeration, param defaults, error reporting,
// system memory).
// Build (from the repository root, after building the static library):
// clang++ -std=c++17 -g -fsanitize=address,undefined -Iinclude test/api_robustness.cpp \
// build/libstable-diffusion.a build/ggml/src/libggml.a build/ggml/src/libggml-cpu.a \
// build/ggml/src/libggml-base.a <platform libs> -o api_robustness
// Run: ./api_robustness ; exit code 0 = all checks passed.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <thread>
#include <vector>
#include "stable-diffusion.h"
static int failures = 0;
#define CHECK(cond, msg) \
do { \
if (!(cond)) { \
printf("FAIL: %s\n", msg); \
failures++; \
} else { \
printf("ok: %s\n", msg); \
} \
} while (0)
int main() {
CHECK(!sd_get_device_info(0, nullptr), "info(null out) rejected");
sd_device_info_t info;
CHECK(!sd_get_device_info((size_t)-1, &info), "info(SIZE_MAX index) rejected");
CHECK(!sd_get_device_info(sd_get_device_count(), &info), "info(index == count) rejected");
const size_t n = sd_get_device_count();
CHECK(n >= 1, "at least one device (CPU)");
bool has_cpu = false, terminated = true;
for (size_t i = 0; i < n; i++) {
memset(&info, 0xAB, sizeof(info));
CHECK(sd_get_device_info(i, &info), "info(i) valid");
terminated = terminated && memchr(info.name, 0, sizeof(info.name)) &&
memchr(info.description, 0, sizeof(info.description));
has_cpu = has_cpu || info.type == SD_DEVICE_TYPE_CPU;
CHECK(info.free_memory_bytes <= info.total_memory_bytes || info.total_memory_bytes == 0,
"free <= total");
}
CHECK(terminated, "strings always null-terminated");
CHECK(has_cpu, "CPU device always present (fallback base)");
CHECK(strcmp(sd_device_type_name((sd_device_type_t)9999), "unknown") == 0,
"type_name(invalid) = unknown");
const size_t need = sd_list_devices(nullptr, 0);
char tiny[4];
CHECK(sd_list_devices(tiny, sizeof(tiny)) == need && tiny[3] == '\0',
"list_devices tiny buffer: no overflow");
std::vector<std::thread> threads;
std::vector<int> bad(8, 0);
for (int t = 0; t < 8; t++) {
threads.emplace_back([&, t] {
for (int k = 0; k < 2000; k++) {
sd_device_info_t x;
const size_t c = sd_get_device_count();
for (size_t i = 0; i < c; i++) {
if (!sd_get_device_info(i, &x)) {
bad[t]++;
}
}
}
});
}
for (auto& th : threads) {
th.join();
}
int total_bad = 0;
for (int b : bad) {
total_bad += b;
}
CHECK(total_bad == 0, "8-thread enumeration stress without errors");
sd_ctx_opt_t* p = sd_ctx_opt_create();
CHECK(p != nullptr && sd_opt_set_int(p, "memory_guard", 0) == SD_STATUS_OK &&
sd_opt_set_bool(p, "disable_backend_fallback", false) == SD_STATUS_OK &&
sd_opt_set_string(p, "multi_gpu", "auto") == SD_STATUS_OK,
"the context options know memory_guard, disable_backend_fallback and multi_gpu");
CHECK(sd_opt_set_int(p, "memory_guard", 101) != SD_STATUS_OK, "memory_guard refuses a percent above 100");
sd_opt_free(p);
sd_system_memory_t memory;
CHECK(!sd_get_system_memory(nullptr), "system_memory(null out) rejected");
memset(&memory, 0xAB, sizeof(memory));
const bool have_memory = sd_get_system_memory(&memory);
#if defined(__linux__) || defined(_WIN32) || defined(__APPLE__)
CHECK(have_memory && memory.total_bytes > 0 && memory.available_bytes > 0, "system memory is reported");
#endif
CHECK(!have_memory || memory.total_bytes == 0 || memory.available_bytes <= memory.total_bytes,
"available RAM never exceeds the total");
CHECK(!have_memory || memory.total_bytes == 0 || memory.process_bytes <= memory.total_bytes,
"process RAM never exceeds the total");
for (size_t i = 0; i < n; i++) {
if (sd_get_device_info(i, &info) && info.type == SD_DEVICE_TYPE_CPU && have_memory && memory.available_bytes > 0) {
const uint64_t spread = info.free_memory_bytes > memory.available_bytes
? info.free_memory_bytes - memory.available_bytes
: memory.available_bytes - info.free_memory_bytes;
CHECK(spread < (uint64_t)1 << 30, "CPU device reports the available RAM as free memory");
}
}
char message[256];
CHECK(sd_get_last_error_code(nullptr, 0) == SD_ERROR_NONE, "no error before any failure; null buffer accepted");
sd_ctx_t* ctx = reinterpret_cast<sd_ctx_t*>(0x1);
CHECK(sd_ctx_create(nullptr, &ctx) != SD_STATUS_OK && ctx == nullptr, "sd_ctx_create(null) fails");
CHECK(sd_get_last_error_code(message, sizeof(message)) == SD_ERROR_INVALID_ARGUMENT && message[0] != '\0',
"null parameters are an invalid argument, with a message");
char tiny_message[8];
memset(tiny_message, 'x', sizeof(tiny_message));
CHECK(sd_get_last_error_code(tiny_message, sizeof(tiny_message)) == SD_ERROR_INVALID_ARGUMENT &&
memchr(tiny_message, 0, sizeof(tiny_message)) != nullptr,
"a small message buffer is truncated and terminated");
CHECK(sd_get_last_error_code(message, 0) == SD_ERROR_INVALID_ARGUMENT, "a zero-size buffer is accepted");
// The weights load at the first generation, so a missing model file is reported there.
sd_ctx_opt_t* missing = sd_ctx_opt_create();
sd_opt_set_string(missing, "model_path", "/nonexistent/diffusione/model.safetensors");
CHECK(sd_ctx_create(missing, &ctx) == SD_STATUS_OK && ctx != nullptr, "sd_ctx_create does not read the model file yet");
sd_opt_free(missing);
CHECK(ctx != nullptr && !sd_ctx_supports_image_generation(ctx), "a missing model supports no generation");
sd_img_gen_opt_t* request = sd_img_gen_opt_create();
sd_result_t* missing_result = reinterpret_cast<sd_result_t*>(0x1);
CHECK(request != nullptr && sd_opt_set_string(request, "prompt", "a cat") == SD_STATUS_OK &&
sd_generate_image(ctx, request, &missing_result) != SD_STATUS_OK && missing_result == nullptr,
"generating with a missing model fails and clears the result");
CHECK(sd_get_last_error_code(message, sizeof(message)) == SD_ERROR_MODEL_FILE && strstr(message, "nonexistent") != nullptr,
"a missing model is a model file error that names the file");
sd_opt_free(request);
sd_ctx_free(ctx);
sd_result_t* result = reinterpret_cast<sd_result_t*>(0x1);
CHECK(sd_generate_image(nullptr, nullptr, &result) != SD_STATUS_OK && result == nullptr,
"sd_generate_image(null) fails and clears the result");
CHECK(sd_get_last_error_code(message, sizeof(message)) == SD_ERROR_INVALID_ARGUMENT, "sd_generate_image(null) is an invalid argument");
CHECK(sd_generate_image(nullptr, nullptr, nullptr) != SD_STATUS_OK &&
sd_get_last_error_code(message, sizeof(message)) == SD_ERROR_INVALID_ARGUMENT,
"sd_generate_image without a place for the result is an invalid argument");
std::thread other([&] {
CHECK(sd_get_last_error_code(nullptr, 0) == SD_ERROR_NONE, "the error state belongs to the thread that made the call");
});
other.join();
CHECK(strcmp(sd_error_code_name(SD_ERROR_OUT_OF_MEMORY), "out_of_memory") == 0 &&
strcmp(sd_error_code_name(SD_ERROR_MODEL_FILE), "model_file") == 0 &&
strcmp(sd_error_code_name(SD_ERROR_BACKEND), "backend") == 0 &&
strcmp(sd_error_code_name(SD_ERROR_BUSY), "busy") == 0 &&
strcmp(sd_error_code_name(SD_ERROR_CANCELLED), "cancelled") == 0 &&
strcmp(sd_error_code_name(SD_ERROR_NONE), "none") == 0 &&
strcmp(sd_error_code_name((sd_error_code_t)9999), "unknown") == 0,
"error code names");
printf("\n%s (%d failures)\n", failures ? "TEST FAILED" : "ALL TESTS PASSED", failures);
return failures ? 1 : 0;
}