Skip to content

perf(xds): a registry refresh keeps the proto objects of every service whose inputs did not change, so the version memo stops re-hashing them (#1115) - #1120

Merged
bpalermo merged 2 commits into
mainfrom
perf/1115-reuse-unchanged-registry-entries
Oct 1, 2026
Merged

bpalermo merged 2 commits into
mainfrom
perf/1115-reuse-unchanged-registry-entries

Conversation

@bpalermo

@bpalermo bpalermo commented Oct 1, 2026 •

Copy link
Copy Markdown
Owner

Closes #1115

What was wrong

#1114 (#1105) memoizes a resource's xDS version when the build publishes the same proto object under the same name. A registry refresh never produced one:

  • LoadClustersFromRegistry rebuilt every cluster-cache entry (cluster, load assignment, per-port and alias entries) as fresh protos, even for services whose registry rows had not changed.
  • recomputeMTLSClustersLocked then re-cloned and re-injected every mTLS cluster. It does the same on every pod add or remove.
  • On every snapshot, clustersEndpointsAndVhosts rebuilt each port alias's and QUIC twin's republished load assignment (proxy.LoadAssignmentAlias) and each twin cluster (proxy.QUICClusterFrom). That covers two thirds of the node's load assignments at the benchmark shape, and it happens on plain rebuilds too.

At the benchmark shape, a refresh with no registry change re-hashed 625 of 1027 resources.

Fix

The rule is to compare the inputs and reuse the previous object only when every input is unchanged. A change always builds a new object. Nothing published is ever mutated in place, so the #1105 invariant holds.

1. Registry entries (registryreuse.go)

For each (protocol pass, service), the reuse key is an exact byte string compared with bytes.Equal. It is not a digest, so there is no collision argument to make. It contains:

input why it is in the key
pass (HTTP / TCP / UDP) each pass runs a different builder
node localRegion, localZone EDS priority banding (EndpointPriority)
waypoint rewrite (Enabled, TunnelPort, LocalCluster) dial address and port, priority band, waypoint tag
mesh domain, edge flag cluster and alias names, FQDN, whether aliases exist
bare-CLA ownership (TCP/UDP) whether the L4 floor entry owns <svc>'s load assignment. This depends on the HTTP pass of the same refresh (ownsBareCLALocked)
every registry row, in listing order, as its deterministic protobuf encoding, length-prefixed see below

The row is the whole ServiceEndpoint: ip, port, ports, port_protocols, health (so a DRAINING or UNHEALTHY drain mark changes the key), health-check mode, locality, cluster name, Kubernetes metadata (namespace for the SAN pin, pod, node IP for the waypoint), endpoint metadata (subset keys), weight, and any field added later, unknown fields included. An added or removed endpoint changes the list. Order is kept because the builder reads it: the default port comes from the first row.

Completeness argument. Every value the three builders read (buildHTTPServiceEntryLocked, buildTCPServiceEntriesLocked, the UDP closure) is one of the following:

  • (a) a row field. The key holds the whole row.
  • (b) one of the refresh-wide values in the table above.
  • (c) a compile-time constant: meshconst.ProxyOutboundPort, the proxy.* builders. I checked those builders for package-level mutable state. The only setters are access-log and tracing config, which feed listeners and not clusters.
  • (d) the GAMMA rules and chain filters. These feed only the outbound vhosts. A vhost is not an xDS resource (it is embedded in out_http, which every snapshot rebuilds), so a reused HTTP entry always gets its vhosts rebuilt from the current rules (refreshReusedVhostsLocked) and they need no key.

The dependency set decides whether a service is built at all, not what is built for it. The builders now write into a dst map instead of c.clusters, so a new input cannot reach the cluster map except through them. Each builder's doc comment says that any new input must join the key.

Other writers invalidate the reuse. A record is reused only if every entry it produced is still in the map exactly as built: same cluster and load-assignment objects, and not retained as absent. RemoveEndpoint replaces the load assignment, RemoveCluster deletes the entry, and absent-service retention replaces the load assignment and sets absentSince. All three therefore force a rebuild from the rows. Records live for exactly one refresh.

2. mTLS render (mtls.go)

refreshEntryMTLSLocked skips the clone and inject while its render key is unchanged. The key is:

  • the base cluster object
  • service, sni, SAN namespaces, l4Floor
  • node SPIFFE ID, trust domain, validation-context name
  • edge, waypoint, mesh domain

That is everything renderEntryMTLSLocked reads. A side effect is that a pod add or remove no longer re-clones all ~300 mTLS clusters. Since #842 the render has no per-workload input.

3. Derived per-snapshot objects (derivedmemo.go)

LoadAssignmentAlias(base, name) and QUICClusterFrom(base, name, id, vc, sanURIs, sni, idle) are pure functions of their arguments. The base object is never mutated once built, so its pointer stands for its bytes. The memo is keyed on the name and returns the previous object only when every argument matches. It keeps two generations, rotated once per snapshot, so it never holds more than the last snapshot asked for.

Proof

(1) Stale-resource detection: strict mode extended, not just kept green

The #1105 strict mode only detects in-place mutation. It cannot see a stale reuse, because a stale object is still byte-stable. So in this package's tests (versionmemo_strict_test.go), every reuse is now rebuilt fresh and compared with proto.Equal, and any difference panics. That covers registry entries, skipped mTLS renders, alias load assignments and twin clusters. The whole cache suite, which drives every builder, becomes the detector for a missing input.

I checked that the audit is not vacuous by injecting three bugs, one at a time:

injected bug result
rows dropped from the key TestLatePortAliasSubscribesToItsOwnEDSResource panics: registry reuse: service "demo/echo" reused a STALE entry
trust/identity state dropped from the mTLS render key TestIdentityBindingSummaryAboveThreshold panics: kept a STALE mTLS render
base pointer ignored in the alias memo TestCachedMTLSClusterInvalidatedOnSANNamespaceChange panics: alias load assignment ... is STALE

New tests (registryreuse_test.go). The fixture is 2 HTTP services, 1 TCP service, 1 UDP service, a local pod, a node SVID and an observed QUIC twin.

  • TestRegistryRefreshUnchangedReusesEveryObject: an unchanged refresh returns the identical pointer for every cluster and load assignment (twins included) and builds 0 services.

  • TestRegistryRefreshRebuildsExactlyWhatChanged is a table test. Each case asserts that the affected resources are new objects with a new version, that the other services' objects are identical, and that the next unchanged refresh reuses everything again. The cases are:

    • endpoint added
    • endpoint removed
    • drain mark (DRAINING)
    • health UNHEALTHY
    • health-check mode
    • endpoint locality
    • subset metadata
    • namespace (SAN pin)
    • port (SNI)
    • TCP drain mark
    • UDP endpoint added
    • node locality
    • waypoint
    • node identity (mTLS render)

    The drain and endpoint cases also assert that the twin load assignment changes, and that the h2 cluster keeps its version (no spurious CDS push).

  • TestRegistryRefreshUnrenderedFieldRebuildsWithoutPush: a weight change rebuilds the objects (the whole row is the key) but versions stay equal, because weight is not rendered.

  • TestRegistryRefreshTCPOwnershipFollowsHTTPPass: when a service gains an HTTP entry, its reused TCP entry loses the bare load assignment, with the rows unchanged.

  • TestRegistryRefreshRebuildsAfterRemoveEndpoint: a trimmed entry is not reused.

  • TestRegistryRefreshMemoSplit: pins the split at the benchmark shape.

(2) BenchmarkSnapshotBuild, same method as #1114

Both binaries were built from the same benchmark file. main is 5b7cc7d's cache package plus this benchmark file. Runs were interleaved main/fix under systemd-run --user --scope -p CPUQuota=20% (the 200m cap), 60 builds per cell. The workstation was shared: load average was 40–70 from other jobs.

Benchmark changes:

  • A registry-refresh-nochange case.
  • A versions-memo/build and versions-hashed/build split per build. This split is aether.agent.snapshot.resource_versions{source=memo|hashed}: a hit means the same object under the same name, as in versionMemo.version.
  • A fix to the benchmark itself. Its SVIDs were all named …/sa/<sa>#<i>, so no identity had its client certificate and none of the 10 documented QUIC twins was ever built. The first pod of each ServiceAccount now carries the exact ID, so the shape is 1027 resources with 10 twins.
  • registry-refresh now changes two services per refresh: the one perturbed now, and the one restored from the previous perturbation.

Wall clock at 20% quota, build p50 / p99 (ms):

case main GOMAXPROCS=1 (2 rounds) fix GOMAXPROCS=1 main GOMAXPROCS=2 fix GOMAXPROCS=2
registry-refresh 212–216 / 306–379 99.5–100 / 194–195 ¹ 212 / 297–303 102–103 / 194–196
registry-refresh-nochange 209–291 / 295–470 99–100 / 191–197 211–217 / 297–303 101–102 / 191–194
rebuild 106–108 / 199–205 97 / 190–192 104–106 / 198–200 97–98 / 190–195

¹ One fix round was contaminated by a concurrent bazel build //agent/... that I started myself (p99 3153 ms). I re-ran that cell in isolation, and the reported range is the two clean rounds plus the re-run.

Gate: registry-refresh p99 < 200 ms under the 200m-like quota is met (194–196 ms). It is met by a small margin: wall clock is quantized into 100 ms CFS periods, and a refresh is now about 20 ms of CPU, so it spans 2 periods instead of 3–4.

resource_versions split per build:

case main memo / hashed fix memo / hashed
no-change refresh 402 / 625 1022 / 5
refresh with 2 services changed 402 / 625 1009 / 17.6 (≤ 8 per changed service)
rebuild 802 / 225 1022 / 5

The 5 that are always hashed are the resources every snapshot builds from scratch: out_http, cap_http, the subset-headers ECDS, the health-gateway listener and the passthrough cluster.

CPU per refresh, unquota'd, GOMAXPROCS=1 (noisy host):

time allocs bytes
main 49–90 ms 118.5k 8.5 MB
fix 22 ms 58k 4.7 MB

(3) Race

bazel test --config=race //agent/internal/xds/cache/... //agent/internal/xds/server/... passes.

(4) kind

I ran e2e/eastwest-quic.sh up && verify on kind cluster aether-1115. The images were re-tagged aether1115, and the agent image carries org.opencontainers.image.revision=c14d89c. E0–E7 all green:

  • E2, E4b, E5: every batch 10/10 × 200 with the caller's own XFCC URI on its own twin over HTTP/3.
  • E4: the weighted route stays on h2.
  • E4c: 6 twins = 6 driven pairs.
  • E6: the identity gate passes.
  • E7: 50/50 first-use requests × 200 to 10 fresh QUIC destinations, p50 0.349 s, p99 0.360 s. 10 admissions were coalesced into 2 publishes, with build_ms 122 and 63.

Two earlier verify attempts on the same cluster died silently with exit 141 (SIGPIPE), at different points (mid-E5, then at E4). No assertion failed, and every ✓ before the abort was green. This is the harness, not the data path. The script runs under set -euo pipefail, and some of its pipelines end in a reader that exits early (for example pod_of's awk '…{ print $1; exit }'), so the writer gets SIGPIPE and the pipeline fails. Which pipeline fails depends on timing, and the host's load average was 40–70. The third, passing run used an uncommitted copy with pod_of made SIGPIPE-safe, run under bash -x. The script is unchanged on main; this is worth its own issue.

Other checks

  • bazel test //agent/... --test_tag_filters=-integration: 43/43 pass.
  • make gazelle, make format, and bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //... are clean. gocognit flagged the audit function at 21; it is now split.
  • No chart change.

Risk

The failure mode is an input missing from a key, which would publish a stale resource. The worst case is a stale EDS, for example a drain mark that is not propagated.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

…e whose inputs did not change, so the version memo stops re-hashing them (#1115)

LoadClustersFromRegistry rebuilt every cluster-cache entry as fresh protos on
every refresh, and the mTLS render, the port-alias / QUIC-twin load
assignments and the twin clusters were rebuilt as fresh protos on every
snapshot. The #1105 version memo only reuses a version for the SAME object
under the same name, so none of them was ever a hit.

- registryreuse.go: per (protocol pass, service), the exact input key (pass,
  node locality, waypoint rewrite, mesh domain, edge, bare-CLA ownership, and
  every registry row's deterministic encoding, length-prefixed, in order) is
  compared with bytes.Equal; an unchanged key whose entries are still in the
  map exactly as built reuses them. Vhosts (not xDS resources) are always
  rebuilt from the current GAMMA rules / chain filters.
- mtls.go: the mTLS render is skipped while its render key (base cluster
  object, service, sni, SAN namespaces, l4Floor, node mTLS state, edge,
  waypoint, mesh domain) is unchanged.
- derivedmemo.go: alias load assignments and QUIC twin clusters are memoized
  on their full argument list (base object + values), two generations.
- Tests: every reuse / skipped render / derived hit is rebuilt fresh and
  compared in this package's tests (panic on difference), and table tests flip
  each input and assert a new object + new version.
- Bench: registry-refresh-nochange case, memo/hashed split per build, and the
  bench's SVID names fixed so its 10 QUIC twins are actually published.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit 030102f into main Oct 1, 2026
24 checks passed
@bpalermo
bpalermo deleted the perf/1115-reuse-unchanged-registry-entries branch October 1, 2026 20:55
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.

agent: a registry refresh rebuilds every cluster entry as new protos, so the snapshot version memo never reuses them (refresh still ~400 ms p99 at 200m)

1 participant