Skip to content

perf: eliminate hot-path recompute in the registrar snapshot and xDS cache - #615

Merged
bpalermo merged 2 commits into
mainfrom
perf/sweep-safe
Aug 1, 2026
Merged

bpalermo merged 2 commits into
mainfrom
perf/sweep-safe

Conversation

@bpalermo

@bpalermo bpalermo commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Summary

Final cohort of the improvement sweep: the six SAFE findings from the hot-path analysis, implemented exactly as specified; the four NEEDS-CARE findings are deferred (listed below). No behavior change; no iteration or sort order that feeds xDS output was touched.

registrar (internal/server)

  1. Snapshot.serviceCounts — the per-event full scan in serviceCountLocked (O(events × total endpoints) under the write lock, per Register/Unregister RPC cluster-wide) becomes an incrementally-maintained map lookup. Invariant: the key set IS the service catalog (no zero rests in the map); ServiceNames() iterates it (sort kept). SERVICE_ADDED/REMOVED transitions are byte-identical.
  2. FullSnapshotEvents(filter) — a new watcher's initial snapshot skips out-of-scope entries before allocating their protos. Agents reconnect with a fresh filter on every dependency-set change, so this was N_reconnects × N_cluster_endpoints proto allocations during a roll — the dominant registrar allocation source under churn. sendFilteredSnapshot keeps its guard as defense in depth.
  3. Broadcast metrics batching — per-type tallies during the fan-out, one counter Add per type after the read lock drops, with measurement options pre-built from the generated enum table (was one WithAttributes allocation per event per watcher inside the lock). Totals identical.

agent xDS cache

  1. Extension-union hoist — the node-global escape-hatch filter union is computed once per regeneration loop (AddPod, LoadListenersFromStorage, regenerateAllHTTPListeners, SetCaptureTCPServices, regenerateAllCaptureListeners) instead of once-or-twice per pod. The shared slice is documented immutable; the per-pod authz prepend still allocates fresh. Side benefit: depMu is no longer acquired under listenerMu on these paths.
  2. Snapshot-shape counts ride the dep-set memo — declared/observed counts are recorded when the memo rebuilds and share its exact validity window (depGen + the observed-TTL expiry horizon), replacing two full walks per snapshot. The wall-clock expiry path cannot serve a stale count — expiry invalidates the memo.
  3. dependencySetShared() — captureVhosts (read-only membership tests on the hottest path) reads the memo directly instead of deep-copying it per snapshot; the exported DependencySet still copies.

Deferred (NEEDS-CARE, from the same analysis — candidates for follow-ups)

  • Cache the built cap_http route table keyed on (depGen, captureAuthGen, depSet identity) — the single biggest remaining win, needs per-trigger invalidation tests
  • TCP-floor clusters: cache the injected cluster on clusterEntry beside mtlsCluster (per-snapshot Any-marshals ∝ pods × identities today)
  • Storage AddResource: move marshal+fsync out of the mutex (CNI ADD latency path)
  • Shared static RetryPolicy via sync.OnceValue (concurrent-marshal sizeCache caveat)

Tests

New: TestSnapshot_ServiceCountsStaySynced (pins the invariant through Apply — add / UPDATED-replace / UPDATED-as-add / remove-absent / full-drain / re-add — and Replace) and TestFullSnapshotEvents_Filter (nil = unfiltered, scoped, unknown-service, empty-non-nil). Existing callers updated for the two signature changes.

bazel test --test_output=errors //... — 79/79 pass. Note: the repo has no benchmarks; if you want before/after numbers I'd add micro-benchmarks for Snapshot.Apply and generateSnapshot in a follow-up rather than pad this PR.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EioJVuoepwStjHoRLB52WR

bpalermo and others added 2 commits August 1, 2026 17:02
…cache

Six pre-verified SAFE fixes from the improvement sweep's hot-path
analysis; no behavior change, no ordering change anywhere that feeds
xDS output.

registrar:
- Snapshot keeps an incremental serviceCounts map: the per-event
  full-scan serviceCountLocked (O(events x total endpoints) under the
  write lock) becomes a map lookup; ServiceNames iterates the catalog
  key set (sort kept). 0<->1 transition events are byte-identical.
- FullSnapshotEvents(filter): a demand-scoped watcher's initial
  snapshot skips out-of-scope entries BEFORE allocating their protos
  (agents reconnect with a fresh filter on every dep-set change, so
  this was N_reconnects x N_cluster_endpoints allocations during churn).
  sendFilteredSnapshot keeps its guard as defense in depth.
- Broadcast tallies events per type during the fan-out and records one
  counter Add per type after releasing the read lock, with pre-built
  per-type measurement options (was one WithAttributes alloc per event
  per watcher inside the lock).

