Repository navigation
graphite: expand globs and braces in render targets for health and flag metrics - #34
Conversation
LukasCuperDT
left a comment
There was a problem hiding this comment.
Nice change and good tests. A few things before merge:
- Unbounded expansion (DoS).
expand_bracesproduces the cartesian product of every{…}group in a user-supplied target.health.prod.{a,b}{a,b}…with 25 groups yields ~33M strings from one unauthenticated request. Please cap the number of groups and/or total expansions (and reject or return[]beyond it). - Sequential backend calls.
health.<env>.*awaitsget_service_healthonce per service in sequence, so N services = N round-trips in a row. Something likefutures::stream::iter(..).buffer_unordered(k)(orjoin_allwith a bound) would keep "All" panels responsive. - Semantics vs Graphite — worth a test or a doc comment:
glob::Patternlets*match across.; Graphite stops at..- Nested braces (
{a,{b,c}}) aren't handled. - The target is split on
.before expansion, so a brace member containing a dot breaks.
LukasCuperDT
left a comment
There was a problem hiding this comment.
Requesting changes per my earlier review: cap brace expansion (currently unbounded cartesian product from user input) and avoid sequential per-service backend calls for globbed health targets.
…n parallel Review follow-up: a target may carry at most 8 brace groups and expand to at most 256 alternatives, anything beyond matches nothing; braces may nest; patterns are matched node by node so * and ? stop at a dot, as in Graphite; health.<env>.<glob> fetches up to 8 services concurrently, order preserved.
|
Addressed in df81808:
|
|
Checked against df81808, the reviewed revision:
CI on this revision: fmt, clippy -D warnings and 80 tests green. |
LukasCuperDT
left a comment
There was a problem hiding this comment.
Thanks for df81808 — bounded concurrency, per-node glob matching and nested braces look good, and I agree with your answers to the autoreview (200 [] unchanged; the expect()s are pre-existing).
One blocker left: the 256 cap is checked after the product is built. expand_pattern calls expand_braces(pattern), which materialises every combination, and only then compares alternatives.len() with MAX_PATTERN_EXPANSIONS. MAX_BRACE_GROUPS limits the number of groups, not members per group: 8 groups × 30 members = 30⁸ ≈ 6.5×10¹¹ strings from a ~500-character query.
Please bound it before expanding, e.g. multiply the top-level member counts of each group (recursively for nested ones) and return [] once the product exceeds 256, or thread a remaining budget through expand_braces and stop as soon as it is exhausted. A test with something like 8 groups × 30 members that returns [] quickly would lock it in.
expand_braces built the whole cartesian product and only then was its length compared with MAX_PATTERN_EXPANSIONS; MAX_BRACE_GROUPS limits the groups, not their members, so 8 groups of 30 members materialised 30^8 strings before being refused. The budget is now threaded through the recursion and expansion stops as soon as it would exceed 256. The cap test gains that 8x30 case and asserts the at-limit pattern is really accepted.
|
Agreed, done in 2ebd2f8: the budget is threaded through the recursion so expansion stops as soon as it would exceed 256 alternatives, and the cap test now covers 8 groups x 30 members returning [] quickly. |
LukasCuperDT
left a comment
There was a problem hiding this comment.
Requesting changes once more, narrowly: 2ebd2f8 closes the expansion-count blocker from the earlier review (verified below), but the same single-request resource-exhaustion class is still reachable through the size of each alternative rather than their number -- a 400 KB GET target peaks at 4.3 GiB and a 2 MiB POST body extrapolates to ~21 GiB -- and a one-line length cap closes it.
Resolved (earlier blocker: cap checked after the product was built)
expand_braces_within(src/graphite.rs:455-493) threads the remaining budget through the recursion (limit - expanded.len()at :485) and returnsNoneas soon asexpanded.len() > limit(:487). The product is never materialised past 256: every member yields at least one leaf, so the recursion visits at most257 x depthnodes before aborting. No multiplication is involved, so there is no overflow to check;limit - expanded.len()cannot underflow becauselen <= limitis re-established after everyextend, anddepth -= 1(:466) cannot underflow because the scan starts on the opening{and breaks the moment depth returns to 0.- Measured on this head (counting global allocator, single-threaded): 8 groups x 30 members (888-byte pattern) ->
[]in 414 us, 57 KB allocated, 16 KB peak; same with 60-char members (15 KB pattern) -> 1.95 ms; one group of 60,000 members (409 KB pattern) -> 14 ms, 1 MB allocated. - Cap boundaries are exact: one group of 256 members accepted, 257 refused;
{a,b,c,d}x4 (256) accepted,{a,b,c,d}x3{a,b,c,d,e}(320) refused;{a,b}x8 now really returns the match (the test at :669-673 was fixed to assert that). - Still in place from df81808:
.buffered(HEALTH_FETCH_CONCURRENCY)= 8 (:368, :393); per-node matching so*,?,[..]never cross a.(verified:*vsa.bno match,a.*/*.*match,*.*.*only the 3-node name); nested{a,{b,c}}and{a,{b,{c,d}}}expand correctly; unbalanced{a,b,{a,{b,c},}}}{{{are kept literal and match only a literally-named candidate;{}->""; exact unknown names pass through unchanged (nope,no.pe). - Per request:
RenderRequest.targetis a singleOption<String>; a secondtarget=is a serde "duplicate field" and the Query extractor returns 400 ("Failed to deserialize query string"), so the caps are effectively per request. Nothing in the expansion path can panic; the onlyexpect/unwraps are the pre-existing ones already agreed to be out of scope. - Logging: the TraceLayer span logs
uri.path()only, and the target is logged attrace!/debug!, so user input does not reach INFO logs./renderis not described inopenapi-schema.yamlordoc/api/endpoints.md(both cover only/v1/healthand/v1/maintenances), so there is no schema entry to update for this change. - Autoreview points: all three answered or fixed (200
[]unchanged,expect()s pre-existing, fan-out bounded); its final approve noted it could not read the helper bodies -- I did, and the only open point is the one below.
Still open
- src/graphite.rs:409-427 -- the count cap does not bound the size of each alternative; one request can OOM the process.
expand_patternkeeps up to 256 copies of the whole pattern (format!("{head}{member}{tail}"), :485) and then compiles each one withglob::Pattern::new(:419-427), which holds ~82 bytes per pattern character (32-byte token per char plus theVec<char>andoriginal). The multiplier is therefore ~256 x 82 on the pattern length, and the pattern length is bounded only by the transport: hyper 0.14's request head is 417,792 bytes (GET) and axum-core 0.3's default body limit is 2,097,152 bytes (POST form/JSON -- the way Grafana actually calls/render). Measured on this head withhealth.prod.{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}xxxx…: 10 KB -> 140 MiB peak (13,900x input, 265 ms); 50 KB -> 564 MiB peak, 1.2 GiB cumulative, 1.4 s; 400 KB (fits in one GET) -> 4,300 MiB peak, 9,265 MiB cumulative, 12.8 s. Growth is linear, so a 2 MiB POST is ~21 GiB -> OOM-kill of the service from one unauthenticated request, and a handful of concurrent 400 KB GETs do the same. Without braces the factor is still ~84x (*+ 50 KB -> 3.4 MiB), so the length, not the braces, is the lever. This was present before 2ebd2f8 as well -- the earlier review missed it because the count issue dominated.
Fix: reject long node patterns before anything is allocated, next to the group check at :413:With 1024 the worst case is ~256 x 1024 x 82 B = 21 MiB transient per request. Optionally also compile each distinct node string once (/// Longest node pattern accepted; Grafana multi-value targets are a few hundred bytes at most. const MAX_PATTERN_LEN: usize = 1024; … if pattern.len() > MAX_PATTERN_LEN || pattern.matches('{').count() > MAX_BRACE_GROUPS { return Vec::new(); }
HashMap<&str, glob::Pattern>) so the 256 alternatives of{a,b}x8.<long>share one compiled glob for the long node. Please add the length case totest_expand_pattern_caps_brace_expansion(e.g.{a,b}x8 + 100 KB literal ->[], with the same elapsed guard).
New / minor (non-blocking)
- src/graphite.rs:414, :417 -- a refused pattern is indistinguishable from "no match" and leaves no trace. Both caps return
Vec::new(), which the handler turns into200 []. That is the behaviour the earlier review accepted, so no objection to the status code, but please emit onetracing::warn!with the pattern length and group count (not the raw pattern, to keep user input out of the logs) so a probe is visible in production. - src/graphite.rs:405-406 (doc comment) -- character classes have the same dot limitation as brace members.
a[.-]bis split on the.intoa[/-]b, the first node failsglob::Pattern::new, and the whole alternative is silently dropped (verified: matches nothing). That matches Graphite, which splits on dots too, so just extend the sentence about brace members to cover[...]. - src/graphite.rs:684-686 -- the timing assertion is loose.
< 1 son a shared CI runner will still pass if the budget regresses to a few hundred thousand allocations; the measured value is 0.4 ms.< 50 mswould catch a regression without being flaky, or assertexpand_braces_within(&wide, MAX_PATTERN_EXPANSIONS).is_none()directly, which is the property that matters.
What is good: the budgeted recursion is the right shape -- small, obviously bounded, no size precompute to keep in sync with the expansion -- and the 8x30 test with the "at-limit must really match" correction is exactly the lock-in that was asked for. The per-node glob matching, nested-brace handling and buffered(8) fan-out are all still intact on this head, and the pre-existing expect() cleanup being deferred to its own PR is the right call. All CI checks (build, test, coverage, CodeQL, Analyze) are green on 2ebd2f8.
|
@sergiubz are you still working on it? |
|
Done in ad2cdc5: patterns longer than 1024 bytes are refused before anything is allocated, a refusal is logged with length and group count only, the doc comment covers |
|
@ecosquad-autoreview |
There was a problem hiding this comment.
Review: graphite: expand globs and braces in render targets for health and flag metrics
Verdict: approve — the change is well-scoped, CI is green (build, 80 tests, CodeQL, clippy Analyze (rust)), and the core semantics (node-by-node glob matching, Graphite-style */? stopping at .) are correct and well tested. Nothing below blocks merge; items are warnings worth a follow-up and a couple of suggestions.
Summary
/render previously only matched exact service names (plus a trailing-* prefix match for flag metrics), so Grafana multi-value variables ({a,b,c}) and All (*) returned empty. This PR introduces expand_pattern() in src/graphite.rs (line 417) which:
- matches pattern and candidate node by node (split on
., per-nodeglob::Pattern) —*/?stop at dots, exactly like Graphite (test_expand_pattern_follows_graphite_node_semantics); - expands nested brace groups (
{a,{b,c}}) by depth tracking, splitting on top-level commas; - is capped: max 1024-byte pattern (refused before allocation, logged with length and group count only), max 8 brace groups, max 256 alternatives, budget threaded through the recursion so it stops early (returns
[]on overflow).
The health branch now fans per-service fetches out through stream::iter(...).buffered(8) (line 352, HEALTH_FETCH_CONCURRENCY), order-preserving, with series in sorted known-service order. The flag branch (line 281) reuses the same expansion against service.metric keys. Exact names behave as before; the find endpoint is untouched.
Findings
Critical
None.
Warning (non-blocking; pre-existing, deferred per discussion)
src/graphite.rs, ~lines 244–258 —handler_renderpanics on missing request fields:x.target.as_ref().expect("Target is required")andx.max_data_points.expect(" is required")(and the query-path equivalents). A/renderrequest withouttarget/maxDataPointspanics the handler (axum turns this into a 500; on some setups repeated malformed requests are a cheap DoS vector). This is pre-existing and the team has agreed to handle it in a separate PR. Suggested fix for that PR: returnStatusCode::BAD_REQUEST(or500with a body) instead ofexpect, e.g.let target = match payload { Some(JsonOrForm(ref x)) => match x.target.as_ref() { Some(t) => t, None => return StatusCode::BAD_REQUEST.into_response(), }, ... };
- Silent empty result on cap overflow (
src/graphite.rs, line 417 area): a pattern exceeding the 8-group / 256-alternative / 1024-byte caps silently matches nothing ([]), so a Grafana panel just goes empty with no visible signal in the UI. The length refusal is logged (length + group count only — good, no target echo). Suggest also logging awarn!(same redacted fields) when the expansion caps are hit, so an over-configured variable is diagnosable in the service logs.
Suggestion
- Deduplication for brace members:
expand_pattern("{a,a}")would fetch serviceatwice for the health branch (two series, two fetches). Cheap to guard: dedupe the returned candidates (the flag branch is already safe since it iterates unique map keys). - Documented unsupported case: a brace member containing a dot (e.g.
{svc.a,svc.b}) is unsupported because the handler splits the target on.first; this is documented onexpand_pattern. Consider additionally logging adebug!when a node contains{/}after splitting, to help operators notice the limitation. - Ordering: health series come back in sorted service order (from the sorted
knownvec), not the order Grafana's{a,b,c}enumerated them.bufferedpreserves input order, so this is fine and deterministic — just noting it's a deliberate choice. - Test coverage: strong — exact names, globs/braces/char classes, node semantics vs Graphite, cap limits (9 groups, 8 groups at limit, 5×4 members, 8×30 wide, 1024-byte boundary, 100 KB refusal with <50 ms assertion). One gap worth adding: a handler-level test that a failing service in a multi-service health expansion is omitted while the others still return data (the single-service error path is covered; the "omit among N" path is the new behavior).
Notes on the analysis
- The health-branch
if let Ok(...)removal is confirmed safe: previously an error inget_service_healthfell through to the handler's finalreturn 200 [], so a target matching nothing already returned200 []. Failing services are now omitted instead of blanking the whole response — behaviour for the no-match case is unchanged, and the multi-service case is strictly better. - Concurrency is bounded at 8 in flight via
.buffered(HEALTH_FETCH_CONCURRENCY)in the same block. - Flag keys (
service.metric) are built the same way as inhandler_metrics_findand verified by the existingtest_render_flag_target. - The 21 MiB worst-case-per-request figure with the 1024-byte cap is the author's estimate for allocation; the cap makes per-request work bounded and the refusal path is tested for latency (< 50 ms), so this is acceptable as documented.
CI on the reviewed revision (ad2cdc5): fmt, clippy -D warnings, and 80 tests green.
LukasCuperDT
left a comment
There was a problem hiding this comment.
Approving. ad2cdc5 closes the last blocker, and all three non-blocking points are done too.
Checked on this head
- Length cap (blocker):
MAX_PATTERN_LEN = 1024is checked together with the group count, beforeexpand_braces_withinruns, so no alternative is copied or compiled for an oversized target.expand_patternis called once per request, ontarget_parts[2](health) or<a>.<b>(flag), so the cap bounds the whole user-controlled part of the target, not just one node. Worst case is about 256 x 1024 x 82 B, around 21 MiB transient per request. - Logging: both refusals log
tracing::warn!withlenandgroupsonly. The raw pattern never reaches the logs. - Docs: the doc comment now covers
[...]classes not crossing a.(a[.-]bmatches nothing, as in Graphite), plus the length cap and the logged refusal. - Tests: both timing guards are
< 50 ms. The cap test covers{a,b}x8 + 100 KB refused, and exactly 1024 bytes ({+ 1020 +,y}) accepted, which pins the boundary.
Merge with main: main has moved on by #35 (health-metric attribute overrides: sd.rs, types.rs, reporter). It doesn't touch graphite.rs, and main + this PR merges cleanly. On that merge result cargo test --lib gives 83 passed, 0 failed, and cargo clippy --lib reports no warnings in src/graphite.rs (same as main). The new test code adds none of the existing test-target clippy findings.
The pre-existing from.unwrap() / to.unwrap() in the health branch stay out of scope as agreed. Worth the follow-up PR you mentioned.
Thanks for working through all the rounds. The budgeted expansion plus the length cap is a clean, obviously bounded design.
Grafana sends
{a,b,c}for a multi-value variable and*for All, but /render only matched exact service names (plus a trailing*on flag metrics), so every such panel and thehealth.<env>.*alert rules on dashboard.tsi-dev came back empty; the health and flag targets are now expanded against the configured services with the same glob syntax Graphite uses, exact names behave as before, and the find endpoint is untouched.