Skip to content

feat(047): cut idle CPU 92% — scanner cache + SSE payload embed + coalescer - #450

Merged
Dumbris merged 3 commits into
mainfrom
047-cpu-hotpath-fix
May 8, 2026
Merged

Dumbris merged 3 commits into
mainfrom
047-cpu-hotpath-fix

Conversation

@Dumbris

@Dumbris Dumbris commented May 8, 2026

Copy link
Copy Markdown
Member

Summary

  • Profile of MCPProxy.app + 30-server config + 1.06 GB BBolt + 91k activity records showed 47% sustained CPU, with 56% of cycles inside bbolt.(*DB).View and 50%+ in encoding/json.checkValid. The driver: every tray-triggered GET /api/v1/servers walked the entire scan-job bucket via BoltDB.ListScanJobs and JSON-unmarshalled every record before filtering.
  • This PR ships three fixes that take steady-state CPU from 47% → 3.78% on the same scenario, no storage migration:
    • A1 (scanner negative cache) — cacheScanSummary stores a nil sentinel for servers with no scans; findLatestPassJobs returns errNoScans for the empty-bucket case so transient I/O failures don't pollute the cache (internal/security/scanner/service.go).
    • B1 (SSE payload embed) — emitServersChanged calls the management service once per coalesced event and embeds the post-redaction server list + stats in the payload. Subscribers consume directly and skip the GET /api/v1/servers refetch (internal/runtime/event_bus.go).
    • B2 (event coalescer) — single drainer goroutine + atomic.Pointer collapses retry-storm bursts into one publish per ~50ms, last-write-wins.
  • Adds /debug/pprof/ on the parent mux (API-key gated, zero overhead until hit) so future regressions can be diagnosed without a custom build.
  • Swift tray (CoreProcessManager.swift) and Vue Pinia servers store consume payload.servers when present; fall back to GET /api/v1/servers on older cores.

Verification

specs/047-cpu-hotpath-fix/verification/ contains the post-fix profile artifacts.

Metric Before After
60s CPU sample total 47.32% 3.78%
Cumulative cputime / 60s wall ~19s 2.91s
bbolt.(*DB).View cum CPU 56% not in top 15
encoding/json.checkValid flat 13.05% 8.37%
Goroutines (steady) 80–84 71

Web UI live console capture confirmed zero refetch after servers.changed events.

Test plan

  • go test -race ./internal/... — green (full Go suite)
  • go test -tags server ./internal/teams/... — green (server edition)
  • go vet ./... clean
  • gofmt -l clean
  • golangci-lint 0 issues
  • make build (personal) builds clean
  • go build -tags server ./cmd/mcpproxy builds clean
  • Swift tray (swiftc) builds clean
  • make build re-embeds frontend dist; Web UI loads with new SSE handler
  • TDD-first: TestGetScanSummary_* (3 tests), TestEmitServersChanged_* (4 tests), TestCoalescer_* (6 tests) all green; failing-first → passing
  • macOS tray live verification: 22 servers.changed events captured with full payload during a context7 toggle
  • Web UI live verification: servers.changed arrives, store updates, no follow-up /api/v1/servers fetch
  • Pprof verification: 60s CPU profile captured against the same MCPProxy.app + 30-server scenario as the original measurement

The pre-existing 10 failures in ./scripts/test-api-e2e.sh were verified unchanged on main and are unrelated to this PR.

Out of scope (deferred to follow-up specs)

  • In-memory (serverName, pass) → latestJobID index — true O(1) lookup, eliminates cold-cache spike
  • Activity log retention/pagination — 91k records is excessive
  • security_scan_jobs bucket re-keying — clean root-cause fix, needs migration
  • encoding/json replacement (goccy/go-json or sonic) on storage hot paths
  • PGO build

Spec & artifacts

🤖 Generated with Claude Code

…lescer

Profile of MCPProxy.app + 30-server config + 1.06 GB BBolt + 91k activity
records showed 47% sustained CPU, with 56% of cycles inside bbolt.(*DB).View
and 50%+ in encoding/json.checkValid. The driver: every tray-triggered
GET /api/v1/servers walked the entire scan-job bucket via
BoltDB.ListScanJobs and JSON-unmarshalled every record before filtering.

This PR ships three fixes that take steady-state CPU from 47% (60s sample)
to 3.78% on the same scenario, without any storage migration:

- A1 (scanner negative cache): cacheScanSummary now stores a nil sentinel
  for servers with no scans, distinguished from "not in map" by the
  existing (value, ok) lookup. findLatestPassJobs returns errNoScans for
  the empty-bucket case so transient I/O failures don't pollute the
  cache. internal/security/scanner/service.go.

- B1 (SSE payload embed): emitServersChanged calls the management service
  once per coalesced event window and embeds the post-redaction server
  list + stats in the payload. Subscribers (Swift tray, Web UI) consume
  directly and skip the GET /api/v1/servers refetch.
  internal/runtime/event_bus.go.

- B2 (event coalescer): a single drainer goroutine + atomic.Pointer
  collapses retry-storm bursts into one publish per ~50ms, last-write-
  wins. internal/runtime/event_bus.go (new serversChangedCoalescer).

Plus a pprof endpoint at /debug/pprof/ on the parent mux (API-key gated;
zero overhead until hit) so future regressions can be diagnosed without
a custom build. internal/server/server.go.

Client wiring: the Swift tray (CoreProcessManager.swift) and the Vue Pinia
servers store consume payload.servers when present and fall back to
GET /api/v1/servers when running against an older core. New
ServersChangedPayload + ServersChangedEnvelope decode structs in
API/Models.swift.

