test: check that cancel answers a POST without Content-Length at once

Python clients add Content-Length: 0 to a POST without a body, so they
never met the 5-second wait of the HTTP library; `curl -X POST` does. The
end-to-end test of the cancel route now also sends the request the way
curl does, written on a socket, once with ?wait=0 to a job that is
generating and once to a job that has completed, and requires the answer
in less than 2 seconds.

Against the previous route the answer took 5.10 s, so the new checks fail
on the code they are meant to guard. Against the fixed route all 32 checks
pass on a CPU build with a synthetic model.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
This commit is contained in:
Claude 2026-10-14 22:15:52 +02:00
parent 8b6acc9316
commit 025124e655
No known key found for this signature in database
2 changed files with 36 additions and 3 deletions

View file

@ -14,7 +14,7 @@ sezione "Sicurezza".
| `profile_test.cpp` | profili di risorse (`--profile`): scelta automatica da dimensione del modello e memoria (anche sommando la memoria di più GPU), ordine dei livelli, opzioni esplicite che vincono sul profilo | vedi intestazione del file |
| `backend_fit_plan_test.cpp` | pianificatore multi-GPU dell'auto-fit (`--multi-gpu auto\|on\|off`) con GPU simulate: quale modulo va su quale GPU, quando il modello si divide per blocchi, nessun device riceve più pesi del suo budget, i moduli assegnati dall'utente non si muovono (include `src/core/backend_fit.cpp`, quindi serve la libreria compilata; nessuna GPU né modello) | 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. Annullamento di una generazione in corso: lo stop raggiunge solo il job che lo ha chiesto, un job annullato prima di partire non genera nulla, non costa nessuna ricarica del modello e non conta come errore. Non serve nessun modello: libreria e orologio sono simulati (con ASan/UBSan e TSan) | vedi intestazione del file |
| `server_cancel_e2e.py` | annullamento di un job in corso su un vero `sd-server` (serve un modello qualsiasi, su qualunque backend): job fermato, richiesta ripetuta, job in coda, `?wait=0`, richiesta sincrona in attesa che poi completa, job già finito, id sconosciuto, `wait` non valido, contatori di `/sdcpp/v1/health` e log senza righe di errore | `python3 test/server_cancel_e2e.py --server build/bin/sd-server --model <modello>` |
| `server_cancel_e2e.py` | annullamento di un job in corso su un vero `sd-server` (serve un modello qualsiasi, su qualunque backend): job fermato, richiesta ripetuta, job in coda, `?wait=0`, POST senza corpo né `Content-Length` (come `curl -X POST`: risposta subito, non dopo 5 secondi), richiesta sincrona in attesa che poi completa, job già finito, id sconosciuto, `wait` non valido, contatori di `/sdcpp/v1/health` e log senza righe di errore | `python3 test/server_cancel_e2e.py --server build/bin/sd-server --model <modello>` |
| `fuzz_model_loader.py` | fuzzing a mutazione del caricamento modelli (safetensors/GGUF) | `python3 test/fuzz_model_loader.py <sd-cli> --seconds 300` |
Per il fuzzing è consigliata una build con AddressSanitizer:

View file

@ -25,6 +25,7 @@ import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
failures = 0
@ -128,6 +129,34 @@ def wait_ready(client, process, timeout):
raise Abort("the server was not ready after %d s" % timeout)
def post_without_length(base_url, path, api_key):
"""What `curl -X POST url` sends: a POST with neither a body nor a Content-Length header.
Python's own clients add Content-Length: 0, so this one is written on a socket. Returns the status, the
JSON body (None when it is not JSON) and the seconds the answer took."""
parsed = urllib.parse.urlparse(base_url)
request = "POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n" % (path, parsed.netloc)
if api_key:
request += "Authorization: Bearer %s\r\n" % api_key
request += "\r\n"
started = time.time()
data = b""
with socket.create_connection((parsed.hostname, parsed.port), timeout=60) as sock:
sock.sendall(request.encode())
while True:
chunk = sock.recv(65536)
if not chunk:
break
data += chunk
seconds = time.time() - started
head, _, payload = data.partition(b"\r\n\r\n")
try:
body = json.loads(payload.decode())
except ValueError:
body = None
return int(head.split(b" ", 2)[1]), body, seconds
def png_looks_valid(image_b64):
return isinstance(image_b64, str) and image_b64.startswith("iVBORw0KGgo")
@ -191,8 +220,9 @@ def run_scenarios(client, args, mark_log):
check(status == 200 and body["status"] == "cancelled" and body["started"] is None,
"a queued job is cancelled at once, without ever starting")
time.sleep(1.0)
status, body, seconds = client.call("POST", "/sdcpp/v1/jobs/%s/cancel?wait=0" % running)
check(status in (200, 202) and seconds < 2.0, "?wait=0 answers at once")
status, body, seconds = post_without_length(client.base_url, "/sdcpp/v1/jobs/%s/cancel?wait=0" % running, args.api_key)
check(status in (200, 202) and seconds < 2.0,
"?wait=0 answers at once, also to a POST with no body and no Content-Length (%.2f s)" % seconds)
if status == 202:
check(body.get("cancel_requested") is True, "and says the stop is pending")
check(client.job(running)["status"] in ("generating", "cancelled"),
@ -229,6 +259,9 @@ def run_scenarios(client, args, mark_log):
"cancelling a job that already completed leaves it completed")
status, body, _ = client.call("POST", "/sdcpp/v1/jobs/job_does_not_exist/cancel")
check(status == 404, "an unknown job is 404")
status, body, seconds = post_without_length(client.base_url, "/sdcpp/v1/jobs/%s/cancel" % job_id, args.api_key)
check(status == 200 and body is not None and body["status"] == "completed" and seconds < 2.0,
"a POST with no body and no Content-Length (what curl -X POST sends) is answered at once (%.2f s)" % seconds)
for wrong in ("abc", "-1", "1.5", ""):
status, body, _ = client.call("POST", "/sdcpp/v1/jobs/%s/cancel?wait=%s" % (job_id, wrong))
check(status == 400, "wait=%r is rejected with 400" % wrong)