Skip to content

feat(storage): in-flight staging part-objects - #1352

Merged
kalbasit merged 2 commits into
mainfrom
feat-storage-in-flight-staging
Jun 8, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-storage-in-flight-staging

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Add staging part-object storage to the NarStore interface and both
backends (local, S3), the transport layer for in-flight NAR staging
(GitHub #660, #1289). Parts are immutable, fixed-size, sequentially
indexed objects under a per-hash staging namespace that any replica can
read while another is still downloading.

Why: S3 cannot serve an in-progress object, so to stream an in-flight
NAR cross-pod the holder must commit completed immutable pieces during
the download. These methods are the storage substrate; the holder/reader
wiring lands in a later commit.

How:

  • NarStore gains PutStagingPart / GetStagingPart / DeleteStagingParts.
  • local: parts live at /staging//.part, written via
    atomic temp+rename so a part is only readable once fully committed.
  • s3: keys /store/staging//.part; delete lists and
    removes the per-hash prefix. A missing part returns storage.ErrNotFound.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kalbasit, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 13 minutes and 39 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 423f0366-dc98-4923-af43-658a5e366b25

📥 Commits

Reviewing files that changed from the base of the PR and between 08d1cec and a989104.

📒 Files selected for processing (4)
  • pkg/storage/local/local.go
  • pkg/storage/local/staging_part_test.go
  • pkg/storage/s3/s3.go
  • pkg/storage/store.go
📝 Walkthrough

Walkthrough

Adds immutable "staging part" operations to NarStore (write/read/delete) and implements them for both local filesystem (temp-file then atomic rename, per-hash staging dirs) and S3 (object keys per hash/index), plus tests and an exported ErrInvalidArgument sentinel.

Changes

Staging Parts Storage

Layer / File(s) Summary
NarStore interface extension
pkg/storage/store.go
Adds ErrInvalidArgument and extends NarStore with PutStagingPart(ctx, hash, index, body, size) (int64, error), GetStagingPart(ctx, hash, index) (io.ReadCloser, error), and DeleteStagingParts(ctx, hash) error with documented semantics for negative indices, missing-part reads, and delete no-op behavior.
Local storage staging parts implementation
pkg/storage/local/local.go, pkg/storage/local/staging_part_test.go
Implements local Store staging parts via streaming to a temp file then atomic rename into staging/<hash>/<zero-padded-index>.part, applies fileMode, maps missing files to storage.ErrNotFound, and deletes all parts by removing the per-hash staging directory. Includes end-to-end and negative-index tests.
S3 storage staging parts implementation
pkg/storage/s3/s3.go
Implements S3 Store staging parts with key-generation helpers, PutStagingPart using streaming or sized PutObject, GetStagingPart mapping S3 NoSuchKey to storage.ErrNotFound, and DeleteStagingParts that lists under the hash prefix and batches deletions via RemoveObjects.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰
I hopped a temp file round and round,
then nudged it to its hash-bound ground.
Parts in order, safe and neat,
read and joined — a perfect treat.
Delete a hole? I skip a beat.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main addition: in-flight staging part-objects support for the storage layer, which matches the core changeset.
Description check ✅ Passed The description provides substantive context for the changes, explaining the motivation (S3 limitations), implementation details across backends, and references to related issues.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces staging part-object storage capabilities (PutStagingPart, GetStagingPart, and DeleteStagingParts) to the NarStore interface, with implementations for both local and S3 storage backends, alongside corresponding unit tests. The review feedback highlights several critical improvements: preventing potential out-of-memory issues in S3 by configuring a streaming PartSize for unknown stream sizes, avoiding temporary file leaks in the local backend on error paths, and optimizing S3 deletion performance by utilizing batch object removal instead of sequential individual requests.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread pkg/storage/s3/s3.go Resolved
Comment thread pkg/storage/local/local.go Resolved
Comment thread pkg/storage/s3/s3.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
pkg/storage/s3/s3.go (1)

766-795: ⚡ Quick win

Consider enforcing staging part immutability and validating index.

Similar to the local implementation, this method:

  1. Does not check if the part already exists before writing, so duplicate writes will silently overwrite.
  2. Does not validate that index >= 0, which could lead to unexpected key names.

If staging parts are truly immutable (as documented), consider adding an existence check (using StatObject) and index validation.

🔒 Proposed immutability enforcement
 func (s *Store) PutStagingPart(
 	ctx context.Context,
 	hash string,
 	index int64,
 	body io.Reader,
 	size int64,
 ) (int64, error) {
 	_, span := tracer.Start(ctx, "s3.PutStagingPart", trace.WithSpanKind(trace.SpanKindInternal))
 	defer span.End()
+
+	if index < 0 {
+		return 0, fmt.Errorf("staging part index must be >= 0, got %d", index)
+	}
+
+	key := s.stagingPartKey(hash, index)
+
+	// Check if part already exists (enforce immutability)
+	if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err == nil {
+		return 0, storage.ErrAlreadyExists
+	}
 
 	objSize := size
🤖 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 `@pkg/storage/s3/s3.go` around lines 766 - 795, PutStagingPart currently allows
overwrites and accepts negative indexes; update PutStagingPart to first validate
the index (ensure index >= 0) and return a clear error if not, then check for an
existing object at s.stagingPartKey(hash, index) using the S3 client's
StatObject (or equivalent) before calling PutObject and return a specific
"already exists" error if StatObject indicates the object exists; only call
s.client.PutObject when the object is not present so staging parts remain
immutable.
pkg/storage/store.go (1)

100-100: ⚡ Quick win

Remove or clarify the reference to "change serve-whole-nar-in-flight".

This reference is unclear and appears to be an internal note rather than API documentation. Either remove it or replace it with a clear description of the use case (e.g., "enables serving in-progress NARs by writing fixed-size immutable parts").

🤖 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 `@pkg/storage/store.go` at line 100, The inline comment containing "See change
serve-whole-nar-in-flight" is unclear and should be removed or replaced with an
explicit description; locate the comment in pkg/storage/store.go (the comment
near the Store implementation/related method) and either delete that reference
or replace it with a short clarifying sentence such as: "Enables serving
in-progress NARs by writing fixed-size immutable parts so partial reads are
safe" (or a description matching the actual behavior), ensuring the comment
clearly describes the use case and expected behavior rather than an internal
change reference.
pkg/storage/local/local.go (1)

488-527: ⚡ Quick win

Consider handling duplicate staging part writes.

The current implementation will silently overwrite an existing staging part without returning storage.ErrAlreadyExists. This differs from the behavior of PutNar (line 451-453) and PutNarInfo (line 280-287), which check for existing files.

If staging parts are intended to be truly immutable (as documented in the interface), consider adding an existence check before writing.

🔒 Proposed fix to enforce immutability
 func (s *Store) PutStagingPart(
 	ctx context.Context,
 	hash string,
 	index int64,
 	body io.Reader,
 	_ int64,
 ) (int64, error) {
 	_, span := tracer.Start(ctx, "local.PutStagingPart", trace.WithSpanKind(trace.SpanKindInternal))
 	defer span.End()
 
 	partPath := s.stagingPartPath(hash, index)
+
+	if _, err := os.Stat(partPath); err == nil {
+		return 0, storage.ErrAlreadyExists
+	}
 
 	if err := os.MkdirAll(filepath.Dir(partPath), dirMode); err != nil {
🤖 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 `@pkg/storage/local/local.go` around lines 488 - 527, The PutStagingPart
implementation currently overwrites existing parts; before creating the temp
file, check for an existing staging part at s.stagingPartPath(hash, index)
(e.g., via os.Stat) and if it already exists return storage.ErrAlreadyExists to
enforce immutability (consistent with PutNar and PutNarInfo); if the stat
returns a non-existence error proceed as before and handle other stat errors
normally. Ensure you still create the temp file in s.storeTMPPath(), write,
close, rename and set permissions as currently done, but avoid a blind
Rename-overwrite by early-exiting with storage.ErrAlreadyExists when the target
file exists.
pkg/storage/local/staging_part_test.go (1)

15-66: ⚡ Quick win

Consider adding test coverage for edge cases.

The current test validates the happy path comprehensively, but consider adding tests for:

  1. Duplicate writes: Writing the same (hash, index) twice to verify the expected behavior (currently undefined in the interface).
  2. Non-sequential indices: Writing parts 0, 2, 5 to ensure indexing is independent.
  3. Negative index: Verify that negative indices are rejected or handled gracefully.

These tests would help define and enforce the contract more clearly.

🤖 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 `@pkg/storage/local/staging_part_test.go` around lines 15 - 66, Add additional
unit tests in pkg/storage/local/staging_part_test.go alongside
TestStagingParts_WriteReadDelete to cover edge cases: (1) duplicate writes —
call PutStagingPart twice for the same (hash, index) and assert expected
behavior (error or idempotent overwrite) using PutStagingPart and
GetStagingPart; (2) non-sequential indices — write parts at indices 0, 2, 5 and
verify GetStagingPart returns each independently and that reassembly only uses
written indices; (3) negative index — call PutStagingPart and GetStagingPart
with a negative index and assert that the implementation rejects it or returns
storage.ErrNotFound/validation error as your contract requires; use the existing
helper functions/newContext(), and assertions similar to
TestStagingParts_WriteReadDelete (require.NoError, require.ErrorIs,
assert.Equal) to keep style consistent.
🤖 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 `@pkg/storage/local/local.go`:
- Around line 501-503: The code doesn't validate that the incoming part index is
non-negative, so add a guard that checks the index parameter (the variable named
index used to build partPath) before constructing/using partPath and before
calling os.MkdirAll; if index < 0 return a descriptive error (e.g.
fmt.Errorf("invalid part index %d: must be >= 0", index)). Update the function
that owns partPath (the method handling staging/writing parts in
pkg/storage/local/local.go) to perform this validation early and avoid creating
invalid filenames or directories.

In `@pkg/storage/s3/s3.go`:
- Around line 766-795: PutStagingPart currently passes objSize = -1 when size <=
0 which makes the MinIO client buffer the whole stream; change PutStagingPart to
detect size <= 0 and call s.client.PutObject with minio.PutObjectOptions that
include PartSize: 5 * 1024 * 1024 (same approach used by putObjectStream/PutNar)
so the upload uses multipart streaming instead of in-memory buffering; update
the call in PutStagingPart to use minio.PutObjectOptions{ContentType:
"application/octet-stream", PartSize: 5 * 1024 * 1024} when objSize <= 0 and
keep the existing options when size is known.

In `@pkg/storage/store.go`:
- Around line 97-101: Update the PutStagingPart comment to fully specify its
contract: state that parts are immutable so attempting to write the same (hash,
index) twice must return an error (no overwrite), require index to be >= 0 and
treat negative indices as invalid (return error), and clarify that size <= 0
indicates unknown length (allowed) while size > 0 is the known byte length; also
mention the function returns the number of bytes written and the expected error
behavior for duplicate/invalid-index cases so all backends implement consistent
semantics for PutStagingPart.

---

Nitpick comments:
In `@pkg/storage/local/local.go`:
- Around line 488-527: The PutStagingPart implementation currently overwrites
existing parts; before creating the temp file, check for an existing staging
part at s.stagingPartPath(hash, index) (e.g., via os.Stat) and if it already
exists return storage.ErrAlreadyExists to enforce immutability (consistent with
PutNar and PutNarInfo); if the stat returns a non-existence error proceed as
before and handle other stat errors normally. Ensure you still create the temp
file in s.storeTMPPath(), write, close, rename and set permissions as currently
done, but avoid a blind Rename-overwrite by early-exiting with
storage.ErrAlreadyExists when the target file exists.

In `@pkg/storage/local/staging_part_test.go`:
- Around line 15-66: Add additional unit tests in
pkg/storage/local/staging_part_test.go alongside
TestStagingParts_WriteReadDelete to cover edge cases: (1) duplicate writes —
call PutStagingPart twice for the same (hash, index) and assert expected
behavior (error or idempotent overwrite) using PutStagingPart and
GetStagingPart; (2) non-sequential indices — write parts at indices 0, 2, 5 and
verify GetStagingPart returns each independently and that reassembly only uses
written indices; (3) negative index — call PutStagingPart and GetStagingPart
with a negative index and assert that the implementation rejects it or returns
storage.ErrNotFound/validation error as your contract requires; use the existing
helper functions/newContext(), and assertions similar to
TestStagingParts_WriteReadDelete (require.NoError, require.ErrorIs,
assert.Equal) to keep style consistent.

In `@pkg/storage/s3/s3.go`:
- Around line 766-795: PutStagingPart currently allows overwrites and accepts
negative indexes; update PutStagingPart to first validate the index (ensure
index >= 0) and return a clear error if not, then check for an existing object
at s.stagingPartKey(hash, index) using the S3 client's StatObject (or
equivalent) before calling PutObject and return a specific "already exists"
error if StatObject indicates the object exists; only call s.client.PutObject
when the object is not present so staging parts remain immutable.

In `@pkg/storage/store.go`:
- Line 100: The inline comment containing "See change serve-whole-nar-in-flight"
is unclear and should be removed or replaced with an explicit description;
locate the comment in pkg/storage/store.go (the comment near the Store
implementation/related method) and either delete that reference or replace it
with a short clarifying sentence such as: "Enables serving in-progress NARs by
writing fixed-size immutable parts so partial reads are safe" (or a description
matching the actual behavior), ensuring the comment clearly describes the use
case and expected behavior rather than an internal change reference.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: acd44022-1e6d-4f20-8624-1caa894f7178

📥 Commits

Reviewing files that changed from the base of the PR and between c4ad41d and 87a504c.

📒 Files selected for processing (4)
  • pkg/storage/local/local.go
  • pkg/storage/local/staging_part_test.go
  • pkg/storage/s3/s3.go
  • pkg/storage/store.go

Comment thread pkg/storage/local/local.go Resolved
Comment thread pkg/storage/s3/s3.go Resolved
Comment thread pkg/storage/store.go Resolved
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-issue-1289 branch from c4ad41d to 86502af Compare June 8, 2026 00:11
kalbasit added a commit that referenced this pull request Jun 8, 2026
Address review feedback on PR #1352:

- s3 PutStagingPart streams via multipart (putObjectStream, PartSize set)
  when the size is unknown instead of PutObject(-1), which buffers the
  whole part in memory and can OOM the holder
  (PRRT_kwDONV6tZs6Hr364, PRRT_kwDONV6tZs6Hr2-U).
- s3 DeleteStagingParts batches removals via RemoveObjects (up to 1000
  per request) rather than one RemoveObject HTTP round-trip per part
  (PRRT_kwDONV6tZs6Hr2-a).
- local PutStagingPart rejects a negative index with ErrInvalidArgument
  and removes the temp file on the Close/Rename error paths so a failed
  write never leaks a tmp file (PRRT_kwDONV6tZs6Hr361, PRRT_kwDONV6tZs6Hr2-W).
- Document the PutStagingPart contract (index >= 0, immutable-by-protocol,
  size<=0 means unknown/streamed) (PRRT_kwDONV6tZs6Hr366).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-storage-in-flight-staging branch from 87a504c to 08d1cec Compare June 8, 2026 00:11
Base automatically changed from user/wnasreddine/fix-issue-1289 to main June 8, 2026 00:19
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 8, 2026
kalbasit and others added 2 commits June 8, 2026 00:19
Add staging part-object storage to the NarStore interface and both
backends (local, S3), the transport layer for in-flight NAR staging
(GitHub #660, #1289). Parts are immutable, fixed-size, sequentially
indexed objects under a per-hash staging namespace that any replica can
read while another is still downloading.

Why: S3 cannot serve an in-progress object, so to stream an in-flight
NAR cross-pod the holder must commit completed immutable pieces during
the download. These methods are the storage substrate; the holder/reader
wiring lands in a later commit.

How:
- NarStore gains PutStagingPart / GetStagingPart / DeleteStagingParts.
- local: parts live at <root>/staging/<hash>/<index>.part, written via
  atomic temp+rename so a part is only readable once fully committed.
- s3: keys <prefix>/store/staging/<hash>/<index>.part; delete lists and
  removes the per-hash prefix. A missing part returns storage.ErrNotFound.
Address review feedback on PR #1352:

- s3 PutStagingPart streams via multipart (putObjectStream, PartSize set)
  when the size is unknown instead of PutObject(-1), which buffers the
  whole part in memory and can OOM the holder
  (PRRT_kwDONV6tZs6Hr364, PRRT_kwDONV6tZs6Hr2-U).
- s3 DeleteStagingParts batches removals via RemoveObjects (up to 1000
  per request) rather than one RemoveObject HTTP round-trip per part
  (PRRT_kwDONV6tZs6Hr2-a).
- local PutStagingPart rejects a negative index with ErrInvalidArgument
  and removes the temp file on the Close/Rename error paths so a failed
  write never leaks a tmp file (PRRT_kwDONV6tZs6Hr361, PRRT_kwDONV6tZs6Hr2-W).
- Document the PutStagingPart contract (index >= 0, immutable-by-protocol,
  size<=0 means unknown/streamed) (PRRT_kwDONV6tZs6Hr366).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-storage-in-flight-staging branch from 08d1cec to a989104 Compare June 8, 2026 00:19
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jun 8, 2026
@kalbasit
kalbasit enabled auto-merge (squash) June 8, 2026 00:19
Comment thread pkg/storage/local/staging_part_test.go Dismissed
Comment thread pkg/storage/local/staging_part_test.go Dismissed
@kalbasit
kalbasit merged commit ca604f1 into main Jun 8, 2026
39 checks passed
@kalbasit
kalbasit deleted the feat-storage-in-flight-staging branch June 8, 2026 00:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code merge-stack size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants