Repository navigation
feat: add chunked uploads for large stack payloads - #2251
Conversation
Dependency Review✅ No vulnerabilities or license issues found.Snapshot WarningsEnsure that dependencies are being submitted on PR branches and consider enabling retry-on-snapshot-warnings. See the documentation for more information and troubleshooting advice. Scanned FilesNone |
|
Warning Release Documentation RequiredThis PR is labeled
|
|
Warning Release Documentation RequiredThis PR is labeled
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds configurable max-payload and generic chunking support to the Atmos Pro client: large stack/instance uploads are measured, split into multiple POSTs when exceeding a threshold, and each chunk is annotated with batch metadata; DTOs, client senders, tests, schema, and docs updated. Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as "CLI"
participant Client as "AtmosProAPIClient"
participant API as "Remote API"
CLI->>Client: prepare UploadAffectedStacks / UploadInstances DTO
Client->>Client: marshal items, estimate metadataOverhead
alt fits within MaxPayloadBytes
Client->>API: POST single compact JSON request
API-->>Client: 200 OK
else exceeds MaxPayloadBytes
Client->>Client: split into chunks, generate BatchID, set indices
loop per chunk
Client->>API: POST chunk with batch metadata (batch_id, batch_index, batch_total)
API-->>Client: 200 OK
end
end
Client-->>CLI: return result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 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 |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2251 +/- ##
==========================================
+ Coverage 77.22% 77.26% +0.03%
==========================================
Files 1017 1018 +1
Lines 96260 96368 +108
==========================================
+ Hits 74341 74457 +116
+ Misses 17726 17712 -14
- Partials 4193 4199 +6
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
pkg/pro/api_client_instances.go (1)
46-59: Consider adding HTTP-level test for instances chunking.
TestUploadAffectedStacks_Chunkedvalidates chunking behavior for affected stacks, but there's no equivalent forUploadInstances. WhilesendChunkedhas unit tests, an integration test would catch any wiring issues.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/pro/api_client_instances.go` around lines 46 - 59, Add an HTTP-level integration test that mirrors TestUploadAffectedStacks_Chunked to ensure UploadInstances/ sendChunked wiring works correctly: create a TestUploadInstances_Chunked that starts a test HTTP server which expects multiple POSTs to the same endpoint and validates the received payloads are dtos.InstancesUploadRequest with correct RepoURL/RepoName/RepoOwner/RepoHost, that BatchID/BatchIndex/BatchTotal are set for non-first chunks, and that total instances equal the input; call the public UploadInstances (or the client method that triggers sendChunked and sendInstancesRequest) with a large dto.Instances slice to force chunking and assert the server received the expected number of chunks and correct fields.pkg/pro/chunked_upload_test.go (2)
58-67: Add negative-path test for marshal failure fallback.The implementation falls back to
DefaultMetadataOverheadByteswhen marshaling fails. A test covering this recovery path would strengthen coverage.Proposed additional test case
func TestMetadataOverhead_Fallback(t *testing.T) { // Channels cannot be marshaled to JSON. ch := make(chan int) overhead := metadataOverhead(ch) assert.Equal(t, DefaultMetadataOverheadBytes, overhead) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/pro/chunked_upload_test.go` around lines 58 - 67, Add a negative-path unit test to chunked_upload_test.go that verifies metadataOverhead falls back to DefaultMetadataOverheadBytes when json.Marshal fails; create a value that cannot be marshaled (e.g., a channel like make(chan int)) and call metadataOverhead with it, then assert the returned overhead equals DefaultMetadataOverheadBytes, referencing metadataOverhead and DefaultMetadataOverheadBytes in the test name and assertions.
46-50: Assert element contents, not just length.Per guidelines,
require.Lenalone isn't sufficient. Assert at least the first and last element by value to prevent silent regressions.Proposed fix
t.Run("zero chunk size defaults to 1", func(t *testing.T) { items := []int{1, 2} chunks := splitSlice(items, 0) require.Len(t, chunks, 2) + assert.Equal(t, []int{1}, chunks[0]) + assert.Equal(t, []int{2}, chunks[1]) })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/pro/chunked_upload_test.go` around lines 46 - 50, Update the test "zero chunk size defaults to 1" to assert element contents of the returned chunks, not just length: after calling splitSlice(items, 0) verify that chunks contains the expected first and last chunk values (e.g., that chunks[0] contains 1 and chunks[len(chunks)-1] contains 2) so the test uses content assertions on the splitSlice result rather than only require.Len.pkg/pro/chunked_upload.go (2)
128-130: Comment doesn't match implementation.The comment says "items field set to an empty array" but the function just marshals whatever value is passed. Consider clarifying that callers should pass the metadata struct with an empty items field.
Suggested comment fix
-// metadataOverhead returns the JSON byte size of a struct with the items field -// set to an empty array. This is used to estimate the overhead for chunking. +// metadataOverhead returns the JSON byte size of a value, used to estimate +// the non-item portion of the request payload. Callers should pass the request +// struct with the items field set to empty. func metadataOverhead(v any) int {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/pro/chunked_upload.go` around lines 128 - 130, Update the comment for metadataOverhead to accurately describe its behavior: state that it marshals the provided value to JSON and returns its byte length, and explicitly require that callers pass the metadata struct with its items field set to an empty array (or equivalent) so the returned size represents the metadata overhead for chunking; reference the metadataOverhead(v any) function and note that callers must prepare v accordingly before calling.
54-56: Consider using a static error for consistency.Per the coding guidelines, errors should be wrapped using static errors from
errors/errors.go. The current dynamic error string could be refactored for consistency with the rest of the codebase.Most similar marshal operations in
pkg/pro/useerrors.Join(errUtils.ErrFailedToMarshalPayload, err). You could either define a specific static error for payload size estimation or reuse the existingErrFailedToMarshalPayloadif appropriate.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/pro/chunked_upload.go` around lines 54 - 56, Replace the dynamic fmt.Errorf("failed to estimate payload size: %w", err) return with a wrapped static error per codebase conventions: use errors.Join(errUtils.ErrFailedToMarshalPayload, err) (or define and use a new static error like errUtils.ErrFailedToEstimatePayload and join it with err) so the error uses the shared sentinel from errors/errors.go instead of a custom string; update the return in the chunked_upload.go code path where the payload size estimation error is currently returned.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@pkg/pro/api_client_upload_affected_stacks_test.go`:
- Around line 156-172: The test’s httptest handler appends to receivedBodies
without synchronization causing a race; protect access to receivedBodies by
introducing a sync.Mutex (e.g., mu) and lock/unlock around the append in the
handler and around any reads of receivedBodies after the upload completes (also
keep requestCount atomic use as-is); update TestUploadAffectedStacks_Chunked to
guard all modifications/reads of receivedBodies with mu to ensure visibility and
eliminate the race.
---
Nitpick comments:
In `@pkg/pro/api_client_instances.go`:
- Around line 46-59: Add an HTTP-level integration test that mirrors
TestUploadAffectedStacks_Chunked to ensure UploadInstances/ sendChunked wiring
works correctly: create a TestUploadInstances_Chunked that starts a test HTTP
server which expects multiple POSTs to the same endpoint and validates the
received payloads are dtos.InstancesUploadRequest with correct
RepoURL/RepoName/RepoOwner/RepoHost, that BatchID/BatchIndex/BatchTotal are set
for non-first chunks, and that total instances equal the input; call the public
UploadInstances (or the client method that triggers sendChunked and
sendInstancesRequest) with a large dto.Instances slice to force chunking and
assert the server received the expected number of chunks and correct fields.
In `@pkg/pro/chunked_upload_test.go`:
- Around line 58-67: Add a negative-path unit test to chunked_upload_test.go
that verifies metadataOverhead falls back to DefaultMetadataOverheadBytes when
json.Marshal fails; create a value that cannot be marshaled (e.g., a channel
like make(chan int)) and call metadataOverhead with it, then assert the returned
overhead equals DefaultMetadataOverheadBytes, referencing metadataOverhead and
DefaultMetadataOverheadBytes in the test name and assertions.
- Around line 46-50: Update the test "zero chunk size defaults to 1" to assert
element contents of the returned chunks, not just length: after calling
splitSlice(items, 0) verify that chunks contains the expected first and last
chunk values (e.g., that chunks[0] contains 1 and chunks[len(chunks)-1] contains
2) so the test uses content assertions on the splitSlice result rather than only
require.Len.
In `@pkg/pro/chunked_upload.go`:
- Around line 128-130: Update the comment for metadataOverhead to accurately
describe its behavior: state that it marshals the provided value to JSON and
returns its byte length, and explicitly require that callers pass the metadata
struct with its items field set to an empty array (or equivalent) so the
returned size represents the metadata overhead for chunking; reference the
metadataOverhead(v any) function and note that callers must prepare v
accordingly before calling.
- Around line 54-56: Replace the dynamic fmt.Errorf("failed to estimate payload
size: %w", err) return with a wrapped static error per codebase conventions: use
errors.Join(errUtils.ErrFailedToMarshalPayload, err) (or define and use a new
static error like errUtils.ErrFailedToEstimatePayload and join it with err) so
the error uses the shared sentinel from errors/errors.go instead of a custom
string; update the return in the chunked_upload.go code path where the payload
size estimation error is currently returned.
🪄 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: 6a659783-b6e5-4b4a-a3c2-5093e7f7761d
📒 Files selected for processing (10)
pkg/pro/api_client.gopkg/pro/api_client_instances.gopkg/pro/api_client_upload_affected_stacks_test.gopkg/pro/chunked_upload.gopkg/pro/chunked_upload_test.gopkg/pro/dtos/instances.gopkg/pro/dtos/upload_affected_stacks.gopkg/schema/pro.gowebsite/blog/2026-03-25-chunked-stack-uploads.mdxwebsite/src/data/roadmap.js
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@pkg/pro/api_client_upload_affected_stacks_test.go`:
- Around line 218-228: The test uses assert.Greater to check totalRequests but
then immediately indexes bodies[0], which can panic if the assertion fails;
replace the non-fatal assertion with a fatal check (e.g., use require.Greater(t,
totalRequests, 1) or require.NotEmpty(t, bodies)) before accessing bodies[0] so
the test stops safely on failure; update the assertion in the test in
pkg/pro/api_client_upload_affected_stacks_test.go (the block that computes
totalRequests from requestCount.Load() and later copies receivedBodies into
bodies) to use require instead of assert or add a require.Len/require.NotEmpty
on bodies prior to reading bodies[0].
- Around line 164-168: The handler currently calls require.NoError inside the
httptest server goroutine when reading and unmarshaling the request (reading
r.Body into body and unmarshalling into dtos.UploadAffectedStacksRequest), which
can call runtime.Goexit and silently hide failures; instead capture any handler
errors (e.g., read/unmarshal errors) into an error channel or variable and
return them to the main test goroutine to assert there after the upload
completes; likewise replace non-fatal assert.Greater checks that guard unsafe
indexing of bodies with require.Greater in the main goroutine so you never index
bodies[0] when bodies is empty.
🪄 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: 2c387cc1-9267-4024-b695-696165ea3ee4
📒 Files selected for processing (1)
pkg/pro/api_client_upload_affected_stacks_test.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/pro/api_client_upload_affected_stacks_test.go (1)
157-259: Add a below-threshold/non-chunked scenario.This test covers chunking well, but the feature contract also needs an explicit small-payload case asserting exactly one request and nil/empty
batch_*fields.As per coding guidelines "Every new feature must include comprehensive unit tests targeting >80% code coverage for all packages."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/pro/api_client_upload_affected_stacks_test.go` around lines 157 - 259, Add a new test (e.g., TestUploadAffectedStacks_SmallPayload) that mirrors TestUploadAffectedStacks_Chunked but builds a payload strictly under DefaultMaxPayloadBytes so UploadAffectedStacks does not chunk; set up the same httptest server and AtmosProAPIClient, call UploadAffectedStacks, assert requestCount==1 (or Greater/Equal exact 1) and then inspect the single received dtos.UploadAffectedStacksRequest to assert BatchID is empty/nil and BatchIndex and BatchTotal are nil (or zero-value/absent per dtos definition), and also assert metadata fields (HeadSHA/BaseSHA/RepoOwner) and total stacks equal the original count; reference UploadAffectedStacks, DefaultMaxPayloadBytes, dtos.UploadAffectedStacksRequest, and the BatchID/BatchIndex/BatchTotal fields to locate the assertions to add.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@pkg/pro/api_client_upload_affected_stacks_test.go`:
- Around line 161-175: Replace the atomic.Value usage for handlerErr with a
package-level or local plain error variable plus a sync.Mutex to guard access:
remove handlerErr (atomic.Value) and add a mutex and an error var, then in both
error branches inside the httptest server handler (the io.ReadAll error branch
and the json.Unmarshal error branch) lock the mutex, set the error only if the
stored error is nil (first-write-wins), and unlock; likewise, when the test
later reads the captured error for assertions, lock the mutex, copy the error to
a local var, unlock, and use that value for assertions to avoid type-panic and
race conditions.
---
Nitpick comments:
In `@pkg/pro/api_client_upload_affected_stacks_test.go`:
- Around line 157-259: Add a new test (e.g.,
TestUploadAffectedStacks_SmallPayload) that mirrors
TestUploadAffectedStacks_Chunked but builds a payload strictly under
DefaultMaxPayloadBytes so UploadAffectedStacks does not chunk; set up the same
httptest server and AtmosProAPIClient, call UploadAffectedStacks, assert
requestCount==1 (or Greater/Equal exact 1) and then inspect the single received
dtos.UploadAffectedStacksRequest to assert BatchID is empty/nil and BatchIndex
and BatchTotal are nil (or zero-value/absent per dtos definition), and also
assert metadata fields (HeadSHA/BaseSHA/RepoOwner) and total stacks equal the
original count; reference UploadAffectedStacks, DefaultMaxPayloadBytes,
dtos.UploadAffectedStacksRequest, and the BatchID/BatchIndex/BatchTotal fields
to locate the assertions to add.
🪄 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: f70f3c66-5691-4581-bd09-ee6e97eb2a09
📒 Files selected for processing (1)
pkg/pro/api_client_upload_affected_stacks_test.go
|
These changes were released in v1.213.0-test.7. |
|
Important Cloud Posse Engineering Team Review RequiredThis pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes. To expedite this process, reach out to us on Slack in the |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
website/docs/cli/configuration/settings/pro.mdx (1)
105-112: Optional precision tweak: label the default as4 MiB.Line [110] uses a binary-byte value (
4194304), so4 MiBis the exact unit and avoids ambiguity.Suggested doc tweak
- - **Default:** `4194304` (4 MB) + - **Default:** `4194304` (4 MiB)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@website/docs/cli/configuration/settings/pro.mdx` around lines 105 - 112, The default value for settings.pro.max_payload_bytes is presented as "4 MB" but the numeric value 4194304 is a binary value (4 * 1024 * 1024), so update the documentation to label the default as "4 MiB" (or "4 MiB (4,194,304 bytes)") wherever settings.pro.max_payload_bytes is described to avoid ambiguity; ensure the description text that mentions 4 MB is changed to 4 MiB and keep the numeric default unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@website/docs/cli/configuration/settings/pro.mdx`:
- Around line 105-112: The default value for settings.pro.max_payload_bytes is
presented as "4 MB" but the numeric value 4194304 is a binary value (4 * 1024 *
1024), so update the documentation to label the default as "4 MiB" (or "4 MiB
(4,194,304 bytes)") wherever settings.pro.max_payload_bytes is described to
avoid ambiguity; ensure the description text that mentions 4 MB is changed to 4
MiB and keep the numeric default unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 2851123f-251a-49d8-8ddb-24984085f70c
📒 Files selected for processing (1)
website/docs/cli/configuration/settings/pro.mdx
|
Warning Release Documentation RequiredThis PR is labeled
|
|
These changes were released in v1.212.1-rc.1. |
|
These changes were released in v1.213.0. |
What
Add automatic chunking for large stack/instance upload payloads to Atmos Pro. When payloads exceed the configurable threshold (default 4MB), the CLI splits the array into chunks and sends them sequentially with batch metadata (
batch_id,batch_index,batch_total).Why
Large infrastructure repos generate affected stack and instance payloads that exceed Vercel's ~4.5MB serverless body size limit, producing HTTP 413 Request Entity Too Large errors. The existing
StripAffectedForUpload()reduces payloads by 70-75% but is insufficient for repos with hundreds of stacks.Changes
pkg/pro/chunked_upload.go— generic chunking logic (sendChunked,splitSlice,metadataOverhead)UploadAffectedStacks()andUploadInstances()to use chunked uploadbatch_id,batch_index,batch_totalfields to upload DTOsmax_payload_bytesconfig tosettings.proin atmos.yamlRef
Companion server-side PR: cloudposse-corp/apps (feat/chunked-stack-uploads → staging)
Summary by CodeRabbit
New Features
Documentation
Tests