Latenz als Histogramm statt als Mittelwert

/status und /metrics zeigten die letzte Dauer und einen Durchschnitt. Ein Durchschnitt
versteckt genau die Anfragen, die weh tun: ein Ziel, das 95 Prozent schnell und 5 Prozent
in einer Minute beantwortet, hat einen harmlosen Mittelwert. Jetzt zählt jeder Endpunkt
ein Histogramm mit festen Grenzen (0,1 s bis 60 s, plus +Inf) und exportiert es in
kumulativer Form, damit histogram_quantile je Ziel rechnet. /status nennt dazu p95_ms,
ausdrücklich als Obergrenze des Eimers, in dem die 95-Prozent-Marke liegt — und -1,
solange nichts gemessen wurde.

Neue Alarmregel JunctionEndpointSlowP95 (p95 über 20 s, 15 Minuten, nur bei Verkehr) in
packaging/prometheus-junction.yml; auf n95 geladen, health=ok.

Beim Testen einen Fehler gebaut und gefunden, der auf dem laufenden Router sofort
zugeschlagen hätte: die Histogramm-Ausgabe ließ die Zustandssperre gesperrt zurück. Der
ERSTE /metrics-Scrape ging noch durch, danach antwortete der ganze Prozess nicht mehr —
Prometheus scrapt alle 15 Sekunden, der Router wäre still gestorben. Gefunden, weil ich
den Ablauf Status → Scrape → Status → Anfrage einzeln durchgespielt habe, nicht weil die
Suite es gemerkt hätte (sie scrapt einmal). Jetzt steht die Sperre richtig und der Ablauf
ist auf n95 live geprüft: Scrape, Status, Chat, 20 Sekunden später wieder alles 200.

Tests: drei Prüfungen mehr — +Inf-Eimer gleich der Zahl bedienter Anfragen, Eimer
monoton, p95 im Status. make test: PASS, 232 Prüfungen, 160 s.
This commit is contained in:
Hermes committed 2026-11-08 13:21:45 +00:00
1 parent 6bb63268f1
commit db422ba36d
5 files changed
+118 -5

No files matched your search

