8000 dashboard: merging an over-cap channel snapshot costs linear work per poll · Issue #340 · stratum-mining/sv2-ui · GitHub
[go: up one dir, main page]

Skip to content

dashboard: merging an over-cap channel snapshot costs linear work per poll #340

Open

Description

@lucasbalieiro

Affected layers

  • Frontend (src/): affected. The eviction loops in mergeMetricEntries and mergeShareStatsEntries in src/hooks/usePersistentDashboardMetrics.ts pick each victim with a linear find over the remaining candidates and remove it with indexOf and splice, once per entry over the cap. For a snapshot of keys the state has not seen, every candidate is live, so the first find scans 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.md asks.

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

Related issues and PRs

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

  1. added
    area:dashboard
    and removed on Oct 14, 2026
  2. changed the title [-]Bound quadratic metric eviction work[/-] [+]dashboard: merging an over-cap channel snapshot costs linear work per poll[/+] on Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:dashboard

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0