Skip to content

Commit f7b8962

Browse files
authored
feat(mesh): routing decision observability 1/2 — decision metrics on the router port (#3141)
* feat(mesh): define routing decision metric schema Add names, help text, label values and histogram buckets for the routing decision metrics of the P0-4 spec: route branches, prefix match ratio, route cost, session affinity, prefill overlap blocks, dispatched DP rank, and the estimated versus engine-reported cached tokens. Recorder APIs land with them; labels carry pool, policy, branch, worker and rank only, never session or request IDs. * feat(mesh): serve /metrics on the router port Build the Prometheus recorder instead of install() so the handle stays available, keep the exporter listener on --prometheus-port (29000 by default), and render the same registry at GET /metrics on the router port. Clients that discover <router>:<port>/metrics, such as AIPerf in InferenceX, can now scrape Mesh self metrics; worker atom: metrics are unaffected. * feat(mesh): report routing decisions from every policy Each built-in policy declares its decision branches and reports one per selection through policies::decision, feeding mesh_route_branch_total, mesh_route_prefix_match_ratio (cache_aware), mesh_route_cost (load-based branches) and mesh_session_affinity_total (dp_sticky). New policies plug in the same way by declaring decision_branches() and calling decision::report. * ci(atomesh): keep a router /metrics snapshot with each agentic run After each aiperf run the PD benchmark saves the router port's /metrics to metrics/router-metrics.prom (best effort), and the latency report staging keeps .prom files, so the routing-decision counters ship in the artifact. * refactor(mesh): deprecate mesh_prefix_hash_policy_branch_total mesh_route_branch_total{policy="prefix_hash"} now counts the same branches by pool, so mark the old counter and its recorder deprecated instead of dropping a metric that main already exports. It stays until its scrapers move to the new counter. * refactor(mesh): record the selected worker's active requests on every selection mesh_route_cost was named and described as a cost in the policy's own unit, but every caller recorded Worker::load(), the router-tracked active request count, and only on five branches that its pool and policy labels could not tell apart. Rename it mesh_route_selected_worker_active_requests, record it for every selection that picks a worker, read before the router adds the request, label it by branch, and size its buckets for request counts. Policies no longer compute a cost. * test(mesh): count a selection without healthy candidates once in its pool Every policy given only unhealthy prefill candidates reports one no_healthy_workers decision labeled pool="prefill" and records no active requests sample. * fix(mesh): register metric HELP text after installing the recorder start_prometheus described every metric before installing the Prometheus recorder, so the descriptions went to the no-op recorder and the exporter rendered no # HELP lines. Describe after the install. * fix(mesh): count a pool without candidates as no_healthy_workers When a pool has no available worker, the planner returns before any policy runs, so the failure never reached mesh_route_branch_total and no-capacity alerts could not see it. Count it where the pool is known: a regular, prefill or decode pool left empty by the health filter, and a PD request without any prefill or decode worker. A request for a model without any worker has no pool and stays uncounted. * docs(mesh): document the router /metrics endpoint List /metrics with the other router endpoints and note that the router port serves the whole Mesh registry whatever --prometheus-host binds the exporter to. The README is already part of this pull request, which keeps #3141 within its 15-file budget. * docs(mesh): add a routing metrics reference Explain each routing decision metric: type, labels and their values, units and buckets, the policies and branches that record it, and which change starts recording it. Cover how to read the prefix match ratio, the route cost, session affinity results and the router estimate against the engine-reported cached tokens, with collection steps, example queries and a sample scrape. Link it from the README's Prometheus metrics section. * docs(mesh): document the selected worker's active requests and empty pools #3141 replaced mesh_route_cost with mesh_route_selected_worker_active_requests, labeled by branch and recorded on every selection that picks a worker, and #3213 counts a pool without candidates as no_healthy_workers. The reference states when the active requests are read and which branches record none, and the sample is recaptured. * feat(mesh): count session requests that move to a different worker dp_sticky records where each session's last request was dispatched. Routers report the dispatched worker, after DP rank mapping, through LoadBalancingPolicy::on_dispatch, and mesh_session_worker_change_total{pool, reason} counts a request dispatched to a different worker (URL and DP rank) than the session's previous one: rebind or expired when the policy reassigned the session, rank_mapping when idx2idx moved a pinned session. A new session, a hit and an expiry back to the same worker count nothing. * fix(ci): save a router metrics baseline and increase for each concurrency level Concurrency levels reuse one router, so the snapshot after a level also counted every earlier level. Each level now saves router-metrics-before.prom just before aiperf and router-metrics.prom after it, both with their scrape time, and router-metrics-delta.prom with the increase of every counter and histogram series, including buckets, sums and counts. A counter that went down means the router restarted; the increase then counts from the restart and says so. * docs(mesh): document session worker changes and the per-run CI baseline The reference lists mesh_session_worker_change_total and when each reason applies, describes the before, after and delta router snapshots that CI saves for each concurrency level, and states that the router counts a pool without candidates as no_healthy_workers. Sections about #3142 metrics say so, and the sample comes from a build of this PR. * fix(mesh): count a session worker change when the request is sent Routers reported the dispatched worker to the policy as soon as the PD pair was reserved, and before the regular request was prepared. A reserved worker that never received the request, such as the decode worker after an ATOM prefill failure or an external-processing reservation that is canceled or expires, still counted a change and became the session's previous worker. Call on_dispatch from send_worker as each upstream request starts, with the mapped worker, and in the regular router right before the send. * refactor(mesh): keep only the routing metrics this PR records mesh_prefill_overlap_blocks had no caller in either PR, so it goes with its medium labels, inventory entry, buckets and recorder. The DP rank and cached-token metrics, their labels, recorders and test move to #3142, which first records them, so this PR no longer declares planned metrics. The reference drops their rows and sections. * refactor(mesh): return each routing decision from the policy and record it once A policy now returns the branch that chose the worker along with its index (select_with_decision; select_worker wraps it), and apply_policy, the only production caller, records one decision per call. Policies no longer touch the routing metrics, so policies/decision.rs, decision_branches and its debug_assert go away. mesh_session_affinity_total duplicated mesh_route_branch_total{policy="dp_sticky"} and is dropped; the documented hit rate reads the branch counter. A stale_tenant match is on a worker that is gone, so it no longer records a prefix match ratio. * fix(mesh): run the PD dispatch hook before spawning the mooncake prefill send_worker took the headers only so on_dispatch could read the session ID, and the mooncake path cloned the whole HeaderMap and the router into the prefill task for it. dispatch now runs the hook on the request task, once the request is built and right before it is sent, and returns the worker's policy; the spawned task only sends.
1 parent f9698ba commit f7b8962

25 files changed

Lines changed: 1513 additions & 132 deletions
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
"""Router metrics of one benchmark run: the increase of every counter and
2+
histogram series between the /metrics snapshots taken before and after it."""
3+
4+
import argparse
5+
import re
6+
import sys
7+
from pathlib import Path
8+
9+
SCRAPED_AT = "# scraped_at "
10+
SAMPLE = re.compile(r"^([A-Za-z_:][A-Za-z0-9_:]*)(\{.*\})?\s+(\S+)")
11+
CUMULATIVE = {"counter", "histogram"}
12+
13+
14+
def parse(text: str) -> tuple:
15+
"""Returns the scrape time, the metric types and the samples by (name, labels)."""
16+
scraped_at, types, samples = None, {}, {}
17+
for line in text.splitlines():
18+
if line.startswith(SCRAPED_AT):
19+
scraped_at = line[len(SCRAPED_AT) :].strip()
20+
elif line.startswith("# TYPE "):
21+
_, _, name, kind = line.split(maxsplit=3)
22+
types[name] = kind.strip()
23+
elif line and not line.startswith("#"):
24+
match = SAMPLE.match(line)
25+
if match:
26+
samples[match[1], match[2] or ""] = float(match[3])
27+
return scraped_at, types, samples
28+
29+
30+
def family(name: str, types: dict) -> str:
31+
for suffix in ("_bucket", "_sum", "_count"):
32+
if name.endswith(suffix) and types.get(name[: -len(suffix)]) == "histogram":
33+
return name[: -len(suffix)]
34+
return name
35+
36+
37+
def number(value: float) -> str:
38+
return str(int(value)) if value.is_integer() else repr(value)
39+
40+
41+
def delta(before: str, after: str) -> tuple:
42+
"""Returns the run's increase in Prometheus text format, and whether the
43+
router restarted between the snapshots."""
44+
start, before_types, start_samples = parse(before)
45+
end, types, end_samples = parse(after)
46+
types = {**before_types, **types}
47+
48+
def cumulative(key):
49+
return types.get(family(key[0], types)) in CUMULATIVE
50+
51+
# Counters and buckets only grow while the router runs, so a lower or
52+
# missing series means it restarted. Histogram sums can fall.
53+
reset = any(
54+
end_samples.get(key, 0.0) < value
55+
for key, value in start_samples.items()
56+
if cumulative(key) and not key[0].endswith("_sum")
57+
)
58+
lines = [
59+
f"# router metrics increase from {start or 'unknown'} to {end or 'unknown'}",
60+
"# counter reset: "
61+
+ ("yes, values count from the router restart" if reset else "no"),
62+
]
63+
typed = set()
64+
for (name, labels), value in end_samples.items():
65+
if not cumulative((name, labels)):
66+
continue
67+
base = family(name, types)
68+
if base not in typed:
69+
typed.add(base)
70+
lines.append(f"# TYPE {base} {types[base]}")
71+
if not reset:
72+
value -= start_samples.get((name, labels), 0.0)
73+
lines.append(f"{name}{labels} {number(value)}")
74+
return "\n".join(lines) + "\n", reset
75+
76+
77+
def main() -> int:
78+
parser = argparse.ArgumentParser(description=__doc__)
79+
parser.add_argument("before", type=Path)
80+
parser.add_argument("after", type=Path)
81+
parser.add_argument("--output", type=Path, required=True)
82+
args = parser.parse_args()
83+
text, reset = delta(args.before.read_text(), args.after.read_text())
84+
args.output.write_text(text)
85+
if reset:
86+
print(
87+
f"WARNING: the router restarted during the run; {args.output} counts "
88+
"from the restart",
89+
file=sys.stderr,
90+
)
91+
return 0
92+
93+
94+
if __name__ == "__main__":
95+
sys.exit(main())

‎.github/scripts/atomesh/observability/stage_reports.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def stage_reports(results: Path, cell: str, output: Path) -> dict:
3434
if (
3535
source.is_file()
3636
and not source.is_symlink()
37-
and source.suffix in {".html", ".json", ".log", ".yml"}
37+
and source.suffix in {".html", ".json", ".log", ".prom", ".yml"}
3838
):
3939
shutil.copy2(source, destination / source.name)
4040
status_file = destination / "status.json"

‎.github/scripts/atomesh/pd_server_atom.sh‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2453,6 +2453,18 @@ wait_for_torch_traces() {
24532453
done
24542454
}
24552455

2456+
# Saves the router's /metrics with its scrape time. A failed scrape only warns.
2457+
save_router_metrics() {
2458+
local output="$1"
2459+
local scraped_at metrics
2460+
scraped_at="$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)"
2461+
if metrics="$(curl -sSf --max-time 10 "http://127.0.0.1:${ROUTER_PORT}/metrics")"; then
2462+
printf '# scraped_at %s\n%s\n' "${scraped_at}" "${metrics}" > "${output}"
2463+
else
2464+
echo "[aiperf] WARNING: router /metrics snapshot failed" >&2
2465+
fi
2466+
}
2467+
24562468
run_aiperf_agentic_benchmark() {
24572469
ensure_agentx_harness
24582470

@@ -2522,6 +2534,12 @@ run_aiperf_agentic_benchmark() {
25222534
> >(tee "${out_dir}/torch_profile.log") 2>&1 &
25232535
profile_pid=$!
25242536
fi
2537+
# collect_metrics.py creates metrics/ itself, so the baseline waits outside it.
2538+
local router_before="${out_dir}/router-metrics-before.prom"
2539+
rm -f "${router_before}"
2540+
if [[ "${AGGREGATED}" != "1" ]]; then
2541+
save_router_metrics "${router_before}"
2542+
fi
25252543
AIPERF_TIMING_CANCEL_DRAIN_TIMEOUT="${AIPERF_TIMING_CANCEL_DRAIN_TIMEOUT}" \
25262544
AIPERF_HTTP_TCP_USER_TIMEOUT="${AIPERF_HTTP_TCP_USER_TIMEOUT}" \
25272545
AIPERF_DATASET_CONFIGURATION_TIMEOUT="${AIPERF_DATASET_CONFIGURATION_TIMEOUT}" \
@@ -2563,6 +2581,22 @@ run_aiperf_agentic_benchmark() {
25632581
echo "${aiperf_pid}" > "${aiperf_pid_file}"
25642582
local aiperf_rc=0
25652583
wait "${aiperf_pid}" || aiperf_rc=$?
2584+
if [[ "${AGGREGATED}" != "1" ]]; then
2585+
# Every concurrency level shares this router, so the counters after the
2586+
# run include the earlier levels. Stage the baseline and this run's
2587+
# increase with the latency report.
2588+
local router_metrics="${out_dir}/metrics"
2589+
mkdir -p "${router_metrics}"
2590+
save_router_metrics "${router_metrics}/router-metrics.prom"
2591+
if [[ -f "${router_before}" ]]; then
2592+
mv "${router_before}" "${router_metrics}/"
2593+
fi
2594+
python3 "${ATOMESH_SCRIPT_DIR}/observability/router_metrics_delta.py" \
2595+
"${router_metrics}/router-metrics-before.prom" \
2596+
"${router_metrics}/router-metrics.prom" \
2597+
--output "${router_metrics}/router-metrics-delta.prom" \
2598+
|| echo "[aiperf] WARNING: router metrics increase not computed" >&2
2599+
fi
25662600

25672601
if [[ -n "${profile_pid}" ]]; then
25682602
touch "${profile_done}"

‎atom/mesh/README.md‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ Atomesh can also run in an **ATOM standalone** mode. In this mode, Python owns t
2828
| `POST /parse/reasoning` / `/parse/function_call` | Reasoning and tool-call parsing |
2929
| `GET /health` / `/readiness` / `/liveness` | Health probes |
3030
| `GET /engine_metrics` | Aggregated worker engine Prometheus metrics |
31+
| `GET /metrics` | Mesh self metrics, the same registry as the Prometheus exporter |
3132
| `GET /v1/models` | Model metadata |
3233

3334
Responses resource operations (GET, DELETE, cancel and input_items) probe regular
@@ -298,20 +299,29 @@ registered token-routing template, so under `prefix_hash` they return
298299

299300
Default bind: `0.0.0.0:29000` (`--prometheus-host` / `--prometheus-port`)
300301

301-
Mesh self metrics are exposed by the Prometheus exporter above. Worker engine
302-
metrics remain available through the router's `/engine_metrics` endpoint, which
303-
scrapes backend workers, injects `worker_addr`, and aggregates their Prometheus
304-
text without changing worker metric names.
302+
Mesh self metrics are exposed by the Prometheus exporter above and by the
303+
router's own `/metrics` endpoint, which returns 503 when the exporter is not
304+
running. The router port serves the whole registry whatever `--prometheus-host`
305+
is set to, so binding the exporter to a private address does not hide these
306+
metrics from clients that can reach the router. Worker engine metrics remain
307+
available through the router's `/engine_metrics` endpoint, which scrapes backend
308+
workers, injects `worker_addr`, and aggregates their Prometheus text without
309+
changing worker metric names.
305310

306311
| Layer | Prefix | Description |
307312
|-------|--------|-------------|
308313
| HTTP | `mesh_http_*` | Request counts, duration, connections, rate limiting |
309314
| Router | `mesh_router_*` | Requests by model/endpoint, latency, errors |
310315
| Inference | `mesh_router_ttft/tpot/tokens_*` | TTFT, TPOT, token counts (gRPC) |
311316
| Worker | `mesh_worker_*` | Pool size, connections, health, selection |
317+
| Routing | `mesh_route_*`, `mesh_session_*` | Policy decisions, session worker changes |
312318
| Circuit breaker | `mesh_worker_cb_*` | State, transitions, outcomes |
313319
| Retry | `mesh_worker_retries_*` | Attempts, exhaustion, backoff |
314320

321+
[Routing metrics](docs/metrics.md) covers each routing metric's labels, the
322+
policies and branches that record it, how to read the values, and example
323+
queries.
324+
315325
### Logging
316326

317327
Structured logging via `tracing`, optional file sink (`--log-dir`), and log level (`--log-level`).

0 commit comments

Comments
 (0)