Repository navigation
perf(agent): version snapshot resources outside the cache mutex and reuse unchanged versions (#1105) - #1114
Merged
Conversation
…ide the cache mutex, and reuse unchanged resources' versions (#1105) go-control-plane builds a snapshot's delta version map lazily: the first delta watch that looks at the snapshot calls ConstructVersionMap, which deterministically marshals and sha256-hashes every resource. That call runs inside SetSnapshot (respondDeltaWatches) or CreateDeltaWatch, so it holds the snapshot-cache mutex that the ADS stream goroutine needs for every request. On the 200m talos agent that was about 93% of a build and 200-870 ms of wall clock. ODCDS answers, EDS subscriptions and drains all waited behind it. generateSnapshot now fills Snapshot.VersionMap itself before calling SetSnapshot. go-control-plane's ConstructVersionMap returns early when the map is non-nil. The version for each resource is the same value go-control-plane would compute: hex(sha256(deterministic marshal)). If a build publishes the same proto object under the same name as the previous build, the memo reuses that resource's version instead of marshalling it again. That reuse is only correct if published protos are never mutated in place. The cache already has to follow this rule, because the xDS server marshals published resources without holding any agent lock. The rule is now enforced in two places. In production, a full re-hash audit runs once a minute; it counts and logs any in-place mutation (aether.agent.snapshot. version_memo_mismatch, seeded at zero) and publishes the correct version. In this package's tests, every build is a strict audit that panics on a mismatch. The test suite passes under strict audit, and a deliberately injected in-place mutation makes it panic. New instruments: aether.agent.snapshot.set_duration (the time spent under the mutex) and aether.agent.snapshot.resource_versions{source=memo|hashed}. Also fixes a pre-existing data race found by the new race test: LoadClustersFromRegistry logged len(c.clusters) after releasing clusterMu. Closes #1105 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
This was referenced Oct 1, 2026
bpalermo
added a commit
that referenced
this pull request
Oct 1, 2026
…limit, and pins GOMAXPROCS=2 (#1116) (#1119) Snapshot builds are 5-25 ms CPU bursts on the ODCDS/EDS path. Under a 200m CFS quota they became 100 ms steps and a goroutine could be throttled while holding the snapshot-cache mutex (#1105/#1114). The agent pod is now Burstable rather than Guaranteed; an operator who needs Guaranteed sets limits.cpu = requests.cpu >= 1000m. GOMAXPROCS was derived from limits.cpu via resourceFieldRef, which falls back to node allocatable once the limit is gone (and the Go >= 1.25 runtime would likewise scale to the node's cores). It is now an explicit env from the new agent.goMaxProcs value (default 2); 0/empty omits it. Chart 2.1.1 -> 2.1.2. Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr Co-authored-by: Claude Fable 5.1 <[email protected]>
This was referenced Oct 1, 2026
bpalermo
added a commit
that referenced
this pull request
Oct 3, 2026
…hashResource in xds/cache) (#1162) - agent/internal/spire.sleepCtx lost its last caller in #1135 (the bridge's retry ladder moved to a context-bounded wait). - agent/internal/xds/cache.hashResource was added in #1114 alongside versionMemo.hash and was never called; every caller uses the memo. Proof: golang.org/x/tools/cmd/deadcode run through rules_go's gopackagesdriver over every first-party main package reports both as unreachable, and `grep -rnw` finds no reference outside the definition in any .go file (production or test), chart, doc, e2e script or workflow. Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr Co-authored-by: Claude Fable 5.1 <[email protected]>
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 #1105
What was wrong
go-control-plane v0.14.0 builds a snapshot's per-resource delta version map lazily. The first delta watch that reads a snapshot calls
Snapshot.ConstructVersionMap, which deterministically marshals and sha256-hashes every resource. That call happens in exactly two places, and both holdsnapshotCache.mu:SetSnapshot→respondDeltaWatchesCreateDeltaWatchThe ADS stream goroutine takes the same mutex for every request it handles (watch cancel plus
CreateDeltaWatch). So for the length of each build's hashing, the stream could not answer ODCDS requests, open EDS subscriptions or propagate drains (#1086, #1103). On the 200m talos agent, that hashing was about 93% of a build.Fix
(a) Version outside the mutex.
generateSnapshotnow fillsSnapshot.VersionMapitself, beforeSetSnapshot, while holding only the agent's ownsnapshotMu. go-control-plane'sConstructVersionMapreturns early whenVersionMap != nil("The snapshot resources never change, so no need to ever rebuild"), so neitherSetSnapshotnorCreateDeltaWatchhas any hashing left to do under its lock. The map is written before the snapshot is published and only read afterwards, so there is no data race.(b) Memoize per-resource versions.
versionmemo.gokeeps the previous build's(type, name) → (proto object, version). When a resource is the same proto object under the same name, its version is reused and the resource is not marshalled again. Anything else is hashed exactly as go-control-plane hashes it:hex(sha256(proto.MarshalOptions{Deterministic: true})). The marshal buffer is reused across resources. The memo is replaced on every build, so it never holds a removed resource. Because the memo holds a reference to each object, a memoized pointer cannot be freed and then reused by a new object.(c) Per-type dirty tracking: not done. There is no seam for it. The remaining registry-refresh cost is the cluster cache rebuilding every entry as new protos (see "Not met" below). Reusing unchanged entries belongs in
LoadClustersFromRegistry, which is the EDS path #1103 is also changing. I left it as a follow-up.Why reuse is correct (delta: a version changes iff the resource's bytes change)
ConstructVersionMapon a fresh snapshot. A rebuilt object with identical bytes keeps its version, so it causes no spurious push. A changed object gets a new version. A removed object has no version, so go-control-plane reports it inremoved_resources.cluster.gorebuilds load assignments ("Build a NEW load assignment rather than mutating the existing one in place"), andrefreshEntryMTLSLockedusesproto.Clonebefore injecting. I audited the field-assignment sites in the cache package, and each one writes to a freshly built or cloned proto.versionmemo_strict_test.go), every build is an audit that re-hashes every resource, memo hits included, and panics on a mismatch. The whole cache suite, which drives every builder, passes under that mode. As a check that the audit is not vacuous, I injected an in-placeAltStatNameedit intogenerateSnapshot; the suite then panicked withversion memo: ...Cluster "app_client-0_8080" was mutated in place after it was published (#1105).aether.agent.snapshot.version_memo_mismatch(an anomaly counter, seeded at zero), logged at ERROR with the resource names, and published with the correct version. A future violation therefore costs at most one audit interval of staleness, not a permanently stuck resource.New instruments
aether.agent.snapshot.set_duration(histogram, s): time spent inSetSnapshot, which is the part of a build that runs under the mutex.aether.agent.snapshot.resource_versions{source="memo"|"hashed"}: how many versions were reused vs computed.aether.agent.snapshot.version_memo_mismatch: audit failures. Healthy value is 0 forever.There are also span attributes on
agent.snapshot.generate:versions_memoized,versions_hashedandversions_audit.Also fixed
A pre-existing data race surfaced by the new race test:
LoadClustersFromRegistryloggedlen(c.clusters)afterclusterMu.Unlock(), whileAddPod→recomputeMTLSClusterscould be writing the map. The count is now taken under the lock. This is a one-line change.Measurements
BenchmarkSnapshotBuild(new, insnapshot_build_bench_test.go) models a busy talos worker:The delta watches matter: without them go-control-plane never hashes, so a benchmark without watches would show none of the cost.
There are two triggers:
A stand-in for the ADS stream takes the cache mutex about 1000 times per second and records its longest wait per build. Both binaries were built from the same benchmark file, and runs were interleaved main/fix/main/fix under
systemd-run --user --scope -p CPUQuota=20%(the 200m cap), 60 builds per cell. The tables give the range across both rounds.Time under the cache mutex (
BenchmarkSnapshotVersioning)SetSnapshotwith up-to-date delta watches open, at 20% quota:Memo-filling an unchanged snapshot takes 0.38 ms at p50, compared with 191 ms at p50 for a full
ConstructVersionMap.ADS stand-in: longest wait per build (GOMAXPROCS=2, 20% quota)
The residual p99 of about 80 ms is not hashing. It is CFS throttling: when the agent's quota runs out while a goroutine holds the mutex for its sub-millisecond
SetSnapshot, the holder is parked until the next 100 ms period. Under GOMAXPROCS=1 the same p99 is 0.02 ms. This residual is what the CPU-limit recommendation below addresses.Total build wall clock at 20% quota
CPU per build (unquota'd, GOMAXPROCS=1, same machine)
The rebuild cost drops by 60%. On a rebuild, about 80% of resource bytes are memo hits; on a registry refresh, about 50%.
Gate status
BenchmarkQUICAdmissionBurstat 20% quota. Main gives 1.0 builds/burst, 13.9–18.9 ms published. The fix gives 1.0 builds/burst, 15.4–17.9 ms.buildHTTPServiceEntryLockedplusrecomputeMTLSClustersLockedproto.Clone/inject) and then hashing them, because new objects are never memo hits. Reusing unchanged cluster entries across refreshes is option (c), in the EDS path, and is left as a follow-up. In practice the first-use burst path is a rebuild, not a refresh.kind (
e2e/eastwest-quic.sh, clusteraether-1105)Full
verify(E0–E7) is green with the fix image. E7: 50/50 first-use requests answered 200, p50 0.220 s, p99 0.227 s, 10 admissions, 1 coalesced publish, 1 build (build_ms91).E7 A/B on the same cluster. I swapped the agent DaemonSet image between main (
dev-fe006e5…) and the fix, two rounds of three bursts each, a fresh ServiceAccount per burst. Every run was 50/50 × 200.kind's resource shape is small (6 pods), so this is a regression check rather than the proof. The proof is the benchmark at the talos shape.
Other checks
bazel test //agent/...: 43/43 pass.bazel test --config=race //agent/internal/xds/cache/... //agent/internal/xds/server/..., run twice: all pass.TestVersionMemoVersionChangesIffBytesChange: same object keeps its version and is not re-hashed; changed object gets a new version; a rebuilt object with identical bytes keeps its version; a removed object has none; all versions match go-control-plane's.TestDeltaPushesExactlyWhatChanged: through the realSnapshotCacheand real delta watches, with the production memo posture: a registry refresh pushes exactly the changed services' CLAs; a pod removal reports exactly its listeners inremoved_resourcesand does not re-push the others; a re-added pod is pushed once.TestVersionMemoAuditCatchesInPlaceMutation: an in-place mutation is stale until the audit; the audit counts it and corrects the version; strict mode panics.TestSnapshotArrivesVersioned: the snapshot reachesSetSnapshotwith its version map already built.TestSnapshotBuildRacesADSStream: builds race delta watches opening, being answered and being cancelled.make gazelle,make format, andbazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //...are clean.charts/change.Recommended agent CPU setting (separate decision for the owner; not changed here)
The agent currently has
resources.requests.cpu: 200mandlimits.cpu: 200m.Recommendation: keep the 200m request and remove the CPU limit. If policy requires a limit, raise it to at least 1000m.
on_demandtimeout and of drain propagation.GOMAXPROCS=2in the agent's env alongside the change.Should this ride the 2026-10-02T01:00Z soak?
Yes, if it merges before the cut. The change is confined to how versions are computed and when they are attached. The versions are byte-identical to go-control-plane's own, so an Envoy reconnecting with
initial_resource_versionssees no difference. The only new failure mode is an in-place mutation, which tests forbid and the production audit bounds to one minute. To watch during the soak:aether.agent.snapshot.version_memo_mismatch(must stay 0)aether.agent.snapshot.set_duration(should be in the low milliseconds)resource_versionsmemo/hashed split🤖 Generated with Claude Code
https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr