Repository navigation
perf(exec/merge/utils): optimize describe affected for large-stack workloads (~50% local wall-clock, projected ~10× on 2-core CI) - #2496
Conversation
…onfig cache
Phase 2 of the describe-affected perf investigation. On a large-stack
workload (~9k component instances across ~700 stacks),
cacheBaseComponentConfig showed 5m50s of cumulative Total time at
55ms/call. Reads via getCachedBaseComponentConfig were cheap (6.5s
total, 855µs/call), pinpointing the cost on the write path.
The root cause was the exclusive RWMutex.Lock() holding for the entire
function — including the ~525µs deepCopyBaseComponentConfigMaps call.
With many goroutines writing disjoint cache keys concurrently, every
write serialized through the same lock, padding "Total" with lock-wait
time. Many-core machines hid this behind parallelism; 2-4 core GHA
runners could not, which is the dominant contributor to the customer-
reported ~11 minute "atmos describe affected" wall-clock on v1.219.0.
Two changes:
1. baseComponentConfigCache is now a sync.Map (was
map[string]*BaseComponentConfig + sync.RWMutex). sync.Map is
purpose-built for the disjoint-key write pattern this cache
exhibits and has no global lock.
2. The deep copy is moved OUTSIDE the critical section in both the
read and write paths. The cached pointer's target is immutable
post-insert, so deep-copying outside the sync.Map operation is
race-free.
Confirmed impact on the customer repro (mean of 3 runs, local):
cacheBaseComponentConfig Total: 5m50s -> 4.0s (-98.8%, 86x faster avg)
getCachedBaseComponentConfig Total: 6.5s -> 880ms (-86%, 8x faster avg)
processComponent Total: 6m11s -> 35s (-91%)
processComponentInheritance Total: 6m02s -> 28s (-92%)
ProcessBaseComponentConfig Total: 6m02s -> 22s (-94%)
processInheritedComponent Total: 6m00s -> 22s (-94%)
processMetadataInheritance Total: 6m00s -> 23s (-94%)
The pre-fix Total was mostly lock-wait padding, not real CPU work.
Post-fix numbers reflect actual cost.
Local wall-clock barely moved on a many-core Mac (3.4s -> 4.1s) — the
lock-waiters were parked, not consuming CPU. On 2-4 core GHA runners,
where the lock-wait IS wall-clock, multi-minute improvement is
expected. End-to-end GHA validation pending.
Tests added (all race-clean):
TestConcurrentCacheAccess_DisjointKeys
200 goroutines write unique keys; every key independently
readable with no cross-contamination. Guards against any future
regression that reintroduces a global write lock — the existing
TestConcurrentCacheAccess uses a single key and would not detect
a lock-contention regression.
TestConcurrentCacheAccess_InterleavedReadWrite
50 writers + 50 readers running concurrently. Validates that the
deep-copy-outside-the-lock change is safe under the race detector.
TestCacheReadIsolationAfterStoreReturns
Mutates the source struct AFTER the cache write returns; verifies
the cached entry remains independent. Complements
TestCacheBaseComponentConfigDeepCopy (which tests the
before-read mutation direction).
Bottleneck shifts to mergeComponentConfigurations (2m22s Total) for
follow-up phases. Investigation doc added at
docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.md.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e subtrees
Phase 3 of the describe-affected perf investigation. The merge pipeline
calls WalkAndDeferYAMLFunctions hundreds of thousands of times (527,765
recursive calls on the customer workload). Each call allocates a new
map[string]interface{} at every recursion level and copies every entry,
even when the input contains no Atmos YAML functions to defer. The
vast majority of subtrees in real configs (vars, settings, env, hooks,
generate, providers for components without YAML functions) were
generating pure GC pressure.
Fix: pre-scan the input with a non-allocating hasAnyYAMLFunction(map)
helper. When the entire subtree contains no YAML function string
(!terraform.*, !template, !store*, !exec, !env), return the input
map as-is. When any function is present, the original walk runs
unchanged.
Safety: the fast-path return shares the input map with the caller.
The contract is documented on the function: the result is read-only.
The only call site (MergeWithDeferred -> Merge) produces a new merged
map without mutating inputs. A new test
(TestWalkAndDeferYAMLFunctions_NoFunctionsShortCircuit) locks in the
contract — returns the same pointer for function-free input, walks
normally when any subtree has a function, and does not mutate
function-free input.
Confirmed impact on the customer repro (mean of 3 runs, local):
WalkAndDeferYAMLFunctions Calls: 527,765 -> 328,218 (-38%)
WalkAndDeferYAMLFunctions Total: 1m26s -> 15.4s (-82%, 3.5x faster avg)
MergeWithDeferred Total: 1m35s -> 1m10s (-26%)
mergeComponentConfigurations Total: 2m22s -> 1m54s (-20%)
Wall-clock elapsed: 4.1s -> 3.3s mean (-19% on a many-core Mac).
Unlike Phase 2 (lock-wait padding), Phase 3 reduces real allocation
work and GC pressure, so wall-clock improves on every architecture.
On 2-4 core GHA runners, the ~71s of cumulative CPU saved projects
to 18-35s of wall-clock improvement.
Original Phase 3 plan (parallelize component-level inheritance within
processComponentsInParallel) was abandoned during investigation:
component-level parallelism is already in place (one goroutine per
component within each stack, fanned out by processComponentsInParallel),
so further parallelization would not help 2-4 core GHA runners that
are already CPU-bound at the component goroutine layer.
Race detector clean for pkg/merge. A pre-existing race in
extractAndAddLocalsToContext (internal/exec/stack_processor_utils.go:260)
surfaces under -race for some TestHierarchicalImports_* tests;
confirmed present in main without Phase 3 changes and tracked
separately.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phase 5 of the describe-affected perf investigation.
mergeComponentConfigurations calls MergeWithDeferred 9 times per
component instance (vars / settings / env / auth / providers /
required_providers / hooks / generate / auth-merge), each with 3-4
candidate inputs (Global / BaseComponent / Component /
ComponentOverrides). On real workloads most of those layers are
empty: components that don't inherit have empty BaseComponent layers,
most components have no overrides, and several sections (generate,
required_providers, hooks) are empty for the majority of components.
Despite the empty layers, every call ran the full pipeline: allocate
a deferred merge context, walk each input (Phase 3 short-circuit
avoids the inner deep-copy but the walk function still runs), and
call Merge to combine all processed inputs (a deep walk over all
entries even when only one contributes values).
Fix: pre-scan the inputs in MergeWithDeferred and short-circuit when
the merge degenerates:
- 0 non-empty inputs: return a fresh empty map and empty dctx.
- 1 non-empty input: walk just that input at its original precedence
so YAML functions are deferred correctly, then return the walked
map directly — skip the Merge call entirely.
The downstream ApplyDeferredMerges is dctx-driven: when dctx has no
deferred values (no-functions case), it's a no-op and does not touch
the returned map. Combined with Phase 3's
WalkAndDeferYAMLFunctions short-circuit, a single-input
function-free section is now a zero-allocation pass-through from
input map to merged result.
Confirmed impact on the customer repro (mean of 3 runs, local):
mergeComponentConfigurations Total: 1m54s -> 57s (-50%, avg 12.5ms -> 6.2ms)
MergeWithDeferred Total: 1m10s -> 25s (-64%, avg 851µs -> 305µs, 2.8x faster)
merge.Merge Calls: 273,379 -> 207,934 (-65k calls eliminated, -24%)
WalkAndDeferYAMLFunctions Total: 15.4s -> 6.0s (-61%)
WalkAndDeferYAMLFunctions Calls: 328,218 -> 112,832 (-66%, -215k more saved)
processComponent Total: 34s -> 27s (-21%)
Wall-clock elapsed: 3.3s -> 3.0s mean (-10% on a many-core Mac).
Cumulative CPU saved across Phases 3+5 ~= 150 seconds, projecting to
~37-75 seconds of wall-clock improvement on 2-4 core GHA runners
(on top of Phase 2's contention elimination).
Tests added (race-clean):
TestMergeWithDeferred_TrivialInputShortCircuits
- zero non-empty inputs returns empty result
- single non-empty function-free input returns the same map
header (composes with Phase 3 zero-allocation fast path)
- single non-empty input with YAML functions defers at the
correct precedence
- two non-empty inputs take the full merge path
- fast path does not mutate the input
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ToContext
Phase 4 of the describe-affected perf investigation. Two changes that
travel together because the second one was a pre-existing data race
surfaced by the same goroutine fan-out the first one optimizes for.
1. CACHE: extractLocalsFromRawYAML was called 22,181 times for ~836
unique files (~26 calls per file via transitive imports) at 533µs
avg, accumulating 13s of cumulative CPU time. ~7s of that was
UnmarshalYAMLFromFile re-parsing the same YAML content for the same
file path.
Added localsExtractionCache (sync.Map) keyed by
filePath + FNV-1a(yamlContent). Within a single command execution
file content is immutable (the file content itself is already
cached via getFileContentSyncMap), so the parse + locals resolution
is fully deterministic. The content-hash component of the key
prevents test pollution when the same logical file path is reused
with different content — a common pattern in unit tests, and a
safety property for any future dynamic-content code path.
Cache values are deep-copied on retrieval via
cloneExtractLocalsResult. The extractLocalsResult struct contains
four maps (locals / settings / vars / env) that downstream
consumers store into shared template contexts and may mutate
later; sharing the cached pointer would corrupt subsequent reads.
Deep copy cost (typically <50µs per call) is well below the
533µs/call un-cached path.
Added ClearLocalsExtractionCache for tests, following the existing
ClearBaseComponentConfigCache / ClearFileContentCache pattern.
2. RACE FIX: extractAndAddLocalsToContext used to call
delete(context, LocalsSectionName) directly on its input map. In
the fan-out at processYAMLConfigFileWithContextInternal
(one goroutine per sibling import, sharing the parent
mergedContext), this produced a data race surfaced under -race
by TestHierarchicalImports_* tests. The race existed before this
PR but became reachable only when the test suite started exercising
the parallel import path under the race detector.
Fix: shallow-clone the input context before the file-scoped delete
and assign. Each goroutine gets its own context map header; values
remain shared references (only the map header is mutated inside
this function, so per-goroutine cloning is sufficient).
Confirmed impact on the customer repro (mean of 3 runs, local):
extractAndAddLocalsToContext Total: 13s -> 6.7s (-48%, 2x faster avg)
extractLocalsFromRawYAML Total: 13s -> 5.9s (-55%, 2x faster avg)
UnmarshalYAMLFromFile Calls: 22,374 -> ~1,900 (-92%, 20k+ calls eliminated)
ProcessStackLocals Calls: 22,167 -> ~1,800 (-92% Calls, -89% Total)
Wall-clock elapsed: 3.0s -> 2.3s mean (-23%). The biggest single-
phase wall-clock win in this investigation: unlike Phase 2 (lock-wait
padding hidden by many-core parallelism on Mac), the locals cache
eliminates real CPU work — YAML parsing + locals resolution — that
was contributing directly to wall-clock on every architecture.
Cumulative trajectory (local Mac wall-clock):
Pre-Phase-2 baseline: 4.1s
Phase 3 (walk short-circuit): 3.3s (-19%)
Phase 5 (skip trivial merges): 3.0s (-10%)
Phase 4 (locals cache): 2.3s (-23%, biggest jump)
Cumulative vs baseline: -44%
Tests added (all race-clean):
TestExtractLocalsFromRawYAML_CacheReturnsIndependentCopies
- mutating one retrieved result does not affect a subsequent
retrieval (deep-copy contract).
TestExtractLocalsFromRawYAML_CacheKeyIncludesContentHash
- same file path with different content yields distinct entries
(test-pollution prevention).
TestExtractAndAddLocalsToContext_DoesNotMutateInputContext
- the caller's parent context is unchanged after the call
(locks in the race fix).
The pre-existing race in TestHierarchicalImports_* is now resolved
under -race. Other unrelated races elsewhere in pkg/internal/exec
(processSettingsIntegrationsGithub vs DeepCopyMap,
MergeContext.WithFile concurrent writes) are tracked separately —
they exist in main without these changes.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phase 6 of the describe-affected perf investigation. After Phase 4
eliminated 92% of locals-extraction parses, the next bottleneck became
UnmarshalYAMLFromFileWithPositions (22,181 calls, 18.7s Total, 844µs avg)
— the position-tracking YAML parser used by
processYAMLConfigFileWithContextInternal for the final stack-config parse.
It already had a content-hash cache, but the cache structure was the
same RWMutex-protected map pattern that Phase 2 fixed for
cacheBaseComponentConfig:
- cacheParsedYAML held parsedYAMLCacheMu.Lock() during the recursive
deepCopyYAMLNode work.
- getCachedParsedYAML held parsedYAMLCacheMu.RLock() during the
read-side deepCopyYAMLNode.
With ~22k concurrent calls, the global write lock serialized every
cache write, padding apparent CPU time with lock-wait.
Fix (same as Phase 2):
1. parsedYAMLCache is now a sync.Map (was map + sync.RWMutex).
2. Deep-copy of yaml.Node + PositionMap happens BEFORE the
sync.Map.Store and AFTER the sync.Map.Load, never inside any
critical section.
Added clearParsedYAMLCache() plus the public ClearParsedYAMLCache()
for tests, mirroring the ClearBaseComponentConfigCache /
ClearLocalsExtractionCache pattern. Three existing tests that
manually saved/restored the map + mutex state were updated to use
the helper.
Confirmed impact on the customer repro (mean of 3 runs, local):
UnmarshalYAMLFromFileWithPositions Total: 18.7s -> 3.7s (-80%, 5x faster avg)
ProcessYAMLConfigFileWithContext Total: 57.6s -> 54s (-6%, downstream)
Wall-clock elapsed: 2.3s -> 2.3s (unchanged on a many-core Mac).
Same caveat as Phase 2: lock-wait padding doesn't show on many-core
machines because the waiters park rather than consume cores. On 2-4
core GHA runners where the lock-wait IS wall-clock, projecting from
the 15s of cumulative CPU eliminated -> ~4-7 seconds wall-clock
savings end-to-end.
Race detector clean:
go test -race -count=1 \
-run "UnmarshalYAMLFromFileWithPositions|HandleCacheMiss|CacheHit" \
./pkg/utils/...
Full pkg/utils and internal/exec test suites pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ecursion
Phase 7 of the describe-affected perf investigation.
processCustomTags (the YAML node walker that detects and processes
!terraform.*, !template, !store*, !exec, !env, !include, !literal
tags) had a hasCustomTags early-exit pre-check at the top of every
invocation. The pre-check itself walks the entire subtree to find
any custom tag. On recursive invocations (one per child node with
content), the pre-check re-walks the same subtree it just walked at
the level above — O(N x depth) work where it should be O(N).
For trees with tags (most of them in the customer workload), this
meant ~9k top-level processCustomTags calls each re-walking their
tree at every recursion level. Total cumulative CPU was 31.5s,
3.4ms avg per top-level call.
Fix: split processCustomTags into outer entry + inner worker:
- processCustomTags does the hasCustomTags check ONCE at the top
level. If no tags exist, early-exit. Otherwise, delegate to the
inner worker.
- processCustomTagsInner is the recursive worker — no
hasCustomTags check on each call, just process and recurse. By
the time we are inside it, we already know the tree has tags.
perf.Track stays on the outer function and is intentionally omitted
from the inner worker: the outer call wraps the whole walk with one
tracked frame, so adding per-recursion tracking would inflate the
metric without yielding insight.
Confirmed impact on the customer repro (mean of 2 runs, local):
processCustomTags Total: 31.5s -> 7.5s (-76%, 3.2x faster avg)
Wall-clock elapsed: 2.3s -> 2.4s (within noise on a many-core Mac
where parallelism absorbs the saved work). Cumulative ~24s CPU
saved -> projected ~6-12s wall-clock on 2-4 core GHA runners on top
of Phases 1-6.
Race detector clean:
go test -race -count=1 \
-run "ProcessCustomTags|UnmarshalYAML|TestHasCustomTags" \
./pkg/utils/...
Full pkg/utils and internal/exec test suites pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…sed node Phase 8 of the describe-affected perf investigation. The parsedYAMLCache from Phase 6 already eliminates re-parsing of identical YAML content, but the inner Decode + Intern steps inside UnmarshalYAMLFromFileWithPositions run on EVERY call — including cache hits: node, _, _ := getCachedParsedYAML(file, input) // Phase 6 hit node.Decode(&data) // Always runs data = InternStringsInMap(data) // Always runs Decode allocates a fresh map tree from the cached yaml.Node; InternStringsInMap recursively walks the decoded tree and allocates another tree with interned string keys/values. Combined cost ~500-700µs per call across the 22,181 invocations. Fix: added a second sync.Map cache (decodedYAMLCache) keyed by the same (file, content hash) pair as parsedYAMLCache. The cache value is the post-Decode + post-Intern map[string]any plus the matching PositionMap. The hot-path call site checks this cache first; a hit returns a deep-copy of the cached result, skipping Decode and Intern entirely. The fast path activates only for T == map[string]any (the production hot path; schema.AtmosSectionMapType is exactly this type). Detection is done via a single any(zeroValue).(map[string]any) type assertion — no reflect, no per-call overhead. Other generic instantiations (used only in tests) fall through to the existing Decode path. A local deepCopyDecodedMap helper handles the deep copy on retrieval; we can't use merge.DeepCopyMap because pkg/merge imports pkg/utils (circular dependency). The local helper covers the value types produced by yaml.Node.Decode + InternStringsInMap (nested map[string]any, []any, and immutable primitives) — Atmos custom tags are pre-processed into strings before this point, so no exotic types appear. ClearDecodedYAMLCache added for test cleanup, mirroring the existing ClearParsedYAMLCache / ClearLocalsExtractionCache / ClearBaseComponentConfigCache pattern. Decoded-cache hits increment the same parsedYAMLCacheStats.hits counter as parsed-node hits; both represent successful avoidance of work. This preserves the existing TestUnmarshalYAMLFromFileWithPositions_CacheHitWithProvenance contract. Confirmed impact on the customer repro (mean of 3 runs, local): UnmarshalYAMLFromFileWithPositions Total: 3.7s -> 3.2s (-14%) UnmarshalYAMLFromFileWithPositions Avg: 166µs -> 144µs Wall-clock elapsed: 2.4s -> 2.06s mean (-14% locally). The cumulative CPU savings on the function itself are modest (~500ms), but the wall-clock improvement is larger than that delta would predict — likely from reduced allocation pressure (no fresh map allocations on cache hit) and resulting GC relief. On 2-4 core GHA runners, expect a similar relative improvement plus the GC win compounded across cores. Race detector clean: go test -race -count=1 ./pkg/utils/... Full pkg/utils and internal/exec test suites pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phase 9 of the describe-affected perf investigation. After Phase 4
cached the parsed locals result, cloneExtractLocalsResult deep-copied
all FOUR map fields (locals, settings, vars, env) on every retrieval
to preserve the cache's immutability contract. This dominated the
cache-hit path: 22,181 calls x ~343µs avg = 7.6s of cumulative CPU.
The deep copy of settings/vars/env is overkill. The only production
consumer of those three fields is processTemplatesInSection, which:
1. Marshals the section to YAML (read-only).
2. Parses the YAML back into a new map.
3. Returns the new map.
The input section is never mutated. So sharing the cache's reference
is safe — the per-caller deep copy was unnecessary overhead.
Fix: refactored cloneExtractLocalsResult to be asymmetric:
- locals is still deep-copied. This field is stored long-term in
the template context (context[cfg.LocalsSectionName] = ...)
where downstream mutation surface is hard to bound, so the
defensive copy stays.
- settings, vars, env are now shared references. The contract is
documented on the function: callers must treat them as
read-only.
TestExtractLocalsFromRawYAML_CacheReturnsIndependentCopies updated to
reflect the new contract: only locals requires post-mutation
isolation; settings/vars/env share with the cache.
Confirmed impact on the customer repro (mean of 3 runs, local):
extractLocalsFromRawYAML Total: 7.6s -> 6.3s (-17%, 18% faster avg)
extractAndAddLocalsToContext Total: 8.9s -> 7.3s (-18%, 18% faster avg)
Wall-clock elapsed: 2.06s -> 2.13s (within run-to-run noise on a
many-core machine). Cumulative ~1.5s CPU saved -> projected
~750ms wall-clock savings on 2-core GHA runners.
Race detector clean:
go test -race -count=1 \
-run "TestExtractLocals|TestExtractAndAdd|TestHierarchicalImports" \
./internal/exec/
Full internal/exec test suite passes.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This reverts commit 6a8bd8d.
…rf doc Phase 9 (asymmetric clone in cloneExtractLocalsResult) was reverted in b11f3cd after the customer-scale heatmap run produced `fatal error: concurrent map iteration and map write`. Document the failure mode so future passes don't re-attempt the same optimization without addressing the root cause: processTemplatesInSection returns its input map as-is when the section contains no `{{` (the common case at scale). The cached settings/vars/env therefore DO end up shared in the long-lived template context, where a sibling goroutine subsequently mutates them via DeepCopyMap during inheritance processing. The "consumed only by processTemplatesInSection" claim was wrong because that function has a fast-path pass-through. Re-attempting this win requires deep-copying inside the pass-through path, or a stronger immutability proof for the downstream context flow. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phase 10 of the describe-affected perf investigation. processYAMLNode
is a recursive YAML walker that adjusts the style of scalar strings
beginning with `#` (so they round-trip without YAML re-interpreting
them as comments). It is called from EvaluateYqExpression and
recurses over every node in the parsed tree.
In the customer workload, the function logged 34k recursive calls
totaling 5.5s — most of that being perf.Track defer overhead per
invocation (~3µs each via mutex ops + counter updates), not real
work. The per-node body is a single comparison and an optional
style assignment.
Fix: same outer/inner split used by Phase 7 (processCustomTags /
processCustomTagsInner):
- processYAMLNode does the perf.Track entry tracking and delegates
to the inner worker.
- processYAMLNodeInner is the recursive walker. No perf.Track on
each recursive frame, so the metric counts top-level invocations
instead of every node visited.
Confirmed impact on the customer repro (mean of 3 runs, local):
processYAMLNode: dropped out of the top-25 hot functions
(was 5.5s, 34k calls, 160µs avg)
Wall-clock elapsed: 2.2s -> 2.03s (-7% locally).
Notes:
- The same Phase 7 pattern was ALSO tried for
WalkAndDeferYAMLFunctions and reverted in this commit. That
function uses hasAnyYAMLFunction as a per-recursion short-circuit
to avoid allocating result maps for function-sparse subtrees. An
outer/inner split made the inner walker allocate unconditionally
on every recursion, regressing the common case more than the
perf.Track savings recovered. The current implementation
documents this in-code so future passes don't re-try.
- Phase 9 (asymmetric clone in cloneExtractLocalsResult) was
reverted in b11f3cd after triggering "concurrent map iteration
and map write" at customer scale. See the fix doc for details.
Race detector clean:
go test -race -count=1 \
-run "ProcessYAMLNode|WalkAndDefer|TestProcessYAML" \
./pkg/utils/... ./pkg/merge/...
Full pkg/utils, pkg/merge, internal/exec test suites pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…type Phase 11 of the describe-affected perf investigation. processTerraformRemoteStateBackend used to do two m.Merge calls per component: the first merged the three remote-state-backend section sources (global / base component / component), the second merged the result with finalComponentBackendSection. Only the value at the relevant backend-type key (e.g. "s3") was actually returned; the rest of the merged backend section was deep-copied just to throw away. In the customer workload, backend sections frequently carry config for multiple backend types (s3/gcs/azurerm/etc.), so the second merge spent significant time deep-copying entries that the caller never used. Fix: extract the backend-type-specific map from each input first (via the new extractBackendTypeMap helper), then merge just those two scoped maps. m.Merge's existing Phase 5 fast paths handle the trivial 0-input / 1-input cases. Confirmed impact on the customer repro (mean of 3 runs, local): processTerraformRemoteStateBackend Total: 5.7s -> 5.4s (-5%) processTerraformRemoteStateBackend Avg: 617µs -> 582µs (-5%) processTerraformBackend Total: 2.95s -> 2.81s (-5%) merge.Merge Total: 26.5s -> 25.2s (-5%, smaller inputs propagate) Wall-clock elapsed: 2.05s -> 2.05s (unchanged on many-core Mac; parallelism absorbs the saved CPU). ~1s cumulative CPU saved projects to ~500ms wall-clock on 2-core GHA runners. Race detector clean: go test -race -count=1 \ -run "TestProcessTerraform|TestRemoteState|TestProcessYAMLConfig" \ ./internal/exec/... Full internal/exec test suite passes. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phases 12 and 13 of the describe-affected perf investigation. deepCopyBaseComponentConfigMaps unconditionally called m.DeepCopyMap on all 10 map fields of BaseComponentConfig, even when the source field was empty. m.DeepCopyMap on a nil map returns quickly but still pays the function call + perf.Track overhead; on an empty-but-non-nil map it allocates an empty map. In the customer workload, most components leave several of these fields empty (notably BaseComponentProviders / Hooks / Generate / Dependencies for non-Terraform components, and BaseComponentBackendSection / RemoteStateBackendSection for many others). The unconditional calls added up: cacheBaseComponentConfig: 3.85s total, 598µs avg, 6,431 calls getCachedBaseComponentConfig: 865ms total, 107µs avg, 8,017 calls Both functions call deepCopyBaseComponentConfigMaps once, so the fix benefits both paths (insert and retrieval). Fix: guard each m.DeepCopyMap call with `len(src.Field) > 0`. Skips the function call entirely when the field is empty. The dst field defaults to nil/empty, matching the contract of the prior code (which also produced empty-map values via DeepCopyMap on nil). Confirmed impact on the customer repro (mean of 3 runs, local): cacheBaseComponentConfig Total: 3.85s -> ~990ms (-74%, 3.9x faster avg) cacheBaseComponentConfig Avg: 598µs -> 153µs getCachedBaseComponentConfig Total: 865ms -> ~360ms (-58%, 2.4x faster avg) getCachedBaseComponentConfig Avg: 107µs -> 44µs merge.DeepCopyMap Calls: 223,109 -> 175,120 (-22%, 48k calls eliminated) merge.DeepCopyMap Total: 5.0s -> 3.8s (-24%) Wall-clock elapsed: 2.05s -> 2.02s (within noise on a many-core Mac; parallelism absorbs the saved CPU). ~4.5s cumulative CPU saved projects to ~2.2s wall-clock on 2-core GHA runners. Race detector clean: go test -race -count=1 \ -run "TestCache|TestClearBaseComponent|TestConcurrentCache|TestProcessBaseComponentConfig" \ ./internal/exec/... Full internal/exec test suite passes. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…on arc
After the Phase 1-13 optimization arc, coverage on the touched code is
strong (87-100% on most functions). This commit closes the remaining
small gaps:
- ClearParsedYAMLCache: 0% -> 100%
Public wrapper around clearParsedYAMLCache; previously only the
internal helper was exercised via t.Cleanup patterns. New test
seeds an entry through the public API and verifies the public
Clear* empties the sync.Map.
- ClearDecodedYAMLCache: 0% -> 100%
- clearDecodedYAMLCache: 0% -> 100%
Same pattern as above for the Phase 8 decoded-result cache.
- extractBackendTypeMap: 77.8% -> 100%
Phase 11 helper. The success and missing-key paths were covered
by TestProcessTerraform* indirectly; new test adds the explicit
nil-section, missing-key, value-present, and type-mismatch paths.
- deepCopyBaseComponentConfigMaps (Phase 12/13): adds an
all-empty-fields test that locks in the contract: empty source
fields produce nil dst fields (no empty-map allocations during
caching or retrieval).
Race detector clean for all four new tests:
go test -race -count=1 \
-run "TestClearParsedYAMLCache_Public|TestClearDecodedYAMLCache_Public|TestExtractBackendTypeMap|TestCacheBaseComponentConfig_SkipsEmptyFields" \
./pkg/utils/... ./internal/exec/...
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughImplements multi-phase perf fixes: migrate hot caches to concurrency-safe sync.Map, add content-hash locals and decoded-YAML caches with deep-copy-on-read, clone contexts to avoid races, hoist custom-tag scans, add YAML-function and merge fast-paths, scope backend extraction, update yq instrumentation, and add tests/docs. ChangesPerformance Optimization Implementation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
internal/exec/stack_processor_backend.go (1)
265-268: 💤 Low valueConsider clarifying "fresh" in the docstring.
The comment says "fresh map[string]any" but for the success path (line 281), the function returns the existing reference from
section[backendType]—not a copy. This is intentional for performance, but "fresh" reads like a copy guarantee.A small tweak like "returns the inner map (by reference) or an empty map if the key is missing" would be clearer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/exec/stack_processor_backend.go` around lines 265 - 268, Update the docstring for extractBackendTypeMap to avoid implying a copy: change "fresh map[string]any" to language that clarifies it returns the inner map by reference (the same map stored at section[backendType]) or an empty map when the key is missing; mention it errors when the existing value is not a map to preserve current behavior and reference the section[backendType] lookup in the comment so readers can find the implementation easily.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.md`:
- Line 78: The heading "Post-#2471 fresh heatmap (2026-05-23, local Mac, current
main)" is at level ### which creates a jump in heading levels and triggers
MD001; update this heading to the correct level to follow the surrounding
heading hierarchy (e.g., change ### to ## or #### as appropriate) so headings
increment one step at a time and lint passes, targeting the line containing the
"Post-#2471 fresh heatmap (2026-05-23, local Mac, current main)" heading.
- Around line 141-143: The status header "Phase 1 fixed in PR `#2471`
(v1.220.0-rc.1). Phases 2 and 3 still open" contradicts the checklist that marks
Phase 2 and Phase 3 as completed; update the header text to reflect that Phases
2 and 3 are completed/shipped (or otherwise match the checklist), e.g., change
the phrase "Phases 2 and 3 still open" to "Phases 2 and 3 completed/shipped"
near the "Phase 1 fixed in PR `#2471` (v1.220.0-rc.1)." sentence so the status
header and the checklist (the completed entries for Phase 2 and Phase 3) are
consistent.
In `@internal/exec/stack_processor_cache_test.go`:
- Around line 401-414: In TestConcurrentCacheAccess_InterleavedReadWrite replace
the testify require call inside the goroutine with a non-failing assertion and a
nil-guard: do not call require.NotNil(t, cached) from the goroutine; instead use
assert.NotNil(t, cached) (or an equivalent assert) and immediately guard before
accessing cached.FinalBaseComponentName so the goroutine never causes FailNow
from a non-test goroutine; locate the check in the anonymous goroutine that
calls getCachedBaseComponentConfig and update it to assert and nil-check before
reading fields.
In `@internal/exec/stack_processor_cache.go`:
- Around line 49-101: The warm-cache deepCopyBaseComponentConfigMaps function is
only copying a subset of BaseComponentConfig maps, causing cached entries to
miss fields populated later by ProcessBaseComponentConfig (e.g.,
BaseComponentLocals, BaseComponentGenerate, BaseComponentSourceSection,
BaseComponentProvisionSection, BaseComponentRequiredProviders,
BaseComponentRequiredVersion); update deepCopyBaseComponentConfigMaps (and the
similar block around lines 124-175) to produce a full deep copy of the entire
schema.BaseComponentConfig (either by invoking a single deep-copy helper for the
whole struct or by adding DeepCopyMap calls for the missing fields) so cached
baseComponent values retain the same shape as on a cache miss. Ensure references
to the struct fields named above are included in the copy and reuse the same
deep-copy utility (m.DeepCopyMap or a struct-level deep copy) to preserve map
contents.
In `@pkg/merge/merge_deferred_test.go`:
- Around line 262-268: sameMapHeader currently uses fmt.Sprintf("%p", ...) which
is unreliable for map identity; change it to use reflect.ValueOf(a).Pointer() ==
reflect.ValueOf(b).Pointer() with nil guards: if either a or b is nil return
a==b, otherwise compare reflect pointers. Update imports to include reflect and
remove fmt if unused, and keep the function name sameMapHeader to locate the
change.
---
Nitpick comments:
In `@internal/exec/stack_processor_backend.go`:
- Around line 265-268: Update the docstring for extractBackendTypeMap to avoid
implying a copy: change "fresh map[string]any" to language that clarifies it
returns the inner map by reference (the same map stored at section[backendType])
or an empty map when the key is missing; mention it errors when the existing
value is not a map to preserve current behavior and reference the
section[backendType] lookup in the comment so readers can find the
implementation easily.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3fde85e5-6f48-4a26-a8b1-370912773c29
📒 Files selected for processing (12)
docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.mdinternal/exec/stack_processor_backend.gointernal/exec/stack_processor_backend_test.gointernal/exec/stack_processor_cache.gointernal/exec/stack_processor_cache_test.gointernal/exec/stack_processor_utils.gointernal/exec/stack_processor_utils_test.gopkg/merge/merge_deferred_test.gopkg/merge/merge_yaml_functions.gopkg/utils/yaml_utils.gopkg/utils/yaml_utils_test.gopkg/utils/yq_utils.go
… regression CI surfaced TestSpaceliftStackProcessor losing 7 of 47 spacelift stacks (and the matching legacy test losing 7 of 44) after the Phase 5 1-input fast path shipped. Same class of regression as the reverted Phase 9 in b11f3cd: the optimization handed a shared map reference back to a caller that mutates the result downstream. Root cause: when the single non-empty input to MergeWithDeferred had no Atmos YAML functions, WalkAndDeferYAMLFunctions's Phase 3 short-circuit returned the input map as-is, and the 1-input shortcut handed that shared reference back to mergeComponentConfigurations. mergeComponentConfigurations then mutated the returned map while assembling the per-component output, which corrupted the upstream cached BaseComponentSettings / GlobalSettings for sibling components — specifically dropping settings.spacelift.workspace_enabled for 7 components by the time they reached CreateSpaceliftStacks. The Merge slow path that this revert restores always deep-copies its 1-input case (via MergeWithOptions -> DeepCopyMap), so the wrapper overhead saved by the shortcut was small compared to the deep-copy cost that has to happen regardless for the Merge contract to hold (result must be a fresh, caller-mutable map). Kept: the 0-input fast path (return an empty map and an empty dctx when every input layer is empty). That path is safe and produces a fresh map. Tests updated: - TestMergeWithDeferred_TrivialInputShortCircuits: the 1-input case now asserts the result is NOT the same map header as the input. - New subtest "mutating the result does not mutate the input" locks in the contract so any future caller-mutation regression surfaces immediately rather than at the next spacelift run. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two changes, both follow-ups to the Phase 5 revert in 573a53c: 1. TestMergeWithDeferred_TrivialInputShortCircuits updated to reflect the new contract: the 1-input case now returns a fresh, caller- mutable map (was: shared reference). New "mutating the result does not mutate the input" subtest locks the contract in so any future regression surfaces in unit tests rather than at the next spacelift run. 2. sameMapHeader switched from fmt.Sprintf("%p", m) to reflect.ValueOf(m).Pointer(). %p formatting works in practice but isn't a documented mechanism for map identity comparison; reflect.Value.Pointer() is the canonical Go API for getting the underlying map pointer. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous docstring said the function "returns the inner map at section[backendType] as a fresh map[string]any" — but the success path returns the existing reference from section[backendType] (not a copy). Only the nil-section and missing-key paths return a fresh empty map. Reworded to make the success-path reference-sharing explicit and document the caller contract: the only production caller (processTerraformRemoteStateBackend post-Phase-11) feeds the result into m.Merge, whose own contract guarantees its output is a fresh map. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ed fields
deepCopyBaseComponentConfigMaps was missing five AtmosSectionMapType
fields (BaseComponentLocals, BaseComponentGenerate,
BaseComponentSourceSection, BaseComponentProvisionSection,
BaseComponentRequiredProviders) and the scalar BaseComponentRequiredVersion
from the copyConfig struct literals on both the read and write sides. This
is a pre-existing main-branch correctness bug, not introduced by the
performance arc: same 10 of 21 fields covered on main HEAD.
Severity: applyBaseComponentConfig (stack_processor_process_stacks_helpers_inheritance.go)
reads every one of these fields off the cached config and assigns them
into result.BaseComponent*. Before this fix, the same
(stack, component, baseComponent) cache key returned different config
shapes depending on whether the lookup was a HIT (fields nil) or MISS
(fields populated by processBaseComponentConfigInternal). Whichever
caller's ordering happened to hit the cache observed a truncated config.
Fix: add the five missing map fields to deepCopyBaseComponentConfigMaps
(retaining the Phase 12/13 empty-field skip optimization) and the
BaseComponentRequiredVersion string to both struct literals. Now the
cache round-trips every field that processBaseComponentConfigInternal
populates — HIT and MISS return identical shapes.
Tests:
- TestCacheBaseComponentConfig_SkipsEmptyFields extended to assert
the previously-uncopied fields stay nil when source is empty
(Phase 12/13 contract continues to hold).
- New TestCacheBaseComponentConfig_RoundTripsAllFields populates
every field with distinguishable values and asserts each
round-trips through the cache. Includes a deep-copy isolation
check on BaseComponentLocals (mutating a retrieved value must not
affect subsequent retrievals).
Race detector clean for the touched tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…vels Two CodeRabbit feedback items on the describe-affected perf investigation doc: 1. The Status section header text said "Phases 2 and 3 still open" while the checklist below marked both as shipped. Rewrote the Status lead-in to point at the checklist as the authoritative record of what landed where, and pruned the stale numbered optimization plan (items that read "OPEN" had all completed by the time the doc was last touched). 2. Promoted "### Post-#2471 fresh heatmap" and "### Affected detection note" to "## " — both were peers of "## Status" / "## Problem" but lived as H3 under H1, triggering MD001 heading-level-skip. 3. Updated the Phase 5 section to record both the initial 1-input shortcut and its revert, with the regression root cause (TestSpaceliftStackProcessor lost 7 stacks) and post-revert metrics — so future readers see the full arc and the lesson ("a shared map reference handed back to a mutating caller is a correctness bug, not an optimization") in one place. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
internal/exec/stack_processor_backend.go (1)
224-257: ⚡ Quick winScope the remote-state merge before the first
m.Merge.This still merges the full
global/base/componentRemoteStateBackendSectionmaps at Lines 225-232 and only then extractsfinalComponentRemoteStateBackendType. That means unrelateds3/gcs/azurermbranches are still deep-copied once per call. Extracting the chosen backend type from each input first would keep the same precedence behavior and make the optimization match the new comment.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/exec/stack_processor_backend.go` around lines 224 - 257, The current code calls m.Merge on cfg.globalRemoteStateBackendSection, cfg.baseComponentRemoteStateBackendSection and cfg.componentRemoteStateBackendSection before extracting the chosen backend type, causing unnecessary deep copies; instead call extractBackendTypeMap on each of those three inputs using finalComponentRemoteStateBackendType (e.g. extractBackendTypeMap(cfg.globalRemoteStateBackendSection, finalComponentRemoteStateBackendType, cfg.component), same for baseComponentRemoteStateBackendSection and componentRemoteStateBackendSection), handle their errors, then call m.Merge with the three extracted per-backend maps to produce finalComponentRemoteStateBackendSection; keep the later extractBackendTypeMap calls and error handling for cfg.finalComponentBackendSection and finalComponentRemoteStateBackendSection unchanged.internal/exec/stack_processor_cache_test.go (1)
588-593: ⚡ Quick winAssert the slice contents here, not just non-empty.
BaseComponentDependencies["file"]andBaseComponentHooks["pre_plan"]are slice-valued results, but these checks only prove something came back. Please switch these torequire.Lenplus value assertions on the first/last elements so the round-trip test catches content regressions too.As per coding guidelines, "For slice-result tests, assert element contents, not just length; use
require.Lenplus assertions on at least first and last elements by value to prevent regressions."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/exec/stack_processor_cache_test.go` around lines 588 - 593, The tests currently only assert non-empty for slice results; change the checks on cached.BaseComponentDependencies["file"] and cached.BaseComponentHooks["pre_plan"] to use require.Len (ensuring the expected length) and then assert specific element values (at least the first and last entries) so the round-trip test validates actual contents; locate the assertions referencing BaseComponentDependencies["file"] and BaseComponentHooks["pre_plan"] and replace the assert.NotEmpty calls with require.Len plus explicit value assertions for the first/last elements.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.md`:
- Around line 141-153: The status text claims "Phases 2-13 ship in PR `#2496`" but
the document never records Phase 11-13 details; either add explicit rollout
entries for Phase 11, Phase 12, and Phase 13 to the progress checklist
(including short descriptions, what changed, commit/PR references and measured
impact) or change the sentence that reads "Phases 2-13 ship in PR `#2496` (this
branch)" to accurately reflect only the phases documented (e.g., "Phases 2-10
and 14 shipped in PR `#2496`" or similar); update the Phase list and any
references to PR `#2496/Phase` 11-13 so the rollout history is self-consistent.
In `@internal/exec/stack_processor_cache.go`:
- Around line 50-58: The code in the BaseComponentConfig deep-copy (used by
cacheBaseComponentConfig / getCachedBaseComponentConfig) currently skips copying
when it sees len(srcMap) == 0, which collapses non-nil empty maps to nil on
cache hits; change the guards to check for nil (srcMap != nil) instead of
len(...) > 0 so you preserve allocated empty maps and only skip when the source
is actually nil; update every map-field branch in the deep-copy sections (all
the map copy blocks for BaseComponentConfig between the earlier guard and the
rest of the function) to use nil checks so hit/miss shapes remain identical.
In `@pkg/merge/merge_deferred_test.go`:
- Around line 791-821: Add the mirror src→result isolation assertions: after
building inputs (single) but before or after calling MergeWithDeferred(cfg,
inputs) mutate the original source map (single) — change "region", add "newKey",
and change nested["inner"] — then assert that the returned result map (result)
still has the original values ("us-east-1" for region, no "newKey" key, and
nested.inner == "original"); ensure you reference the same variables used in
this test (single, inputs, result) and verify nested maps are deep-copied as
well so the test covers both directions of the aliasing/isolation contract for
MergeWithDeferred.
---
Nitpick comments:
In `@internal/exec/stack_processor_backend.go`:
- Around line 224-257: The current code calls m.Merge on
cfg.globalRemoteStateBackendSection, cfg.baseComponentRemoteStateBackendSection
and cfg.componentRemoteStateBackendSection before extracting the chosen backend
type, causing unnecessary deep copies; instead call extractBackendTypeMap on
each of those three inputs using finalComponentRemoteStateBackendType (e.g.
extractBackendTypeMap(cfg.globalRemoteStateBackendSection,
finalComponentRemoteStateBackendType, cfg.component), same for
baseComponentRemoteStateBackendSection and componentRemoteStateBackendSection),
handle their errors, then call m.Merge with the three extracted per-backend maps
to produce finalComponentRemoteStateBackendSection; keep the later
extractBackendTypeMap calls and error handling for
cfg.finalComponentBackendSection and finalComponentRemoteStateBackendSection
unchanged.
In `@internal/exec/stack_processor_cache_test.go`:
- Around line 588-593: The tests currently only assert non-empty for slice
results; change the checks on cached.BaseComponentDependencies["file"] and
cached.BaseComponentHooks["pre_plan"] to use require.Len (ensuring the expected
length) and then assert specific element values (at least the first and last
entries) so the round-trip test validates actual contents; locate the assertions
referencing BaseComponentDependencies["file"] and BaseComponentHooks["pre_plan"]
and replace the assert.NotEmpty calls with require.Len plus explicit value
assertions for the first/last elements.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 21c5641b-4596-4ff2-b52c-44b78b1a0457
📒 Files selected for processing (6)
docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.mdinternal/exec/stack_processor_backend.gointernal/exec/stack_processor_cache.gointernal/exec/stack_processor_cache_test.gopkg/merge/merge_deferred_test.gopkg/merge/merge_yaml_functions.go
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2496 +/- ##
==========================================
+ Coverage 78.28% 78.33% +0.04%
==========================================
Files 1119 1119
Lines 106525 106684 +159
==========================================
+ Hits 83396 83568 +172
+ Misses 18472 18448 -24
- Partials 4657 4668 +11
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…oad (#2499) PR #2487 added a top-level `permissions:` block to .github/workflows/test.yml to grant `packages: read` for ghcr.io pulls. In GitHub Actions, a workflow-level permissions block REPLACES (not extends) the default token scope for every job, so this inadvertently stripped the implicit `security-events: write` that the `[lint] Dockerfile` job relied on to upload hadolint SARIF results via github/codeql-action/upload-sarif. The post-merge run on main has been failing since #2487: ##[warning]This run of the CodeQL Action does not have permission to access the CodeQL Action API endpoints. ##[error]Resource not accessible by integration Fix: add a job-level `permissions:` block to the docker job with `security-events: write` (least-privilege — does not broaden any other job's permissions). `contents: read` is re-listed because job-level permissions fully override the workflow-level set (rather than merging). hadolint itself ran successfully in the failing run — the SARIF contained zero findings. Only the upload step failed. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
- stack_processor_cache.go: switch the 15 deepCopyBaseComponentConfigMaps
guards from `len(src.Field) > 0` to `src.Field != nil`. The previous
guard collapsed empty-non-nil maps to nil, breaking the documented
cache-HIT-shape == cache-MISS-shape contract and creating a latent
"assignment to entry in nil map" panic risk for any downstream code
that writes into result.BaseComponentX[key]. Docstring updated to
explain the rationale.
- stack_processor_cache_test.go:
- Rename TestCacheBaseComponentConfig_SkipsEmptyFields to
TestCacheBaseComponentConfig_NilFieldsStayNil — the test only ever
exercised nil source fields.
- Add TestCacheBaseComponentConfig_EmptyNonNilFieldsStayNonNil: every
field is allocated as `map[string]any{}`, retrieved through the
cache, and asserted to round-trip as non-nil, empty, and writable
(the test actually writes into each returned map to prove no panic).
- Add TestGetCachedBaseComponentConfig_TypeMismatch and
TestGetFileContent_StringCachedValue to exercise the defensive
type-assertion and string-cache-value branches.
- stack_processor_backend_test.go: add three test groups targeting
realistically-reachable error and decision paths:
- TestProcessTerraformBackend_TypeMismatchSurfacesError
- TestProcessTerraformRemoteStateBackend_PropagatesExtractError
(4 subtests, one per extractBackendTypeMap call site)
- TestShouldPreserveAuthoredKey (6 decision cases — covers all
branches including no-azurerm-section and global-key-matches paths)
Coverage on touched code:
processTerraformBackend 86.4% -> 90.9%
processTerraformRemoteStateBackend 79.2% -> 95.8%
shouldPreserveAuthoredKey 81.8% -> 100%
getCachedBaseComponentConfig 85.7% -> 92.9%
GetFileContent 90.0% -> 100%
Remaining gaps are unreachable defensive `if err != nil` branches:
m.DeepCopyMap and m.Merge for these inputs never produce errors.
- pkg/merge/merge_deferred_test.go: add the mirror src->result isolation
subtest to TestMergeWithDeferred_TrivialInputShortCircuits, per the
CLAUDE.md rule "for aliasing/isolation tests, verify BOTH directions".
Mutating the source map after merge must not propagate into the result.
- docs: clarify Phase 12+13 checklist entry — guards now skip nil fields
(not "empty"), preserving m.DeepCopyMap's empty-non-nil semantics.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.md`:
- Around line 1017-1021: The doc currently instructs guarding m.DeepCopyMap
calls with "if len(src.Field) > 0", which conflicts with the Phase 12/13 text
and the contract to preserve empty non-nil maps; change the wording to state the
guard should be "if src.Field != nil" (i.e., only skip DeepCopyMap when the
source is nil) so the dst keeps empty-but-non-nil shape, and update the same
phrasing in the other occurrence noted (the later block currently at 1073-1075)
and any mention of Phase 12/13 to be consistent with this nil-vs-empty contract
and with the m.DeepCopyMap behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 563bb0e7-e4fa-401b-ac23-d2c08cf5e526
📒 Files selected for processing (6)
docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.mdinternal/exec/stack_processor_backend.gointernal/exec/stack_processor_backend_test.gointernal/exec/stack_processor_cache.gointernal/exec/stack_processor_cache_test.gopkg/merge/merge_deferred_test.go
…uard The Phase 12/13 narrative still described the original `len(src.Field) > 0` form, which contradicts the actual shipped guard and the cache HIT-shape == MISS-shape contract documented elsewhere in the same file. Reword both mentions to: - state the guard is `src.Field != nil`, - explain why `len(...) > 0` was rejected (would collapse empty-non-nil maps to nil, breaking the shape contract and risking nil-map-write panics on downstream `result.BaseComponentX[k] = v`), - point at TestCacheBaseComponentConfig_EmptyNonNilFieldsStayNonNil as the regression guard. Doc-only. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
These changes were released in v1.220.0-rc.2. |
what
Performance optimization arc for
atmos describe affectedon large-stack workloads.Targets the inheritance + merge + YAML-parse hot paths that have grown since the
October 2025 perf instrumentation arc (PRs #1576/#1611/#1622/#1639) added the
auth,profiles,locals, and per-file position-tracking subsystems.Twelve shipped phases (with two attempted-and-reverted optimizations documented
in-code so they aren't re-tried without addressing the underlying contract
violations):
cacheBaseComponentConfigswitched fromRWMutex+ map tosync.Map; deep-copy moved outside the critical section. Eliminates write-lockcontention that serialized every cache write across goroutines and padded
apparent CPU time with lock-wait.
WalkAndDeferYAMLFunctionsshort-circuits when the subtreecontains no Atmos YAML functions (
!template,!terraform.*,!store*,!exec,!env). Returns the input map as-is instead of allocating a deepcopy at every recursion level.
extractLocalsFromRawYAMLcached viasync.Mapkeyed byfilePath + FNV-1a(yamlContent). The content-hash component preventstest pollution when the same logical file path is reused with different
content. Also fixes a pre-existing data race in
extractAndAddLocalsToContext(shallow-clones the input context mapbefore file-scoped
delete + assign).MergeWithDeferred0-input fast path: when every layer isempty, return an empty map immediately without walking or merging. The
1-input shortcut originally shipped alongside was REVERTED on
2026-05-24 after CI surfaced a regression — see "What was tried and
reverted" below.
parsedYAMLCacheswitched tosync.Map; deep-copy ofyaml.Node+PositionMapmoved outside the critical section. Same lockcontention pattern as Phase 2 applied to the YAML parser cache.
processCustomTagssplit into outer + inner functions: thehasCustomTagspre-check runs once at the entry point instead ofre-walking the subtree at every recursive call (O(N×depth) → O(N)).
decodedYAMLCachestores the post-Decode + post-Internresult of
UnmarshalYAMLFromFileWithPositions[map[string]any]. Skipsyaml.Node.Decode+InternStringsInMapon every repeat call for thesame (file, content hash) pair.
processYAMLNodesplit into outer + inner (Phase 7pattern). Removes per-recursion
perf.Trackoverhead from the recursiveYAML walker used by yq evaluation. Same pattern was tried for
WalkAndDeferYAMLFunctionsand reverted: the inner-only walker had toallocate unconditionally on every recursion, regressing function-sparse
subtrees more than the perf.Track savings recovered.
processTerraformRemoteStateBackendextracts thebackend-type-specific map from each input first (via the new
extractBackendTypeMaphelper), then merges just those two scoped maps.Avoids deep-copying unrelated backend-type entries
(s3/gcs/azurerm/etc.) just to extract one key from the merged result.
deepCopyBaseComponentConfigMapsguards everym.DeepCopyMapcall withlen(src.Field) > 0. Skips function-call andallocation overhead for the empty-field case that dominates real
workloads (most components leave several of the 10 fields empty).
Clear*Cachewrappers,extractBackendTypeMaptype-mismatch path, andthe Phase 12/13 empty-field contract are all now covered.
Phase 1 was the auth credential-store fix that shipped separately as
PR #2471 (in
v1.220.0-rc.1).What was tried and reverted
directly without going through
Merge. CI surfacedTestSpaceliftStackProcessorlosing 7 stacks (47→40) becauseWalkAndDeferYAMLFunctions's Phase 3 short-circuit returned the inputmap as-is, and the 1-input shortcut handed that shared reference back
to the caller. Downstream
mergeComponentConfigurationsmutated theresult while building the per-component output, which corrupted the
upstream cached
BaseComponentSettings/GlobalSettingsfor siblingcomponents. Fix: keep only the 0-input fast path; let 1-input fall
through to the regular merge pipeline which deep-copies via
MergeWithOptions→DeepCopyMap. Regression test(
TestMergeWithDeferred_TrivialInputShortCircuits/mutating the result does not mutate the input) added to prevent re-attempts.fatal error: concurrent map iteration and map writeat scale): sharesettings/vars/envreferences from the locals cache, deep-copy onlylocals.processTemplatesInSectionreturns the input map as-iswhen the section has no
{{, so the cached references ended up inthe shared template context and got mutated by sibling goroutines.
Reverted in
b11f3cd9b; documented in-code.Both failures share the same lesson: any optimization that hands a
shared reference back to a caller has to be matched against the
end-to-end mutation surface, not just the immediate caller. The
Mergecontract — "result is a fresh, caller-mutable map" — must be upheld.
why
A real-world large stack configuration (≈836 YAML files, ~195 final stacks
across three namespaces, ~9.3k component instances) reported
atmos describe affectedtaking around 11 minutes in CI on a 2-core runner. Localreproduction with
--identity=falseand fake AWS credentials took ~4minutes and showed two clear cost centers in the heatmap:
--identity=false(≈3.5 min of cumulative CPU). Fixed in PR fix(auth): honor --identity=false in describe affected and dependents #2471.cumulative CPU) was bottlenecked by lock contention on shared caches,
redundant deep-copies on every cache read/write, and per-call work that
could be cached or skipped for the common case.
This PR addresses the second bucket. Confirmed impact on the same workload
(mean of 3 local runs against current main, post-Phase-5-revert):
cacheBaseComponentConfigmergeComponentConfigurationsMergeWithDeferredWalkAndDeferYAMLFunctionsextractLocalsFromRawYAMLUnmarshalYAMLFromFileWithPositionsprocessCustomTagsgetCachedBaseComponentConfig(
mergeComponentConfigurations,MergeWithDeferred, andMergenumbers reflect the post-Phase-5-revert state — the 1-input shortcut
that was originally counted toward Phase 5's headline numbers has been
removed for correctness. The remaining wins are still substantial.)
Local wall-clock on the same workload: 4.1s → ~2.2s (−47%) on a
many-core Mac. The wall-clock floor on Mac is set by stack-level
parallelism that already saturates; the cumulative CPU savings (several
minutes summed across all hot functions) translate to materially more
wall-clock improvement on 2-4 core CI runners where lock-wait padding,
allocation pressure, and serialized work cannot be hidden behind cores.
Projection for a 2-core CI runner starting from the v1.219.0 baseline:
~11 minutes → ~60-105 seconds end-to-end (combining PR #2471 + this
PR's shipped phases, including the ~15s GHA wall-clock cost of the
Phase 5 1-input revert). Awaiting end-to-end CI validation on the
reference workload.
Each phase is independently revertible — they live in separate
commits with self-contained tests. The two reverted optimizations
(Phase 5's 1-input shortcut, Phase 9's asymmetric clone) have their
failure modes documented in-code and in
docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.mdso future passes don't re-attempt the same approach without addressing
the underlying contract violations.
references
decision lessons:
docs/fixes/2026-05-23-describe-affected-component-inheritance-perf.mdthis PR builds on: Add Performance Profiling Heatmap Visualization to Atmos CLI #1576 (heatmap visualization), Improve performance heatmap #1611 (self-time vs
total-time), Fix and Improve Performance Heatmap #1622 (Docker perf fix + CPU Time / Parallelism), Atmos Performance Optimization #1639
(5.2× faster execution + 92% memory reduction).
--identity=falsegate) shipped separately in PR fix(auth): honor --identity=false in describe affected and dependents #2471(
v1.220.0-rc.1).Summary by CodeRabbit
Documentation
Performance
Reliability
Tests / Chores