Repository navigation
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
Conversation
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
LoadClustersFromRegistryrebuilt every cluster-cache entry (cluster, load assignment, per-port and alias entries) as fresh protos, even for services whose registry rows had not changed.recomputeMTLSClustersLockedthen re-cloned and re-injected every mTLS cluster. It does the same on every pod add or remove.clustersEndpointsAndVhostsrebuilt 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:localRegion,localZoneEndpointPriority)Enabled,TunnelPort,LocalCluster)<svc>'s load assignment. This depends on the HTTP pass of the same refresh (ownsBareCLALocked)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:meshconst.ProxyOutboundPort, theproxy.*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.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
dstmap instead ofc.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.
RemoveEndpointreplaces the load assignment,RemoveClusterdeletes the entry, and absent-service retention replaces the load assignment and setsabsentSince. All three therefore force a rebuild from the rows. Records live for exactly one refresh.2. mTLS render (
mtls.go)refreshEntryMTLSLockedskips the clone and inject while its render key is unchanged. The key is:That is everything
renderEntryMTLSLockedreads. 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)andQUICClusterFrom(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 withproto.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:
TestLatePortAliasSubscribesToItsOwnEDSResourcepanics:registry reuse: service "demo/echo" reused a STALE entryTestIdentityBindingSummaryAboveThresholdpanics:kept a STALE mTLS renderTestCachedMTLSClusterInvalidatedOnSANNamespaceChangepanics:alias load assignment ... is STALENew 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.TestRegistryRefreshRebuildsExactlyWhatChangedis 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: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 #1114Both binaries were built from the same benchmark file. main is
5b7cc7d's cache package plus this benchmark file. Runs were interleaved main/fix undersystemd-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:
registry-refresh-nochangecase.versions-memo/buildandversions-hashed/buildsplit per build. This split isaether.agent.snapshot.resource_versions{source=memo|hashed}: a hit means the same object under the same name, as inversionMemo.version.…/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-refreshnow 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):
¹ 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_versionssplit per build: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):
(3) Race
bazel test --config=race //agent/internal/xds/cache/... //agent/internal/xds/server/...passes.(4) kind
I ran
e2e/eastwest-quic.sh up && verifyon kind clusteraether-1115. The images were re-taggedaether1115, and the agent image carriesorg.opencontainers.image.revision=c14d89c. E0–E7 all green:build_ms122 and 63.Two earlier
verifyattempts 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 underset -euo pipefail, and some of its pipelines end in a reader that exits early (for examplepod_of'sawk '…{ 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 withpod_ofmade SIGPIPE-safe, run underbash -x. The script is unchanged onmain; this is worth its own issue.Other checks
bazel test //agent/... --test_tag_filters=-integration: 43/43 pass.make gazelle,make format, andbazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //...are clean. gocognit flagged the audit function at 21; it is now split.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.
aether.agent.snapshot.resource_versions{source="memo"}should rise to about 99% on talos;version_memo_mismatchmust stay 0;loaded clusters from registry ... servicesReused/servicesBuilt.🤖 Generated with Claude Code
https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr