Skip to content

perf(agent): version snapshot resources outside the cache mutex and reuse unchanged versions (#1105) - #1114

Merged
bpalermo merged 2 commits into
mainfrom
perf/1105-snapshot-build-outside-mutex
Oct 1, 2026
Merged

bpalermo merged 2 commits into
mainfrom
perf/1105-snapshot-build-outside-mutex

Conversation

@bpalermo

@bpalermo bpalermo commented Oct 1, 2026

Copy link
Copy Markdown
Owner

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 hold snapshotCache.mu:

  • SetSnapshot → respondDeltaWatches
  • CreateDeltaWatch

The 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. generateSnapshot now fills Snapshot.VersionMap itself, before SetSnapshot, while holding only the agent's own snapshotMu. go-control-plane's ConstructVersionMap returns early when VersionMap != nil ("The snapshot resources never change, so no need to ever rebuild"), so neither SetSnapshot nor CreateDeltaWatch has 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.go keeps 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)

  • A version computed here is byte-for-byte the one go-control-plane computes: the same deterministic marshal and the same hex sha256. Tests assert map equality against ConstructVersionMap on 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 in removed_resources.
  • Reusing a version for the same object is safe only if a proto is never mutated in place after it is published. The cache already has to follow that rule: go-control-plane's server goroutines marshal published resources without holding any agent lock, so an in-place edit would be a torn-marshal data race. Existing code shows the rule is followed deliberately: cluster.go rebuilds load assignments ("Build a NEW load assignment rather than mutating the existing one in place"), and refreshEntryMTLSLocked uses proto.Clone before injecting. I audited the field-assignment sites in the cache package, and each one writes to a freshly built or cloned proto.
  • The rule is enforced, not assumed:
    • Tests. In this package (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-place AltStatName edit into generateSnapshot; the suite then panicked with version memo: ...Cluster "app_client-0_8080" was mutated in place after it was published (#1105).
    • Production. At most one build per minute is a full audit. It re-hashes everything outside the mutex. Any mismatch is counted in 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 in SetSnapshot, 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_hashed and versions_audit.

Also fixed

A pre-existing data race surfaced by the new race test: LoadClustersFromRegistry logged len(c.clusters) after clusterMu.Unlock(), while AddPod → recomputeMTLSClusters could be writing the map. The count is now taken under the lock. This is a one-line change.

Measurements

BenchmarkSnapshotBuild (new, in snapshot_build_bench_test.go) models a busy talos worker:

  • 50 local pods across 10 ServiceAccounts
  • 100 in-scope Services with 3 endpoints each
  • 52 SVID secrets (each about 1.8 KiB)
  • capture with redirect-all on
  • 10 QUIC twins
  • 1007 resources in total
  • a live up-to-date delta watch on every type

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)

SetSnapshot with up-to-date delta watches open, at 20% quota:

p50 p99
main (unversioned snapshot: hashing under the mutex) 189–197 ms 293–306 ms
fix (memo-versioned snapshot) 0.55–0.59 ms 3.0 ms

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)

rebuild p50 / p99 registry-refresh p50 / p99
main 191–197 / 300–380 ms 196–199 / 389–391 ms
fix 0.003–0.02 / 81–83 ms 0.25–0.27 / 81–82 ms

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

rebuild p50 / p99 registry-refresh p50 / p99
main (GOMAXPROCS=1) 179–198 / 293–300 ms 291–304 / 400–404 ms
fix (GOMAXPROCS=1) 94–98 / 198–202 ms 211–216 / 398–407 ms
main (GOMAXPROCS=2) 201–202 / 387 ms 313–393 / 491–493 ms
fix (GOMAXPROCS=2) 99–100 / 209–288 ms 297–299 / 403–406 ms

CPU per build (unquota'd, GOMAXPROCS=1, same machine)

rebuild registry-refresh
main 20.7 ms, 3.06 MB, 32.4k allocs 24.6 ms, 7.05 MB, 82.7k allocs
fix 8.3 ms, 1.66 MB, 22.9k allocs 20.8 ms, 5.85 MB, 79.9k allocs

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

  • Met: time under the cache mutex below 20 ms per build. CPU time under the mutex is about 0.5 ms at p50 and 3 ms at p99. Wall-clock time only exceeds that when the quota throttles the holder.
  • Met: no regression in BenchmarkQUICAdmissionBurst at 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.
  • Not met: total build p99 below 200 ms under the 200m-like quota. The rebuild p99 sits right at the boundary (198–288 ms), and the registry-refresh p99 stays at about 400 ms. At 200m, wall clock is quantized into 100 ms CFS periods: a build that needs more than about 20 ms of CPU, including GC, spans at least two periods. The registry refresh's remaining cost is mostly the cluster cache rebuilding every entry as new protos (buildHTTPServiceEntryLocked plus recomputeMTLSClustersLocked proto.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, cluster aether-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_ms 91).

  • 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.

    agent first-use p99 per run builds per burst
    main 0.628, 0.202, 0.172, 0.443, 0.496, 0.266 s 2, 4, 2, 2, 5, 3
    fix 0.223, 0.296, 0.403, 0.227, 0.151, 0.187 s 1, 2, 2, 1, 2, 1

    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.
  • New tests:
    • 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 real SnapshotCache and real delta watches, with the production memo posture: a registry refresh pushes exactly the changed services' CLAs; a pod removal reports exactly its listeners in removed_resources and 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 reaches SetSnapshot with its version map already built.
    • TestSnapshotBuildRacesADSStream: builds race delta watches opening, being answered and being cancelled.
  • make gazelle, make format, and bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //... are clean.
  • No charts/ change.

Recommended agent CPU setting (separate decision for the owner; not changed here)

The agent currently has resources.requests.cpu: 200m and limits.cpu: 200m.

Recommendation: keep the 200m request and remove the CPU limit. If policy requires a limit, raise it to at least 1000m.

  • The cost is bursty and latency-critical. Steady state is near idle, but a snapshot build is a 5–25 ms CPU burst, and it sits on the path of a 2 s on_demand timeout and of drain propagation.
  • A 200m CFS quota turns any burst over about 20 ms into one or more extra 100 ms periods. In the table above, every main and fix number is close to a multiple of 100 ms.
  • The quota also parks a goroutine while it holds the cache mutex, which is the residual 80 ms ADS stall above. That residual cannot be fixed in code.
  • The request already reserves the steady-state share for scheduling. Removing the limit lets a build finish in its real CPU time: about 8–20 ms here, and the talos arm64 nodes are slower.
  • GOMAXPROCS caveat: since Go 1.25 the runtime sizes GOMAXPROCS from the cgroup CPU limit. With no limit it would follow the node's core count, so pin GOMAXPROCS=2 in 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_versions sees 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)
  • the resource_versions memo/hashed split

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

…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
@bpalermo
bpalermo merged commit 967c166 into main Oct 1, 2026
24 checks passed
@bpalermo
bpalermo deleted the perf/1105-snapshot-build-outside-mutex branch October 1, 2026 18:18
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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant