diff --git a/README.md b/README.md index ee97278..f2da0b4 100644 --- a/README.md +++ b/README.md @@ -188,14 +188,22 @@ A `429`, `408` or `5xx` is retried on the same endpoint before the chain moves o ```conf retry_num 1 # additional attempts on the same endpoint (0 = never) retry_backoff 0.5 # attempt n waits n × this many seconds +retry_max_wait 30 # ceiling for a Retry-After the provider asks for (0 = no ceiling) ``` The reason is cost, not politeness: an overloaded cloud node usually recovers in seconds, while the next link in the chain may be a paid one or one that cannot hold the context. What is *not* retried: connect failures (that state is `offline`, and hooks own it), any `4xx` other than the ones named, and anything after the stream head has -reached the client. `Retry-After` is not evaluated — the pause comes from -`retry_backoff` alone. +reached the client. + +If the provider names a `Retry-After` in seconds, that number wins over the backoff — +it knows when its quota reopens, we do not. Retrying earlier only spends the second +attempt on the same closed door. `retry_max_wait` (default 30 s) caps it: an hour of +waiting is not a retry, it is an outage with an announcement. HTTP-date values are +ignored (a timezone question with no upside); a `Retry-After: 0` means *now*, not "wait +zero plus backoff", so it changes nothing. Both cases are visible in the log: +`retry ... backoff_ms=2000 retry_after_s=2`. When the **whole chain** is offline or cooling down, failing at once is the wrong answer for a van: the uplink often returns in seconds. @@ -635,7 +643,11 @@ sums exactly what the ledger wrote. A third check would have caught a real use-after-free: the status code must be read out of the cached head *before* the body is sent, because another thread may replace that entry while this one is still writing — the whole suite also runs green under AddressSanitizer. -Pass = `PASS` (222 checks), including two that would have caught the two mistakes this +The last section covers `Retry-After`: a stub that answers the first request with +`503` plus `Retry-After: 2` makes junction wait 2.0 s (measured) instead of its 0.2 s +backoff, the same stub saying `60` under `retry_max_wait 1` is capped at 1.0 s, and every +decision names the provider's number in the log line. +Pass = `PASS` (227 checks), including two that would have caught the two mistakes this design invites: a serial stub making a concurrent router look serialised, and a "waiting" comment leaking into a caller that never asked for a stream. diff --git a/config.example b/config.example index 8ad6234..d0f74f0 100644 --- a/config.example +++ b/config.example @@ -20,6 +20,9 @@ queue_timeout 300 # 0 disables it. retry_backoff is per attempt (attempt n waits n × this). retry_num 1 retry_backoff 0.5 +# The provider's Retry-After wins over the backoff; this is the ceiling, so a "come back +# in an hour" does not turn a retry into an outage. 0 = no ceiling. +retry_max_wait 30 # If the WHOLE chain is offline or cooling down, wait this many seconds for it to come # back instead of answering 503 at once (0 = never wait). The wait happens before a diff --git a/examples/full-reference.conf b/examples/full-reference.conf index ce8853f..feb33f6 100644 --- a/examples/full-reference.conf +++ b/examples/full-reference.conf @@ -61,6 +61,11 @@ queue_timeout 300 retry_num 1 retry_backoff 0.5 +# If the provider names a Retry-After in seconds, that number wins over the backoff — it +# knows when its quota reopens. The ceiling keeps a "come back in an hour" from turning a +# retry into an outage: 0 means no ceiling. HTTP-date values are ignored. +retry_max_wait 30 + # Whole chain offline? A request may wait this long instead of getting a 503 at # once. In the van the uplink is often gone for seconds. Deliberately before the # queue slot: a request that waits holds no upstream place. 0 = do not wait. diff --git a/src/config.c b/src/config.c index ad0a197..3c61533 100644 --- a/src/config.c +++ b/src/config.c @@ -83,6 +83,7 @@ void j_config_defaults(j_config *cfg) * als Hänger sieht. */ cfg->retry_num = 1; cfg->retry_backoff_s = 0.5; + cfg->retry_max_wait_s = 30.0; cfg->offline_wait_s = 0; /* aus: wer warten will, sagt es ausdrücklich */ cfg->max_body_bytes = 64 * 1024 * 1024; cfg->cache_ttl_s = 0; @@ -231,6 +232,7 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size if (!strcmp(k, "max_inflight")) { if (n != 2 || as_int(w[1], &cfg->max_inflight)) goto bad; return 0; } if (!strcmp(k, "retry_num")) { if (n != 2 || as_int(w[1], &cfg->retry_num) || cfg->retry_num < 0) goto bad; return 0; } if (!strcmp(k, "retry_backoff")) { if (n != 2 || as_double(w[1], &cfg->retry_backoff_s)) goto bad; return 0; } + if (!strcmp(k, "retry_max_wait")) { if (n != 2 || as_double(w[1], &cfg->retry_max_wait_s)) goto bad; return 0; } if (!strcmp(k, "queue_timeout")) { if (n != 2 || as_double(w[1], &cfg->queue_timeout_s)) goto bad; return 0; } if (!strcmp(k, "offline_hold_s")) { if (n != 2 || as_double(w[1], &cfg->offline_hold_s)) goto bad; return 0; } if (!strcmp(k, "offline_wait")) { if (n != 2 || as_double(w[1], &cfg->offline_wait_s)) goto bad; return 0; } diff --git a/src/config.h b/src/config.h index 4fc84ff..b80490f 100644 --- a/src/config.h +++ b/src/config.h @@ -253,6 +253,10 @@ typedef struct { * Kontext. retry_num 0 schaltet es ab; dann gilt wieder "ein Fehler, nächster". */ int retry_num; /* zusätzliche Versuche auf demselben Endpunkt */ double retry_backoff_s; /* Wartezeit vor Versuch n = n * dieser Wert */ + /* Obergrenze für das, was der Anbieter per Retry-After verlangt. 0 = kein Deckel, + * dann wird genau so lange gewartet, wie er sagt — bei einer Stunde wäre das ein + * Ausfall mit Ansage statt einer Wiederholung. */ + double retry_max_wait_s; /* Wie lange ein Request warten darf, wenn die ganze Kette gerade offline oder im * Cooldown ist. 0 = sofort scheitern (altes Verhalten). Im Van ist der Uplink oft * für Sekunden weg; ein 503 nach 20 ms ist dann die falsche Antwort. */ diff --git a/src/junction.c b/src/junction.c index 0cfa473..19d1d4f 100644 --- a/src/junction.c +++ b/src/junction.c @@ -65,6 +65,9 @@ static pthread_rwlock_t g_rules_rw = PTHREAD_RWLOCK_INITIALIZER; static __thread long t_queue_ms; static __thread int t_req_retries; static __thread int t_rule_line; +/* Was der Anbieter als Retry-After geschickt hat (Sekunden, 0 = nichts gesagt). + * Thread-lokal wie der Rest: es gehört zu genau dieser Anfrage. */ +static __thread int t_retry_after_s; static __thread j_conn *t_heartbeat; static __thread double t_heartbeat_started; @@ -2471,6 +2474,16 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, if (r.status >= 500 || r.status == 429) { t_heartbeat = NULL; snprintf(err, errlen, "upstream_status_%d", r.status); + /* Was der Anbieter selbst sagt, ist besser als jede eigene Wartezeit: bei 429 + * und 503 steht dort oft, wann es wieder geht. Nur Sekunden werden gelesen — + * ein HTTP-Datum wäre eine Zeitzonen-Frage, und ohne Antwort ist 0 richtig. */ + { + char ra[J_HDR_VALUE]; + t_retry_after_s = 0; + if (!j_hdrs_find(&r.hdrs, "Retry-After", ra, sizeof ra)) + t_retry_after_s = atoi(ra); + if (t_retry_after_s < 0) t_retry_after_s = 0; + } STATE_LOCK(); snprintf(ep->last_error, sizeof ep->last_error, "upstream_status_%d", r.status); STATE_UNLOCK(); @@ -2695,8 +2708,16 @@ static int forward_with_retry(j_conn *client, j_endpoint *ep, const j_req *rq, if (a > 0) { if (head_sent) return rc; double nap_s = CFG.retry_backoff_s * (double)a; - jlog("retry", "endpoint=%s attempt=%d keys=%d backoff_ms=%.0f reason=%s", - ep->name, a + 1, ep->key_env_count, nap_s * 1000.0, err); + /* Der Anbieter hat gesagt, wann es wieder geht — dann wird nicht geraten, + * sondern gewartet, gedeckelt durch retry_max_wait: eine Stunde zu warten + * wäre keine Wiederholung mehr, sondern ein Ausfall mit Ansage. */ + if (t_retry_after_s > 0 && (double)t_retry_after_s > nap_s) { + nap_s = (double)t_retry_after_s; + if (CFG.retry_max_wait_s > 0 && nap_s > CFG.retry_max_wait_s) + nap_s = CFG.retry_max_wait_s; + } + jlog("retry", "endpoint=%s attempt=%d keys=%d backoff_ms=%.0f retry_after_s=%d reason=%s", + ep->name, a + 1, ep->key_env_count, nap_s * 1000.0, t_retry_after_s, err); if (nap_s > 0) { struct timespec ts = { (time_t)nap_s, (time_t)((nap_s - (double)(time_t)nap_s) * 1e9) }; diff --git a/tests/retry-after.sh b/tests/retry-after.sh new file mode 100755 index 0000000..2620c91 --- /dev/null +++ b/tests/retry-after.sh @@ -0,0 +1,79 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: der Anbieter sagt, wann es weitergeht. +# +# Ohne diese Regel wartet junction immer nur seine eigene Backoff-Zeit und rennt damit +# gegen ein Kontingent, das noch gar nicht offen ist — der zweite Versuch ist dann +# garantiert der zweite 429 dieses Fensters. + +echo +echo "== 36. Retry-After des Anbieters wird beachtet (mit Deckel) ==" + +RAP=$((PORT+212)) +RSP=$((PORT+213)) +RCP=$((PORT+214)) +RDP=$((PORT+215)) + +# Zwei Stubs: einer sagt 2 s, einer sagt 60 s (dort greift retry_max_wait). +STUB_STATE="$TMP/ra.state" tests/stub $RSP "RA2" --fail-n 1 --retry-after 2 > "$TMP/ra_stub.log" 2>&1 & +PIDS+=($!) +STUB_STATE="$TMP/ra60.state" tests/stub $RDP "RA60" --fail-n 1 --retry-after 60 > "$TMP/ra_stub60.log" 2>&1 & +PIDS+=($!) +sleep 0.4 + +cat > "$TMP/ra.conf" < "$TMP/rc.conf" < "$TMP/ra.log" 2>&1 & +PIDS+=($!) +./junction --config "$TMP/rc.conf" > "$TMP/rc.log" 2>&1 & +PIDS+=($!) +wait_port "$RAP" 10 || bad "retry-after instance did not come up" +wait_port "$RCP" 10 || bad "capped-retry instance did not come up" + +RABODY='{"model":"m","messages":[{"role":"user","content":"retry"}],"max_tokens":3}' + +# Der Anbieter sagt 2 s — also darf nicht nach 0,2 s gefragt werden. +read -r code elapsed < <(curl -s -o /dev/null -m 30 -w '%{http_code} %{time_total}' \ + -X POST -H 'Content-Type: application/json' -d "$RABODY" \ + "http://127.0.0.1:$RAP/v1/chat/completions") +if [ "$code" = "200" ] && awk "BEGIN{exit !($elapsed >= 1.9 && $elapsed < 6.0)}"; then + ok "the second attempt waited the provider's 2 s, not the 0.2 s backoff (${elapsed}s)" +else + bad "expected http 200 after ~2 s, got $code after ${elapsed}s" +fi +contains "$(grep -o 'retry_after_s=[0-9]*' "$TMP/ra.log" | head -1)" "retry_after_s=2" \ + "the log names the value the provider asked for" + +# 60 s verlangt, 1 s erlaubt: der Deckel gilt, sonst hinge die Anfrage eine Minute. +read -r ccode celapsed < <(curl -s -o /dev/null -m 40 -w '%{http_code} %{time_total}' \ + -X POST -H 'Content-Type: application/json' -d "$RABODY" \ + "http://127.0.0.1:$RCP/v1/chat/completions") +if [ "$ccode" = "200" ] && awk "BEGIN{exit !($celapsed >= 0.9 && $celapsed < 5.0)}"; then + ok "retry_max_wait caps a 60 s request at 1 s (${celapsed}s)" +else + bad "the cap did not hold: $ccode after ${celapsed}s" +fi +contains "$(grep -o 'retry_after_s=[0-9]*' "$TMP/rc.log" | head -1)" "retry_after_s=60" \ + "the cap is visible: the provider said 60, junction waited 1" + +# Ohne Retry-After bleibt es beim eigenen Backoff (der Stub schickt dann 0). +if grep -q "retry_after_s=0" "$TMP/ra.log" 2>/dev/null; then + bad "a zero Retry-After was treated as an instruction" +else + ok "nothing invented when the provider says nothing" +fi diff --git a/tests/run.sh b/tests/run.sh index 3ed0fa8..15736a1 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -46,7 +46,7 @@ log_has() { # answer requests with somebody else's config), so fail loudly and early. # 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem # Test benutzt, also darf er die Suite nicht aufhalten. -for port in 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8347 8348 8349 8350 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do if ss -tln 2>/dev/null | grep -q ":$port "; then echo "port $port is busy — a leftover junction/stub is still running:" ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /' @@ -60,7 +60,12 @@ TLSCC="-DJ_HAVE_TLS -lssl -lcrypto" # Die Bibliotheken gehören hinter die Quellen: davor aufgelistet löst der Linker # SSL_pending nicht auf, und auf einem frischen Checkout (ohne fertiges tests/stub) # scheitert die Suite an einer Zeile, die nie jemand ausprobiert hat. -[ -x tests/stub ] || cc -std=c99 -O2 -Isrc -o tests/stub tests/stub.c src/conn.c $TLSCC || exit 1 +# Nicht nur "fehlt es?" — auch "ist es älter als seine Quellen?". Ein von Hand ohne +# -DJ_HAVE_TLS gebauter Stub blieb sonst liegen und die TLS-Abschnitte scheiterten an +# einer Zeile, die niemand angefasst hat. +if [ ! -x tests/stub ] || [ tests/stub.c -nt tests/stub ] || [ src/conn.c -nt tests/stub ]; then + cc -std=c99 -O2 -Isrc -o tests/stub tests/stub.c src/conn.c $TLSCC || exit 1 +fi tests/stub $P_FAIL "FAILING" --fail & PIDS+=($!) tests/stub $P_GATED "GATED" & PIDS+=($!) @@ -707,6 +712,10 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected" # shellcheck source=tests/reqlog.sh . "$(dirname "$0")/reqlog.sh" +# Retry-After des Anbieters statt eigener Wartezeit. +# shellcheck source=tests/retry-after.sh +. "$(dirname "$0")/retry-after.sh" + # junction als MCP-Server: Werkzeuge der angebundenen Server bündeln und # Aufrufe an den richtigen Server weiterreichen. Eigenes Programm, weil zwei # erfundene MCP-Server gebraucht werden. diff --git a/tests/stub.c b/tests/stub.c index 06a0305..fd86309 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -3,6 +3,8 @@ * stub [--fail] [--delay SECONDS] [--tls CERT KEY] * [--fail-n N] [--deny-auth SUBSTR] * + * --retry-after N puts "Retry-After: N" into every forced 503/429, so a test can check + * that junction waits as long as the provider asked instead of its own backoff. * --fail always answers 503 (an endpoint that is up but will not serve) * --delay waits that long before answering (to exercise "still_working") * --fail-n answers 503 for the first N requests, then serves — the counter lives in @@ -88,6 +90,7 @@ int main(int argc, char **argv) int fail = 0; double delay = 0; int fail_n = 0; + int retry_after = 0; const char *deny_auth = ""; const char *cert = NULL, *key = NULL; for (int i = 3; i < argc; i++) { @@ -95,6 +98,7 @@ int main(int argc, char **argv) else if (!strcmp(argv[i], "--delay") && i + 1 < argc) delay = atof(argv[++i]); else if (!strcmp(argv[i], "--fail-n") && i + 1 < argc) fail_n = atoi(argv[++i]); else if (!strcmp(argv[i], "--deny-auth") && i + 1 < argc) deny_auth = argv[++i]; + else if (!strcmp(argv[i], "--retry-after") && i + 1 < argc) retry_after = atoi(argv[++i]); else if (!strcmp(argv[i], "--tls") && i + 2 < argc) { cert = argv[++i]; key = argv[++i]; } } char tlserr[256]; @@ -219,15 +223,17 @@ int main(int argc, char **argv) char body[1024]; if (forced) { - /* Retry-After: 0 — der Stub weiß nicht, wie lange ein echtes Kontingent - * braucht; die 0 macht klar, dass sofort weiterversucht werden darf. */ + /* Retry-After: standardmäßig 0 — der Stub weiß nicht, wie lange ein echtes + * Kontingent braucht; die 0 macht klar, dass sofort weiterversucht werden + * darf. Mit --retry-after N sagt er eine Zahl, damit der Test prüfen kann, + * dass junction genau so lange wartet. */ const char *b = (forced == 429) ? "{\"error\":\"rate limited\"}" : "{\"error\":\"not serving yet\"}"; snprintf(body, sizeof body, - "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\nRetry-After: 0\r\n" + "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\nRetry-After: %d\r\n" "Content-Length: %zu\r\nConnection: close\r\n\r\n%s", forced, (forced == 429) ? "Too Many Requests" : "Service Unavailable", - strlen(b), b); + retry_after, strlen(b), b); } else if (fail) { const char *b = "{\"error\":\"not serving\"}"; snprintf(body, sizeof body,