Repository navigation
Description
Affected layers
- Frontend (
src/): affected. The eviction loops inmergeMetricEntriesandmergeShareStatsEntriesinsrc/hooks/usePersistentDashboardMetrics.tspick each victim with a linearfindover the remaining candidates and remove it withindexOfandsplice, once per entry over the cap. For a snapshot of keys the state has not seen, every candidate is live, so the firstfindscans the whole array before the second one picks a freshly created key. Measured on main: 1,000 fresh entries cost 470,000 set lookups; 10,000 cost 50 million, about 0.9 s for the metric merge and 0.5 s for the share-stats merge on a desktop CPU. The dashboard runs three merges per poll, blocks found, best difficulty and share stats, every 3 seconds. The entries are the channels sv2-apps lists; their number is whatever the peers open. - Backend (
server/): not affected. It holds no dashboard state. shared/: not affected.
Problem
The 256-entry cap bounds storage, but the loop that enforces it does work proportional to the square of the number of entries over the cap. The evicted live keys are absent from the stored state, so the next poll of an unchanged snapshot creates them again, reports the state as changed, and evicts them again. The cost is paid on the UI thread on every poll for as long as the snapshot stays over the cap.
Impact
The operator's dashboard turns sluggish or unresponsive while the merges run; the mining service is untouched. It needs thousands of monitored channels: a downstream party able to open many clients or channels can supply them, and 100 JDC clients with 100 channels each already make 10,000 entries. No counter is corrupted. Severity low.
Expected outcome
- The work to merge a snapshot grows in proportion to the number of entries in it, for any mix of new, live and no longer reported keys, however many are over the cap.
- Eviction keeps its order of preference, entries no longer reported first, then entries the snapshot just created, then established live entries, and the lifetime totals after a merge stay what they are today.
- A regression test bounds the work for a 10,000-entry snapshot, with entries built from representative channel payloads as
docs/monitoring-api-compatibility.mdasks.
Possible approach (non-binding)
Partition the candidates once into the three preference classes and take the victims from the front of that list, as the Loupe suggestion does, in both merges. The eviction tests in src/hooks/usePersistentDashboardMetrics.test.ts guard the totals and the preference order; the lookup count in the Loupe PoC is one way to bound the work, a time budget in a child process is another.
Loupe findings
- project-loupe/audit-sv2-ui#50: eviction scans the full candidate list for each victim, which is quadratic in the entries over the cap (reported as dashboard: merging an over-cap channel snapshot costs linear work per poll #340)
Related issues and PRs
- dashboard: every page of a paginated monitoring endpoint is read #330 asks the dashboard to read every page of the paginated monitoring endpoints; loading every page raises the number of entries that reach eviction.
- dashboard: replaying a share-stats update never inflates lifetime totals #333 changes the same eviction loop in the share-stats merge.
- Tracker: [Tracker] Dashboard metrics #373.
Loupe export for #340 (finding #50)
Finding
- repo:
stratum-mining/sv2-ui(https://github.com/stratum-mining/sv2-ui.git) - reviewed revision:
b610455ac2d1e017c1df5db8787c0b2e505eabdc - title: Bound quadratic metric eviction work
- severity:
low - location:
src/hooks/usePersistentDashboardMetrics.ts:223-241 - cwe: CWE-400
- scanner:
llm-code-review - fingerprint:
d0fad56fe60de91206425a0685e6233eb7e62d65b7d2ea833929e88946ed740d
Description
mergeMetricEntries first inserts every incoming telemetry key and then evicts down to 256 entries. For an over-cap snapshot where the keys are freshly created and therefore all in liveKeys, each loop iteration runs evictable.find((k) => !liveKeys.has(k)) across the entire shrinking array before selecting a created key, then also performs a linear indexOf/splice. This is quadratic work: the PoC observes about 470,000 membership checks for only 1,000 entries. The dashboard caller can collect up to 100 JDC clients with 100 channels each (10,000 entries), and a downstream party able to open many monitored clients/channels can force tens of millions of UI-thread operations. Because evicted live keys are absent from prev, the same keys are reinserted and re-evicted on later polling updates, so the cost repeats and can make the operator dashboard unresponsive. Prior searches for mergeMetricEntries denial service found no match. Finding #8071 was reviewed; it added the cardinality cap but does not cover the cap's quadratic eviction algorithm.
Proof of Concept
diff --git a/src/hooks/usePersistentDashboardMetrics.quadratic.test.ts b/src/hooks/usePersistentDashboardMetrics.quadratic.test.ts
new file mode 100644
--- /dev/null
+++ b/src/hooks/usePersistentDashboardMetrics.quadratic.test.ts
@@ -0,0 +1,30 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { mergeMetricEntries } from './usePersistentDashboardMetrics.js';
+
+test('metric eviction performs bounded work for the maximum dashboard snapshot', () => {
+ const entryCount = 1_000;
+ const entries = Array.from({ length: entryCount }, (_, index) => ({
+ key: `channel:${index}`,
+ value: 1,
+ }));
+ const originalHas = Set.prototype.has;
+ let membershipChecks = 0;
+
+ Set.prototype.has = function countedHas(value: unknown): boolean {
+ membershipChecks += 1;
+ return originalHas.call(this, value);
+ };
+
+ try {
+ mergeMetricEntries({}, entries);
+ } finally {
+ Set.prototype.has = originalHas;
+ }
+
+ assert.ok(
+ membershipChecks < entryCount * 20,
+ `evicting ${entryCount - 256} entries required ${membershipChecks} Set lookups`,
+ );
+});
Suggested Fix
diff --git a/src/hooks/usePersistentDashboardMetrics.ts b/src/hooks/usePersistentDashboardMetrics.ts
--- a/src/hooks/usePersistentDashboardMetrics.ts
+++ b/src/hooks/usePersistentDashboardMetrics.ts
@@ -219,25 +219,26 @@ export function mergeMetricEntries(
});
const evictable = Object.keys(next).filter((k) => k !== AGGREGATE_KEY);
- while (evictable.length > MAX_SHARE_STATS_ENTRIES) {
- // Prefer entries that are no longer reported, then entries the current
- // snapshot itself just created, and only then established live entries.
- const victim =
- evictable.find((k) => !liveKeys.has(k)) ??
- evictable.find((k) => createdKeys.has(k)) ??
- evictable[0];
+ // Prefer entries that are no longer reported, then entries the current
+ // snapshot itself just created, and only then established live entries.
+ const victims = [
+ ...evictable.filter((k) => !liveKeys.has(k)),
+ ...evictable.filter((k) => liveKeys.has(k) && createdKeys.has(k)),
+ ...evictable.filter((k) => liveKeys.has(k) && !createdKeys.has(k)),
+ ].slice(0, Math.max(0, evictable.length - MAX_SHARE_STATS_ENTRIES));
+
+ victims.forEach((victim) => {
const victimValue = next[victim] ?? 0;
const freshlyCreatedLive = liveKeys.has(victim) && createdKeys.has(victim);
if (victimValue > 0 && !(mode === 'sum' && freshlyCreatedLive)) {
next[AGGREGATE_KEY] =
mode === 'max'
? Math.max(next[AGGREGATE_KEY] ?? 0, victimValue)
: (next[AGGREGATE_KEY] ?? 0) + victimValue;
}
delete next[victim];
- evictable.splice(evictable.indexOf(victim), 1);
changed = true;
- }
+ });
return { next, changed };
}
This finding was discovered by Project Loupe.
Activity
[-]Bound quadratic metric eviction work[/-][+]dashboard: merging an over-cap channel snapshot costs linear work per poll[/+]