Skip to content

Commit ce2e7f2

Browse files
committed
fix(aws/recs): cap coverage/utilization CE calls with shared semaphore
fetchCoveragePage and fetchUtilizationPage called the Cost Explorer SDK without acquiring the shared concurrency semaphore, so the scheduler's coverage-enrichment fan-out (AttachDailyUsageHistory per service, region, resourceType tuple) escaped the CUDLY_MAX_PARALLELISM cap that protects Lambda memory and CE rate limits. Worst case added roughly 6 x min(N,20) uncapped concurrent CE calls on top of the capped 20, and made the GetAllRecommendations docstring invariant ("the Acquire/Release boundary lives around the individual CE SDK call") false for a third of the CE call sites. Wrap both SDK calls in concurrency.Acquire/Release, holding the slot only across the outbound call (released during rate-limit backoffs), matching fetchRIPageWithRetry and fetchSPPageWithRetry. Add regression tests that saturate a capacity-1 shared semaphore and assert the CE mock is never reached (both fail on the pre-fix code), plus a slot-release guard against Acquire/Release pairing leaks. Closes #1144
1 parent d484c9d commit ce2e7f2

3 files changed

Lines changed: 117 additions & 1 deletion

File tree

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package recommendations
2+
3+
import (
4+
"context"
5+
"sync/atomic"
6+
"testing"
7+
8+
"github.com/aws/aws-sdk-go-v2/service/costexplorer"
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
11+
"golang.org/x/sync/semaphore"
12+
13+
"github.com/LeanerCloud/CUDly/pkg/concurrency"
14+
)
15+
16+
// semCountingCE counts coverage/utilization SDK calls so the tests below can
17+
// assert whether a CE call escaped the shared concurrency semaphore.
18+
type semCountingCE struct {
19+
mockCostExplorerAPI
20+
coverageCalls atomic.Int32
21+
utilizationCalls atomic.Int32
22+
}
23+
24+
func (m *semCountingCE) GetReservationCoverage(ctx context.Context, params *costexplorer.GetReservationCoverageInput, optFns ...func(*costexplorer.Options)) (*costexplorer.GetReservationCoverageOutput, error) {
25+
m.coverageCalls.Add(1)
26+
return &costexplorer.GetReservationCoverageOutput{}, nil
27+
}
28+
29+
func (m *semCountingCE) GetReservationUtilization(ctx context.Context, params *costexplorer.GetReservationUtilizationInput, optFns ...func(*costexplorer.Options)) (*costexplorer.GetReservationUtilizationOutput, error) {
30+
m.utilizationCalls.Add(1)
31+
return &costexplorer.GetReservationUtilizationOutput{}, nil
32+
}
33+
34+
// fullSemaphoreCtx returns a cancelled context carrying a capacity-1 shared
35+
// semaphore whose only slot is already held, replicating the scheduler's
36+
// collection path when the CUDLY_MAX_PARALLELISM cap is saturated. A correct
37+
// leaf call must block on Acquire (and surface ctx cancellation) instead of
38+
// issuing the CE request; the pre-fix code escaped the cap and called CE
39+
// immediately (review finding PERF-02).
40+
func fullSemaphoreCtx(t *testing.T) context.Context {
41+
t.Helper()
42+
sem := semaphore.NewWeighted(1)
43+
require.NoError(t, sem.Acquire(context.Background(), 1))
44+
t.Cleanup(func() { sem.Release(1) })
45+
46+
ctx, cancel := context.WithCancel(concurrency.WithSharedSemaphore(context.Background(), sem))
47+
cancel()
48+
return ctx
49+
}
50+
51+
// TestFetchCoveragePage_RespectsSharedSemaphore is the PERF-02 regression
52+
// test for the coverage path (scheduler's AttachDailyUsageHistory fan-out):
53+
// with the cap saturated, fetchCoveragePage must not reach the CE SDK.
54+
// Pre-fix this test fails: the call escaped the semaphore, hit the mock,
55+
// and returned success.
56+
func TestFetchCoveragePage_RespectsSharedSemaphore(t *testing.T) {
57+
mock := &semCountingCE{}
58+
client := NewClientWithAPI(mock, "us-east-1")
59+
60+
_, err := client.fetchCoveragePage(fullSemaphoreCtx(t), &costexplorer.GetReservationCoverageInput{})
61+
62+
require.Error(t, err, "fetch must fail when the cap is saturated and ctx is cancelled")
63+
assert.ErrorIs(t, err, context.Canceled)
64+
assert.Equal(t, int32(0), mock.coverageCalls.Load(),
65+
"GetReservationCoverage escaped the shared concurrency semaphore")
66+
}
67+
68+
// TestFetchUtilizationPage_RespectsSharedSemaphore is the PERF-02 regression
69+
// test for the utilization path: same invariant as the coverage test.
70+
func TestFetchUtilizationPage_RespectsSharedSemaphore(t *testing.T) {
71+
mock := &semCountingCE{}
72+
client := NewClientWithAPI(mock, "us-east-1")
73+
74+
_, err := client.fetchUtilizationPage(fullSemaphoreCtx(t), &costexplorer.GetReservationUtilizationInput{})
75+
76+
require.Error(t, err, "fetch must fail when the cap is saturated and ctx is cancelled")
77+
assert.ErrorIs(t, err, context.Canceled)
78+
assert.Equal(t, int32(0), mock.utilizationCalls.Load(),
79+
"GetReservationUtilization escaped the shared concurrency semaphore")
80+
}
81+
82+
// TestFetchPages_ReleaseSemaphoreSlot verifies the Acquire/Release pairing:
83+
// after a successful fetch under a free capacity-1 semaphore, the slot must
84+
// be available again (no leak that would starve later leaf calls).
85+
func TestFetchPages_ReleaseSemaphoreSlot(t *testing.T) {
86+
mock := &semCountingCE{}
87+
client := NewClientWithAPI(mock, "us-east-1")
88+
89+
sem := semaphore.NewWeighted(1)
90+
ctx := concurrency.WithSharedSemaphore(context.Background(), sem)
91+
92+
_, err := client.fetchCoveragePage(ctx, &costexplorer.GetReservationCoverageInput{})
93+
require.NoError(t, err)
94+
_, err = client.fetchUtilizationPage(ctx, &costexplorer.GetReservationUtilizationInput{})
95+
require.NoError(t, err)
96+
97+
assert.Equal(t, int32(1), mock.coverageCalls.Load())
98+
assert.Equal(t, int32(1), mock.utilizationCalls.Load())
99+
require.True(t, sem.TryAcquire(1), "semaphore slot leaked: fetch did not release after the SDK call")
100+
sem.Release(1)
101+
}