agent xDS cache:
- The node-global extension-filter union is computed once per
  regeneration loop and threaded through, instead of once (or twice)
  per pod; the shared slice is documented immutable and per-pod
  prepends still allocate fresh.
- The snapshot-shape metric's declared/observed dependency counts ride
  the existing dep-set memo (same inputs, same validity window incl.
  the observed-TTL expiry horizon) instead of two full walks per
  snapshot.
- captureVhosts reads the memoized dependency set via a new shared
  read-only accessor instead of deep-copying it every snapshot.

New tests pin the serviceCounts invariant through Apply/Replace and the
FullSnapshotEvents filter semantics.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EioJVuoepwStjHoRLB52WR
The serviceCounts bookkeeping pushed both to 18 (gate is 15). Extract
the per-event upsert/remove handling into applyUpsertLocked/
applyRemoveLocked, and allocate the broadcast tally map up front
instead of lazily inside the send closure. No behavior change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EioJVuoepwStjHoRLB52WR
@bpalermo
bpalermo merged commit 126de75 into main Aug 1, 2026
15 checks passed
@bpalermo
bpalermo deleted the perf/sweep-safe branch August 1, 2026 20:16
bpalermo added a commit that referenced this pull request Aug 1, 2026
Renumber 002 -> 034 (002 is taken by the merged agent-concurrency
audit) and revise every code reference after two months of drift:

- Ports post-030: inbound is 18008 (defaultInboundPort); the outbound
  listener is unchanged at 18081 (mesh.ProxyOutboundPort)
- Multi-port routing (005): delivery is app_<pod>_<port>, so the
  original "port is ignored for delivery" semantic is REVERSED —
  port(s) stay required for demux/EDS; the annotation only changes
  what the app cluster dials (one socket serves all declared ports)
- Redirect-all (022) + mesh DNS narrowed Phase 2's audience; keep it,
  priority lowered, re-evaluate after Phase 1
- E/W waypoint (019) and cleartext inbound (#421) confirmed covered
  for free (delivery sits behind the inbound listener)
- New facts folded in: UID already fetched but deliberately not
  persisted (resubscribe.go), storage is protojson in agent/storage,
  builder is exported GenerateOutboundHTTPListener with the 025/#470
  extension union (hoisted per-loop in #615), authz emptyDir socket
  (#499) documented as the intra-pod precedent (cross-pod still needs
  the kubelet hostPath), RESULT_IGNORED unmanaged pods, TCP
  connect-probe analogue on pipes
- New constraint: the kubelet-pods mount must not be readOnly
  (connect(2) on AF_UNIX needs write on the inode; EROFS otherwise)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EioJVuoepwStjHoRLB52WR
bpalermo added a commit that referenced this pull request Aug 1, 2026
* docs: proposal 002 — UDS support for pods

Plan for letting pods serve on and dial the mesh via Unix domain sockets,
in two phases (inbound first). Pathname UDS is mount-namespace-scoped, so
the design bridges pod emptyDir volumes to the node proxy through kubelet's
pod-volumes directory; abstract sockets and workload hostPath mounts are
evaluated and rejected. Registry/EDS endpoints stay TCP :15008, so UDS pods
are indistinguishable from TCP pods to clients.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(034): re-ground the pod-UDS proposal in the current codebase

Renumber 002 -> 034 (002 is taken by the merged agent-concurrency
audit) and revise every code reference after two months of drift:

- Ports post-030: inbound is 18008 (defaultInboundPort); the outbound
  listener is unchanged at 18081 (mesh.ProxyOutboundPort)
- Multi-port routing (005): delivery is app_<pod>_<port>, so the
  original "port is ignored for delivery" semantic is REVERSED —
  port(s) stay required for demux/EDS; the annotation only changes
  what the app cluster dials (one socket serves all declared ports)
- Redirect-all (022) + mesh DNS narrowed Phase 2's audience; keep it,
  priority lowered, re-evaluate after Phase 1
- E/W waypoint (019) and cleartext inbound (#421) confirmed covered
  for free (delivery sits behind the inbound listener)
- New facts folded in: UID already fetched but deliberately not
  persisted (resubscribe.go), storage is protojson in agent/storage,
  builder is exported GenerateOutboundHTTPListener with the 025/#470
  extension union (hoisted per-loop in #615), authz emptyDir socket
  (#499) documented as the intra-pod precedent (cross-pod still needs
  the kubelet hostPath), RESULT_IGNORED unmanaged pods, TCP
  connect-probe analogue on pipes
- New constraint: the kubelet-pods mount must not be readOnly
  (connect(2) on AF_UNIX needs write on the inode; EROFS otherwise)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EioJVuoepwStjHoRLB52WR

---------

Co-authored-by: Claude Opus 4.8 <[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.

1 participant