Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(queue): answer a remote profile's upstream refusal at once with its wait (#570)

Krisztian Gajdar22aa8250d41a
diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.md
index f13db0193..ebb9eed98 100644
--- a/packages/sie_gateway/README.md
+++ b/packages/sie_gateway/README.md
@@ -170,7 +170,7 @@ Common behaviors:
- `503` + `Retry-After` for no-consumer or backpressure publish failures
- `504` + `X-SIE-Error-Code: GATEWAY_TIMEOUT` + `Retry-After: 5` on non-generation queue routes when a queued request was published but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`. Generation routes use their own streaming/direct-dispatch timeout contract. Worker-emitted `MODEL_LOADING` remains a separate retryable `503 MODEL_LOADING` signal.
- `X-SIE-Served-By` (`local` or `remote`) on every successful response and every `5xx`, once the request has resolved to a model and profile, and `X-SIE-Upstream` with the upstream's name when that profile is remote. The value comes from the dispatched profile's configuration, as on the single server: a profile whose adapter is a remote adapter is served remotely. Client errors carry neither header. The OpenAI-compatible routes forward both from the native route they wrap.
-- When every item in a batch fails with the same retryable code (`RESOURCE_EXHAUSTED`, `MODEL_LOADING`, `LORA_LOADING`, or `QUEUE_FULL`), the gateway returns `503` with `X-SIE-Error-Code: <retryable code>` and `Retry-After`. For `RESOURCE_EXHAUSTED` and `QUEUE_FULL`, it uses the longest worker hint that is an integer in `1..=60` seconds; other hints are ignored. If none qualify, or the code is `MODEL_LOADING` or `LORA_LOADING` even when a worker provides a hint, it uses a five-second default compiled into the gateway. The SDK auto-retries with bounded exponential backoff. Mixed batches keep returning `500 all_items_failed` with per-item `code` fields in the response body so callers can see which items hit which failure mode.
+- When every item in a batch fails with the same retryable code (`RESOURCE_EXHAUSTED`, `MODEL_LOADING`, `LORA_LOADING`, or `QUEUE_FULL`), the gateway returns `503` with `X-SIE-Error-Code: <retryable code>` and `Retry-After`. For `RESOURCE_EXHAUSTED`, `QUEUE_FULL` and `MODEL_LOADING`, it uses the longest worker hint that is an integer in `1..=60` seconds; other hints are ignored. If none qualify, or the code is `LORA_LOADING` even when a worker provides a hint, it uses a five-second default compiled into the gateway. The SDK auto-retries with bounded exponential backoff. Mixed batches keep returning `500 all_items_failed` with per-item `code` fields in the response body so callers can see which items hit which failure mode.
The same gateway-owned OpenAPI contract is available at runtime via `GET /openapi.json` and as a committed static artifact at `packages/sie_gateway/openapi.json`. Regenerate it with `mise run openapi` before committing API-surface changes.
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index ce9e761f3..6320e3ca6 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -62,7 +62,7 @@ Rules enforced on the inference path:
- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.
- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (`Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`. Backpressure is evaluated twice: pool-wide against the `WORK_POOL_{pool}` stream's pending count (`SIE_GATEWAY_MAX_STREAM_PENDING`), and per lane (`pool`/`machine_profile`/`bundle`) against a gateway-local in-flight work-item count (`SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS`). The per-lane decision is always computed and recorded on `sie.gateway.queue.lane_admission.decisions`, but it only sheds when `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` is set; with the flag off (the default) the pool-wide check is the sole gate. Both sheds produce the same `503` contract and both record pending demand for the exact physical lane so KEDA scales it.
- On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` signal.
-- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED`, `MODEL_LOADING`, `LORA_LOADING`, and `QUEUE_FULL` (a worker that cannot serve the item now, such as a remote profile whose upstream is busy, unreachable or rate capped). Generation workers attach the operator's validated `oom_recovery.retry_after_s` value to a `RESOURCE_EXHAUSTED` terminal chunk, and a worker may set `WorkResult.retry_after_s` on a failed item; for `RESOURCE_EXHAUSTED` and `QUEUE_FULL` batch failures, the gateway uses the longest worker hint that qualifies as an integer in `1..=60` seconds, ignoring other hints. If no hint qualifies, or the code is `MODEL_LOADING` or `LORA_LOADING` even when a worker provides a hint, it uses the current five-second default compiled into the gateway. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.
+- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED`, `MODEL_LOADING`, `LORA_LOADING`, and `QUEUE_FULL` (a worker that cannot serve the item now, such as a remote profile whose upstream is busy, unreachable, rate capped or behind an open circuit breaker; a remote profile whose upstream model is not ready answers `MODEL_LOADING`). A remote worker answers these upstream refusals at once with the upstream's wait rather than redelivering the item. Generation workers attach the operator's validated `oom_recovery.retry_after_s` value to a `RESOURCE_EXHAUSTED` terminal chunk, and a worker may set `WorkResult.retry_after_s` on a failed item; for `RESOURCE_EXHAUSTED`, `QUEUE_FULL` and `MODEL_LOADING` failures, the gateway uses the longest worker hint that qualifies as an integer in `1..=60` seconds, ignoring other hints. If no hint qualifies, or the code is `LORA_LOADING` even when a worker provides a hint, it uses the current five-second default compiled into the gateway. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.
- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.
- Every successful response and every `5xx` of an inference route carries `X-SIE-Served-By` (`local` or `remote`) once routing has resolved the dispatched model, and `X-SIE-Upstream` with the upstream's name when that model's default profile uses a remote adapter (`handlers::serving_disclosure`). The value is read from the dispatched route's configuration, as `sie_server.api.helpers.serving_disclosure_headers` reads it on the single server, so a `model:remote` variant or a remote-backed model reports `remote` and the model's local profile reports `local`. Client errors carry neither header. The compatibility routes (`/v1/embeddings`, `/v1/rerank`, `/v2/rerank`, `/v1/audio/transcriptions`) forward both through `is_openai_compat_forwarded_header`.
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index b8beff535..cc60f4cb9 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -5218,7 +5218,7 @@ fn worker_error_retry_after(
QUEUE_FULL_ERROR_CODE,
)),
MODEL_LOADING_ERROR_CODE => Some((
- MODEL_LOADING_RETRY_AFTER.to_string(),
+ worker_hint().unwrap_or_else(|| MODEL_LOADING_RETRY_AFTER.to_string()),
MODEL_LOADING_ERROR_CODE,
)),
LORA_LOADING_ERROR_CODE => Some((
@@ -27201,6 +27201,29 @@ mod tests {
assert!(value["error"]["param"].is_null());
}
+ #[tokio::test]
+ async fn test_model_loading_uses_the_workers_retry_hint() {
+ for (retry_after_s, retry_after) in [(Some(7), "7"), (None, MODEL_LOADING_RETRY_AFTER)] {
+ let err = StreamingDriverErr::WorkerError {
+ code: MODEL_LOADING_ERROR_CODE.to_string(),
+ message: "the upstream is not ready, please retry".to_string(),
+ param: None,
+ retry_after_s,
+ request_id: "req-loading".to_string(),
+ attempt_id: "att-loading".to_string(),
+ };
+
+ let response = build_streaming_error_response(&err);
+
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(response.headers().get("retry-after").unwrap(), retry_after);
+ assert_eq!(
+ response.headers().get("x-sie-error-code").unwrap(),
+ MODEL_LOADING_ERROR_CODE
+ );
+ }
+ }
+
/// HTTP status mapping unit test — guards against an off-by-one
/// edit that drops the 429 mapping without touching
/// ``build_streaming_error_response``.
@@ -27283,9 +27306,13 @@ mod tests {
);
assert_eq!(
worker_error_retry_after(MODEL_LOADING_ERROR_CODE, Some(12)),
+ Some(("12".to_string(), MODEL_LOADING_ERROR_CODE))
+ );
+ assert_eq!(
+ worker_error_retry_after(LORA_LOADING_ERROR_CODE, Some(12)),
Some((
- MODEL_LOADING_RETRY_AFTER.to_string(),
- MODEL_LOADING_ERROR_CODE
+ LORA_LOADING_RETRY_AFTER.to_string(),
+ LORA_LOADING_ERROR_CODE
)),
"only the codes that take a worker hint use it"
);
@@ -27311,6 +27338,13 @@ mod tests {
RESOURCE_EXHAUSTED_ERROR_CODE
))
);
+ assert_eq!(
+ worker_error_retry_after(MODEL_LOADING_ERROR_CODE, Some(invalid)),
+ Some((
+ MODEL_LOADING_RETRY_AFTER.to_string(),
+ MODEL_LOADING_ERROR_CODE
+ ))
+ );
}
}
diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rs
index c89019112..f98fde9d5 100644
--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs
+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs
@@ -1716,6 +1716,54 @@ mod tests {
assert_eq!(stamped(&response), (Some("remote"), Some("team-sie")));
}
+ #[tokio::test]
+ async fn a_remote_only_request_its_upstream_cannot_serve_now_answers_503_with_the_wait() {
+ for (code, retry_after_s, retry_after) in [
+ ("QUEUE_FULL", Some(9), "9"),
+ ("MODEL_LOADING", Some(7), "7"),
+ ("QUEUE_FULL", None, "5"),
+ ("MODEL_LOADING", None, "5"),
+ ] {
+ let gateway = TestGateway::new(&[REMOTE_ENCODE_MODEL]).await;
+ gateway.add_worker("remote-1", REMOTE_LANE, &[]).await;
+ gateway.dispatcher.refuse_remote_work(code, retry_after_s);
+ let native = proxy_request(
+ State(Arc::clone(&gateway.state)),
+ json_request(
+ "/v1/encode/acme/remote",
+ json!({"items": [{"text": "hello"}]}),
+ ),
+ "encode",
+ )
+ .await;
+ let embeddings = proxy_openai_embeddings(
+ State(Arc::clone(&gateway.state)),
+ json_request(
+ "/v1/embeddings",
+ json!({"model": "acme/remote", "input": "hello"}),
+ ),
+ )
+ .await;
+ for response in [&native, &embeddings] {
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{code}");
+ assert_eq!(response.headers()["retry-after"], retry_after, "{code}");
+ assert_eq!(response.headers()["x-sie-error-code"], code);
+ assert_eq!(stamped(response), (Some("remote"), Some("team-sie")));
+ }
+ let body: serde_json::Value = serde_json::from_slice(
+ &axum::body::to_bytes(native.into_body(), 8192)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(body["error"]["code"], code);
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ vec![dispatched("encode", REMOTE_LANE, "acme/remote"); 2]
+ );
+ }
+ }
+
#[tokio::test]
async fn generation_routes_name_the_profile_they_dispatch_to() {
let gateway = gateway().await;
diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rs
index 6387325c5..4612fd307 100644
--- a/packages/sie_gateway/src/handlers/test_support.rs
+++ b/packages/sie_gateway/src/handlers/test_support.rs
@@ -161,11 +161,18 @@ pub(crate) struct RecordingDispatcher {
stream_error: AtomicBool,
stream_mid_error: AtomicBool,
stream_terminal_failure: Mutex<Option<&'static str>>,
+ remote_refusal: Mutex<Option<(&'static str, Option<u32>)>>,
dispatched: Mutex<Vec<Dispatched>>,
execution_authority: Mutex<Vec<bool>>,
}
impl RecordingDispatcher {
+ /// Answer remote-lane work as a remote worker does when its upstream cannot
+ /// serve now: a published `code` error with the upstream's wait, if any.
+ pub(crate) fn refuse_remote_work(&self, code: &'static str, retry_after_s: Option<u32>) {
+ *self.remote_refusal.lock().unwrap() = Some((code, retry_after_s));
+ }
+
pub(crate) fn dispatched(&self) -> Vec<Dispatched> {
self.dispatched.lock().unwrap().clone()
}
@@ -237,6 +244,23 @@ fn successful_result(request_id: &str, item_index: u32, payload: serde_json::Val
result
}
+fn refused_result(
+ request_id: &str,
+ item_index: u32,
+ (code, retry_after_s): (&str, Option<u32>),
+) -> WorkResult {
+ serde_json::from_value(json!({
+ "work_item_id": format!("{request_id}.{item_index}"),
+ "request_id": request_id,
+ "item_index": item_index,
+ "success": false,
+ "error": "The upstream serving the model is busy, please retry",
+ "error_code": code,
+ "retry_after_s": retry_after_s,
+ }))
+ .unwrap()
+}
+
fn terminal_chunk_collector(
display_model: &str,
bundle_config_hash: &str,
@@ -337,7 +361,14 @@ impl WorkDispatcher for RecordingDispatcher {
return Err(DispatchError::Other("private upstream failure".into()));
}
let request_id = "request-1".to_string();
- let results = if endpoint == "score" {
+ let remote_refusal = *self.remote_refusal.lock().unwrap();
+ let results = if let Some(refusal) =
+ remote_refusal.filter(|_| target.bundle() == REMOTE_LANE.2)
+ {
+ (0..items.len().max(1) as u32)
+ .map(|index| refused_result(&request_id, index, refusal))
+ .collect()
+ } else if endpoint == "score" {
vec![successful_result(
&request_id,
0,
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index a55fc1518..51f338413 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -192,7 +192,9 @@ Each upstream has a required rate cap and a circuit breaker. The limits are
shared by that worker process's adapters, not across replicas: adding remote
worker replicas increases the aggregate permitted traffic. Under
`remote_only`, unavailable upstreams, open breakers and reached caps return
-retryable `503` responses. Under single-node `fallback`, an upstream failure
+retryable `503` responses with `Retry-After`. In a cluster the remote worker
+answers such a request at once instead of redelivering it, and the gateway
+returns the worker's code and wait. Under single-node `fallback`, an upstream failure
returns the original local refusal with its retry delay. A client error is
never retried remotely, and fallback cannot replay work after local acceptance
or after output reaches the caller.
diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.py
index 260c57272..0c687f950 100644
--- a/packages/sie_server/src/sie_server/queue_executor.py
+++ b/packages/sie_server/src/sie_server/queue_executor.py
@@ -104,7 +104,6 @@ _INFERENCE_ERROR_CODE: Final[str] = "inference_error"
# which under a systemic failure is also the correct answer, because every one
# of them was going to fail anyway.
_MAX_ENCODE_ISOLATION_PASSES: Final[int] = 24
-_UPSTREAM_NAK_MAX_DELAY_S: Final[float] = 60.0
_CANONICAL_AUDIO_SAMPLE_RATE: Final[int] = 16_000
_MAX_AUDIO_CHANNELS: Final[int] = 2
_MIN_AUDIO_SAMPLE_RATE: Final[int] = 8_000
@@ -2238,19 +2237,27 @@ def _oom_nak_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem) ->
)
-def _upstream_nak_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem, retry_after_s: int) -> ItemOutcome:
- # Never shorter than the base delay: a work item has a fixed number of
- # deliveries, and a one-second hint would spend them long before the
- # gateway stops waiting for the result.
- delay_s = min(_UPSTREAM_NAK_MAX_DELAY_S, max(_default_nak_delay_s(), float(retry_after_s)))
+def _upstream_refusal_outcome(
+ bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem, error: UpstreamUnavailableError
+) -> ItemOutcome:
+ """A retryable error with the upstream's wait for an item its upstream did not serve.
+
+ The code is the single server's (``api.helpers.upstream_unavailable_exception``):
+ ``MODEL_LOADING`` while the model is not ready upstream, ``QUEUE_FULL``
+ otherwise. The message is fixed text.
+ """
+ if error.kind == "not_ready":
+ code, message = ErrorCode.MODEL_LOADING, "The model is loading on its upstream, please retry"
+ else:
+ code, message = ErrorCode.QUEUE_FULL, f"The upstream serving the model is {error.kind}, please retry"
return ItemOutcome(
work_item_id=bi.work_item_id,
request_id=bi.request_id,
item_index=bi.item_index,
- disposition="nak_retry",
- nak_delay_ms=int(delay_s * 1000),
- error_code=ErrorCode.QUEUE_FULL.value,
- retry_after_s=retry_after_s,
+ disposition="publish_error_and_ack",
+ error=message,
+ error_code=code.value,
+ retry_after_s=error.retry_after_s,
)
@@ -2269,9 +2276,7 @@ def _inference_exception_outcome(
# against a future caller that submits through the queueing path.
return _nak_outcome(bi)
if isinstance(exc, UpstreamUnavailableError):
- # A remote profile's upstream did not serve the item, and asking again
- # later may succeed: redeliver instead of publishing a terminal error.
- return _upstream_nak_outcome(bi, exc.retry_after_s)
+ return _upstream_refusal_outcome(bi, exc)
if isinstance(exc, InputTooLongError):
# The input exceeds the model's window: INPUT_TOO_LONG (HTTP 400), as
# the HTTP path reports it, not a server-side inference failure.
diff --git a/packages/sie_server/tests/adapters/test_remote_upstream_failures.py b/packages/sie_server/tests/adapters/test_remote_upstream_failures.py
index be2adacd5..717caae32 100644
--- a/packages/sie_server/tests/adapters/test_remote_upstream_failures.py
+++ b/packages/sie_server/tests/adapters/test_remote_upstream_failures.py
@@ -1,8 +1,9 @@
"""What the caller sees when an SIE upstream cannot serve a request yet.
Every upstream here is a real SIE app on loopback. Its fake model is held in its
-load, fails to load, or is never reached, so the local server answers through
-the real error path on both ingress paths: single-node HTTP and the queue worker.
+load, fails to load, or is never reached, or the local rate cap or circuit
+breaker refuses the call, so the local server answers through the real error
+path on both ingress paths: single-node HTTP and the queue worker.
"""
from __future__ import annotations
@@ -22,7 +23,8 @@ import numpy as np
import pytest
from fastapi.testclient import TestClient
from sie_sdk import SIEClient
-from sie_server.adapters.errors import UpstreamUnavailableError
+from sie_server.adapters.errors import UpstreamRefusedError, UpstreamUnavailableError
+from sie_server.api.helpers import upstream_unavailable_exception
from sie_server.config.upstreams import Upstream, install_upstreams
from sie_server.core.registry import ModelRegistry
from sie_server.ipc_types import EncodeBatchItem, ItemOutcome, ProcessEncodeBatchRequest
@@ -155,10 +157,13 @@ def test_an_upstream_that_cannot_load_the_model_is_a_final_error(
assert "retry-after" not in response.headers
+RETRYABLE_CODES = ("QUEUE_FULL", "MODEL_LOADING")
+
+
async def queue_outcome(
registry: ModelRegistry, text: str = "cold", *, attempts: int = 1, interval_s: float = 0.0
) -> ItemOutcome:
- """Process one encode work item, again while it is NAKed, up to ``attempts`` times."""
+ """Process one encode work item, again while it is refused as retryable, up to ``attempts`` times."""
executor = QueueExecutor(registry)
for attempt in range(attempts):
batch = await executor.process_encode_batch(
@@ -177,13 +182,15 @@ async def queue_outcome(
)
)
outcome = batch.outcomes[0]
- if outcome.disposition != "nak_retry":
+ if outcome.error_code not in RETRYABLE_CODES:
return outcome
await asyncio.sleep(interval_s)
return outcome
-async def queue_worker(tmp_path: Path, upstream_url: str, credential_env: str) -> ModelRegistry:
+async def queue_worker(
+ tmp_path: Path, upstream_url: str, credential_env: str, *, requests_per_minute: int = 600
+) -> ModelRegistry:
models = tmp_path / "queue-models"
models.mkdir()
(models / "remote-fake.yaml").write_text(
@@ -205,7 +212,7 @@ async def queue_worker(tmp_path: Path, upstream_url: str, credential_env: str) -
"kind": "sie",
"base_url": upstream_url,
"api_key_secret": credential_env,
- "rate_cap": {"requests_per_minute": 600, "max_concurrency": 8},
+ "rate_cap": {"requests_per_minute": requests_per_minute, "max_concurrency": 8},
}
)
}
@@ -215,7 +222,24 @@ async def queue_worker(tmp_path: Path, upstream_url: str, credential_env: str) -
return registry
-async def test_the_queue_worker_redelivers_an_item_its_cold_upstream_refused(
+def single_server_answer(error: UpstreamUnavailableError) -> tuple[int, str, str]:
+ """The status, code and ``Retry-After`` the single server answers ``error`` with."""
+ answer = upstream_unavailable_exception(error, REMOTE_MODEL)
+ assert isinstance(answer.detail, dict)
+ assert answer.headers is not None
+ return answer.status_code, answer.detail["code"], answer.headers["Retry-After"]
+
+
+def assert_answered_at_once(outcome: ItemOutcome, error: UpstreamUnavailableError) -> None:
+ """The queue worker publishes the single server's code and wait instead of redelivering."""
+ assert outcome.disposition == "publish_error_and_ack", outcome
+ assert outcome.nak_delay_ms is None
+ assert single_server_answer(error) == (503, outcome.error_code, str(outcome.retry_after_s))
+ assert outcome.error is not None
+ assert error.upstream not in outcome.error
+
+
+async def test_the_queue_worker_answers_an_item_its_cold_upstream_refused_at_once(
sie_upstream: Callable[..., Any], held_upstream_load: Path, tmp_path: Path, upstream_credential_env: str
) -> None:
with sie_upstream() as upstream:
@@ -227,28 +251,63 @@ async def test_the_queue_worker_redelivers_an_item_its_cold_upstream_refused(
finally:
await registry.unload_all_async()
- assert refused.disposition == "nak_retry"
- assert refused.nak_delay_ms == 5_000
- assert refused.error is None
- assert refused.error_code == "QUEUE_FULL"
- assert refused.retry_after_s == 5
+ assert_answered_at_once(refused, UpstreamUnavailableError("fake-sie", "not_ready", retry_after_s=5, reason=""))
+ assert (refused.error_code, refused.retry_after_s) == ("MODEL_LOADING", 5)
assert served.disposition == "publish_and_ack", served.error
-async def test_the_queue_worker_redelivers_an_item_its_unreachable_upstream_never_saw(
- tmp_path: Path, upstream_credential_env: str, monkeypatch: pytest.MonkeyPatch
+async def test_the_queue_worker_answers_an_item_its_unreachable_upstream_never_saw_at_once(
+ tmp_path: Path, upstream_credential_env: str
) -> None:
- monkeypatch.setenv("SIE_NAK_DELAY_S", "2.0")
registry = await queue_worker(tmp_path, f"http://127.0.0.1:{closed_port()}", upstream_credential_env)
try:
outcome = await queue_outcome(registry)
finally:
await registry.unload_all_async()
- assert outcome.disposition == "nak_retry"
- assert outcome.nak_delay_ms == 5_000, "the upstream's wait, which is longer than the base delay"
- assert outcome.error_code == "QUEUE_FULL"
- assert outcome.retry_after_s == 5
+ assert_answered_at_once(outcome, UpstreamUnavailableError("fake-sie", "unavailable", retry_after_s=5, reason=""))
+ assert (outcome.error_code, outcome.retry_after_s) == ("QUEUE_FULL", 5)
+
+
+async def test_the_queue_worker_answers_an_item_over_the_rate_cap_at_once(
+ sie_upstream: Callable[..., Any], tmp_path: Path, upstream_credential_env: str
+) -> None:
+ def warm(url: str) -> None:
+ with SIEClient(url) as direct:
+ direct.encode("sie-fake", {"text": "warm"})
+
+ with sie_upstream() as upstream:
+ await asyncio.to_thread(warm, upstream.url)
+ registry = await queue_worker(tmp_path, upstream.url, upstream_credential_env, requests_per_minute=1)
+ try:
+ served = await queue_outcome(registry, "first")
+ capped = await queue_outcome(registry, "second")
+ finally:
+ await registry.unload_all_async()
+
+ assert served.disposition == "publish_and_ack", served.error
+ assert capped.retry_after_s is not None
+ assert_answered_at_once(capped, UpstreamRefusedError("fake-sie", "rate_cap", retry_after_s=capped.retry_after_s))
+ assert capped.error_code == "QUEUE_FULL"
+ assert 1 <= capped.retry_after_s <= 60
+
+
+async def test_the_queue_worker_answers_an_item_its_open_breaker_refused_at_once(
+ tmp_path: Path, upstream_credential_env: str
+) -> None:
+ registry = await queue_worker(tmp_path, f"http://127.0.0.1:{closed_port()}", upstream_credential_env)
+ try:
+ failures = [await queue_outcome(registry) for _ in range(5)]
+ refused = await queue_outcome(registry)
+ finally:
+ await registry.unload_all_async()
+
+ assert {(outcome.error_code, outcome.retry_after_s) for outcome in failures} == {("QUEUE_FULL", 5)}
+ assert refused.retry_after_s is not None
+ assert_answered_at_once(
+ refused, UpstreamRefusedError("fake-sie", "breaker_open", retry_after_s=refused.retry_after_s)
+ )
+ assert (refused.error_code, refused.retry_after_s) == ("QUEUE_FULL", 60)
async def test_the_queue_worker_publishes_a_final_upstream_error(
@@ -273,18 +332,16 @@ def work_item() -> EncodeBatchItem:
)
- ("base_delay", "retry_after_s", "delay_ms"),
- [("5.0", 1, 5_000), ("5.0", 30, 30_000), ("2.0", 60, 60_000), ("120.0", 5, 60_000)],
- ids=["base-delay-is-the-floor", "upstream-wait-above-the-floor", "upstream-wait-at-the-cap", "capped-at-60-s"],
-)
-def test_the_redelivery_delay_is_the_upstream_wait_between_the_base_delay_and_a_minute(
- monkeypatch: pytest.MonkeyPatch, base_delay: str, retry_after_s: int, delay_ms: int
[email protected]("base_delay", ["2.0", "5.0", "120.0"])
[email protected]("retry_after_s", [1, 30, 60])
[email protected]("kind", ["busy", "unavailable", "not_ready"])
+def test_a_refused_item_carries_the_upstreams_own_wait_whatever_the_redelivery_delay(
+ monkeypatch: pytest.MonkeyPatch, base_delay: str, retry_after_s: int, kind: Any
) -> None:
monkeypatch.setenv("SIE_NAK_DELAY_S", base_delay)
- error = UpstreamUnavailableError("fake-sie", "busy", retry_after_s=retry_after_s, reason="answered 429")
+ error = UpstreamUnavailableError("fake-sie", kind, retry_after_s=retry_after_s, reason="answered 503")
outcome = _inference_exception_outcome(work_item(), error)
- assert outcome.disposition == "nak_retry"
- assert outcome.nak_delay_ms == delay_ms
+ assert_answered_at_once(outcome, error)
+ assert outcome.retry_after_s == retry_after_s
diff --git a/packages/sie_server/tests/adapters/test_remote_upstream_limits.py b/packages/sie_server/tests/adapters/test_remote_upstream_limits.py
index 60382c559..554718c77 100644
--- a/packages/sie_server/tests/adapters/test_remote_upstream_limits.py
+++ b/packages/sie_server/tests/adapters/test_remote_upstream_limits.py
@@ -567,14 +567,15 @@ def test_a_refusal_is_a_retryable_503_with_its_retry_after_and_the_disclosure_he
@pytest.mark.parametrize("refusal", ["rate_cap", "concurrency_cap", "breaker_open"])
-def test_the_queue_path_redelivers_a_refused_item_after_the_wait(refusal: str) -> None:
+def test_the_queue_path_answers_a_refused_item_at_once_with_the_wait(refusal: str) -> None:
item = EncodeBatchItem(
work_item_id="w.0", request_id="w", item_index=0, total_items=1, timestamp=0.0, item={"text": "a"}
)
outcome = _inference_exception_outcome(item, UpstreamRefusedError(UPSTREAM, refusal, retry_after_s=40)) # type: ignore[arg-type]
- assert (outcome.disposition, outcome.nak_delay_ms, outcome.error) == ("nak_retry", 40_000, None)
+ assert (outcome.disposition, outcome.nak_delay_ms) == ("publish_error_and_ack", None)
+ assert (outcome.error_code, outcome.retry_after_s) == ("QUEUE_FULL", 40)
@pytest.mark.parametrize("reason", ["rate_cap", "concurrency_cap", "breaker_open", "half_open", "probe_active"])
diff --git a/packages/sie_server/tests/test_remote_queue_path.py b/packages/sie_server/tests/test_remote_queue_path.py
index 9bb6edff8..d3630d13e 100644
--- a/packages/sie_server/tests/test_remote_queue_path.py
+++ b/packages/sie_server/tests/test_remote_queue_path.py
@@ -167,8 +167,10 @@ async def test_a_remote_lane_worker_serves_a_remote_backed_model_through_the_que
assert seen_authorization == [f"Bearer {CANARY}"]
[email protected]("kind", ["busy", "unavailable", "not_ready"])
-def test_remote_refusal_preserves_retry_hint_on_the_ipc_wire(kind: Any) -> None:
+ ("kind", "code"), [("busy", "QUEUE_FULL"), ("unavailable", "QUEUE_FULL"), ("not_ready", "MODEL_LOADING")]
+)
+def test_remote_refusal_preserves_retry_hint_on_the_ipc_wire(kind: Any, code: str) -> None:
item = EncodeBatchItem(
work_item_id="req.0",
request_id="req",
@@ -181,9 +183,9 @@ def test_remote_refusal_preserves_retry_hint_on_the_ipc_wire(kind: Any) -> None:
item, UpstreamUnavailableError("fake-sie", kind, retry_after_s=9, reason="unavailable")
)
decoded = msgspec.msgpack.decode(msgspec.msgpack.encode(outcome), type=ItemOutcome)
- assert decoded.disposition == "nak_retry"
- assert decoded.error_code == "QUEUE_FULL"
+ assert decoded.disposition == "publish_error_and_ack"
+ assert decoded.error_code == code
assert decoded.retry_after_s == 9
- assert decoded.nak_delay_ms is not None
- assert decoded.nak_delay_ms >= 9_000
- assert decoded.error is None
+ assert decoded.nak_delay_ms is None
+ assert decoded.error is not None
+ assert "fake-sie" not in decoded.error
diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.md
index 605a8dcdd..a3e047724 100644
--- a/packages/sie_server_sidecar/docs/architecture-guide.md
+++ b/packages/sie_server_sidecar/docs/architecture-guide.md
@@ -83,8 +83,9 @@ Message settlement:
config/readiness barriers and failed result publication retain their existing
retry behavior; this does not yet provide the full cluster fallback contract.
- An outcome's optional `retry_after_s` is published on the `WorkResult`
- unchanged; the gateway uses it as `Retry-After` for a `QUEUE_FULL` or
- `RESOURCE_EXHAUSTED` answer.
+ unchanged. For a `QUEUE_FULL`, `MODEL_LOADING` or `RESOURCE_EXHAUSTED`
+ answer the gateway uses a hint of 1 to 60 seconds as `Retry-After`; without
+ one, or with a hint outside that range, it uses five seconds.
- Active local model loads are held with JetStream progress ACKs until
`EnsureModelReady` returns ready; this preserves the delivery budget during
cold starts. The progress delay is clamped below the pool consumer `ack_wait`