From 6a01873d739657af2a08fa5c17a71cbb49183cf5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 11 Oct 2026 10:40:29 +0200 Subject: [PATCH] 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 --- .gitignore | 1 + README.md | 1 + docs/integrazione_progetti.md | 98 +++- docs/performance.md | 17 + examples/common/profile.cpp | 1 + examples/server/CMakeLists.txt | 1 + examples/server/README.md | 18 + examples/server/api.md | 169 ++++++- examples/server/async_jobs.cpp | 138 +++--- examples/server/async_jobs.h | 6 +- examples/server/main.cpp | 70 ++- examples/server/recovery.cpp | 617 +++++++++++++++++++++++++ examples/server/recovery.h | 208 +++++++++ examples/server/routes.h | 1 + examples/server/routes_openai.cpp | 56 ++- examples/server/routes_sdapi.cpp | 43 +- examples/server/routes_sdcpp.cpp | 68 ++- examples/server/runtime.cpp | 16 +- examples/server/runtime.h | 6 +- test/README.md | 1 + test/profile_test.cpp | 6 +- test/server_recovery_test.cpp | 724 ++++++++++++++++++++++++++++++ 22 files changed, 2139 insertions(+), 127 deletions(-) create mode 100644 examples/server/recovery.cpp create mode 100644 examples/server/recovery.h create mode 100644 test/server_recovery_test.cpp diff --git a/.gitignore b/.gitignore index 8c38eeb1..82072512 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ test/* !test/pe_imports_test.cpp !test/file_handle_pool_test.cpp !test/profile_test.cpp +!test/server_recovery_test.cpp !test/fuzz_model_loader.py tests/ .vscode/ diff --git a/README.md b/README.md index 8c1c372c..065fbcb3 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ progetto originale. Modifiche del fork di **Francesco Simeoni** - **Profili di risorse** (`--profile lite|balanced|max|auto`): un'unica opzione imposta guardiano di memoria, encoder di testo su CPU e VAE a tasselli per le macchine piccole; `auto` sceglie in base al modello e alla memoria libera - **Errori leggibili dalle app**: `sd_get_last_error()` distingue memoria esaurita, file del modello e backend; `sd_get_system_memory()` riporta la RAM di sistema - **Server robusto**: parte anche senza modello, autenticazione opzionale (`--api-key`) e allowlist CORS (`--cors-origins`) +- **Server che non cade per la memoria**: una richiesta che esaurisce la RAM/VRAM non ferma `sd-server`; il modello viene ricaricato con un profilo più leggero e la richiesta ripetuta, altrimenti risposta `503` con `Retry-After`; `GET /sdcpp/v1/health` e `/resources` mostrano lo stato (`--disable-degradation` per spegnerlo) - **Pacchetto portabile**: backend ggml come librerie dinamiche caricate a runtime — un solo zip per macchine vecchie e nuove (`scripts/package_portable.sh`); pacchetti con GPU pronti: Windows CUDA 12 (NVIDIA, DLL incluse), Windows/Linux Vulkan, macOS Metal - **Suite di test di sicurezza** in [test/](./test/): file modello ostili, fuzzing, sanitizer diff --git a/docs/integrazione_progetti.md b/docs/integrazione_progetti.md index e1bf0760..e38f607f 100644 --- a/docs/integrazione_progetti.md +++ b/docs/integrazione_progetti.md @@ -28,6 +28,7 @@ controllato: | Profili di risorse | `--profile lite\|balanced\|max\|auto` imposta in un colpo guardiano di memoria, encoder di testo su CPU, VAE a tasselli e CFG non raggruppato; `auto` sceglie dalla dimensione del modello e dalla memoria libera | **disattivo** (come `max`) | | Errori classificati e memoria di sistema | dopo un fallimento `sd_get_last_error()` dà un codice (memoria esaurita, file del modello, backend, ...) e il motivo; `sd_get_system_memory()` riporta RAM totale, disponibile e del processo | sempre disponibile | | Server senza modello | `sd-server` parte anche senza `-m`: device e upscale funzionano, la generazione risponde con un errore chiaro | **attivo** | +| Server che resta in piedi | una richiesta che esaurisce la memoria non ferma `sd-server`: il modello viene ricaricato con un profilo più leggero (`max > balanced > lite > lite-disk > lite-cpu`) e la richiesta ripetuta; se nemmeno il più leggero basta, risposta `503` con `Retry-After`; dopo una pausa il server risale. `GET /sdcpp/v1/health` e `/resources` | **attivo** (`--disable-degradation` lo spegne) | | Autenticazione server | `--api-key` (Bearer o `X-API-Key`) e allowlist CORS `--cors-origins` | **disattivi** | | Pacchetto portabile | backend ggml come librerie dinamiche caricate a runtime: un solo pacchetto, ogni macchina usa ciò che ha | opzionale in build | | Release automatiche | workflow `release-portable.yml`: zip con GPU (Windows CUDA 12 e Vulkan, Linux Vulkan, macOS Metal) a ogni tag `portable-v*` o avvio manuale | su tag | @@ -620,6 +621,41 @@ Il server **parte anche senza modello** (niente loop né uscita silenziosa): scrive in console il percorso del modello e il motivo del fallimento (exit code 1). +Il server **non cade quando la memoria finisce**: + +- una richiesta che esaurisce la memoria (o fa fallire un device) libera il + modello, lo ricarica con il profilo più leggero successivo + (`max > balanced > lite > lite-disk > lite-cpu`; i passi che darebbero la + stessa configurazione vengono saltati) e ripete **la stessa richiesta**. Da + `lite` in poi il VAE decodifica a tasselli qualunque cosa chieda la richiesta. + Con `--eager-load` il passo `lite-disk` non rilegge tutti i pesi all'avvio; +- se nemmeno il profilo più leggero basta, la risposta è `503` con + l'intestazione `Retry-After` e un corpo + `{"error": "...", "code": "out_of_memory", "retry_after_seconds": 30}`; il + server resta attivo e serve le richieste più piccole. Nei job asincroni lo + stesso `code` compare in `error.code`. Una richiesta non valida è `400` + (`invalid_argument`); un file del modello illeggibile o un device guasto sono + `500` (`model_file`, `backend`); +- dopo `--degradation-cooldown` secondi (predefinito 300) il server risale di un + profilo, all'inizio della richiesta successiva, che paga il ricaricamento del + modello; una risalita che non funziona viene annullata e l'attesa raddoppia + (fino a un'ora). `--degradation-cooldown 0` lo lascia sul profilo leggero fino + al riavvio; `--disable-degradation` spegne tutto e la richiesta fallisce subito; +- se il modello non si riesce a ricaricare, le richieste ricevono `503` + (`unavailable`) e il server riprova a partire dalla richiesta successiva, non + più spesso di ogni 15 secondi; +- se il modello non ci sta nemmeno all'avvio, il server parte con il primo + profilo che lo carica (il log dice quale). Se non riesce ad aprire la porta, o + a creare i thread del server HTTP, esce con codice 1 e un messaggio + invece di terminare in silenzio; +- `GET /sdcpp/v1/health` riporta stato (`ok`, `degraded`, `recovering`, + `unavailable`, `no_model`), profilo in uso, contatori (richieste, discese, + risalite, ricaricamenti), ultimo errore e coda dei job, e risponde subito + anche durante una generazione; `GET /sdcpp/v1/resources` riporta RAM del + sistema e memoria dei device. Entrambi richiedono la chiave API se impostata. + +Dettagli e formato delle risposte: [examples/server/api.md](../examples/server/api.md). + ## 4. Retrocompatibilità e risorse La compatibilità va considerata su più livelli: sistema operativo, architettura @@ -997,7 +1033,65 @@ sincronizzazioni future. libera). Le soglie di `auto` non sono ancora state tarate su un modello reale né su una GPU. +17. **Server che non cade per la memoria** — `examples/server/recovery.{h,cpp}`: + `ContextKeeper` possiede il contesto del server (prima era una variabile di + `main`) e tutte le generazioni dei tre gruppi di endpoint passano da + `ContextKeeper::run()`. Su `out_of_memory` o `backend` (codici di + `sd_get_last_error()`) libera il modello, lo ricarica con il profilo più + leggero successivo e ripete la stessa richiesta (da `lite` in poi forza il + VAE a tasselli); un guasto di device salta direttamente a `lite-cpu`. Il + livello di partenza è quello di `--profile`. Risalita di un passo dopo + `--degradation-cooldown` (300 s; 0 = mai) con prova: se il profilo più + pesante fallisce al primo uso, si torna indietro e l'attesa raddoppia (tetto + un'ora). Ricarica con attesa minima di 15 s se il modello non si riesce a + caricare. Risposte: `503` con `Retry-After` per memoria o contesto non + disponibile, `400` per richieste non valide, `500` per il resto, con corpo + `{"error", "code", "retry_after_seconds"}`; i job asincroni riportano lo + stesso `code` in `error.code`; `429` con `Retry-After`; `std::bad_alloc` nei + gestori diventa `503`. Nuovi endpoint `GET /sdcpp/v1/health` (stato, + profilo, contatori, ultimo errore, coda; non aspetta mai il blocco della + generazione) e `GET /sdcpp/v1/resources`. Opzioni `--disable-degradation` e + `--degradation-cooldown`. `main.cpp`: se il server HTTP non riesce a creare i + suoi thread (memoria al limite) o la porta non è libera, esce con codice 1 e + un messaggio; prima il primo caso terminava con `std::terminate` e il secondo + usciva con codice 0. Con `--eager-load` il profilo `lite-disk` non legge più + tutti i pesi all'avvio (altrimenti non risparmiava nulla). + Test: `test/server_recovery_test.cpp` (114 controlli con libreria e orologio + simulati, anche da più thread) con 9 mutazioni del codice, tutte rilevate. + Prove dal vivo con il modello sintetico da 2,1 GB (CPU, `ulimit -v` con + `MALLOC_ARENA_MAX=1` per un limite riproducibile): con 2400 MiB e + un'immagine 384×384 `max`, `balanced` e `lite` falliscono per memoria e + `lite-disk` riesce (200, la richiesta successiva non ricarica), con 2600 MiB + `max` basta, sotto 2200 MiB la risposta è `503` con `Retry-After` e il + server resta attivo; risalita dopo il tempo di attesa, risalita fallita con + attesa raddoppiata, `--disable-degradation` (503 subito), `error.code` dei + job, chiave API sui nuovi endpoint, avvio con `--eager-load` a 2100 MiB sul + profilo `lite-disk`, `health` sempre sotto 12 ms durante una generazione + (347 chiamate), 9 richieste parallele di tipo diverso (OpenAI, sdapi, + sdcpp) tutte servite con contatori coerenti, anche con 2400 MiB: una + richiesta 384×384 ha portato il server fino a `lite-disk` (3 discese, 3 + ricaricamenti) e le altre sono state servite sul profilo raggiunto. + Sanitizer: il test del custode passa anche con AddressSanitizer, + UBSan e ThreadSanitizer; server e motore compilati per intero con + ASan/UBSan, con allocazioni che falliscono oltre una soglia, hanno + percorso tutta la scala dei profili fino al `503`, gli scenari CPU con RAM + occupata (guardia, pesi su disco, segmenti, auto-fit) sono terminati senza + segnalazioni e sei errori di lettura iniettati sul file del modello sono + stati assorbiti dalla riapertura con la stessa immagine; server con chiave + API, senza modello, con modello mancante e con richieste parallele senza + errori di memoria. UBSan ha segnalato tre punti preesistenti: un campo + `resolved_hires_upscaler` non inizializzato (corretto in un commit a + parte), e due scorrimenti a sinistra di valori negativi in + `base64_encode` e nello scrittore JPEG di stb (codice di upstream, + innocui nella pratica, lasciati invariati). Non provato: Windows, GPU, + modelli reali. Un errore che + termina il processo dentro il driver (per esempio CUDA) non si può intercettare + da qui. Ogni risalita costa un ricaricamento del modello: con modelli grandi + conviene un `--profile` più leggero fisso, oppure `--degradation-cooldown 0`. + Passaggi previsti e non ancora svolti: collaudo del workflow di release sui -runner GitHub, generazione con un modello reale (inclusa la memory guard sotto -pressione vera), test su CUDA/Vulkan, e il livello di astrazione +runner GitHub, generazione con un modello reale (inclusa la memory guard e la +discesa di profilo del server sotto pressione vera), test su CUDA/Vulkan e su +Windows (il ramo Windows della memoria di sistema è stato solo controllato nella +sintassi), taratura delle soglie di `--profile auto`, e il livello di astrazione `ImageRuntime` nell'applicazione ospite (fuori da questo repository). diff --git a/docs/performance.md b/docs/performance.md index 40edbc24..fab11e56 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -237,6 +237,23 @@ The estimate comes from the file sizes (it does not read the models) and does no account for `--type` conversions at load time. When the sizes or the memory are unknown, `auto` leaves the defaults alone. The thresholds are heuristics. +### Two more levels for the server + +`sd-server` can go beyond `lite` on its own. When a request runs out of memory, it +loads the model again with the next lighter profile and runs the request again: + +| Level | What it sets | +|---|---| +| `lite-disk` | `--params-backend disk` (weights are streamed from the file instead of kept in memory); `--eager-load` is switched off | +| `lite-cpu` | everything on the CPU (`--backend cpu`); only when the machine has another device | + +These two are not values of `--profile`. The server climbs back one level at a time +after `--degradation-cooldown` seconds; every climb loads the model once, which takes +long on a large model. If that cost is not worth it, start the server on the lighter +profile with `--profile lite` and `--degradation-cooldown 0`, or use +`--disable-degradation` to get the error at once. See [Failures and +recovery](../examples/server/api.md#failures-and-recovery). + ## Use quantization to reduce memory usage. [quantization](./quantization_and_gguf.md) diff --git a/examples/common/profile.cpp b/examples/common/profile.cpp index 9acfb649..fe85be1d 100644 --- a/examples/common/profile.cpp +++ b/examples/common/profile.cpp @@ -169,6 +169,7 @@ namespace sd_profile { if (level >= Level::LITE_DISK && free_to_set("--params-backend")) { ctx.params_backend = "disk"; ctx.offload_params_to_cpu = false; + ctx.eager_load = false; } if (level >= Level::LITE_CPU && free_to_set("--backend")) { ctx.backend = "cpu"; diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt index 615249f9..ae0600c9 100644 --- a/examples/server/CMakeLists.txt +++ b/examples/server/CMakeLists.txt @@ -69,6 +69,7 @@ add_executable(${TARGET} ../common/profile.cpp main.cpp runtime.cpp + recovery.cpp async_jobs.cpp routes_index.cpp routes_openai.cpp diff --git a/examples/server/README.md b/examples/server/README.md index c59fc8ae..cc84cdfe 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -33,6 +33,24 @@ If you want to use a different host or port, pass: --listen-ip --listen-port ``` +# When the memory runs short + +A request that makes the machine run out of memory does not stop the server. It frees the model, loads it again +with a lighter configuration (profiles `max > balanced > lite > lite-disk > lite-cpu`, see `--profile`) and runs the +same request again; from `lite` on, the VAE is decoded in tiles. The request is then served normally. When even the +lightest profile does not fit, the request is answered with `503` and a `Retry-After` header, and the server stays up. +After a quiet period the server climbs back one profile at a time. + +* `--degradation-cooldown ` sets how long the server waits before climbing back (default `300`; `0` = stay + on the lighter profile until the next restart) +* `--disable-degradation` turns this off: a request that runs out of memory is answered with the error at once +* `GET /sdcpp/v1/health` tells which profile is in use, how many times the server had to step down and the last + error; `GET /sdcpp/v1/resources` reports the free memory of the machine and of each device + +If the model does not fit at startup, the server starts on the first profile that loads it (the log says which). When +the model cannot be loaded at all, or the address cannot be used, `sd-server` exits with a non-zero code and says why. +See [Failures and recovery](api.md#failures-and-recovery) for the answers a client gets. + # Frontend ## Build with Frontend diff --git a/examples/server/api.md b/examples/server/api.md index cff4e845..6a5fa3bd 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -53,12 +53,77 @@ Native async API for `stable-diffusion.cpp`. Current endpoints include: - `GET /sdcpp/v1/capabilities` +- `GET /sdcpp/v1/health` +- `GET /sdcpp/v1/resources` - `POST /sdcpp/v1/img_gen` - `GET /sdcpp/v1/jobs/{id}` - `POST /sdcpp/v1/jobs/{id}/cancel` - `POST /sdcpp/v1/vid_gen` - `POST /sdcpp/v1/upscale` +## Failures and recovery + +A generation that cannot be served is answered the same way by all three API families +(for `sdcpp API` jobs, the same `code` is reported in the `error` of the failed job). + +| Status | `code` | Meaning | +| --- | --- | --- | +| `503 Service Unavailable` | `out_of_memory` | The machine ran out of memory, even after the server tried the lighter configurations described below. Retry later, or send a smaller request. | +| `503 Service Unavailable` | `unavailable` | The server has no usable model at this moment, for example because loading it again after a failure did not succeed yet. `cause` holds the reason. | +| `503 Service Unavailable` | `busy` | The model was in use. | +| `400 Bad Request` | `invalid_argument` | The request cannot be generated as it is (for example a size the model cannot handle). Retrying it unchanged will not help. | +| `500 Internal Server Error` | `model_file`, `backend`, `generation_failed` | A model file could not be read, a compute device failed, or the generation failed without a more specific reason. | + +The body is a JSON object, and a `503` also carries a `Retry-After` header: + +```json +{ + "error": "unet compute buffer allocation failed (out of memory)", + "code": "out_of_memory", + "retry_after_seconds": 30 +} +``` + +| Field | Type | Notes | +| --- | --- | --- | +| `error` | `string` | Human-readable reason | +| `code` | `string` | One of the codes above | +| `cause` | `string` | Only with `unavailable`: the code of the failure that left the server without a model | +| `retry_after_seconds` | `integer` | Only with `503`: how long to wait before trying again; mirrors the `Retry-After` header | + +Other `4xx` answers (`400` for a malformed request, `429` when the job queue is full, `401` for a missing API key, ...) +keep their meaning. A `429` carries `Retry-After: 10`. + +### Stepping down + +A request that fails because the machine ran out of memory (or because a compute device failed) does not end the +server and is not simply refused. The server frees the model, loads it again with the next lighter profile of the +ladder `max > balanced > lite > lite-disk > lite-cpu`, and runs the same request again: + +| Profile | What changes | +| --- | --- | +| `balanced` | `--memory-guard 90` | +| `lite` | memory guard 85, text encoder on the CPU, VAE decoded in tiles, no batched CFG | +| `lite-disk` | weights are streamed from disk (`--params-backend disk`) instead of being kept in memory; `--eager-load` is switched off | +| `lite-cpu` | everything is computed on the CPU (only when the machine has another device) | + +Steps that would load the same configuration as the previous one are skipped, so the ladder is shorter when +the server was started with some of these options already. The profile the server was started with +(`--profile`, default `max`) is the top of the ladder. From `lite` on, the VAE is decoded in tiles whatever the +request asked. A device failure goes straight to the last profile of the ladder, `lite-cpu`. + +A request served after a step-down is a normal `200`. When even the lightest profile does not fit, the request +fails with the `503` above, and the server stays up, on the lightest profile that could load the model. + +After `--degradation-cooldown` seconds (default `300`) the server climbs back one profile, at the beginning of the next +request, which pays for loading the model again. A climb that does not work is undone and the wait doubles (up to an +hour); a climb that works resets it. With `--degradation-cooldown 0` the server stays where it stepped down, +and with `--disable-degradation` it never steps down: such a request is answered with the error at once. +`GET /sdcpp/v1/health` reports the profile in use. + +If the model cannot be loaded again after a failure, requests are answered with `503` / `unavailable` and +the server tries again from the next request on, no more often than every 15 seconds. + ## `sd_cpp_extra_args` `sd_cpp_extra_args` is an extension mechanism for the compatibility APIs. @@ -649,6 +714,99 @@ Fields returned in `features_by_mode.vid_gen`: - `cancel_generating` - `preview` +#### `GET /sdcpp/v1/health` + +Reports whether the server can generate and how it is coping with the memory of the machine. It never waits for a +generation in progress, so it answers quickly even while the server is busy. It needs the API key when one is set. + +Example response: + +```json +{ + "status": "degraded", + "model_loaded": true, + "profile": "lite", + "base_profile": "max", + "degradation": true, + "busy": false, + "counters": { + "requests": 12, + "succeeded": 11, + "failed": 1, + "recovered": 2, + "step_downs": 3, + "promotions": 1, + "failed_promotions": 0, + "rebuilds": 4 + }, + "last_error": { + "code": "out_of_memory", + "message": "unet compute buffer allocation failed (out of memory)", + "at": 1775401204 + }, + "next_promotion_seconds": 214, + "uptime_seconds": 3601, + "version": "stable-diffusion.cpp ...", + "queue": { + "pending": 0, + "waiting": 0, + "max": 64 + } +} +``` + +| Field | Type | Notes | +| --- | --- | --- | +| `status` | `string` | `ok`, `degraded` (running on a lighter profile than the one it was started with), `recovering` (the model is being loaded), `unavailable` (no usable model at the moment), or `no_model` (started without a model) | +| `model_loaded` | `boolean` | | +| `profile` | `string \| null` | Profile in use: `max`, `balanced`, `lite`, `lite-disk` or `lite-cpu`; `null` without a model | +| `base_profile` | `string` | Profile the server was started with | +| `degradation` | `boolean` | `false` with `--disable-degradation` | +| `busy` | `boolean` | A generation is running | +| `counters` | `object` | Since the start. `requests`, `succeeded`, `failed`; `recovered` is the number of requests served after a step-down; `step_downs`, `promotions`, `failed_promotions` and `rebuilds` (times the model was loaded again) | +| `last_error` | `object \| null` | Last failure the server saw (`code`, `message`, `at` as a Unix time). Invalid requests are not recorded | +| `next_promotion_seconds` | `integer \| null` | Seconds until the next attempt to climb back; `null` when the server is on its base profile or does not climb | +| `uptime_seconds` | `integer` | | +| `version` | `string` | | +| `queue` | `object` | Jobs of the async API: `pending` (queued or generating), `waiting` (queued) and `max` (limit before `429`) | + +Typical status codes: + +- `200 OK` +- `503 Service Unavailable` only when `status` is `unavailable`; the body is the same + +#### `GET /sdcpp/v1/resources` + +Reports the memory the server can see right now, for clients that want to size a request before sending it. +It needs the API key when one is set. + +Example response: + +```json +{ + "system_memory": { + "total_bytes": 17179869184, + "available_bytes": 9126805504, + "process_bytes": 3221225472 + }, + "devices": [ + { + "name": "CUDA0", + "description": "NVIDIA GeForce RTX ...", + "type": "gpu", + "free_memory_bytes": 3758096384, + "total_memory_bytes": 6442450944 + } + ] +} +``` + +| Field | Type | Notes | +| --- | --- | --- | +| `system_memory` | `object \| null` | RAM of the machine (`total_bytes`, `available_bytes`) and the memory used by the server process (`process_bytes`); `null` where the platform does not report it | +| `devices` | `array` | The compute devices, as listed by `--list-devices` | +| `devices[].type` | `string` | `cpu`, `gpu`, `igpu`, `accel` or `unknown` | + #### `POST /sdcpp/v1/img_gen` Submits an async image generation job. @@ -725,6 +883,7 @@ Typical status codes: - `200 OK` - `400 Bad Request` (invalid request, unsupported output format, unreadable image, incompatible upscaler, or output dimensions exceeding the limit) - `500 Internal Server Error` +- `503 Service Unavailable` when the machine runs out of memory (see [Failures and recovery](#failures-and-recovery)) Notes: @@ -1028,6 +1187,10 @@ Example failed job: } ``` +`error.code` is `generation_failed` when the cause is not known, or one of `out_of_memory`, `model_file`, +`backend`, `invalid_argument`, `busy` or `unavailable` (see [Failures and recovery](#failures-and-recovery)). +A job that failed for lack of memory has already been tried on every lighter profile the server could use. + ### Cancelled Result Example cancelled job: @@ -1055,7 +1218,7 @@ Example cancelled job: - `202 Accepted` when the job is created - `400 Bad Request` for an empty body, unsupported model mode, invalid JSON, or invalid generation parameters -- `429 Too Many Requests` when the job queue is full +- `429 Too Many Requests` when the job queue is full (with `Retry-After: 10`) - `500 Internal Server Error` for unexpected server exceptions during submission ### `vid_gen` @@ -1441,6 +1604,8 @@ Example failed job: } ``` +`error.code` takes the same values as for `img_gen` jobs. + ### Cancelled Result Example cancelled job: @@ -1468,5 +1633,5 @@ Example cancelled job: - `202 Accepted` when the job is created - `400 Bad Request` for an empty body, unsupported model mode, invalid JSON, invalid generation parameters, or an unsupported output format -- `429 Too Many Requests` when the job queue is full +- `429 Too Many Requests` when the job queue is full (with `Retry-After: 10`) - `500 Internal Server Error` for unexpected server exceptions during submission diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index 88408088..9bab28ee 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -225,31 +225,45 @@ json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJo 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& output_images, - std::string& error_message) { - sd_img_gen_params_t params = job.img_gen.to_sd_img_gen_params_t(); + GenerationFailure& failure) { + const sd_img_gen_params_t params = job.img_gen.to_sd_img_gen_params_t(); SDImageVec results; - - { - std::lock_guard lock(*runtime.sd_ctx_mutex); - set_preview_callback(job); - sd_image_t* raw_results = nullptr; - int num_results = 0; - if (!generate_image(runtime.sd_ctx, ¶ms, &raw_results, &num_results)) { - raw_results = nullptr; - num_results = 0; - } - clear_preview_callback(); - results.adopt(raw_results, num_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) { - error_message = "generate_image returned no results"; - return false; + return fail_with(failure, "generate_image returned no results"); } EncodedImageFormat encoded_format = EncodedImageFormat::PNG; @@ -285,8 +299,7 @@ bool execute_img_gen_job(ServerRuntime& runtime, } if (output_images.empty()) { - error_message = "generate_image returned empty encoded outputs"; - return false; + return fail_with(failure, "generate_image returned empty encoded outputs"); } return true; @@ -298,32 +311,46 @@ bool execute_vid_gen_job(ServerRuntime& runtime, std::string& output_media_mime_type, int& output_frame_count, int& output_fps, - std::string& error_message) { - 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) - : ""; + 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; - { - std::lock_guard lock(*runtime.sd_ctx_mutex); - set_preview_callback(job); - sd_image_t* raw_results = nullptr; - if (!generate_video(runtime.sd_ctx, ¶ms, &raw_results, &num_results, &generated_audio, &output_fps)) { - raw_results = nullptr; - } - clear_preview_callback(); - results.adopt(raw_results, num_results); + 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); - error_message = "generate_video returned no results"; - return false; + return fail_with(failure, "generate_video returned no results"); } std::vector video_bytes = create_video_from_sd_images_to_vector(job.vid_gen.output_format, @@ -335,8 +362,7 @@ bool execute_vid_gen_job(ServerRuntime& runtime, str_params); free_sd_audio(generated_audio); if (video_bytes.empty()) { - error_message = "failed to encode generated video container"; - return false; + return fail_with(failure, "failed to encode generated video container"); } output_media_b64 = base64_encode(video_bytes); @@ -381,21 +407,31 @@ void async_job_worker(ServerRuntime& runtime) { std::string output_media_mime_type; int output_frame_count = 0; int output_fps = 0; - std::string error_message; + GenerationFailure failure; bool ok = false; - if (job->kind == AsyncJobKind::ImgGen) { - ok = execute_img_gen_job(runtime, *job, output_images, error_message); - } 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, - error_message); - } else { - error_message = "unsupported job kind"; + 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"); } { @@ -417,8 +453,8 @@ void async_job_worker(ServerRuntime& runtime) { job->error_message.clear(); } else { job->status = AsyncJobStatus::Failed; - job->error_code = "generation_failed"; - job->error_message = error_message.empty() ? "unknown generation error" : error_message; + 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(); diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h index 2fe79bb2..a50eb372 100644 --- a/examples/server/async_jobs.h +++ b/examples/server/async_jobs.h @@ -9,7 +9,7 @@ #include #include - +#include "recovery.h" #include "runtime.h" enum class AsyncJobKind { @@ -72,12 +72,12 @@ json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJo bool execute_img_gen_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::vector& output_images, - std::string& error_message); + GenerationFailure& failure); 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, - std::string& error_message); + GenerationFailure& failure); void async_job_worker(ServerRuntime& runtime); diff --git a/examples/server/main.cpp b/examples/server/main.cpp index d7ed6262..9938cae0 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -11,6 +11,7 @@ #include "common/common.h" #include "common/profile.h" #include "common/resource_owners.hpp" +#include "recovery.h" #include "routes.h" #include "runtime.h" @@ -29,11 +30,11 @@ static void print_usage(const char* argv0, const std::vector& option options_list[2].print(); } -static void parse_args(int argc, - const char** argv, - SDSvrParams& svr_params, - SDContextParams& ctx_params, - SDGenerationParams& default_gen_params) { +static sd_profile::Level parse_args(int argc, + const char** argv, + SDSvrParams& svr_params, + SDContextParams& ctx_params, + SDGenerationParams& default_gen_params) { std::vector options_vec = { svr_params.get_options(), ctx_params.get_options(), @@ -64,6 +65,7 @@ static void parse_args(int argc, if (random_seed_requested) { default_gen_params.seed = -1; } + return profile_level; } void sd_log_cb(enum sd_log_level_t level, const char* log, void* data) { @@ -124,7 +126,7 @@ int main(int argc, const char** argv) { SDGenerationParams default_gen_params; sd_set_log_callback(sd_log_cb, (void*)&svr_params); - parse_args(argc, argv, svr_params, ctx_params, default_gen_params); + const sd_profile::Level profile_level = parse_args(argc, argv, svr_params, ctx_params, default_gen_params); LOG_VERBOSE("version: %s", version_string().c_str()); LOG_VERBOSE("%s", sd_get_system_info()); @@ -132,32 +134,44 @@ int main(int argc, const char** argv) { LOG_VERBOSE("%s", ctx_params.to_string().c_str()); LOG_VERBOSE("%s", default_gen_params.to_string().c_str()); - sd_ctx_params_t sd_ctx_params = ctx_params.to_sd_ctx_params_t(false); - const bool model_requested = !ctx_params.model_path.empty() || !ctx_params.diffusion_model_path.empty(); - SDCtxPtr sd_ctx(model_requested ? new_sd_ctx(&sd_ctx_params) : nullptr); + const bool model_requested = !ctx_params.model_path.empty() || !ctx_params.diffusion_model_path.empty(); - if (model_requested && sd_ctx == nullptr) { - LOG_ERROR("the model could not be loaded: '%s'; check the model file and the logs above, then restart the server", - !ctx_params.model_path.empty() ? ctx_params.model_path.c_str() - : ctx_params.diffusion_model_path.c_str()); - return 1; - } - if (!model_requested) { + ContextKeeper::Settings keeper_settings; + keeper_settings.degradation = !svr_params.disable_degradation; + keeper_settings.cooldown_seconds = svr_params.degradation_cooldown; + ContextKeeper keeper(ctx_params, profile_level, keeper_settings); + + if (model_requested) { + GenerationFailure failure; + if (!keeper.start(failure)) { + LOG_ERROR("the model could not be loaded: '%s' (%s: %s); check the model file and the logs above, then restart the server", + !ctx_params.model_path.empty() ? ctx_params.model_path.c_str() + : ctx_params.diffusion_model_path.c_str(), + sd_error_code_name(failure.code), + failure.message.c_str()); + return 1; + } + if (svr_params.disable_degradation) { + LOG_INFO("a request that runs out of memory is answered with an error (--disable-degradation)"); + } else if (!keeper.can_step_down()) { + LOG_INFO("a request that runs out of memory is answered with an error: no profile is lighter than %s", + keeper.describe_ladder().c_str()); + } else { + LOG_INFO("a request that runs out of memory makes the server step down: %s", keeper.describe_ladder().c_str()); + } + } else { LOG_WARN("starting without a model: device and upscale endpoints work, " "generation endpoints will report that no model is loaded " "(restart with -m/--diffusion-model to enable generation)"); } - std::mutex sd_ctx_mutex; - std::vector lora_cache; std::mutex lora_mutex; std::vector upscaler_cache; std::mutex upscaler_mutex; AsyncJobManager async_job_manager; ServerRuntime runtime = { - sd_ctx.get(), - &sd_ctx_mutex, + &keeper, &svr_params, &ctx_params, &default_gen_params, @@ -208,7 +222,19 @@ int main(int argc, const char** argv) { register_sdcpp_api_endpoints(svr, runtime); LOG_INFO("listening on: http://%s:%d\n", svr_params.listen_ip.c_str(), svr_params.listen_port); - svr.listen(svr_params.listen_ip, svr_params.listen_port); + int exit_code = 0; + try { + if (!svr.listen(svr_params.listen_ip, svr_params.listen_port)) { + LOG_ERROR("the server could not listen on %s:%d; check that the port is free and the address is valid", + svr_params.listen_ip.c_str(), + svr_params.listen_port); + exit_code = 1; + } + } catch (const std::exception& error) { + // The worker threads of the HTTP server could not be created, typically for lack of memory. + LOG_ERROR("the HTTP server could not run: %s", error.what()); + exit_code = 1; + } { std::lock_guard lock(async_job_manager.mutex); @@ -216,5 +242,5 @@ int main(int argc, const char** argv) { } async_job_manager.cv.notify_all(); async_worker.join(); - return 0; + return exit_code; } diff --git a/examples/server/recovery.cpp b/examples/server/recovery.cpp new file mode 100644 index 00000000..7c319dd5 --- /dev/null +++ b/examples/server/recovery.cpp @@ -0,0 +1,617 @@ +#include "recovery.h" + +#include +#include +#include +#include +#include +#include + +#include "httplib.h" + +#include "common/log.h" + +namespace { + + constexpr int kMaxCooldownSeconds = 3600; + constexpr int kRestoreBackoffSeconds = 15; + constexpr int kOutOfMemoryRetryAfterSeconds = 30; + + int64_t unix_now() { + return static_cast(std::time(nullptr)); + } + + // The fields a profile changes, so that two levels that would load the same configuration compare equal. + std::string describe(const SDContextParams& params) { + std::string text = std::to_string(params.memory_guard) + '|' + params.backend + '|' + params.params_backend + '|'; + for (bool flag : {params.clip_on_cpu, params.vae_on_cpu, params.control_net_cpu, params.offload_params_to_cpu, params.batched_cfg, params.eager_load}) { + text += flag ? '1' : '0'; + } + return text; + } + + bool has_accelerator() { + const size_t count = sd_get_device_count(); + for (size_t i = 0; i < count; ++i) { + sd_device_info_t info; + if (sd_get_device_info(i, &info) && info.type != SD_DEVICE_TYPE_CPU) { + return true; + } + } + return false; + } + + GenerationFailure capture_failure() { + GenerationFailure failure; + char message[1024]; + message[0] = '\0'; + failure.code = sd_get_last_error(message, sizeof(message)); + failure.message = message; + if (failure.code == SD_ERROR_NONE) { + failure.code = SD_ERROR_UNKNOWN; + } + if (failure.message.empty()) { + failure.message = "the generation failed without a reported reason"; + } + if (failure.code == SD_ERROR_OUT_OF_MEMORY) { + failure.retry_after_seconds = kOutOfMemoryRetryAfterSeconds; + } + return failure; + } + +} // namespace + +bool failure_is_recoverable(sd_error_code_t code) { + return code == SD_ERROR_OUT_OF_MEMORY || code == SD_ERROR_BACKEND; +} + +const char* failure_code_name(const GenerationFailure& failure) { + if (failure.unavailable) { + return "unavailable"; + } + switch (failure.code) { + case SD_ERROR_NONE: + case SD_ERROR_UNKNOWN: + return "generation_failed"; + default: + return sd_error_code_name(failure.code); + } +} + +int failure_http_status(const GenerationFailure& failure) { + if (failure.unavailable) { + return 503; + } + switch (failure.code) { + case SD_ERROR_OUT_OF_MEMORY: + case SD_ERROR_BUSY: + return 503; + case SD_ERROR_INVALID_ARGUMENT: + return 400; + default: + return 500; + } +} + +GenerationFailure out_of_memory_failure() { + GenerationFailure failure; + failure.code = SD_ERROR_OUT_OF_MEMORY; + failure.message = "the server ran out of memory while handling the request"; + failure.retry_after_seconds = kOutOfMemoryRetryAfterSeconds; + return failure; +} + +GenerationFailure failure_from_exception(const std::exception& error) { + if (dynamic_cast(&error) != nullptr) { + return out_of_memory_failure(); + } + GenerationFailure failure; + failure.code = SD_ERROR_UNKNOWN; + failure.message = error.what(); + return failure; +} + +std::string safe_json_dump(const nlohmann::json& value) { + return value.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); +} + +void send_generation_failure(httplib::Response& res, const GenerationFailure& failure) { + res.status = failure_http_status(failure); + + nlohmann::json body; + body["error"] = failure.message.empty() ? std::string("the generation failed") : failure.message; + body["code"] = failure_code_name(failure); + if (failure.unavailable) { + body["cause"] = sd_error_code_name(failure.code); + } + if (res.status == 503) { + const int wait = std::max(1, failure.retry_after_seconds > 0 ? failure.retry_after_seconds : kOutOfMemoryRetryAfterSeconds); + body["retry_after_seconds"] = wait; + res.set_header("Retry-After", std::to_string(wait)); + } + res.set_content(safe_json_dump(body), "application/json"); +} + +static ContextKeeper::Hooks with_defaults(ContextKeeper::Hooks hooks) { + if (!hooks.create_context) { + hooks.create_context = [](const sd_ctx_params_t& params, GenerationFailure& failure) { + SDCtxPtr ctx(new_sd_ctx(¶ms)); + if (ctx == nullptr) { + failure = capture_failure(); + } + return ctx; + }; + } + if (!hooks.read_failure) { + hooks.read_failure = capture_failure; + } + if (!hooks.has_accelerator) { + hooks.has_accelerator = has_accelerator; + } + if (!hooks.now) { + hooks.now = [] { return ContextKeeper::Clock::now(); }; + } + return hooks; +} + +ContextKeeper::ContextKeeper(const SDContextParams& base_params, + sd_profile::Level base_level, + const Settings& settings, + const Hooks& hooks) + : settings_(settings), + hooks_(with_defaults(hooks)), + base_params_(base_params), + base_level_(base_level), + cooldown_seconds_(std::max(settings.cooldown_seconds, 0)), + started_at_(hooks_.now()) { + backend_choice_.backend = base_params.backend; + backend_choice_.params_backend = base_params.params_backend; + backend_choice_.diffusion_conv_direct = base_params.diffusion_conv_direct; + backend_choice_.n_threads = base_params.n_threads; + build_ladder(); +} + +std::string ContextKeeper::describe_ladder() const { + std::string text; + for (sd_profile::Level level : ladder_) { + text += text.empty() ? "" : " > "; + text += sd_profile::level_name(level); + } + return text; +} + +std::unique_ptr ContextKeeper::params_for(sd_profile::Level level) const { + auto params = std::make_unique(base_params_); + if (level > base_level_) { + SDGenerationParams unused; + sd_profile::apply(level, *params, unused, /*respect_explicit=*/false); + } + return params; +} + +bool ContextKeeper::force_tiling_at(sd_profile::Level level) const { + return level > base_level_ && level >= sd_profile::Level::LITE; +} + +std::string ContextKeeper::fingerprint(sd_profile::Level level) const { + return describe(*params_for(level)) + (force_tiling_at(level) ? "|tiled" : ""); +} + +void ContextKeeper::build_ladder() { + ladder_.push_back(base_level_); + std::string previous = fingerprint(base_level_); + const bool accelerator = hooks_.has_accelerator(); + sd_profile::Level level = base_level_; + while (level != sd_profile::Level::LITE_CPU) { + level = sd_profile::lighter(level); + if (level == sd_profile::Level::LITE_CPU && !accelerator) { + break; + } + const std::string current = fingerprint(level); + if (current == previous) { + continue; + } + ladder_.push_back(level); + previous = current; + } +} + +bool ContextKeeper::start(GenerationFailure& failure) { + std::lock_guard lock(mutex_); + failure = GenerationFailure(); + if (!build_from(0, failure)) { + return false; + } + { + std::lock_guard state(state_mutex_); + if (index_ > 0) { + next_promotion_ = hooks_.now() + std::chrono::seconds(cooldown_seconds_); + } + } + model_loaded_ = true; + return true; +} + +void ContextKeeper::release_context() { + ctx_.reset(); + ctx_params_.reset(); + std::lock_guard state(state_mutex_); + has_ctx_ = false; +} + +void ContextKeeper::record_error(const GenerationFailure& failure) { + if (failure.code == SD_ERROR_NONE || failure.code == SD_ERROR_INVALID_ARGUMENT || failure.code == SD_ERROR_CANCELLED) { + return; + } + std::lock_guard state(state_mutex_); + last_error_.code = failure_code_name(failure); + last_error_.message = failure.message; + last_error_.at = unix_now(); +} + +void ContextKeeper::note_build_failure(const GenerationFailure& failure) { + std::lock_guard state(state_mutex_); + restore_not_before_ = hooks_.now() + std::chrono::seconds(kRestoreBackoffSeconds); + restore_failure_ = failure; +} + +bool ContextKeeper::try_build(size_t index, GenerationFailure& failure) { + const sd_profile::Level level = ladder_[index]; + std::unique_ptr params = params_for(level); + // The context may keep pointing into these strings, so they stay where they are for as long as it lives. + sd_ctx_params_t raw = params->to_sd_ctx_params_t(false); + + LOG_INFO("loading the model with profile %s", sd_profile::level_name(level)); + SDCtxPtr ctx = hooks_.create_context(raw, failure); + if (ctx == nullptr) { + if (failure.code == SD_ERROR_NONE) { + failure.code = SD_ERROR_UNKNOWN; + failure.message = "the model could not be loaded"; + } + record_error(failure); + LOG_WARN("the model could not be loaded with profile %s: %s: %s", + sd_profile::level_name(level), + sd_error_code_name(failure.code), + failure.message.c_str()); + return false; + } + + const bool image = sd_ctx_supports_image_generation(ctx.get()); + const bool video = sd_ctx_supports_video_generation(ctx.get()); + ctx_ = std::move(ctx); + ctx_params_ = std::move(params); + { + std::lock_guard state(state_mutex_); + index_ = index; + has_ctx_ = true; + if (model_loaded_) { + ++counters_.rebuilds; + } + backend_choice_.backend = ctx_params_->backend; + backend_choice_.params_backend = ctx_params_->params_backend; + backend_choice_.diffusion_conv_direct = ctx_params_->diffusion_conv_direct; + backend_choice_.n_threads = ctx_params_->n_threads; + } + supports_image_ = image; + supports_video_ = video; + LOG_INFO("the model is loaded (profile %s)", sd_profile::level_name(level)); + return true; +} + +bool ContextKeeper::build_from(size_t index, GenerationFailure& failure) { + { + std::lock_guard state(state_mutex_); + rebuilding_ = true; + } + struct Done { + ContextKeeper& keeper; + ~Done() { + std::lock_guard state(keeper.state_mutex_); + keeper.rebuilding_ = false; + } + } done{*this}; + + while (index < ladder_.size()) { + if (try_build(index, failure)) { + return true; + } + if (!settings_.degradation || !failure_is_recoverable(failure.code)) { + return false; + } + // A failing backend is not cured by trimming memory: go straight to the profile that avoids the devices. + size_t next = index + 1; + if (failure.code == SD_ERROR_BACKEND && ladder_.size() > next) { + next = ladder_.size() - 1; + } + if (next < ladder_.size()) { + LOG_WARN("trying profile %s instead of %s", sd_profile::level_name(ladder_[next]), sd_profile::level_name(ladder_[index])); + } + index = next; + } + return false; +} + +bool ContextKeeper::restore(GenerationFailure& failure) { + size_t index = 0; + { + std::lock_guard state(state_mutex_); + const auto now = hooks_.now(); + if (now < restore_not_before_) { + failure = restore_failure_; + failure.unavailable = true; + failure.message = "the model is not loaded and the last attempt to load it failed: " + restore_failure_.message; + failure.retry_after_seconds = + static_cast(std::chrono::duration_cast(restore_not_before_ - now).count()) + 1; + return false; + } + index = index_; + } + + LOG_WARN("the model is not loaded; loading it again"); + GenerationFailure rebuild_failure; + if (build_from(index, rebuild_failure)) { + std::lock_guard state(state_mutex_); + if (index_ > 0) { + next_promotion_ = hooks_.now() + std::chrono::seconds(cooldown_seconds_); + } + return true; + } + note_build_failure(rebuild_failure); + failure = rebuild_failure; + failure.unavailable = true; + failure.retry_after_seconds = kRestoreBackoffSeconds; + return false; +} + +bool ContextKeeper::step_down(GenerationFailure& failure) { + size_t from = 0; + { + std::lock_guard state(state_mutex_); + from = index_; + } + const size_t last = ladder_.size() - 1; + if (from >= last) { + LOG_ERROR("%s with profile %s and no lighter profile is left: %s", + sd_error_code_name(failure.code), + sd_profile::level_name(ladder_[from]), + failure.message.c_str()); + return false; + } + + const size_t to = failure.code == SD_ERROR_BACKEND ? last : from + 1; + LOG_WARN("%s with profile %s: %s; loading the model again with profile %s to run the request again", + sd_error_code_name(failure.code), + sd_profile::level_name(ladder_[from]), + failure.message.c_str(), + sd_profile::level_name(ladder_[to])); + { + std::lock_guard state(state_mutex_); + ++counters_.step_downs; + if (probation_) { + probation_ = false; + ++counters_.failed_promotions; + cooldown_seconds_ = std::min(cooldown_seconds_ * 2, std::max(kMaxCooldownSeconds, settings_.cooldown_seconds)); + } + next_promotion_ = hooks_.now() + std::chrono::seconds(cooldown_seconds_); + } + + // The old context goes first: both would not fit. + release_context(); + GenerationFailure rebuild_failure; + if (!build_from(to, rebuild_failure)) { + { + // The next attempt to load the model starts from the profile that was just tried. + std::lock_guard state(state_mutex_); + index_ = to; + } + note_build_failure(rebuild_failure); + failure = rebuild_failure; + failure.unavailable = true; + failure.retry_after_seconds = kRestoreBackoffSeconds; + return false; + } + return true; +} + +void ContextKeeper::promote_if_due() { + if (!settings_.degradation || settings_.cooldown_seconds <= 0 || ctx_ == nullptr) { + return; + } + size_t index = 0; + { + std::lock_guard state(state_mutex_); + if (index_ == 0 || hooks_.now() < next_promotion_) { + return; + } + index = index_; + } + + const size_t target = index - 1; + LOG_INFO("trying profile %s again", sd_profile::level_name(ladder_[target])); + release_context(); + GenerationFailure failure; + bool built = build_from(target, failure); + if (!built) { + // The profile in use before the climb worked, so give it another go before giving up. + built = build_from(index, failure); + } + + if (!built) { + note_build_failure(failure); + return; + } + std::lock_guard state(state_mutex_); + if (index_ <= target) { + ++counters_.promotions; + probation_ = true; + } else { + ++counters_.failed_promotions; + cooldown_seconds_ = std::min(cooldown_seconds_ * 2, std::max(kMaxCooldownSeconds, settings_.cooldown_seconds)); + } + next_promotion_ = hooks_.now() + std::chrono::seconds(cooldown_seconds_); +} + +bool ContextKeeper::run(const Attempt& attempt, GenerationFailure& failure) { + std::lock_guard lock(mutex_); + failure = GenerationFailure(); + + struct Active { + ContextKeeper& keeper; + explicit Active(ContextKeeper& owner) + : keeper(owner) { + std::lock_guard state(keeper.state_mutex_); + ++keeper.active_runs_; + ++keeper.counters_.requests; + } + ~Active() { + std::lock_guard state(keeper.state_mutex_); + --keeper.active_runs_; + } + } active(*this); + + auto fail = [&]() { + std::lock_guard state(state_mutex_); + ++counters_.failed; + return false; + }; + + if (!model_loaded_) { + failure.code = SD_ERROR_INVALID_ARGUMENT; + failure.message = "no model loaded"; + return fail(); + } + + promote_if_due(); + if (ctx_ == nullptr && !restore(failure)) { + return fail(); + } + + bool stepped_down = false; + // The wait before the next climb counts from the end of a request that had to step down, not from its + // start: reloading the model and generating on a lighter profile can take longer than the wait itself. + struct Rearm { + ContextKeeper& keeper; + const bool& armed; + ~Rearm() { + if (armed) { + std::lock_guard state(keeper.state_mutex_); + keeper.next_promotion_ = keeper.hooks_.now() + std::chrono::seconds(keeper.cooldown_seconds_); + } + } + } rearm{*this, stepped_down}; + + for (;;) { + ContextView view; + view.ctx = ctx_.get(); + { + std::lock_guard state(state_mutex_); + view.level = ladder_[index_]; + } + view.force_vae_tiling = force_tiling_at(view.level); + + if (attempt(view)) { + std::lock_guard state(state_mutex_); + ++counters_.succeeded; + if (stepped_down) { + ++counters_.recovered; + } + if (probation_) { + probation_ = false; + cooldown_seconds_ = std::max(settings_.cooldown_seconds, 0); + LOG_INFO("profile %s works; it stays", sd_profile::level_name(view.level)); + } + return true; + } + + failure = hooks_.read_failure(); + record_error(failure); + if (!settings_.degradation || !failure_is_recoverable(failure.code)) { + return fail(); + } + if (!step_down(failure)) { + return fail(); + } + stepped_down = true; + } +} + +ContextKeeper::BackendChoice ContextKeeper::backend_choice() const { + std::lock_guard state(state_mutex_); + return backend_choice_; +} + +ContextKeeper::Status ContextKeeper::status_locked() const { + if (!model_loaded_) { + return Status::NO_MODEL; + } + if (rebuilding_) { + return Status::RECOVERING; + } + if (!has_ctx_) { + return Status::UNAVAILABLE; + } + return index_ > 0 ? Status::DEGRADED : Status::OK; +} + +const char* ContextKeeper::status_text(Status status) { + switch (status) { + case Status::NO_MODEL: + return "no_model"; + case Status::OK: + return "ok"; + case Status::DEGRADED: + return "degraded"; + case Status::RECOVERING: + return "recovering"; + case Status::UNAVAILABLE: + return "unavailable"; + } + return "ok"; +} + +const char* ContextKeeper::status_name() const { + std::lock_guard state(state_mutex_); + return status_text(status_locked()); +} + +nlohmann::json ContextKeeper::health_json() const { + std::lock_guard state(state_mutex_); + nlohmann::json out; + + const auto now = hooks_.now(); + + out["status"] = status_text(status_locked()); + out["model_loaded"] = model_loaded_.load(); + out["profile"] = model_loaded_ ? nlohmann::json(sd_profile::level_name(ladder_[index_])) : nlohmann::json(nullptr); + out["base_profile"] = sd_profile::level_name(base_level_); + out["degradation"] = settings_.degradation; + out["busy"] = active_runs_ > 0; + out["counters"] = { + {"requests", counters_.requests}, + {"succeeded", counters_.succeeded}, + {"failed", counters_.failed}, + {"recovered", counters_.recovered}, + {"step_downs", counters_.step_downs}, + {"promotions", counters_.promotions}, + {"failed_promotions", counters_.failed_promotions}, + {"rebuilds", counters_.rebuilds}, + }; + if (last_error_.code.empty()) { + out["last_error"] = nullptr; + } else { + out["last_error"] = { + {"code", last_error_.code}, + {"message", last_error_.message}, + {"at", last_error_.at}, + }; + } + if (model_loaded_ && has_ctx_ && index_ > 0 && settings_.degradation && settings_.cooldown_seconds > 0) { + const auto remaining = std::chrono::duration_cast(next_promotion_ - now).count(); + out["next_promotion_seconds"] = std::max(remaining, 0); + } else { + out["next_promotion_seconds"] = nullptr; + } + out["uptime_seconds"] = std::chrono::duration_cast(now - started_at_).count(); + out["version"] = version_string(); + return out; +} diff --git a/examples/server/recovery.h b/examples/server/recovery.h new file mode 100644 index 00000000..6cbd5d51 --- /dev/null +++ b/examples/server/recovery.h @@ -0,0 +1,208 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "common/common.h" +#include "common/profile.h" +#include "common/resource_owners.hpp" +#include "stable-diffusion.h" + +namespace httplib { + struct Response; +} + +// Why a generation could not be served, in terms a client can act on. +struct GenerationFailure { + sd_error_code_t code = SD_ERROR_NONE; + std::string message; + // No usable context at this moment (it is being rebuilt, or could not be); code holds the cause. + bool unavailable = false; + // How long a client should wait before trying again; 0 when waiting is not expected to help. + int retry_after_seconds = 0; +}; + +// Out of memory and backend failures are the ones a lighter configuration can get around. +bool failure_is_recoverable(sd_error_code_t code); +// "out_of_memory", "backend", "model_file", "invalid_argument", "unavailable", ..., and +// "generation_failed" for failures without a more specific cause. +const char* failure_code_name(const GenerationFailure& failure); +int failure_http_status(const GenerationFailure& failure); +GenerationFailure out_of_memory_failure(); +GenerationFailure failure_from_exception(const std::exception& error); +// 503 (with Retry-After) for lack of memory or of a context, 400 for invalid input, 500 otherwise. +void send_generation_failure(httplib::Response& res, const GenerationFailure& failure); +// Serializes without ever throwing on text that is not valid UTF-8 (library messages can carry file names). +std::string safe_json_dump(const nlohmann::json& value); + +// Owns the diffusion context of the server and keeps it serving when memory runs short. +// +// A request that fails because the machine ran out of memory (or because a backend failed) makes the +// keeper free the context, load the model again with the next lighter profile of the ladder +// max > balanced > lite > lite-disk > lite-cpu, and run the same request again. Once the machine has been +// quiet for a while, it climbs back one step at a time; a climb that fails doubles the wait. +// +// The mutex returned by mutex() serializes everything that uses the compute devices: it is held for +// the whole of a run() and by the upscale endpoint. Reading the health or the resources never takes it. +class ContextKeeper { +public: + using Clock = std::chrono::steady_clock; + + struct Settings { + bool degradation = true; + int cooldown_seconds = 300; // wait before climbing back one step; 0 = stay where the server stepped down + }; + + // Everything that touches the library or the machine, replaceable so that the logic can be tested + // without a model. An empty function selects the real behavior. + struct Hooks { + // Loads the model; returns null and describes the reason when it cannot. Default: new_sd_ctx. + std::function create_context; + // The reason the attempt that just returned false failed. Default: sd_get_last_error(). + std::function read_failure; + // Whether a device other than the CPU is present. Default: asks the library. + std::function has_accelerator; + std::function now; + }; + + // What an attempt needs to run one generation. + struct ContextView { + sd_ctx_t* ctx = nullptr; + sd_profile::Level level = sd_profile::Level::MAX; + // The server stepped down to a lite profile: decode the VAE in tiles whatever the request asked. + bool force_vae_tiling = false; + }; + + // Runs one generation. Must return false only when the generation itself failed, and must not call + // the library again after that call: the reason is read on the same thread right after it returns. + using Attempt = std::function; + + ContextKeeper(const SDContextParams& base_params, + sd_profile::Level base_level, + const Settings& settings, + const Hooks& hooks = Hooks()); + ContextKeeper(const ContextKeeper&) = delete; + ContextKeeper& operator=(const ContextKeeper&) = delete; + + // Loads the model, stepping down the ladder when the memory is not enough. Returns false when no + // profile could load it; failure holds the reason of the last attempt. + bool start(GenerationFailure& failure); + + std::mutex& mutex() { + return mutex_; + } + + // Safe to call from any thread, without the mutex. Both stay true while the context is being rebuilt. + bool has_model() const { + return model_loaded_.load(); + } + bool supports_image_generation() const { + return supports_image_.load(); + } + bool supports_video_generation() const { + return supports_video_.load(); + } + + // Runs attempt on the context, recovering from a lack of memory as described above. Returns true when + // an attempt succeeded. + bool run(const Attempt& attempt, GenerationFailure& failure); + + // The settings the context in use was created with; for the upscale endpoint, which loads its own model. + struct BackendChoice { + std::string backend; + std::string params_backend; + bool diffusion_conv_direct = false; + int n_threads = -1; + }; + BackendChoice backend_choice() const; + + // The profiles the server can step down through, e.g. "max > lite > lite-cpu". + std::string describe_ladder() const; + bool can_step_down() const { + return settings_.degradation && ladder_.size() > 1; + } + + nlohmann::json health_json() const; + // "ok", "degraded", "recovering", "unavailable" or "no_model" + const char* status_name() const; + +private: + enum class Status { NO_MODEL, + OK, + DEGRADED, + RECOVERING, + UNAVAILABLE }; + + struct Counters { + uint64_t requests = 0; + uint64_t succeeded = 0; + uint64_t failed = 0; + uint64_t recovered = 0; // requests that succeeded after a step down + uint64_t step_downs = 0; + uint64_t promotions = 0; + uint64_t failed_promotions = 0; + uint64_t rebuilds = 0; + }; + + struct LastError { + std::string code; + std::string message; + int64_t at = 0; + }; + + std::unique_ptr params_for(sd_profile::Level level) const; + std::string fingerprint(sd_profile::Level level) const; + bool force_tiling_at(sd_profile::Level level) const; + void build_ladder(); + + bool build_from(size_t index, GenerationFailure& failure); + bool try_build(size_t index, GenerationFailure& failure); + bool restore(GenerationFailure& failure); + bool step_down(GenerationFailure& failure); + void promote_if_due(); + void release_context(); + void note_build_failure(const GenerationFailure& failure); + void record_error(const GenerationFailure& failure); + Status status_locked() const; + static const char* status_text(Status status); + + // Settings and the ladder do not change after construction. + const Settings settings_; + const Hooks hooks_; + const SDContextParams base_params_; + const sd_profile::Level base_level_; + std::vector ladder_; + + // Held for the whole of a run(); guards ctx_ and the parameters it was created with. + std::mutex mutex_; + SDCtxPtr ctx_; + std::unique_ptr ctx_params_; + + // Small lock for the figures health reads; always taken after mutex_ when both are needed. + mutable std::mutex state_mutex_; + size_t index_ = 0; // position in ladder_ + bool has_ctx_ = false; + bool rebuilding_ = false; + bool probation_ = false; // the context in use is a promotion nobody has tried yet + int cooldown_seconds_ = 300; + Clock::time_point next_promotion_; + Clock::time_point restore_not_before_; + GenerationFailure restore_failure_; // why the last attempt to load the model again failed + Counters counters_; + LastError last_error_; + BackendChoice backend_choice_; + const Clock::time_point started_at_; + int active_runs_ = 0; + + std::atomic model_loaded_{false}; + std::atomic supports_image_{false}; + std::atomic supports_video_{false}; +}; diff --git a/examples/server/routes.h b/examples/server/routes.h index 1a4efb5b..1a6c6a06 100644 --- a/examples/server/routes.h +++ b/examples/server/routes.h @@ -3,6 +3,7 @@ #include #include "httplib.h" +#include "recovery.h" #include "runtime.h" void register_index_endpoints(httplib::Server& svr, const SDSvrParams& svr_params, const std::string& index_html); diff --git a/examples/server/routes_openai.cpp b/examples/server/routes_openai.cpp index ce156686..b2ad73c6 100644 --- a/examples/server/routes_openai.cpp +++ b/examples/server/routes_openai.cpp @@ -2,11 +2,13 @@ #include #include +#include #include #include "common/common.h" #include "common/media_io.h" #include "common/resource_owners.hpp" +#include "recovery.h" static std::string extract_and_remove_sd_cpp_extra_args(std::string& text) { std::regex re("(.*?)"); @@ -226,22 +228,32 @@ static bool build_openai_edit_request(const httplib::Request& req, static bool execute_sync_img_gen_request(ServerRuntime& runtime, ImgGenJobRequest& request, SDImageVec& results, - std::string& error_message) { - sd_img_gen_params_t img_gen_params = request.to_sd_img_gen_params_t(); - int num_results = 0; + GenerationFailure& failure) { + const sd_img_gen_params_t img_gen_params = request.to_sd_img_gen_params_t(); - { - std::lock_guard lock(*runtime.sd_ctx_mutex); - sd_image_t* raw_results = nullptr; - if (!generate_image(runtime.sd_ctx, &img_gen_params, &raw_results, &num_results)) { - raw_results = nullptr; - num_results = 0; - } - results.adopt(raw_results, num_results); + const bool generated = runtime.keeper->run( + [&](const ContextKeeper::ContextView& view) { + sd_img_gen_params_t params = img_gen_params; + if (view.force_vae_tiling) { + params.vae_tiling_params.enabled = true; + } + sd_image_t* raw_results = nullptr; + int num_results = 0; + if (!generate_image(view.ctx, ¶ms, &raw_results, &num_results)) { + return false; + } + results.adopt(raw_results, num_results); + return true; + }, + failure); + if (!generated) { + return false; } if (results.empty()) { - error_message = "generate_image returned no results"; + failure = GenerationFailure(); + failure.code = SD_ERROR_UNKNOWN; + failure.message = "generate_image returned no results"; return false; } return true; @@ -276,9 +288,9 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { LOG_VERBOSE("%s\n", request.gen_params.to_string().c_str()); SDImageVec results; - if (!execute_sync_img_gen_request(*runtime, request, results, error_message)) { - res.status = 500; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); + GenerationFailure failure; + if (!execute_sync_img_gen_request(*runtime, request, results, failure)) { + send_generation_failure(res, failure); return; } @@ -322,12 +334,14 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(out.dump(), "application/json"); res.status = 200; + } catch (const std::bad_alloc&) { + send_generation_failure(res, out_of_memory_failure()); } catch (const std::exception& e) { res.status = 500; json err; err["error"] = "server_error"; err["message"] = e.what(); - res.set_content(err.dump(), "application/json"); + res.set_content(safe_json_dump(err), "application/json"); } }); @@ -350,9 +364,9 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { LOG_VERBOSE("%s\n", request.gen_params.to_string().c_str()); SDImageVec results; - if (!execute_sync_img_gen_request(*runtime, request, results, error_message)) { - res.status = 500; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); + GenerationFailure failure; + if (!execute_sync_img_gen_request(*runtime, request, results, failure)) { + send_generation_failure(res, failure); return; } @@ -387,12 +401,14 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(out.dump(), "application/json"); res.status = 200; + } catch (const std::bad_alloc&) { + send_generation_failure(res, out_of_memory_failure()); } catch (const std::exception& e) { res.status = 500; json err; err["error"] = "server_error"; err["message"] = e.what(); - res.set_content(err.dump(), "application/json"); + res.set_content(safe_json_dump(err), "application/json"); } }); } diff --git a/examples/server/routes_sdapi.cpp b/examples/server/routes_sdapi.cpp index 6c4d2951..d8a663a2 100644 --- a/examples/server/routes_sdapi.cpp +++ b/examples/server/routes_sdapi.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -400,24 +401,38 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { LOG_VERBOSE("%s\n", request.gen_params.to_string().c_str()); - sd_img_gen_params_t img_gen_params = request.to_sd_img_gen_params_t(); + const sd_img_gen_params_t img_gen_params = request.to_sd_img_gen_params_t(); SDImageVec results; int num_results = 0; - { - std::lock_guard lock(*runtime->sd_ctx_mutex); - SDAPIPreviewGuard preview_guard(id_task, img_gen_params, img2img ? "img2img" : "txt2img"); - sd_image_t* raw_results = nullptr; - if (!generate_image(runtime->sd_ctx, &img_gen_params, &raw_results, &num_results)) { - raw_results = nullptr; - num_results = 0; - } - results.adopt(raw_results, num_results); + GenerationFailure failure; + const bool generated = runtime->keeper->run( + [&](const ContextKeeper::ContextView& view) { + sd_img_gen_params_t params = img_gen_params; + if (view.force_vae_tiling) { + params.vae_tiling_params.enabled = true; + } + SDAPIPreviewGuard preview_guard(id_task, params, img2img ? "img2img" : "txt2img"); + sd_image_t* raw_results = nullptr; + int count = 0; + if (!generate_image(view.ctx, ¶ms, &raw_results, &count)) { + return false; + } + results.adopt(raw_results, count); + num_results = count; + return true; + }, + failure); + if (!generated) { + send_generation_failure(res, failure); + return; } if (results.empty()) { - res.status = 500; - res.set_content(R"({"error":"generate_image returned no results"})", "application/json"); + failure = GenerationFailure(); + failure.code = SD_ERROR_UNKNOWN; + failure.message = "generate_image returned no results"; + send_generation_failure(res, failure); return; } @@ -464,12 +479,14 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(out.dump(), "application/json"); res.status = 200; + } catch (const std::bad_alloc&) { + send_generation_failure(res, out_of_memory_failure()); } catch (const std::exception& e) { res.status = 500; json err; err["error"] = "server_error"; err["message"] = e.what(); - res.set_content(err.dump(), "application/json"); + res.set_content(safe_json_dump(err), "application/json"); } }; diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index b0480a96..bbe5dca4 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "async_jobs.h" #include "common/common.h" @@ -476,6 +477,53 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(make_capabilities_json(*runtime).dump(), "application/json"); }); + svr.Get("/sdcpp/v1/health", [runtime](const httplib::Request&, httplib::Response& res) { + json body = runtime->keeper->health_json(); + { + AsyncJobManager& manager = *runtime->async_job_manager; + std::lock_guard lock(manager.mutex); + body["queue"] = { + {"pending", count_pending_jobs(manager)}, + {"waiting", manager.queue.size()}, + {"max", manager.max_pending_jobs}, + }; + } + res.status = body.value("status", std::string()) == "unavailable" ? 503 : 200; + res.set_content(safe_json_dump(body), "application/json"); + }); + + svr.Get("/sdcpp/v1/resources", [runtime](const httplib::Request&, httplib::Response& res) { + json body; + sd_system_memory_t memory; + if (sd_get_system_memory(&memory)) { + body["system_memory"] = { + {"total_bytes", memory.total_bytes}, + {"available_bytes", memory.available_bytes}, + {"process_bytes", memory.process_bytes}, + }; + } else { + body["system_memory"] = nullptr; + } + + json devices = json::array(); + for (size_t i = 0; i < sd_get_device_count(); ++i) { + sd_device_info_t info; + if (!sd_get_device_info(i, &info)) { + continue; + } + devices.push_back({ + {"name", info.name}, + {"description", info.description}, + {"type", sd_device_type_name(info.type)}, + {"free_memory_bytes", info.free_memory_bytes}, + {"total_memory_bytes", info.total_memory_bytes}, + }); + } + body["devices"] = std::move(devices); + res.status = 200; + res.set_content(safe_json_dump(body), "application/json"); + }); + svr.Post("/sdcpp/v1/upscale", [runtime](const httplib::Request& req, httplib::Response& res) { try { if (req.body.empty()) { @@ -564,14 +612,16 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { return; } - // One GPU: an upscale must not run while a generation is using it. - std::lock_guard ctx_lock(*runtime->sd_ctx_mutex); + // One GPU: an upscale must not run while a generation is using it. The upscaler follows the + // settings the server is running with, which are lighter after it stepped down. + std::lock_guard ctx_lock(runtime->keeper->mutex()); + const ContextKeeper::BackendChoice choice = runtime->keeper->backend_choice(); UpscalerCtxPtr upscaler_ctx(new_upscaler_ctx(model_path.c_str(), - runtime->ctx_params->diffusion_conv_direct, - runtime->ctx_params->n_threads, + choice.diffusion_conv_direct, + choice.n_threads, tile_size, - runtime->ctx_params->backend.c_str(), - runtime->ctx_params->params_backend.c_str())); + choice.backend.c_str(), + choice.params_backend.c_str())); if (upscaler_ctx == nullptr) { res.status = 500; res.set_content(R"({"error":"the upscaler model could not be loaded"})", "application/json"); @@ -635,9 +685,11 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { } catch (const json::exception& e) { res.status = 400; res.set_content(json({{"error", "invalid request"}, {"message", e.what()}}).dump(), "application/json"); + } catch (const std::bad_alloc&) { + send_generation_failure(res, out_of_memory_failure()); } catch (const std::exception& e) { res.status = 500; - res.set_content(json({{"error", std::string("server_error: ") + e.what()}}).dump(), "application/json"); + res.set_content(safe_json_dump(json({{"error", std::string("server_error: ") + e.what()}})), "application/json"); } }); @@ -675,6 +727,7 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { purge_expired_jobs(manager); if (count_pending_jobs(manager) >= manager.max_pending_jobs) { res.status = 429; + res.set_header("Retry-After", "10"); res.set_content(R"({"error":"job queue is full"})", "application/json"); return; } @@ -737,6 +790,7 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { purge_expired_jobs(manager); if (count_pending_jobs(manager) >= manager.max_pending_jobs) { res.status = 429; + res.set_header("Retry-After", "10"); res.set_content(R"({"error":"job queue is full"})", "application/json"); return; } diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index a641f790..e95a64f4 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -11,6 +11,7 @@ #include "common/common.h" #include "common/log.h" +#include "recovery.h" namespace fs = std::filesystem; @@ -168,16 +169,16 @@ std::string video_mime_type(const std::string& output_format) { bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) { if (mode == VID_GEN) { - return sd_ctx_supports_video_generation(runtime.sd_ctx); + return runtime.keeper->supports_video_generation(); } if (mode == IMG_GEN) { - return sd_ctx_supports_image_generation(runtime.sd_ctx); + return runtime.keeper->supports_image_generation(); } return true; } std::string unsupported_generation_mode_error(const ServerRuntime& runtime, SDMode mode) { - if (runtime.sd_ctx == nullptr) { + if (!runtime.keeper->has_model()) { return "no model loaded; restart the server with -m/--diffusion-model"; } if (mode == VID_GEN) { @@ -201,10 +202,12 @@ ArgOptions SDSvrParams::get_options() { options.int_options = { {"", "--listen-port", "server listen port (default: 1234)", &listen_port}, + {"", "--degradation-cooldown", "seconds the server waits, after stepping down to a lighter profile, before it tries the next heavier one again; a failed attempt doubles the wait up to one hour (default: 300, 0 = never go back up)", °radation_cooldown}, }; options.bool_options = { {"", "--color", "colors the logging tags according to level", true, &color}, + {"", "--disable-degradation", "answer a request that runs out of memory with an error (503) instead of loading the model again with a lighter profile and repeating the request", true, &disable_degradation}, }; auto on_help_arg = [&](int, const char**, int, bool& valid) { @@ -231,6 +234,11 @@ bool SDSvrParams::validate() { return false; } + if (degradation_cooldown < 0) { + LOG_ERROR("error: --degradation-cooldown must be 0 or more seconds"); + return false; + } + if (!serve_html_path.empty() && !fs::exists(serve_html_path)) { LOG_ERROR("error: serve_html_path file does not exist: %s", serve_html_path.c_str()); return false; @@ -254,6 +262,8 @@ std::string SDSvrParams::to_string() const { << " serve_html_path: \"" << serve_html_path << "\",\n" << " api_key: " << (api_key.empty() ? "(not set)" : "(set)") << ",\n" << " cors_origins: \"" << cors_origins << "\",\n" + << " disable_degradation: " << (disable_degradation ? "true" : "false") << ",\n" + << " degradation_cooldown: " << degradation_cooldown << ",\n" << "}"; return oss.str(); } diff --git a/examples/server/runtime.h b/examples/server/runtime.h index 12a20f0a..d41d84db 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -17,6 +17,7 @@ using json = nlohmann::json; struct ArgOptions; struct SDContextParams; struct AsyncJobManager; +class ContextKeeper; struct SDSvrParams { std::string listen_ip = "127.0.0.1"; @@ -24,6 +25,8 @@ struct SDSvrParams { 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; @@ -52,8 +55,7 @@ struct UpscalerEntry { }; struct ServerRuntime { - sd_ctx_t* sd_ctx; - std::mutex* sd_ctx_mutex; + ContextKeeper* keeper; const SDSvrParams* svr_params; const SDContextParams* ctx_params; const SDGenerationParams* default_gen_params; diff --git a/test/README.md b/test/README.md index 78373caf..1db244be 100644 --- a/test/README.md +++ b/test/README.md @@ -12,6 +12,7 @@ sezione "Sicurezza". | `pe_imports_test.cpp` | lettore della tabella di importazione dei file PE (diagnostica delle DLL mancanti su Windows): file validi, troncati e corrotti (con ASan/UBSan) | vedi intestazione del file | | `file_handle_pool_test.cpp` | pool dei flussi aperti sui file modello: riuso, file modificato o sostituito, flussi in errore, limiti, uso concorrente (con ASan/UBSan e TSan) | vedi intestazione del file | | `profile_test.cpp` | profili di risorse (`--profile`): scelta automatica da dimensione del modello e memoria, ordine dei livelli, opzioni esplicite che vincono sul profilo | vedi intestazione del file | +| `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. Non serve nessun modello: libreria e orologio sono simulati | vedi intestazione del file | | `fuzz_model_loader.py` | fuzzing a mutazione del caricamento modelli (safetensors/GGUF) | `python3 test/fuzz_model_loader.py --seconds 300` | Per il fuzzing è consigliata una build con AddressSanitizer: diff --git a/test/profile_test.cpp b/test/profile_test.cpp index 2bec99c6..de260ea4 100644 --- a/test/profile_test.cpp +++ b/test/profile_test.cpp @@ -138,11 +138,13 @@ int main() { CHECK(!p.ctx.clip_on_cpu, "an explicit text encoder placement is not overridden by lite"); } { - Parsed p({"--params-backend", "cpu", "--offload-to-cpu"}); + Parsed p({"--params-backend", "cpu", "--offload-to-cpu", "--eager-load"}); sd_profile::apply(Level::LITE_DISK, p.ctx, p.gen, true); - CHECK(p.ctx.params_backend == "cpu" && p.ctx.offload_params_to_cpu, "an explicit --params-backend is kept at startup"); + CHECK(p.ctx.params_backend == "cpu" && p.ctx.offload_params_to_cpu && p.ctx.eager_load, + "an explicit --params-backend is kept at startup"); sd_profile::apply(Level::LITE_DISK, p.ctx, p.gen, false); CHECK(p.ctx.params_backend == "disk" && !p.ctx.offload_params_to_cpu, "lite-disk streams the weights from disk in a recovery"); + CHECK(!p.ctx.eager_load, "and does not read all of them into memory first"); } { Parsed p({"--backend", "cuda0"}); diff --git a/test/server_recovery_test.cpp b/test/server_recovery_test.cpp new file mode 100644 index 00000000..06fd6722 --- /dev/null +++ b/test/server_recovery_test.cpp @@ -0,0 +1,724 @@ +// Test of the context keeper of the server (examples/server/recovery.*): the ladder of profiles, stepping +// down when a request runs out of memory, climbing back, loading the model again after a failure, the +// HTTP answers for failures, and use from several threads. No model is needed: the library is replaced by +// scripted answers and the clock by a variable. +// Build (from the repository root, after building the library into build/); the sources go in one command: +// 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 +// -Lbuild/bin -lstable-diffusion -Wl,-rpath,build/bin -pthread -o server_recovery_test +// Run: ./server_recovery_test ; exit code 0 = all checks passed. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "httplib.h" +#include "recovery.h" + +using Level = sd_profile::Level; +using Clock = ContextKeeper::Clock; +using json = nlohmann::json; + +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) + +static GenerationFailure failure_of(sd_error_code_t code, const char* message) { + GenerationFailure failure; + failure.code = code; + failure.message = message; + return failure; +} +static GenerationFailure oom() { + return failure_of(SD_ERROR_OUT_OF_MEMORY, "unet ran out of memory"); +} +static GenerationFailure backend_failure() { + return failure_of(SD_ERROR_BACKEND, "the backend failed"); +} +static GenerationFailure model_file_failure() { + return failure_of(SD_ERROR_MODEL_FILE, "failed to open the model"); +} +static const GenerationFailure ok_result; + +// What the keeper asked the library to load, reduced to the options a profile changes. +struct Load { + int memory_guard; + bool batched_cfg; + std::string backend; + std::string params_backend; + bool eager_load; + + Level level() const { + if (backend == "cpu") { + return Level::LITE_CPU; + } + if (params_backend == "disk") { + return Level::LITE_DISK; + } + if (memory_guard == 85) { + return Level::LITE; + } + if (memory_guard == 90) { + return Level::BALANCED; + } + return Level::MAX; + } +}; + +// A scripted library and clock. +struct Env { + std::vector loads; + std::function load_result; // code NONE = the model loads + GenerationFailure next_failure; // what the library reports for the attempt that failed + Clock::time_point now = Clock::now(); + bool accelerator = true; + + ContextKeeper::Hooks hooks() { + ContextKeeper::Hooks hooks; + hooks.create_context = [this](const sd_ctx_params_t& params, GenerationFailure& failure) -> SDCtxPtr { + Load load{params.memory_guard, + params.batched_cfg, + params.backend != nullptr ? params.backend : "", + params.params_backend != nullptr ? params.params_backend : "", + params.eager_load}; + loads.push_back(load); + const GenerationFailure result = load_result ? load_result(load) : ok_result; + if (result.code != SD_ERROR_NONE) { + failure = result; + return nullptr; + } + // free_sd_ctx() accepts a context that holds no model. + return SDCtxPtr(static_cast(calloc(1, 64))); + }; + hooks.read_failure = [this] { return next_failure; }; + hooks.has_accelerator = [this] { return accelerator; }; + hooks.now = [this] { return now; }; + return hooks; + } + + void advance(int seconds) { + now += std::chrono::seconds(seconds); + } +}; + +struct Seen { + std::vector levels; + std::vector tiled; + std::vector contexts; +}; + +using Script = std::function; + +static bool run_with(ContextKeeper& keeper, Env& env, Seen& seen, const Script& script, GenerationFailure& failure) { + return keeper.run( + [&](const ContextKeeper::ContextView& view) { + seen.levels.push_back(view.level); + seen.tiled.push_back(view.force_vae_tiling); + seen.contexts.push_back(view.ctx); + const GenerationFailure result = script(view); + if (result.code == SD_ERROR_NONE) { + return true; + } + env.next_failure = result; + return false; + }, + failure); +} + +static SDContextParams base_params() { + SDContextParams params; + params.model_path = "model.safetensors"; + params.n_threads = 2; + return params; +} + +static ContextKeeper::Settings settings(bool degradation = true, int cooldown = 10) { + ContextKeeper::Settings s; + s.degradation = degradation; + s.cooldown_seconds = cooldown; + return s; +} + +static int64_t counter(const json& health, const char* name) { + return health["counters"][name].get(); +} + +static const GenerationFailure succeed(const ContextKeeper::ContextView&) { + return ok_result; +} + +static void test_ladder() { + Env env; + { + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-cpu", "ladder with an accelerator"); + CHECK(keeper.can_step_down(), "a full ladder can step down"); + } + env.accelerator = false; + { + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk", "no cpu profile without an accelerator"); + } + + // The configuration of a host that already asks for most of it: steps that change nothing are left out. + env.accelerator = true; + SDContextParams explicit_set = base_params(); + explicit_set.memory_guard = 90; + explicit_set.clip_on_cpu = true; + explicit_set.params_backend = "disk"; + { + ContextKeeper keeper(explicit_set, Level::MAX, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "max > lite > lite-cpu", "profiles that would load the same configuration are skipped"); + } + { + ContextKeeper keeper(base_params(), Level::LITE, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "lite > lite-disk > lite-cpu", "the ladder starts at the profile the server was started with"); + } + { + // Reading every weight into memory at load time is what streaming them from disk avoids. + SDContextParams eager = explicit_set; + eager.eager_load = true; + ContextKeeper keeper(eager, Level::MAX, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "max > lite > lite-disk > lite-cpu", + "lite-disk is kept when it only differs by not loading every weight at start"); + } + { + ContextKeeper keeper(base_params(), Level::LITE_CPU, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "lite-cpu" && !keeper.can_step_down(), "nothing is lighter than the cpu profile"); + } + { + ContextKeeper keeper(base_params(), Level::MAX, settings(false), env.hooks()); + CHECK(!keeper.can_step_down(), "no stepping down when degradation is disabled"); + } +} + +static void test_start() { + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(!keeper.has_model(), "no model before start"); + CHECK(keeper.status_name() == std::string("no_model"), "status no_model before start"); + CHECK(keeper.start(failure), "start loads the model"); + CHECK(keeper.has_model(), "model after start"); + CHECK(env.loads.size() == 1 && env.loads[0].level() == Level::MAX, "one load, with the profile of the server"); + const json health = keeper.health_json(); + CHECK(health["status"] == "ok" && health["profile"] == "max" && health["base_profile"] == "max", "healthy after start"); + CHECK(health["next_promotion_seconds"].is_null(), "nothing to climb back to at the base profile"); + CHECK(health["last_error"].is_null(), "no error yet"); + CHECK(health["model_loaded"] == true && health["degradation"] == true, "model_loaded and degradation reported"); + } + { + 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; + CHECK(keeper.start(failure), "start steps down when the memory is not enough"); + CHECK(env.loads.size() == 3 && env.loads[2].level() == Level::LITE, "max, balanced and then lite were tried"); + const json health = keeper.health_json(); + CHECK(health["status"] == "degraded" && health["profile"] == "lite" && health["base_profile"] == "max", + "degraded after a start that had to step down"); + CHECK(health["next_promotion_seconds"] == 10, "the climb back is scheduled"); + CHECK(health["last_error"]["code"] == "out_of_memory", "the lack of memory is the last error"); + } + { + // The weights cannot be streamed from disk if the load reads all of them into memory first. + Env env; + env.load_result = [](const Load& load) { return load.eager_load ? oom() : ok_result; }; + SDContextParams eager = base_params(); + eager.eager_load = true; + ContextKeeper keeper(eager, Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && env.loads.size() == 4 && env.loads[3].level() == Level::LITE_DISK && !env.loads[3].eager_load, + "a server started with --eager-load reaches the disk profile without the eager read"); + CHECK(env.loads[0].eager_load && env.loads[2].eager_load, "the lighter profiles above it keep the option"); + } + { + Env env; + env.load_result = [](const Load&) { return model_file_failure(); }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(!keeper.start(failure) && env.loads.size() == 1, "a damaged model file is not a reason to step down"); + CHECK(failure.code == SD_ERROR_MODEL_FILE, "the failure of the start is reported"); + } + { + Env env; + env.load_result = [](const Load&) { return oom(); }; + ContextKeeper keeper(base_params(), Level::MAX, settings(false), env.hooks()); + GenerationFailure failure; + CHECK(!keeper.start(failure) && env.loads.size() == 1, "with degradation disabled the start gives up at once"); + } + { + Env env; + env.load_result = [](const Load& load) { return load.level() == Level::MAX ? backend_failure() : ok_result; }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && env.loads.size() == 2 && env.loads[1].level() == Level::LITE_CPU, + "a backend failure at start goes straight to the cpu profile"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + Seen seen; + GenerationFailure failure; + CHECK(!run_with(keeper, env, seen, succeed, failure) && failure.code == SD_ERROR_INVALID_ARGUMENT, + "running without a model is refused"); + } +} + +static void test_step_down() { + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(run_with(keeper, env, seen, succeed, failure), "a request that fits succeeds"); + CHECK(seen.levels.size() == 1 && seen.levels[0] == Level::MAX && !seen.tiled[0] && seen.contexts[0] != nullptr, + "it ran once, at max, without forced tiling"); + const json health = keeper.health_json(); + CHECK(counter(health, "requests") == 1 && counter(health, "succeeded") == 1 && counter(health, "step_downs") == 0, + "counted as a plain success"); + CHECK(health["busy"] == false, "not busy once the request is over"); + } + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + // Fits only from the lite-disk profile on. + const bool ok = run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE_DISK ? oom() : ok_result; }, failure); + CHECK(ok, "the request succeeds after stepping down"); + CHECK(seen.levels == std::vector({Level::MAX, Level::BALANCED, Level::LITE, Level::LITE_DISK}), + "the same request was run at each profile in turn"); + CHECK(seen.tiled == std::vector({false, false, true, true}), "tiling is forced from the lite profile on"); + CHECK(seen.contexts[0] != nullptr && seen.contexts[1] != nullptr, "every attempt had a context"); + CHECK(env.loads.size() == 4, "the model was loaded three more times"); + const json health = keeper.health_json(); + CHECK(counter(health, "step_downs") == 3 && counter(health, "recovered") == 1 && counter(health, "rebuilds") == 3 && + counter(health, "failed") == 0, + "counters of a request that recovered"); + CHECK(health["status"] == "degraded" && health["profile"] == "lite-disk", "the server stays on the profile that worked"); + CHECK(health["next_promotion_seconds"] == 10, "the climb back is scheduled"); + CHECK(health["last_error"]["code"] == "out_of_memory" && health["last_error"]["message"] == "unet ran out of memory", + "the last error is kept"); + + Seen second; + CHECK(run_with(keeper, env, second, succeed, failure) && second.levels == std::vector({Level::LITE_DISK}), + "the next request runs on the profile that worked, with no rebuild"); + CHECK(env.loads.size() == 4, "no extra load for it"); + } + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(!run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return oom(); }, failure), "a request that fits nowhere fails"); + CHECK(failure.code == SD_ERROR_OUT_OF_MEMORY && !failure.unavailable && failure.message == "unet ran out of memory", + "with the out of memory reason, not as unavailable"); + CHECK(seen.levels.size() == 4, "every profile was tried"); + const json health = keeper.health_json(); + CHECK(health["status"] == "degraded" && health["profile"] == "lite-disk", "the server keeps the lightest context"); + CHECK(counter(health, "failed") == 1, "one failed request"); + Seen later; + CHECK(run_with(keeper, env, later, succeed, failure), "a smaller request is served afterwards"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(!run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return failure_of(SD_ERROR_INVALID_ARGUMENT, "bad size"); }, failure), "an invalid request fails"); + CHECK(failure.code == SD_ERROR_INVALID_ARGUMENT && seen.levels.size() == 1 && env.loads.size() == 1, + "without stepping down"); + const json health = keeper.health_json(); + CHECK(health["last_error"].is_null(), "a mistake of the client is not an error of the server"); + CHECK(counter(health, "failed") == 1, "but it is a failed request"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(false), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(!run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return oom(); }, failure), "with degradation disabled a request out of memory fails"); + CHECK(failure.code == SD_ERROR_OUT_OF_MEMORY && seen.levels.size() == 1 && env.loads.size() == 1, + "after one attempt and without loading the model again"); + const json health = keeper.health_json(); + CHECK(health["status"] == "ok" && health["profile"] == "max" && health["degradation"] == false, "the server stays as it was"); + CHECK(health["last_error"]["code"] == "out_of_memory", "and reports why"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + const bool ok = run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level == Level::MAX ? backend_failure() : ok_result; }, failure); + CHECK(ok && seen.levels == std::vector({Level::MAX, Level::LITE_CPU}), + "a backend failure goes straight to the cpu profile"); + CHECK(env.loads.back().backend == "cpu", "which loads the model on the cpu"); + CHECK(keeper.backend_choice().backend == "cpu", "and the upscaler follows"); + } +} + +static void test_promotion() { + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE ? oom() : ok_result; }, failure); + const size_t loads = env.loads.size(); + + env.advance(5); + CHECK(keeper.health_json()["next_promotion_seconds"] == 5, "the time left is reported"); + Seen early; + run_with(keeper, env, early, succeed, failure); + CHECK(env.loads.size() == loads && early.levels == std::vector({Level::LITE}), "no climb before the wait is over"); + + env.advance(6); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure), "a request after the wait succeeds"); + CHECK(climb.levels == std::vector({Level::BALANCED}) && env.loads.size() == loads + 1, + "on the next heavier profile, loaded for it"); + json health = keeper.health_json(); + CHECK(counter(health, "promotions") == 1 && counter(health, "failed_promotions") == 0, "a promotion is counted"); + CHECK(health["status"] == "degraded" && health["profile"] == "balanced", "one step at a time"); + + env.advance(11); + Seen top; + run_with(keeper, env, top, succeed, failure); + health = keeper.health_json(); + CHECK(top.levels == std::vector({Level::MAX}) && health["status"] == "ok" && health["profile"] == "max", + "back at the profile the server was started with"); + CHECK(health["next_promotion_seconds"].is_null() && counter(health, "promotions") == 2, "and nothing left to climb"); + env.advance(1000); + Seen quiet; + run_with(keeper, env, quiet, succeed, failure); + CHECK(quiet.levels == std::vector({Level::MAX}), "it never goes above the base profile"); + } + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(true, 0), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::BALANCED ? oom() : ok_result; }, failure); + env.advance(100000); + Seen later; + run_with(keeper, env, later, succeed, failure); + CHECK(later.levels == std::vector({Level::BALANCED}), "a cooldown of 0 never climbs back"); + CHECK(keeper.health_json()["next_promotion_seconds"].is_null(), "and reports no climb"); + } + { + // A climb that fails: the first request on the heavier profile runs out of memory. + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + const Script needs_balanced = [](const ContextKeeper::ContextView& view) { + return view.level < Level::BALANCED ? oom() : ok_result; + }; + run_with(keeper, env, seen, needs_balanced, failure); + env.advance(11); + Seen failed_climb; + CHECK(run_with(keeper, env, failed_climb, needs_balanced, failure), "the request is served even if the climb fails"); + CHECK(failed_climb.levels == std::vector({Level::MAX, Level::BALANCED}), "after going back down"); + json health = keeper.health_json(); + CHECK(counter(health, "promotions") == 1 && counter(health, "failed_promotions") == 1, "a failed climb is counted"); + CHECK(health["next_promotion_seconds"] == 20, "and the wait doubles"); + env.advance(21); + Seen again; + run_with(keeper, env, again, needs_balanced, failure); + CHECK(keeper.health_json()["next_promotion_seconds"] == 40, "again after another failed climb"); + + // A climb that holds puts the wait back to its start. + env.advance(41); + Seen holds; + run_with(keeper, env, holds, succeed, failure); + CHECK(holds.levels == std::vector({Level::MAX}), "a later climb that succeeds reaches max"); + Seen drop; + run_with(keeper, env, drop, needs_balanced, failure); + CHECK(keeper.health_json()["next_promotion_seconds"] == 10, "the wait starts again from the configured one"); + } + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(true, 2000), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + const Script needs_balanced = [](const ContextKeeper::ContextView& view) { + return view.level < Level::BALANCED ? oom() : ok_result; + }; + run_with(keeper, env, seen, needs_balanced, failure); + env.advance(2001); + run_with(keeper, env, seen, needs_balanced, failure); + CHECK(keeper.health_json()["next_promotion_seconds"] == 3600, "the wait stops doubling at an hour"); + } + { + // The wait counts from the end of a request that had to step down, however long that took. + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [&env](const ContextKeeper::ContextView& view) { + env.advance(100); + return view.level < Level::BALANCED ? oom() : ok_result; }, failure); + CHECK(keeper.health_json()["next_promotion_seconds"] == 10, "a slow request does not use up the wait"); + } + { + // The heavier profile cannot be loaded because of the memory: the climb falls back to the one before. + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE ? oom() : ok_result; }, failure); + env.load_result = [](const Load& load) { return load.level() == Level::BALANCED ? oom() : ok_result; }; + env.advance(11); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure) && climb.levels == std::vector({Level::LITE}), + "a climb that cannot load the profile serves the request one step down"); + const json health = keeper.health_json(); + CHECK(counter(health, "failed_promotions") == 1 && health["next_promotion_seconds"] == 20, "counted as a failed climb"); + } + { + // The heavier profile fails for a reason that is not the memory: the profile in use before it comes back. + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE ? oom() : ok_result; }, failure); + env.load_result = [](const Load& load) { return load.level() == Level::BALANCED ? model_file_failure() : ok_result; }; + env.advance(11); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure) && climb.levels == std::vector({Level::LITE}), + "the request is served on the previous profile"); + } +} + +static void test_unavailable() { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + env.load_result = [](const Load& load) { return load.level() == Level::BALANCED ? model_file_failure() : ok_result; }; + Seen seen; + CHECK(!run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return oom(); }, failure), "a request fails when the model cannot be loaded again"); + CHECK(failure.unavailable && failure.code == SD_ERROR_MODEL_FILE && failure.retry_after_seconds > 0, + "as unavailable, with the cause and a time to retry"); + json health = keeper.health_json(); + CHECK(health["status"] == "unavailable", "the health says so"); + CHECK(health["last_error"]["code"] == "model_file", "and why"); + + const size_t loads = env.loads.size(); + Seen blocked; + CHECK(!run_with(keeper, env, blocked, succeed, failure) && failure.unavailable && blocked.levels.empty(), + "requests wait instead of trying again at once"); + CHECK(env.loads.size() == loads && failure.retry_after_seconds >= 1 && failure.retry_after_seconds <= 16, + "no load, and the time left is reported"); + + env.advance(16); + env.load_result = nullptr; + Seen restored; + CHECK(run_with(keeper, env, restored, succeed, failure), "the model is loaded again after the wait"); + CHECK(env.loads.size() == loads + 1 && env.loads.back().level() == Level::BALANCED, "from the profile it had stepped down to"); + CHECK(keeper.health_json()["status"] == "degraded", "and the server serves again"); +} + +static void test_reporting() { + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(false), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return failure_of(SD_ERROR_OUT_OF_MEMORY, "bad \xff\xfe name"); }, failure); + std::string text; + bool threw = false; + try { + text = safe_json_dump(keeper.health_json()); + } catch (...) { + threw = true; + } + CHECK(!threw && text.find("out_of_memory") != std::string::npos, "text that is not UTF-8 never breaks the health"); + const json health = keeper.health_json(); + CHECK(health.contains("uptime_seconds") && health.contains("version") && health.contains("counters"), "the health has its fields"); + } + + GenerationFailure f = oom(); + CHECK(failure_http_status(f) == 503 && std::string(failure_code_name(f)) == "out_of_memory", "out of memory is 503"); + f.unavailable = true; + CHECK(failure_http_status(f) == 503 && std::string(failure_code_name(f)) == "unavailable", "unavailable is 503"); + CHECK(failure_http_status(failure_of(SD_ERROR_INVALID_ARGUMENT, "x")) == 400, "an invalid argument is 400"); + CHECK(failure_http_status(model_file_failure()) == 500 && failure_http_status(backend_failure()) == 500, "model file and backend are 500"); + CHECK(failure_http_status(failure_of(SD_ERROR_UNKNOWN, "x")) == 500 && + std::string(failure_code_name(failure_of(SD_ERROR_UNKNOWN, "x"))) == "generation_failed", + "an unknown failure keeps the code generation_failed"); + CHECK(failure_is_recoverable(SD_ERROR_OUT_OF_MEMORY) && failure_is_recoverable(SD_ERROR_BACKEND) && + !failure_is_recoverable(SD_ERROR_MODEL_FILE) && !failure_is_recoverable(SD_ERROR_INVALID_ARGUMENT), + "only memory and backend failures are worth a lighter profile"); + + { + httplib::Response res; + GenerationFailure failure = oom(); + failure.retry_after_seconds = 42; + send_generation_failure(res, failure); + const json body = json::parse(res.body); + CHECK(res.status == 503 && res.get_header_value("Retry-After") == "42", "503 carries Retry-After"); + CHECK(body["code"] == "out_of_memory" && body["retry_after_seconds"] == 42 && body["error"] == "unet ran out of memory", + "and the code, the wait and the reason in the body"); + } + { + httplib::Response res; + send_generation_failure(res, failure_of(SD_ERROR_INVALID_ARGUMENT, "bad size")); + const json body = json::parse(res.body); + CHECK(res.status == 400 && !res.has_header("Retry-After") && body["code"] == "invalid_argument", "400 has no Retry-After"); + } + { + httplib::Response res; + GenerationFailure failure = model_file_failure(); + failure.unavailable = true; + send_generation_failure(res, failure); + const json body = json::parse(res.body); + CHECK(res.status == 503 && res.has_header("Retry-After") && body["code"] == "unavailable" && body["cause"] == "model_file", + "unavailable names its cause"); + } + { + httplib::Response res; + send_generation_failure(res, failure_of(SD_ERROR_OUT_OF_MEMORY, "bad \xff\xfe")); + CHECK(res.status == 503 && !res.body.empty() && json::accept(res.body), "an answer with text that is not UTF-8 is still JSON"); + } + CHECK(failure_from_exception(std::bad_alloc()).code == SD_ERROR_OUT_OF_MEMORY, "bad_alloc is a lack of memory"); + const GenerationFailure other = failure_from_exception(std::runtime_error("boom")); + CHECK(other.code == SD_ERROR_UNKNOWN && other.message == "boom", "other exceptions keep their text"); +} + +static void test_backend_choice() { + Env env; + SDContextParams params = base_params(); + params.backend = "vulkan"; + params.params_backend = "cpu"; + params.n_threads = 3; + ContextKeeper keeper(params, Level::MAX, settings(), env.hooks()); + ContextKeeper::BackendChoice choice = keeper.backend_choice(); + CHECK(choice.backend == "vulkan" && choice.params_backend == "cpu" && choice.n_threads == 3, + "before a model is loaded, the upscaler uses the options of the server"); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE_CPU ? oom() : ok_result; }, failure); + choice = keeper.backend_choice(); + CHECK(choice.backend == "cpu" && choice.n_threads == 3, "after the cpu profile, the upscaler runs on the cpu"); +} + +static void test_threads() { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure start_failure; + keeper.start(start_failure); + + std::atomic inside{0}; + std::atomic max_inside{0}; + std::atomic done{false}; + std::atomic succeeded{0}; + std::atomic failed{0}; + + std::thread observer([&] { + while (!done) { + const json health = keeper.health_json(); + (void)health["status"]; + (void)keeper.status_name(); + (void)keeper.backend_choice(); + (void)keeper.supports_image_generation(); + } + }); + + std::vector workers; + for (int t = 0; t < 4; t++) { + workers.emplace_back([&, t] { + for (int i = 0; i < 40; i++) { + GenerationFailure failure; + const bool ok = keeper.run( + [&](const ContextKeeper::ContextView& view) { + const int now_inside = ++inside; + int seen_max = max_inside.load(); + while (now_inside > seen_max && !max_inside.compare_exchange_weak(seen_max, now_inside)) { + } + std::this_thread::sleep_for(std::chrono::microseconds(200)); + --inside; + // Now and then the request does not fit on the heavier profiles. + if ((i + t) % 7 == 0 && view.level < Level::LITE) { + env.next_failure = oom(); + return false; + } + return true; + }, + failure); + (ok ? succeeded : failed)++; + } + }); + } + for (auto& worker : workers) { + worker.join(); + } + done = true; + observer.join(); + + const json health = keeper.health_json(); + CHECK(max_inside.load() == 1, "never two generations at the same time"); + CHECK(succeeded + failed == 160 && counter(health, "requests") == 160, "every request was counted"); + CHECK(health["busy"] == false, "idle at the end"); + CHECK(counter(health, "step_downs") >= 1 && health["status"] == "degraded", "the steps down of one request serve the next ones"); +} + +int main() { + sd_set_log_callback([](enum sd_log_level_t, const char*, void*) {}, nullptr); + + test_ladder(); + test_start(); + test_step_down(); + test_promotion(); + test_unavailable(); + test_reporting(); + test_backend_choice(); + test_threads(); + + printf("\n%s (%d failures)\n", failures ? "TEST FAILED" : "ALL TESTS PASSED", failures); + return failures ? 1 : 0; +}