From c8bb095ba6ff84e6ee8acb17efb3c4817d78ac0a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 22:15:52 +0200 Subject: [PATCH] docs: explain how to stop a job that is generating POST /sdcpp/v1/jobs/{id}/cancel now stops a job that has started, not only one in the queue, and the documents still said it answered 409. api.md describes the route as a table by state of the job (queued, generating, finished, unknown), the wait parameter (0 to 60 seconds, default 10), the 200 and 202 answers with examples, cancel_requested on the job, the cancelled counter of /health and the cancel_queued and cancel_generating capabilities. It says what to expect: the stop arrives at the end of the sampling step in progress, a stopped job returns no images, a stop is not a failure, and the synchronous endpoints are not jobs and cannot be stopped. integrazione_progetti.md (in Italian) gets curl examples that can be copied, how to read 200 and 202, how long a stop takes and why, the reference to the capability for older servers, an update of the retry tool that now stops a job that is generating, and a numbered entry in the list of changes with what was tested and what was not (a real GPU, a video model). convivenza_applicazioni.md and the README mention the new behaviour where they described the old limit. Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC --- README.md | 1 + docs/convivenza_applicazioni.md | 15 +++-- docs/integrazione_progetti.md | 97 +++++++++++++++++++++++++++++---- examples/server/api.md | 93 +++++++++++++++++++++++++++++-- 4 files changed, 183 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 59cfc2ff..223cabe6 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ progetto originale. Modifiche del fork di **Francesco Simeoni** - **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) +- **Fermare un job che sta generando**: `POST /sdcpp/v1/jobs/{id}/cancel` ferma anche un job già partito (`200` con il job annullato, `202` se sta ancora finendo; `?wait=` da 0 a 60 secondi). Non è un errore: il modello resta caricato, il server non scende di profilo e `/health` conta `cancelled`. Esempi `curl` e limiti in [docs/integrazione_progetti.md](./docs/integrazione_progetti.md), sezione 3.5 - **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/convivenza_applicazioni.md b/docs/convivenza_applicazioni.md index a5a17c8d..63f178fe 100644 --- a/docs/convivenza_applicazioni.md +++ b/docs/convivenza_applicazioni.md @@ -161,10 +161,14 @@ Da sapere: - Il motore non può chiedere all'altra applicazione di scaricare il suo modello, né il contrario: serve qualcuno che coordini (l'utente o il programma ospite). -- `POST /sdcpp/v1/jobs/{id}/cancel` annulla un job **in coda**; su uno **in - esecuzione** risponde `409` ("cannot be interrupted yet"). Per fermare una - generazione in corso bisogna aspettare che finisca o terminare il processo e - perdere il lavoro. +- `POST /sdcpp/v1/jobs/{id}/cancel` ferma un job **in coda** (subito) e uno **in + esecuzione** (al passo di campionamento successivo): risposta `200` con il job + annullato, oppure `202` se sta ancora finendo (vedi + [integrazione_progetti.md](./integrazione_progetti.md), sezione 3.5). Il modello + resta in memoria e il server non scende di profilo, quindi è il modo giusto per + fare posto all'altra applicazione senza spegnere il server. Le richieste + sincrone (`/sdapi`, `/v1/images`) non sono job e non si fermano; un server più + vecchio risponde `409` a un job già partito. - Per richieste isolate `sd-cli` è la scelta più semplice: carica il modello, genera e restituisce tutto uscendo. Ogni esecuzione paga il caricamento del modello. @@ -282,7 +286,8 @@ momento. | `503` `unavailable` | il server sta ricaricando il modello dopo un errore (`cause` dice quale) | riprova dopo `Retry-After` | | `503` `busy` | il modello era in uso | riprova dopo `Retry-After` | | `429` | coda piena (`queue.max` in `/health`, 64) | riprova dopo `Retry-After` (10 secondi) | -| `409` su `cancel` | il job sta generando | aspetta o termina il processo | +| `202` su `cancel` | lo stop è stato chiesto e il job sta ancora finendo (`cancel_requested: true`) | ripeti `cancel` o interroga il job finché diventa `cancelled` | +| `409` su `cancel` | server più vecchio: il job sta generando e non si può fermare | aspetta o termina il processo | | `401` | manca la chiave API | `Authorization: Bearer ` oppure `X-API-Key` | | `400` `invalid_argument` | la richiesta non è generabile così | non ripeterla uguale | | `200` dopo una discesa di profilo | servita con un profilo più leggero | `/health` mostra `status: degraded` e il `profile` in uso; dopo `--degradation-cooldown` il server prova a risalire | diff --git a/docs/integrazione_progetti.md b/docs/integrazione_progetti.md index ffd0d09d..56676342 100644 --- a/docs/integrazione_progetti.md +++ b/docs/integrazione_progetti.md @@ -684,10 +684,55 @@ Il server **non cade quando la memoria finisce**: 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. + `unavailable`, `no_model`), profilo in uso, contatori (richieste, riuscite, + fallite, annullate, 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. + +Il server **sa fermare un job che sta generando** (non solo uno in coda): + +```shell +# crea un job; la risposta contiene "id" e "poll_url" +curl -s -X POST http://127.0.0.1:1234/sdcpp/v1/img_gen \ + -H "Content-Type: application/json" \ + -d '{"prompt": "a red apple", "width": 512, "height": 512, "sample_params": {"sample_steps": 30}}' + +# fermalo: aspetta fino a 10 secondi che il job finisca davvero +curl -s -X POST http://127.0.0.1:1234/sdcpp/v1/jobs/job_6acf9114_00000000/cancel + +# oppure chiedi lo stop e torna subito, poi controlla con calma +curl -s -X POST "http://127.0.0.1:1234/sdcpp/v1/jobs/job_6acf9114_00000000/cancel?wait=0" +curl -s http://127.0.0.1:1234/sdcpp/v1/jobs/job_6acf9114_00000000 +``` + +- Cosa dice la risposta. `200` = il job è in uno stato finale e la risposta lo + contiene (`"status": "cancelled"`, `error.code` `cancelled`). `202` = lo stop è + stato chiesto ma il job sta ancora finendo (`"status": "generating"` e + `"cancel_requested": true`): richiedi lo stesso `cancel` o interroga + `GET /sdcpp/v1/jobs/{id}` finché diventa `cancelled`. Ripetere la richiesta non + fa danni. Un job in coda esce subito dalla coda (`200`) e non parte mai; un job + già finito resta com'è (`200`); un id sconosciuto è `404`. +- `?wait=` sono i secondi che la richiesta può aspettare: da `0` (risponde subito) + a `60`, predefinito `10`. Un valore che non è un numero intero di secondi dà + `400`. La richiesta tiene aperta la connessione per tutto il tempo che aspetta. +- Quanto ci mette. Il motore controlla lo stop alla fine di ogni passo di + campionamento e fra le fasi (testo, decodifica, secondo passaggio): su una macchina + lenta un passo dura secondi, e la prima generazione dopo l'avvio può passare + molto tempo a leggere i pesi dal disco prima del primo controllo. Se lo stop non + basta nel tempo di `wait` la risposta è `202`, non un errore. +- Se il job finisce prima che lo stop faccia effetto, la risposta è il job + completato (`200`, `"status": "completed"`): non c'è niente da fermare. +- Fermare non è un errore. Il modello non si ricarica, il server non scende a un + profilo più leggero, `last_error` non cambia e `/health` conta il job in + `counters.cancelled`. Il job successivo parte subito sullo stesso contesto. Un + job fermato non restituisce immagini, nemmeno quelle già pronte di un gruppo. +- Le rotte sincrone (`/sdapi/...`, `/v1/images/...`) non sono job e non si + possono fermare: se una di esse aspetta il modello dietro a un job che viene + annullato, parte subito dopo e finisce normalmente. +- Per sapere se un server lo supporta: `features.cancel_generating` in + `GET /sdcpp/v1/capabilities`. Un server più vecchio risponde `409` a un job già + partito. Dettagli e formato delle risposte: [examples/server/api.md](../examples/server/api.md). @@ -915,7 +960,7 @@ def generate_image(prompt, preset="standard", shape="square", seed=None, wait=60 "seed": seed, "seconds": round(time.time() - started)} if job["status"] in ("failed", "cancelled"): return {"error": job["error"]} - call(base, "POST", poll_url + "/cancel") # funziona solo se il job è ancora in coda + call(base, "POST", poll_url + "/cancel?wait=0") # ferma il job, anche se sta già generando, senza attendere return {"error": {"code": "timeout", "message": "nessun risultato entro %d s" % wait}} @@ -969,11 +1014,12 @@ quale dei due è il problema. coda, con `429`); larghezza e altezza no: una larghezza di 4097 è stata accettata e portata a 4160, e una enorme è finita in `out_of_memory` facendo scendere il server di un profilo (un ricaricamento, e prestazioni ridotte per - `--degradation-cooldown` secondi). Un job già partito non si può interrompere - (`409`, `cancel_generating: false`; uno in coda sì, con `200`): una richiesta - sproporzionata occupa il server fino alla fine. Lo strumento di riferimento - ricava le dimensioni dai `limits` e i passi dai default, e non lascia al - modello né le une né gli altri. + `--degradation-cooldown` secondi). Un job già partito si può fermare + (`POST /sdcpp/v1/jobs/{id}/cancel`, sezione 3.5), ma lo stop arriva al controllo + successivo e le rotte sincrone non si fermano: una richiesta sproporzionata + occupa comunque il server per un po'. Lo strumento di riferimento ricava le + dimensioni dai `limits` e i passi dai default, e non lascia al modello né le + une né gli altri. 3. **Chiave API e CORS.** Un agente che controlla il browser sulla stessa macchina apre pagine che non controlla nessuno: con il CORS predefinito (riflette ogni `Origin`, con credenziali) una di esse può chiamare @@ -1496,8 +1542,8 @@ sincronizzazioni future. guida documenta e non cambia: i `limits` di `capabilities` non sono imposti (solo 8 immagini e da 1 a 100 passi lo sono), un blocco `` nel prompt cambia i parametri sulle rotte OpenAI e - `sdapi` ma non sulla nativa, un job già partito non si può annullare - (`409`), i PNG incorporano per default prompt e parametri. Studio di + `sdapi` ma non sulla nativa, un job già partito non si poteva annullare + (`409`; risolto: voce 21), i PNG incorporano per default prompt e parametri. Studio di fattibilità sulla generazione di testo con un modello a diffusione: [studio_testo_a_diffusione.md](./studio_testo_a_diffusione.md) (nessun codice, serve un modello su cui provare). @@ -1519,6 +1565,33 @@ sincronizzazioni future. `--profile lite` non sposta l'encoder di testo sulla CPU. Nessuna prova su una GPU reale. +21. **Annullamento di un job in corso** — `POST /sdcpp/v1/jobs/{id}/cancel` + ferma anche un job che sta generando (prima: `409`). Ogni job ha il proprio + token di annullamento (`CancelToken`, `examples/server/recovery.{h,cpp}`), + registrato nel custode del contesto solo mentre quel job sta generando: lo + stop di un job non può raggiungere un'altra richiesta, un job annullato prima + di partire non genera niente e un contesto liberato o ricostruito non viene + mai toccato. La libreria dimentica una richiesta di stop quando una + generazione comincia, quindi la rotta la ripete ogni 100 ms finché il job è + finito. Risposta `200` con il job annullato, o `202` con + `"cancel_requested": true` se dopo `?wait=` secondi (0-60, predefinito 10) + sta ancora finendo. Un job fermato non è un errore: nessuna ricarica del + modello, nessuna discesa di profilo, nessun `last_error`, contatore + `counters.cancelled` in `/health`; `cancel_generating` è `true` in + `/capabilities`. I messaggi della libreria per uno stop voluto passano da + ERRORE a INFO. La rotta legge il corpo della richiesta tramite il lettore di + contenuti della libreria HTTP: un gestore normale parte solo dopo che il corpo + è stato letto, e per un POST senza `Content-Length` (quello di + `curl -X POST`) la libreria aspetta 5 secondi di timeout prima di accorgersi + che non c'è; così `curl -X POST …/cancel` risponde subito. Test: `test/server_recovery_test.cpp` (149 controlli, con + ASan/UBSan e TSan; sette guasti inseriti di proposito nel custode sono tutti + rilevati) e `test/server_cancel_e2e.py` (32 controlli su un vero + `sd-server`). Provato su CPU con il modello sintetico: lo stop arriva in circa + un passo di campionamento, il contesto resta riutilizzabile e una richiesta + sincrona in attesa dietro il job annullato finisce normalmente. **Non + provato**: l'annullamento su una GPU reale (CUDA/Vulkan) e con un modello + video. + Passaggi previsti e non ancora svolti: collaudo del workflow di release sui runner GitHub, prova di `--multi-gpu` su una macchina con due GPU, generazione con un modello reale (inclusa la memory guard e la discesa di profilo del server diff --git a/examples/server/api.md b/examples/server/api.md index 6a5fa3bd..3cdade76 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -497,6 +497,7 @@ Field types: | `result` | `object \| null` | | `error` | `object \| null` | | `preview` | `object \| null` | +| `cancel_requested` | `boolean`, present (and `true`) only while a job that is generating has been asked to stop | `preview` sub-fields: @@ -714,6 +715,11 @@ Fields returned in `features_by_mode.vid_gen`: - `cancel_generating` - `preview` +`cancel_queued` and `cancel_generating` tell whether [`POST /sdcpp/v1/jobs/{id}/cancel`](#post-sdcppv1jobsidcancel) +can stop a job that is waiting and one that is generating. Both are `true` in this version; a client that must also +talk to older servers checks `cancel_generating` before offering a stop button, because an older server answers `409` +for a job that has started. + #### `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 @@ -733,6 +739,7 @@ Example response: "requests": 12, "succeeded": 11, "failed": 1, + "cancelled": 3, "recovered": 2, "step_downs": 3, "promotions": 1, @@ -763,7 +770,7 @@ Example response: | `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) | +| `counters` | `object` | Since the start. `requests`, `succeeded`, `failed`; `cancelled` is the number of generations stopped on request (not failures, and they never make the server step down); `recovered` is the number of requests served after a step-down; `step_downs`, `promotions`, `failed_promotions` and `rebuilds` (times the model was loaded again). A job cancelled while it was still queued never reaches the model and is not counted | | `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` | | @@ -894,15 +901,89 @@ Notes: #### `POST /sdcpp/v1/jobs/{id}/cancel` -Attempts to cancel an accepted job. +Stops a job, whether it is still waiting in the queue or already generating. There is no body: the URL is enough, +and `curl -X POST ` works as it is. + +What happens depends on the state of the job: + +| State of the job | What the server does | Answer | +| --- | --- | --- | +| `queued` | Takes it out of the queue; it never starts. | `200` with the job, `status: "cancelled"` | +| `generating` | Tells the library to stop and waits for the job to end. | `200` with the job (`status: "cancelled"`) as soon as it has ended; `202` with the job (`status: "generating"`, `"cancel_requested": true`) if it is still stopping after `wait` seconds | +| `completed`, `failed`, `cancelled` | Nothing to stop. | `200` with the job as it is | +| unknown id | | `404`; `410` if the job existed but was removed after its retention time | + +Query parameter: + +| Parameter | Type | Notes | +| --- | --- | --- | +| `wait` | `integer` | Whole seconds the call may wait for a generating job to end: `0` to `60`, default `10`. `0` asks for the stop and answers at once; a larger number is shortened to `60`. Anything that is not a whole number of seconds, 0 or more, is `400`. | + +Example, stopping a job and reading the answer: + +```shell +curl -s -X POST http://127.0.0.1:1234/sdcpp/v1/jobs/job_6acf9114_00000000/cancel +``` + +```json +{ + "id": "job_6acf9114_00000000", + "kind": "img_gen", + "status": "cancelled", + "created": 1775401200, + "started": 1775401203, + "completed": 1775401209, + "queue_position": 0, + "result": null, + "error": { "code": "cancelled", "message": "job cancelled by client" } +} +``` + +When the job is still stopping at the end of the wait, the answer is `202` and the job is still `generating`: + +```json +{ + "id": "job_6acf9114_00000000", + "kind": "img_gen", + "status": "generating", + "cancel_requested": true, + "created": 1775401200, + "started": 1775401203, + "completed": null, + "queue_position": 0, + "result": null, + "error": null +} +``` + +Keep polling `GET /sdcpp/v1/jobs/{id}` (`cancel_requested` stays visible while the job is generating) or send the +same request again: repeating it is harmless. Typical status codes: -- `200 OK` +- `200 OK`: the job is in a final state (the answer carries it) +- `202 Accepted`: the stop was requested and the job had not ended yet +- `400 Bad Request`: invalid `wait` - `404 Not Found` -- `409 Conflict` +- `409 Conflict`: only for a queued job that left the queue at the very moment of the request; ask again - `410 Gone` +Notes: + +- A generation stops at its next check: at the end of the sampling step it is in, and between the stages around it + (encoding the prompt, decoding the image, a second pass). On a slow machine one step can take seconds, and the + first generation after the start can spend a long time reading the weights before it reaches a check, so the stop + may need longer than `wait`. That is what the `202` is for. +- If the job finishes before the stop takes effect, the answer is the finished job: `200` with + `status: "completed"` and its result. +- A stopped job returns no images, not even the ones of a batch that were already done. +- A stop is not a failure. The model is not loaded again, the server does not step down to a lighter profile, nothing + is recorded in `last_error`, and [`GET /sdcpp/v1/health`](#get-sdcppv1health) counts it in `counters.cancelled`. + The next job runs on the same context. +- Only the jobs of this API can be stopped. The synchronous endpoints (`/sdapi/...`, `/v1/images/...`) are not jobs: + a request that is waiting for the model behind a job that gets cancelled simply runs afterwards, as usual. +- The call keeps its HTTP connection open for up to `wait` seconds. + ### Request Body Example: @@ -1193,7 +1274,7 @@ A job that failed for lack of memory has already been tried on every lighter pro ### Cancelled Result -Example cancelled job: +Example cancelled job (it was still waiting in the queue; a job stopped while it was generating has `started` set): ```json { @@ -1608,7 +1689,7 @@ Example failed job: ### Cancelled Result -Example cancelled job: +Example cancelled job (it was still waiting in the queue; a job stopped while it was generating has `started` set): ```json {