diff --git a/test/README.md b/test/README.md index 70b65934..50d4c635 100644 --- a/test/README.md +++ b/test/README.md @@ -15,8 +15,8 @@ sezione "Sicurezza". | `profile_test.cpp` | profili di risorse (`--profile`): scelta automatica da dimensione del modello e memoria (anche sommando la memoria di più GPU), ordine dei livelli, opzioni esplicite che vincono sul profilo | vedi intestazione del file | | `backend_fit_plan_test.cpp` | pianificatore multi-GPU dell'auto-fit (`--multi-gpu auto\|on\|off`) con GPU simulate: quale modulo va su quale GPU, quando il modello si divide per blocchi, nessun device riceve più pesi del suo budget, i moduli assegnati dall'utente non si muovono. Con più backend installati insieme (CUDA e Vulkan): la stessa scheda vista da due backend conta una volta sola, una GPU integrata non diventa la scheda principale finché una scheda ha memoria libera e la sua memoria condivisa (la RAM) non ospita pesi; gli avvisi dopo il piano: `--backend vulkan0` su una scheda che CUDA elenca come CUDA0, e pesi lasciati su disco che vengono riletti a ogni passo (include `src/core/backend_fit.cpp`, quindi serve la libreria compilata; nessuna GPU né modello) | vedi intestazione del file | | `package_windows_cuda_vulkan_test.sh` | script che assembla lo zip Windows con CUDA e Vulkan insieme (`scripts/package_windows_cuda_vulkan.sh`, passo del job `release` di `build.yml`) con zip finti che hanno i nomi di quelli veri: pacchetto in una cartella sola con tutti i file (programmi e `stable-diffusion.dll` dallo zip CUDA, solo `ggml-vulkan.dll` dallo zip Vulkan, DLL di CUDA, `LEGGIMI.txt`), avviso se `ggml-base.dll` o `ggml.dll` hanno dimensioni diverse, rifiuto di uno zip mancante o doppio, di zip di commit diversi, di moduli o DLL mancanti, di file con lo stesso nome in due zip e di un `LEGGIMI.txt` già presente, due esecuzioni nella stessa cartella. Servono `zip` e `unzip`; nessuna build, GPU o modello | `./test/package_windows_cuda_vulkan_test.sh` (meno di un secondo) | -| `server_recovery_test.cpp` | custode del contesto del server (`examples/server/recovery.*`): scala dei profili, discesa su memoria insufficiente, risalita dopo una pausa, ricarica dopo un errore, risposte HTTP 503/400/500 con `Retry-After`, uso da più thread. Annullamento di una generazione in corso: lo stop raggiunge solo il job che lo ha chiesto, un job annullato prima di partire non genera nulla, non costa nessuna ricarica del modello e non conta come errore. Non serve nessun modello: libreria e orologio sono simulati (con ASan/UBSan e TSan) | vedi intestazione del file | -| `server_cancel_e2e.py` | annullamento di un job in corso su un vero `sd-server` (serve un modello qualsiasi, su qualunque backend): job fermato, richiesta ripetuta, job in coda, `?wait=0`, POST senza corpo né `Content-Length` (come `curl -X POST`: risposta subito, non dopo 5 secondi), richiesta sincrona in attesa che poi completa, job già finito, id sconosciuto, `wait` non valido, contatori di `/sdcpp/v1/health` e log senza righe di errore | `python3 test/server_cancel_e2e.py --server build/bin/sd-server --model ` | +| `server_recovery_test.cpp` | custode del contesto del server (`examples/server/recovery.*`): scala dei profili, discesa su memoria insufficiente, risalita dopo una pausa, ricarica dopo un errore, risposte HTTP 503/400/500 con `Retry-After`, uso da più thread. Annullamento di una generazione in corso: lo stop raggiunge solo il job che lo ha chiesto, un job annullato prima di partire non genera nulla, non costa nessuna ricarica del modello e non conta come errore. Caricamento e scaricamento del modello chiesti dal catalogo del server (`load`/`unload`): il vecchio contesto viene liberato prima di crearne uno nuovo, la scala dei profili si ricostruisce dalle opzioni del modello nuovo, un caricamento fallito lascia il server senza modello (richieste rifiutate) e si può ripetere, scaricare due volte è innocuo, salute e stato si possono leggere mentre il modello cambia. Non serve nessun modello: libreria e orologio sono simulati (con ASan/UBSan e TSan) | vedi intestazione del file | +| `server_cancel_e2e.py` | annullamento di un job in corso su un vero `sd-server` (serve un modello qualsiasi, su qualunque backend): job fermato (senza `?wait=` la risposta torna subito con il job ancora in generazione), richiesta ripetuta, job in coda, `?wait=0`, `?wait=30` (`200` appena il job finisce), POST senza corpo né `Content-Length` (come `curl -X POST`: risposta subito, non dopo 5 secondi), richiesta sincrona in attesa che poi completa, job già finito, id sconosciuto, `wait` non valido, contatori di `/sdcpp/v1/health` e log senza righe di errore | `python3 test/server_cancel_e2e.py --server build/bin/sd-server --model ` | | `termico_test.py` | programma di diagnostica termica [`scripts/diagnostica_termica/`](../scripts/diagnostica_termica/README.md) (`termico.py` e `carico_motore.py`) con una GPU finta (un `nvidia-smi` scritto dentro il test) e un motore finto: lettura dei campi e dei motivi di throttling, fasce di temperatura, giudizi, riepilogo e file di stato, confronto fra prove, codici di uscita, interruzione con Ctrl+C e SIGTERM, motore che non risponde, chiave API. Non serve nessuna GPU, driver o modello | `python3 test/termico_test.py` (1-2 minuti; `--veloce` salta le prove che lanciano il programma) | | `agenti_guardiano_test.py` | guardiano d'esempio di [docs/agenti_indipendenti.md](../docs/agenti_indipendenti.md) (sezione 9): il test estrae il codice dalla guida e lo fa girare. Senza opzioni usa un orologio e un motore finti (nessun modello né GPU): lettura dello stato e dato vecchio, livelli, attesa prima di ripartire, tetto orario, file `stop`, registro, `429`/`503` con `Retry-After`, scadenze, stop ignorato dal motore. Con `--server` e `--model` prova la catena vera: `sd-server` (anche su CPU), `termico.py` con la GPU finta di `termico_test.py`, GPU critica = job fermato con `cancel` senza discesa di profilo, job di un altro programma non toccato | `python3 test/agenti_guardiano_test.py` (10 secondi); con il server vero aggiungi `--server build/bin/sd-server --model MODELLO` (circa 2 minuti con un modello piccolo) | | `fuzz_model_loader.py` | fuzzing a mutazione del caricamento modelli (safetensors/GGUF) | `python3 test/fuzz_model_loader.py --seconds 300` | diff --git a/test/api_robustness.cpp b/test/api_robustness.cpp index 2421937d..2ced732e 100644 --- a/test/api_robustness.cpp +++ b/test/api_robustness.cpp @@ -124,11 +124,13 @@ int main() { CHECK(sd_get_last_error(message, sizeof(message)) == SD_ERROR_MODEL_FILE && strstr(message, "nonexistent") != nullptr, "a missing model is a model file error that names the file"); - sd_image_t* images = (sd_image_t*)0x1; - int image_count = 7; - CHECK(!generate_image(nullptr, nullptr, &images, &image_count) && images == nullptr && image_count == 0, - "generate_image(null) fails and clears the outputs"); + sd_image_generation_result_t* result = (sd_image_generation_result_t*)0x1; + CHECK(!generate_image(nullptr, nullptr, &result) && result == nullptr, + "generate_image(null) fails and clears the result"); CHECK(sd_get_last_error(message, sizeof(message)) == SD_ERROR_INVALID_ARGUMENT, "generate_image(null) is an invalid argument"); + CHECK(!generate_image(nullptr, nullptr, nullptr) && + sd_get_last_error(message, sizeof(message)) == SD_ERROR_INVALID_ARGUMENT, + "generate_image without a place for the result is an invalid argument"); std::thread other([&] { CHECK(sd_get_last_error(nullptr, 0) == SD_ERROR_NONE, "the error state belongs to the thread that made the call"); diff --git a/test/profile_test.cpp b/test/profile_test.cpp index fa14981b..947705ee 100644 --- a/test/profile_test.cpp +++ b/test/profile_test.cpp @@ -3,7 +3,8 @@ // Build (from the repository root, after building the library into build/): // cc -c thirdparty/zip.c -o zip.o // c++ -std=c++17 -Iexamples -Iinclude -Ithirdparty -Isrc test/profile_test.cpp examples/common/common.cpp \ -// examples/common/log.cpp examples/common/media_io.cpp examples/common/profile.cpp zip.o \ +// examples/common/log.cpp examples/common/media_io.cpp examples/common/media_metadata.cpp \ +// examples/common/generation_metadata.cpp examples/common/profile.cpp zip.o \ // -Lbuild/bin -lstable-diffusion -Wl,-rpath,build/bin -pthread -o profile_test // Run: ./profile_test ; exit code 0 = all checks passed. #include @@ -163,7 +164,7 @@ int main() { Parsed bad({"--multi-gpu", "sideways"}); CHECK(bad.ok && !bad.ctx.validate(IMG_GEN, false), "--multi-gpu refuses anything but auto, on and off"); Parsed passed({"--multi-gpu", "on"}); - const sd_ctx_params_t raw = passed.ctx.to_sd_ctx_params_t(false); + const sd_ctx_params_t raw = passed.ctx.to_sd_ctx_params_t(); CHECK(raw.multi_gpu != nullptr && strcmp(raw.multi_gpu, "on") == 0, "the value reaches the library"); } { diff --git a/test/server_cancel_e2e.py b/test/server_cancel_e2e.py index ebf03f8c..8da0704c 100644 --- a/test/server_cancel_e2e.py +++ b/test/server_cancel_e2e.py @@ -13,6 +13,11 @@ Extra options for the server (a backend, --flash-attn, ...) go after --extra, on The first generation can take minutes when the weights are read from a slow disk, so the test starts with a warm-up job (--warmup-timeout) and only then looks at how a stop behaves. + +Without ?wait= the cancel route answers at once, with the job still generating, and sends the stop once: the +library forgets a stop that arrives before the generation has begun, so the test asks again when the job does +not end, as a client of the route does. With ?wait=N the server repeats the stop itself and answers 200 when +the job has ended or 202 when it has not. """ import argparse import json @@ -94,6 +99,25 @@ class Client: time.sleep(0.1) raise Abort("job %s did not become %s within %d s" % (job_id, wanted, timeout)) + def stop_until_ended(self, job_id, timeout, patience=10.0): + """What a client of the cancel route without ?wait= does after its first request: the stop is sent + once and the library forgets it when it arrives before the generation has begun, so the request is + repeated every `patience` seconds until the job has ended. Returns the job and how many times the + request had to be repeated.""" + started = time.time() + last_stop = started + repeated = 0 + while time.time() - started < timeout: + job = self.job(job_id) + if job["status"] in ("completed", "failed", "cancelled"): + return job, repeated + if time.time() - last_stop >= patience: + self.call("POST", "/sdcpp/v1/jobs/%s/cancel" % job_id) + last_stop = time.time() + repeated += 1 + time.sleep(0.1) + raise Abort("job %s did not end within %d s of the stop" % (job_id, timeout)) + def health(self): return self.call("GET", "/sdcpp/v1/health")[1] @@ -176,21 +200,22 @@ def run_scenarios(client, args, mark_log): before = start["counters"] mark_log() - # 1. A job that is generating is stopped. + # 1. A job that is generating is stopped. Without ?wait= the answer comes at once, with the job still + # generating and the stop pending, and the client polls the job until it ends. job_id = client.submit(steps, 2, size) client.wait_for(job_id, ("generating",), 60) time.sleep(1.5) status, body, seconds = client.call("POST", "/sdcpp/v1/jobs/%s/cancel" % job_id) if status == 200 and body["status"] == "completed": raise Abort("the job finished before it could be cancelled: raise --steps or --size") - check(status in (200, 202), "cancelling a generating job answers 200 or 202 (got %s)" % status) - if status == 202: - check(body.get("cancel_requested") is True and body["status"] == "generating", - "a 202 carries the job with cancel_requested") - body = client.wait_for(job_id, ("cancelled",), 120) + check(status == 200 and body["status"] == "generating" and body.get("cancel_requested") is True, + "without ?wait= the answer is 200 with the job still generating and the stop pending (got %s)" % status) + check(seconds < 2.0, "and it comes at once (%.2f s)" % seconds) + body, repeated = client.stop_until_ended(job_id, 120) check(body["status"] == "cancelled" and body["error"]["code"] == "cancelled", "the job ends as cancelled with the code cancelled") - print(" the request returned after %.1f s" % seconds, flush=True) + if repeated: + print(" the stop had to be repeated %d time(s): it came before the generation began" % repeated, flush=True) check(body["started"] is not None and body["completed"] is not None, "it records when it started and ended") # 2. Asking again is harmless. @@ -231,6 +256,21 @@ def run_scenarios(client, args, mark_log): check(final["status"] == "cancelled", "the job ends as cancelled") check(client.job(queued)["status"] == "cancelled", "the queued job stayed cancelled and never ran") + # 4b. With ?wait=N the server repeats the stop itself and answers 200 as soon as the job has ended. + wait_seconds = 30 + waiting = client.submit(steps, 8, size) + client.wait_for(waiting, ("generating",), 60) + time.sleep(1.0) + status, body, seconds = client.call("POST", "/sdcpp/v1/jobs/%s/cancel?wait=%d" % (waiting, wait_seconds)) + check(status == 200 and body["status"] == "cancelled" and body["error"]["code"] == "cancelled", + "?wait=%d answers 200 with the job already cancelled (got %s after %.1f s)" % (wait_seconds, status, seconds)) + if status == 200: + check(seconds < wait_seconds - 1, "as soon as the job ended, not when the wait ran out") + else: + check(status == 202 and body.get("cancel_requested") is True, + "a wait that runs out answers 202 with the stop pending") + client.stop_until_ended(waiting, 120) + # 5. A request that waits behind a job being cancelled still completes. long_job = client.submit(steps, 6, size) client.wait_for(long_job, ("generating",), 60) @@ -244,9 +284,8 @@ def run_scenarios(client, args, mark_log): thread = threading.Thread(target=synchronous_request) thread.start() time.sleep(1.5) - status, body, _ = client.call("POST", "/sdcpp/v1/jobs/%s/cancel" % long_job) - if status == 202: - body = client.wait_for(long_job, ("cancelled",), 120) + client.call("POST", "/sdcpp/v1/jobs/%s/cancel" % long_job) + body, _ = client.stop_until_ended(long_job, 120) check(body["status"] == "cancelled", "the long job is cancelled while a synchronous request waits for the model") thread.join(args.warmup_timeout) sync_status, sync_body, _ = outcome.get("result", (None, None, 0)) @@ -272,8 +311,8 @@ def run_scenarios(client, args, mark_log): health = client.health() now = health["counters"] check(health["status"] == start["status"] and health["busy"] is False, "the server is idle and as healthy as before") - check(now["cancelled"] - before["cancelled"] == 3 and now["failed"] == before["failed"], - "three jobs were stopped while generating (the queued one never reached the model), none failed") + check(now["cancelled"] - before["cancelled"] == 4 and now["failed"] == before["failed"], + "four jobs were stopped while generating (the queued one never reached the model), none failed") check(now["step_downs"] == before["step_downs"], "no step down happened") diff --git a/test/server_recovery_test.cpp b/test/server_recovery_test.cpp index 94ec0742..3bb5ec89 100644 --- a/test/server_recovery_test.cpp +++ b/test/server_recovery_test.cpp @@ -6,7 +6,8 @@ // cc -c thirdparty/zip.c -o zip.o // c++ -std=c++17 -Iexamples -Iexamples/server -Iinclude -Ithirdparty -Isrc test/server_recovery_test.cpp // examples/server/recovery.cpp examples/common/common.cpp examples/common/log.cpp -// examples/common/media_io.cpp examples/common/profile.cpp zip.o +// examples/common/media_io.cpp examples/common/media_metadata.cpp examples/common/generation_metadata.cpp +// examples/common/profile.cpp zip.o // -Lbuild/bin -lstable-diffusion -Wl,-rpath,build/bin -pthread -o server_recovery_test // Run: ./server_recovery_test ; exit code 0 = all checks passed. #include @@ -65,6 +66,7 @@ struct Load { std::string backend; std::string params_backend; bool eager_load; + std::string model_path; Level level() const { if (backend == "cpu") { @@ -87,6 +89,7 @@ struct Load { struct Env { std::vector loads; std::function load_result; // code NONE = the model loads + std::function on_create; // runs when the keeper asks the library for a context GenerationFailure next_failure; // what the library reports for the attempt that failed Clock::time_point now = Clock::now(); bool accelerator = true; @@ -103,8 +106,12 @@ struct Env { params.batched_cfg, params.backend != nullptr ? params.backend : "", params.params_backend != nullptr ? params.params_backend : "", - params.eager_load}; + params.eager_load, + params.model_path != nullptr ? params.model_path : ""}; loads.push_back(load); + if (on_create) { + on_create(load); + } const GenerationFailure result = load_result ? load_result(load) : ok_result; if (result.code != SD_ERROR_NONE) { failure = result; @@ -730,6 +737,154 @@ static void test_threads() { CHECK(counter(health, "step_downs") >= 1 && health["status"] == "degraded", "the steps down of one request serve the next ones"); } +// The model catalog of the server asks the keeper to replace the model, so that a model picked there is protected +// like the one given on the command line. +static void test_load_unload() { + SDContextParams other = base_params(); + other.model_path = "other.safetensors"; + + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + + bool model_while_creating = true; + env.on_create = [&](const Load&) { model_while_creating = keeper.has_model(); }; + CHECK(keeper.load(other, failure) && keeper.has_model(), "load replaces the model"); + CHECK(env.loads.size() == 2 && env.loads[1].model_path == "other.safetensors" && env.loads[1].level() == Level::MAX, + "with the one that was asked for, at the profile the server was started with"); + CHECK(!model_while_creating, "the old context is freed before the new one is created"); + + Seen seen; + std::string ran_on; + CHECK(run_with( + keeper, env, seen, + [&](const ContextKeeper::ContextView& view) { + ran_on = view.params != nullptr ? view.params->model_path : ""; + return ok_result; + }, + failure), + "a request runs after the change"); + CHECK(ran_on == "other.safetensors", "on the new model"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-cpu", "the ladder of the first model"); + SDContextParams explicit_set = base_params(); + explicit_set.memory_guard = 90; + explicit_set.clip_on_cpu = true; + explicit_set.params_backend = "disk"; + CHECK(keeper.load(explicit_set, failure) && keeper.describe_ladder() == "max > lite > lite-cpu", + "the ladder is built again from the options of the new model"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + keeper.load(other, failure); + Seen seen; + int attempts = 0; + const bool ok = run_with(keeper, env, seen, [&](const ContextKeeper::ContextView&) { return ++attempts == 1 ? oom() : ok_result; }, failure); + CHECK(ok && seen.levels == std::vector({Level::MAX, Level::BALANCED}), + "a request on the new model that runs out of memory steps down like on the first one"); + CHECK(env.loads.size() == 3 && env.loads[2].model_path == "other.safetensors", "and the lighter profile loads the same file"); + CHECK(keeper.health_json()["status"] == "degraded", "the health reports the lighter profile"); + } + { + Env env; + env.load_result = [](const Load& load) { return load.level() < Level::LITE ? oom() : ok_result; }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + CHECK(keeper.health_json()["profile"] == "lite", "the first model needed the lite profile"); + env.load_result = nullptr; + CHECK(keeper.load(other, failure) && env.loads.back().level() == Level::MAX, + "the next model starts again from the profile the server was started with"); + const json health = keeper.health_json(); + CHECK(health["status"] == "ok" && health["profile"] == "max" && health["next_promotion_seconds"].is_null(), + "nothing is left of the step down of the previous model"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen served; + run_with(keeper, env, served, succeed, failure); + + env.load_result = [](const Load& load) { return load.model_path == "broken.safetensors" ? model_file_failure() : ok_result; }; + SDContextParams broken = base_params(); + broken.model_path = "broken.safetensors"; + CHECK(!keeper.load(broken, failure) && failure.code == SD_ERROR_MODEL_FILE, "a model that cannot be loaded is reported with its cause"); + CHECK(!keeper.has_model() && keeper.status_name() == std::string("no_model"), "and no model is left loaded"); + const size_t loads = env.loads.size(); + Seen refused; + CHECK(!run_with(keeper, env, refused, succeed, failure) && failure.code == SD_ERROR_INVALID_ARGUMENT && refused.levels.empty(), + "requests are refused until a model is loaded"); + CHECK(keeper.load(other, failure) && keeper.has_model() && env.loads.size() == loads + 1, "load can be called again after a failure"); + const json health = keeper.health_json(); + CHECK(counter(health, "requests") == 2 && counter(health, "succeeded") == 1 && counter(health, "failed") == 1, + "the counters are kept across the changes of model"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + keeper.unload(); + CHECK(!keeper.has_model() && keeper.status_name() == std::string("no_model") && keeper.health_json()["model_loaded"] == false, + "unload frees the model"); + Seen seen; + CHECK(!run_with(keeper, env, seen, succeed, failure) && failure.code == SD_ERROR_INVALID_ARGUMENT && seen.levels.empty(), + "and requests are refused after it"); + keeper.unload(); + CHECK(!keeper.has_model(), "unloading twice is harmless"); + CHECK(keeper.load(base_params(), failure) && keeper.has_model() && env.loads.size() == 2, "a model can be loaded again"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + + std::atomic done{false}; + std::atomic readings{0}; + std::vector readers; + for (int t = 0; t < 3; t++) { + readers.emplace_back([&] { + while (!done) { + const json health = keeper.health_json(); + (void)health["status"]; + (void)keeper.describe_ladder(); + (void)keeper.can_step_down(); + (void)keeper.status_name(); + (void)keeper.has_model(); + ++readings; + } + }); + } + for (int i = 0; i < 150; i++) { + if (i % 3 == 0) { + keeper.unload(); + } else { + keeper.load(i % 2 == 0 ? other : base_params(), failure); + } + } + done = true; + for (auto& reader : readers) { + reader.join(); + } + CHECK(readings.load() > 0, "the health, the ladder and the status were read while the model changed"); + CHECK(keeper.load(other, failure) && keeper.has_model() && keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-cpu", + "and the keeper still works after 150 changes"); + } +} + static GenerationFailure cancelled_failure() { return failure_of(SD_ERROR_CANCELLED, "the generation was cancelled"); } @@ -1074,6 +1229,7 @@ int main() { test_reporting(); test_backend_choice(); test_threads(); + test_load_unload(); test_cancel(); test_cancel_threads();