+14 -2
View File
@@ -509,7 +509,15 @@ others still arrive. Nothing is invented to fill the gap.
| POST | `/admin/resume/<name>` | clear pause + cooldown + offline |
| POST | `/admin/flush/cache` | drop every cached response |
`/status` also reports the queue: `inflight`, `waiting`, `max_inflight`, `timeout_s`.
`/status` also reports the queue: `inflight`, `waiting`, `max_inflight`, `timeout_s`, and
per endpoint `last_ms` plus `p95_ms` — the latter computed from a histogram and therefore
an *upper bound* of the bucket the 95 % mark falls into, `-1` when nothing has been
measured yet.
`/metrics` exports that histogram (`junction_endpoint_latency_seconds_bucket{endpoint,
le}`, `_sum`, `_count`), so `histogram_quantile(0.95, …)` works per endpoint. An average
hides exactly the requests that hurt: an endpoint answering 95 % fast and 5 % of the time
in a minute keeps a harmless mean.
Everything else is proxied to the endpoint the rules choose.
@@ -653,7 +661,11 @@ backoff, the same stub saying `60` under `retry_max_wait 1` is capped at 1.0 s,
date two seconds ahead has the same effect as the number, a date two minutes in the past
means "now" (0.2 s, just the backoff), and every decision names the provider's number in
the log line.
Pass = `PASS` (229 checks), including two that would have caught the two mistakes this
The latency histogram is pinned too: the `+Inf` bucket must carry the same count as the
served requests, the buckets must be monotone (Prometheus computes quantiles from
cumulative buckets — non-monotone ones produce nonsense, not an error), and `/status`
must carry a `p95_ms`.
Pass = `PASS` (232 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.
+18
View File
@@ -80,3 +80,21 @@ groups:
summary: "an instance has been draining for 10 minutes"
description: "The listening socket is closed (no new requests) but the process has not exited. Either a request hangs longer than drain_timeout or the drain path itself is stuck; until it exits, a rolling update is only half done."
runbook: "curl -s localhost:8090/status | jq '.queue' — inflight tells whether requests are really running. journalctl -u junction | grep -E 'draining|drained|drain_timeout'."
# Latency as a percentile, not as the average: an endpoint that answers 95 % fast and
# 5 % of the time in a minute keeps a harmless mean. The histogram is per endpoint
# (junction_endpoint_latency_seconds_bucket), so this is decidable per target.
- alert: JunctionEndpointSlowP95
expr: |
histogram_quantile(0.95,
sum by (endpoint, le) (rate(junction_endpoint_latency_seconds_bucket[10m]))) > 20
and
sum by (endpoint) (rate(junction_endpoint_latency_seconds_count[10m])) > 0
for: 15m
labels:
severity: warning
system: junction
annotations:
summary: "p95 latency of {{ $labels.endpoint }} is over 20 s ({{ $value | printf \"%.1f\" }} s)"
description: "Ninety-five percent of the requests to this endpoint were faster than this. A slow-but-working endpoint keeps the mean harmless; the percentile is what a waiting client feels."
runbook: "curl -s localhost:8090/status | jq '.endpoints[] | select(.name==\"{{ $labels.endpoint }}\")' — last_ms, p95_ms and the histogram tell whether it is the endpoint or its queue. journalctl -u junction | grep served_by shows the per-request numbers."
+9
View File
@@ -51,6 +51,9 @@
#define J_MAX_POOLS 16
#define J_MAX_MCP 16
#define J_MAX_CACHE_PEERS 8
/* Endliche Latenzgrenzen in Sekunden; dazu kommt der +Inf-Eimer. */
#define J_LAT_BUCKETS 9
#define J_LAT_BOUNDS { 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0 }
/* Balance modes: how targets inside one rule are ordered. */
enum { J_BALANCE_FIRST = 0, J_BALANCE_RR = 1, J_BALANCE_USAGE = 2, J_BALANCE_COST = 3 };
@@ -176,6 +179,12 @@ typedef struct {
unsigned long fail_count;
unsigned long key_rr; /* welcher Schlüssel des Pools als nächster dran ist */
long last_ms;
/* Latenz als Histogramm, nicht als Mittelwert: ein Durchschnitt versteckt genau die
* Anfragen, die weh tun. Die Grenzen liegen in Sekunden und sind fest — wer andere
* braucht, ändert sie hier und nicht im Betrieb. Der letzte Eimer ist immer +Inf. */
unsigned long lat_bucket[J_LAT_BUCKETS + 1]; /* letzter Eimer: +Inf */
unsigned long lat_n;
double lat_sum_s;
char last_error[256];
char last_hook_reason[256];
+55 -3
View File
@@ -106,6 +106,31 @@ static int drain_inflight(void)
return n;
}
static const double g_lat_bounds[J_LAT_BUCKETS] = J_LAT_BOUNDS;
/* In welchen Eimer fällt diese Dauer? J_LAT_BUCKETS selbst heißt +Inf. */
static int lat_bucket_index(double sec)
{
for (int i = 0; i < J_LAT_BUCKETS; i++)
if (sec <= g_lat_bounds[i]) return i;
return J_LAT_BUCKETS;
}
/* p95 aus dem Histogramm: die obere Grenze des Eimers, in dem die 95-Prozent-Marke
* liegt. Das ist eine Obergrenze, keine Messung — und steht deshalb im Namen. */
static double lat_p95_ms(const j_endpoint *ep)
{
if (ep->lat_n == 0) return -1.0;
unsigned long want = (unsigned long)((double)ep->lat_n * 0.95);
if (want == 0) want = 1;
unsigned long cum = 0;
for (int i = 0; i < J_LAT_BUCKETS; i++) {
cum += ep->lat_bucket[i];
if (cum >= want) return g_lat_bounds[i] * 1000.0;
}
return -1.0; /* nur im +Inf-Eimer: keine Aussage außer "über 60 s" */
}
static double now_s(void)
{
struct timespec ts;
@@ -696,7 +721,7 @@ static char *build_status(size_t *len_out)
used += (size_t)snprintf(out + used, cap - used,
"%s{\"name\":\"%s\",\"base\":\"%s\",\"kind\":\"%s\",\"context\":%ld,"
"\"priority\":%d,\"paused\":%s,\"inflight\":%d,\"ok\":%lu,\"fail\":%lu,"
"\"last_ms\":%ld,\"offline_s\":%d,\"cooldown_s\":%d,"
"\"last_ms\":%ld,\"p95_ms\":%.0f,\"offline_s\":%d,\"cooldown_s\":%d,"
"\"usage_percent\":%.2f,\"usage_used_usd\":%.2f,\"usage_budget_usd\":%.2f,"
"\"usage_ok\":%d,\"exhausted\":%d,\"budget_soft\":%.0f,\"budget_hard\":%.0f,"
"\"offpeak\":%d,\"cost\":%.2f,\"hooks\":%d,\"keys\":%d,"
@@ -704,7 +729,7 @@ static char *build_status(size_t *len_out)
"\"last_error\":\"%s\",\"last_hook_reason\":\"%s\"}",
i ? "," : "", ep->name, ep->base, ep->kind, ep->context, ep->priority,
ep->paused ? "true" : "false", ep->inflight, ep->ok_count, ep->fail_count,
ep->last_ms,
ep->last_ms, lat_p95_ms(ep),
(int)(ep->offline_until > t ? ep->offline_until - t : 0),
(int)(ep->cooldown_until > t ? ep->cooldown_until - t : 0),
ep->usage_percent, ep->usage_used_usd, ep->usage_budget_usd,
@@ -1230,7 +1255,10 @@ static char *build_metrics(size_t *len_out)
"# HELP junction_endpoint_keys gauge Number of API keys in the pool.\n"
"# TYPE junction_endpoint_keys gauge\n"
"# HELP junction_endpoint_cost_usd_total Cost this endpoint reported.\n"
"# TYPE junction_endpoint_cost_usd_total counter\n");
"# TYPE junction_endpoint_cost_usd_total counter\n"
"# HELP junction_endpoint_latency_seconds Latency of served requests, as a histogram:\n"
"# an average hides exactly the requests that hurt.\n"
"# TYPE junction_endpoint_latency_seconds histogram\n");
for (int i = 0; i < CFG.endpoint_count; i++) {
j_endpoint *ep = &CFG.endpoints[i];
STATE_LOCK();
@@ -1262,7 +1290,28 @@ static char *build_metrics(size_t *len_out)
ep->name, ep->key_env_count,
ep->name, ep->paused ? 1 : 0,
ep->name, ep->cost_usd);
/* Das Histogramm in kumulativer Form, wie Prometheus es verlangt: der Eimer
* "le=1" enthält auch alles, was schneller war. */
unsigned long cum = 0;
char lb[2048];
size_t lu = 0;
for (int b = 0; b <= J_LAT_BUCKETS; b++) {
cum += ep->lat_bucket[b];
if (b < J_LAT_BUCKETS)
lu += (size_t)snprintf(lb + lu, sizeof lb - lu,
"junction_endpoint_latency_seconds_bucket{endpoint=\"%s\",le=\"%g\"} %lu\n",
ep->name, g_lat_bounds[b], cum);
else
lu += (size_t)snprintf(lb + lu, sizeof lb - lu,
"junction_endpoint_latency_seconds_bucket{endpoint=\"%s\",le=\"+Inf\"} %lu\n",
ep->name, cum);
}
lu += (size_t)snprintf(lb + lu, sizeof lb - lu,
"junction_endpoint_latency_seconds_sum{endpoint=\"%s\"} %.3f\n"
"junction_endpoint_latency_seconds_count{endpoint=\"%s\"} %lu\n",
ep->name, ep->lat_sum_s, ep->name, ep->lat_n);
STATE_UNLOCK();
met(out, cap, &u, "%s", lb);
}
/* Je virtuellem Schlüssel: Anfragen, Ablehnungen, Verbrauch im Monat. Damit lässt
@@ -3278,6 +3327,9 @@ static void handle_client(j_conn *client)
if (rc == 0) {
ep->ok_count++;
ep->last_ms = (long)((now_s() - started) * 1000.0);
ep->lat_bucket[lat_bucket_index((double)ep->last_ms / 1000.0)]++;
ep->lat_n++;
ep->lat_sum_s += (double)ep->last_ms / 1000.0;
g_req_ok++;
g_latency_ms_sum += (double)ep->last_ms;
g_latency_n++;
+22
View File
@@ -38,6 +38,28 @@ contains "$M" "junction_requests_total{outcome=\"ok\"} 1" "the served request is
S=$(curl -s -m 10 "http://127.0.0.1:$P_RETRYJ/status")
contains "$S" '"retries":{"count":1' "/status reports the retry count too"
# Latenz als Histogramm: ein Mittelwert versteckt genau die Anfragen, die weh tun.
# Der +Inf-Eimer muss die Zahl der bedienten Anfragen tragen, und die Eimer müssen
# kumulativ sein — sonst rechnet histogram_quantile in Prometheus Unsinn.
inf=$(printf '%s' "$M" | sed -n 's/^junction_endpoint_latency_seconds_bucket{endpoint="box",le="+Inf"} \([0-9]*\)$/\1/p')
cnt=$(printf '%s' "$M" | sed -n 's/^junction_endpoint_latency_seconds_count{endpoint="box"} \([0-9]*\)$/\1/p')
if [ -n "$inf" ] && [ "$inf" = "$cnt" ] && [ "${inf:-0}" -ge 1 ]; then
ok "the latency histogram is cumulative and +Inf equals the served count ($inf)"
else
bad "latency histogram: +Inf='${inf:-}' count='${cnt:-}'"
fi
printf '%s' "$M" | awk '
/^junction_endpoint_latency_seconds_bucket\{endpoint="gated",le="/ {
if ($0 ~ /le="\+Inf"/) next;
n = split($0, parts, " ");
v = parts[n] + 0;
if (v < prev) bad = 1;
prev = v;
}
END { exit bad ? 1 : 0 }
' && ok "the buckets are monotone" || bad "the buckets are not monotone"
contains "$S" '"p95_ms"' "/status reports a p95 upper bound per endpoint"
echo "== 26. Schlüssel-Pool pro Endpunkt =="
# Zwei Konten bei einem Anbieter: der erste Schlüssel ist gesperrt (429), der zweite
# nicht. junction muss auf den zweiten rotieren, statt den Endpunkt aufzugeben.