‎providers/aws/recommendations/coverage.go‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/aws/aws-sdk-go-v2/service/costexplorer/types"
1212

1313
"github.com/LeanerCloud/CUDly/pkg/common"
14+
"github.com/LeanerCloud/CUDly/pkg/concurrency"
1415
)
1516

1617
// coverageServiceFilters lists the Cost Explorer service-dimension values
@@ -319,14 +320,20 @@ func serviceRegionFilter(service, region string) *types.Expression {
319320

320321
// fetchCoveragePage calls the Cost Explorer API with rate-limit retry.
321322
// Mirrors fetchUtilizationPage so the two paths fail and back off the
322-
// same way.
323+
// same way. The shared concurrency semaphore (CUDLY_MAX_PARALLELISM) is
324+
// held only across the outbound SDK call, matching fetchRIPageWithRetry,
325+
// so the coverage-enrichment fan-out stays inside the global IO cap.
323326
func (c *Client) fetchCoveragePage(ctx context.Context, input *costexplorer.GetReservationCoverageInput) (*costexplorer.GetReservationCoverageOutput, error) {
324327
c.rateLimiter.Reset()
325328
for {
326329
if waitErr := c.rateLimiter.Wait(ctx); waitErr != nil {
327330
return nil, fmt.Errorf("rate limiter wait failed: %w", waitErr)
328331
}
332+
if acqErr := concurrency.Acquire(ctx); acqErr != nil {
333+
return nil, fmt.Errorf("concurrency acquire failed: %w", acqErr)
334+
}
329335
result, err := c.costExplorerClient.GetReservationCoverage(ctx, input)
336+
concurrency.Release(ctx)
330337
if !c.rateLimiter.ShouldRetry(err) {
331338
if err != nil {
332339
return nil, fmt.Errorf("failed to get reservation coverage: %w", err)

‎providers/aws/recommendations/utilization.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"github.com/aws/aws-sdk-go-v2/service/costexplorer/types"
1313

1414
"github.com/LeanerCloud/CUDly/pkg/common"
15+
"github.com/LeanerCloud/CUDly/pkg/concurrency"
1516
)
1617

1718
// RIUtilization is an alias for common.RIUtilization so existing callers that
@@ -97,14 +98,21 @@ func buildUtilizations(agg map[string]*riAccumulator) []RIUtilization {
9798
}
9899

99100
// fetchUtilizationPage calls the Cost Explorer API with rate-limit retry.
101+
// The shared concurrency semaphore (CUDLY_MAX_PARALLELISM) is held only
102+
// across the outbound SDK call, matching fetchRIPageWithRetry, so callers
103+
// running under a semaphore-carrying context stay inside the global IO cap.
100104
func (c *Client) fetchUtilizationPage(ctx context.Context, input *costexplorer.GetReservationUtilizationInput) (*costexplorer.GetReservationUtilizationOutput, error) {
101105
c.rateLimiter.Reset()
102106
for {
103107
if waitErr := c.rateLimiter.Wait(ctx); waitErr != nil {
104108
return nil, fmt.Errorf("rate limiter wait failed: %w", waitErr)
105109
}
106110

111+
if acqErr := concurrency.Acquire(ctx); acqErr != nil {
112+
return nil, fmt.Errorf("concurrency acquire failed: %w", acqErr)
113+
}
107114
result, err := c.costExplorerClient.GetReservationUtilization(ctx, input)
115+
concurrency.Release(ctx)
108116
if !c.rateLimiter.ShouldRetry(err) {
109117
if err != nil {
110118
return nil, fmt.Errorf("failed to get reservation utilization: %w", err)

0 commit comments

Comments
 (0)