Verification (specs/047-cpu-hotpath-fix/verification/): bbolt.(*DB).View
no longer in top-15 cum. encoding/json.checkValid flat down from 13.05%
to 8.37%. Cumulative cputime delta 19s/60s -> 2.91s/60s. Web UI live
console capture confirms zero refetch after servers.changed events.

Tests: TDD-first across all three sub-changes — TestGetScanSummary_*
(scanner), TestEmitServersChanged_* + TestCoalescer_* (runtime). Full
go test -race ./internal/... green; -tags server suite green; linter
clean. Pre-existing 10 failures in test-api-e2e.sh confirmed identical
on main; unrelated to this PR.

Out of scope (deferred to follow-up specs): in-memory
(serverName, pass)->latestJobID index; activity-log retention/pagination;
scan-job bucket re-keying; encoding/json replacement; PGO build.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 8, 2026 •

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: ad67788
Status: ✅  Deploy successful!
Preview URL: https://5c41c86a.mcpproxy-docs.pages.dev
Branch Preview URL: https://047-cpu-hotpath-fix.mcpproxy-docs.pages.dev

View logs

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 70.29703% with 30 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/server/server.go 0.00% 25 Missing ⚠️
internal/runtime/event_bus.go 93.93% 2 Missing and 2 partials ⚠️
internal/security/scanner/service.go 87.50% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: 047-cpu-hotpath-fix

Available Artifacts

  • archive-darwin-amd64 (26 MB)
  • archive-darwin-arm64 (23 MB)
  • archive-linux-amd64 (15 MB)
  • archive-linux-arm64 (13 MB)
  • archive-windows-amd64 (26 MB)
  • archive-windows-arm64 (23 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (19 MB)
  • installer-dmg-darwin-arm64 (18 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 25567130853 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

claude added 2 commits May 8, 2026 18:40
Live capture against the swap-in MCPProxy-047.app on the user's real
30-server config:

Web UI (Chrome MCP):
  - Toggled context7 disable via REST. Cleared network log first.
  - 10 SSE servers.changed events processed by the new handler.
  - 0 follow-up GET /api/v1/servers requests (network log empty).
  - Visible UI deltas: header counter 14/30 -> 10/30, context7
    card switched from "Connected (2 tools)/Disable" to
    "Disabled/Enable", Total Tools 123 -> 188.

macOS Tray (mcpproxy-ui-test, driven via stdio JSON-RPC since the
MCP server isn't registered in this session):
  - check_accessibility: trusted.
  - context7 menu state captured at three points:
      baseline:           "Connected (2 tools)" / button "Disable"
      after disable + 2s: "Disabled"             / button "Enable"
      after enable + 5s:  "Connected (2 tools)" / button "Disable"
  - The accessibility tree renders directly from appState.servers,
    which is now populated by the embedded SSE payload — no HTTP
    refetch was issued.

Three tray PNGs (baseline + after-disable + after-reenable) are
saved alongside this report; they show the top-level menu (context7
lives in the Servers submenu so the visual deltas live in the
accessibility tree, not the screenshot pixels — see visual.md).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two PR-hygiene fixes:

1. Removed binary verification artifacts that the previous commits
   accidentally bundled into specs/047-cpu-hotpath-fix/verification/:
   pprof *.pb.gz profiles, *.txt dumps, and tray screenshots. Total
   ~6 MB of build output that doesn't belong in git history.
   The textual conclusions remain in report.md and visual.md;
   reproduce the artifacts locally via quickstart.md.

2. Restored web/frontend/dist/ to its main-branch state. The previous
   make build run produced a different set of hash-named asset files
   and orphaned the old ones; git interpreted that as deletions and
   I committed them. That cleanup was unintentional and out of scope
   for this PR — the dist/ contents at this branch tip now match main
   exactly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Dumbris
Dumbris merged commit eae45ef into main May 8, 2026
40 checks passed
@Dumbris
Dumbris deleted the 047-cpu-hotpath-fix branch May 8, 2026 16:45
Dumbris added a commit that referenced this pull request May 8, 2026
Spec 047 (PR #450, v0.29.4) eliminated the burst-storm refetch path
(servers.changed -> refetch). This PR addresses the residual: 5 other
call sites in the Swift tray that still hit /api/v1/servers, totaling
~8 GETs per 60 s at idle on a 30-server config.

All 5 sites now read SSE-driven appState.servers in place of fetching:

- CoreProcessManager case "status": no longer refetches on
  connected_count change. Inline stats are merged unconditionally;
  per-server state arrives via the spec 047 servers.changed payload
  within ~50 ms of any actual transition.

- refreshState (30 s periodic) drops the refreshServers() call.
  refreshActivity / refreshSessions / refreshTokenMetrics /
  refreshSecurityStatus stay (SSE doesn't cover those domains).

- refreshSecurityStatus's Docker fallback now reads
  appState.servers synchronously instead of issuing another GET.

- MCPProxyApp's 10 s server-refresh Timer is removed entirely.

- menuWillOpen no longer refetches on every tray click. The menu
  rebuilds from in-memory state only.

In their place: a single 5-minute Combine timer in MCPProxyApp.swift
calls a new CoreProcessManager.refreshServersForSafetyNet() — pure
defense-in-depth in case SSE drops events past the 256-event buffer.

Verification (specs/048-tray-refetch-elimination/verification/report.md)
on the same MCPProxy.app + 30-server scenario as spec 047:
  - 0 GETs / 60 s at idle (was ~8)
  - context7 disable propagates to tray menu in 1 s
  - context7 enable propagates in 2 s
  - 0 GETs during the entire toggle window

Spec, plan, research, data-model, quickstart, tasks all under
specs/048-tray-refetch-elimination/. No core / Go changes.
Backward-compatible with older cores (spec 047 fallback path retained).

Co-authored-by: Claude Code <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants