Skip to content

fix(pnpr): prevent stale hosted packument writes - #12832

Merged
zkochan merged 8 commits into
pnpm:mainfrom
YESHYUNGSEOK:fix/pnpr-s3-packument-cas
Jul 13, 2026
Merged

zkochan merged 8 commits into
pnpm:mainfrom
YESHYUNGSEOK:fix/pnpr-s3-packument-cas

Conversation

@YESHYUNGSEOK

@YESHYUNGSEOK YESHYUNGSEOK commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix a lost-update risk in pnpr's S3-backed hosted store when multiple replicas update the
same hosted packument, and close the related tarball-overwrite race.

  • Add conditional S3 packument writes using object-store update versions.
  • Thread read-for-update metadata through hosted storage so publish, dist-tag updates, and
    partial unpublish reject or retry stale writes.
  • Rework journal roll-forward to reread and re-merge before conditional writes.
  • Share the packument read-modify-write conflict-retry loop between dist-tag updates and
    journal roll-forward through a single Storage::update_hosted_packument_with_retry helper.
  • Make S3 tarball finalize compare-and-swap (PutMode::Create, byte-identical-tolerant): a
    losing concurrent same-version publish can no longer overwrite the winner's tarball and
    corrupt it against the integrity the winner's packument records.
  • Add regression tests for stale/deleted S3 packument updates and for the tarball overwrite guard.

This is a pnpr registry-server-only change; no TypeScript CLI or pacquet porting is needed.

Verified with:

  • cargo fmt --package pnpr -- --check
  • cargo clippy -p pnpr --all-targets -- --deny warnings
  • cargo test -p pnpr (full suite: 617 passed)
  • cargo test -p pnpr stale_packument_update_is_rejected
  • cargo test -p pnpr concurrent_tarball_finalize_does_not_overwrite
  • cargo test -p pnpr --test s3_backend
  • cargo test -p pnpr --test journal_recovery
  • cargo test -p pnpr --test batch_publish
  • cargo test -p pnpr --test staged_publish
  • cargo test -p pnpr --test auth_publish
  • cargo test -p pnpr dist_tag

Squash Commit Body

S3-backed pnpr deployments can run multiple stateless replicas against the same hosted
object store. The in-process package lock only serializes one replica, so the old
read/merge/write path could let a stale packument overwrite a newer merge.

Add a hosted packument read-for-update path that captures object-store update versions and
use conditional S3 writes for hosted packuments. Publish, partial unpublish, and dist-tag
writes now use that conditional write path; dist-tag writes retry after conflicts because
their mutation can be replayed on a fresh packument. The dist-tag request path and journal
roll-forward share one Storage::update_hosted_packument_with_retry helper so their
conflict/backoff handling stays in a single place.

Tarball finalize on the S3 backend is now compare-and-swap: it promotes with
PutMode::Create, tolerates a byte-identical object, and refuses to overwrite a different
object left by a concurrent same-version publisher. commit_publishes surfaces that as an
HTTP 409 before writing its packument, and journal roll-forward keeps the winner's
immutable version, so a losing publish can no longer corrupt the winner's tarball.

Publish commit journal recovery now rereads the current hosted packument, re-merges the
journaled manifest, and retries conditional writes.
Repeated conflicts surface as HTTP 409 rather than silently losing another writer's update.
The local fs backend keeps its existing single-process behavior because the production
shared-store race is specific to S3-backed replicas.

Regression tests verify that a stale S3 packument update is rejected and that a concurrent
tarball finalize with different bytes is refused without overwriting the first writer.

Checklist

  • Added or updated tests.

Written by an agent (Codex, GPT-5).
Follow-up review fixes (retry-loop dedup, tarball compare-and-swap) by an agent (Claude Code, claude-opus-4-8).

Summary by CodeRabbit

  • New Features
    • Added optimistic/conditional hosted packument writes (including version-aware updates) to safely handle concurrent metadata changes.
    • Updated dist-tag updates and journal recovery roll-forward to use retry-based conflict handling with capped backoff.
  • Bug Fixes
    • Prevents overwriting newer packument metadata when concurrent writes occur.
    • Consistently reports packument write conflicts as HTTP 409 Conflict; improves partial unpublish behavior and validation.
  • Tests
    • Added coverage for rejecting stale/deleted packument updates and capped conflict backoff delay growth.
    • Updated dist-tag auth test to verify authorization is checked before request parsing.

@YESHYUNGSEOK
YESHYUNGSEOK requested a review from zkochan as a code owner July 7, 2026 04:33
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (6) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. Conflicts fail startup 🐞 Bug ⛨ Security
Description
write_merged_packument() gives up after 8 conditional-write conflicts and returns
PackumentWriteConflict, which bubbles out of journal recovery and aborts load_startup_auth().
Under sustained concurrent updates to the same package’s hosted packument, a replica that has a
sealed journal entry touching that package may never start, creating an availability/DoS vector for
authenticated publishers.
Code

pnpr/crates/pnpr/src/journal.rs[R261-280]

+    for _ in 0..PACKUMENT_WRITE_RETRIES {
+        let existing_packument = store.read_hosted_packument_for_update(name).await?;
+        let (existing_bytes, version) = match existing_packument {
+            Some(packument) => (Some(packument.bytes), Some(packument.version)),
+            None => (None, None),
+        };
+        let existing: Option<serde_json::Value> = match existing_bytes.as_deref() {
+            Some(bytes) => Some(serde_json::from_slice(bytes)?),
+            None => None,
+        };
+        let merged = merge_manifest(existing.as_ref(), journaled, existing.as_ref(), &now_iso());
+        let merged_bytes = serde_json::to_vec_pretty(&merged)?;
+        match store.write_hosted_packument_if_current(name, &merged_bytes, version.as_ref()).await?
+        {
+            PackumentWrite::Written => return Ok(()),
+            PackumentWrite::Conflict => {}
+        }
+    }
+    Err(RegistryError::PackumentWriteConflict { package: name.as_str().to_string() })
+}
Evidence
Startup calls publish-journal recovery and propagates any error, so a PackumentWriteConflict from
recovery prevents the server from starting. Recovery’s merged-packument write path is capped at 8
conflict retries, and S3 conditional writes explicitly surface precondition failures as conflicts,
making this failure mode plausible under concurrent writers.

pnpr/crates/pnpr/src/server.rs[233-241]
pnpr/crates/pnpr/src/journal.rs[153-178]
pnpr/crates/pnpr/src/journal.rs[51-56]
pnpr/crates/pnpr/src/journal.rs[256-280]
pnpr/crates/pnpr/src/s3.rs[198-223]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Publish-journal recovery runs during server startup. The new conditional packument write path retries a fixed 8 times and then returns `PackumentWriteConflict`, which causes startup to fail. Under sustained concurrent packument updates for the same package, this can keep a replica from starting (readiness/availability failure).
## Issue Context
- Recovery is explicitly required before serving requests.
- Conflicts are expected/normal under the new optimistic concurrency control.
- A fixed small retry count without delay means transient contention can become a persistent startup crash-loop.
## Fix Focus Areas
- Add a contention-friendly retry strategy for **startup recovery**: exponential backoff + jitter and either a longer configurable cap (time-based) or a “retry until deadline then log and fail” behavior with actionable diagnostics.
- Ensure the recovery failure mode is operationally safe: clear logs about the conflicted package/txn and guidance (e.g., keep retrying vs. operator abort).
### Code references
- pnpr/crates/pnpr/src/journal.rs[53-280]
- pnpr/crates/pnpr/src/server.rs[233-241]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Dist-tag parse amplification 🐞 Bug ⛨ Security
Description
update_dist_tag() now retries and can invoke the mutate closure up to 8 times; set_dist_tag()
parses the request body inside that closure, so a single conflicting dist-tag update can repeatedly
JSON-parse and allocate the full request body. Because the router-wide body limit for registry
routes is 100MiB, an authenticated caller can amplify CPU/memory work by sending a very large body
and inducing write conflicts.
Code

pnpr/crates/pnpr/src/server.rs[R3537-3540]

+    Mutate: Fn(&mut serde_json::Map<String, Value>) -> Result<(), RegistryError>,
{
   let name = match PackageName::parse(raw_name) {
       Ok(n) => n,
Evidence
The router applies a 100MiB body limit broadly to registry routes; with the new retry loop in
update_dist_tag(), the mutate closure may run repeatedly. Since set_dist_tag() parses the raw
body inside that closure, the same large body can be parsed/allocated multiple times when conflicts
occur.

pnpr/crates/pnpr/src/server.rs[389-397]
pnpr/crates/pnpr/src/server.rs[3491-3506]
pnpr/crates/pnpr/src/server.rs[3524-3626]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`update_dist_tag()` now retries conditional packument writes, so it may call the provided `mutate` closure multiple times. `set_dist_tag()` currently parses the request body inside that closure (`serde_json::from_slice(body)`), which means on each retry the same (potentially large) body is re-parsed and re-allocated. With the router-wide 100MiB write body limit, this becomes an authenticated CPU/memory amplification vector under conflicts.
## Issue Context
- `update_dist_tag()` was changed to retry (`PACKUMENT_WRITE_RETRIES`) and accepts `Mutate: Fn(...)` so the closure is callable repeatedly.
- `set_dist_tag()`’s closure performs JSON parsing from the raw request body.
- Registry routes inherit `DefaultBodyLimit::max(MAX_PUBLISH_BODY_BYTES)` (100MiB).
## Fix Focus Areas
- Parse the dist-tag body **once** in `set_dist_tag()` (before calling `update_dist_tag`) and pass the already-parsed `String` into the mutate closure so retries only perform map mutation.
- (Optional hardening) Apply a much smaller per-route `DefaultBodyLimit` for dist-tag endpoints, since the body should be a small JSON string.
### Fix Focus Areas (code locations)
- pnpr/crates/pnpr/src/server.rs[3491-3506]
- pnpr/crates/pnpr/src/server.rs[3524-3626]
- pnpr/crates/pnpr/src/server.rs[361-397]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. S3 NotFound yields 502 🐞 Bug ☼ Reliability
Description
S3Store::write_packument_if_current treats only AlreadyExists/Precondition as a conflict; if the
object disappears between read-for-update and the conditional PUT, an object_store NotFound will
bubble up and be returned as HTTP 502 instead of retrying into a 404/409-style outcome. This can
surface spurious 5xx responses on dist-tag/packument mutation endpoints under concurrent
unpublish/delete of the package.
Code

pnpr/crates/pnpr/src/s3.rs[R208-223]

+        match self
+            .store
+            .put_opts(
+                &self.packument_key(name),
+                PutPayload::from(bytes.to_vec()),
+                PutOptions { mode, ..PutOptions::default() },
+            )
+            .await
+        {
+            Ok(_) => Ok(true),
+            Err(
+                object_store::Error::AlreadyExists { .. }
+                | object_store::Error::Precondition { .. },
+            ) => Ok(false),
+            Err(err) => Err(err.into()),
+        }
Evidence
The S3 conditional put maps only AlreadyExists/Precondition to conflict and treats all other errors
as hard failures; concurrent deletion is possible via remove_package, and the HTTP layer maps
ObjectStore errors to 502, so a NotFound from put_opts would become a user-visible 502 instead of a
retryable conflict/not-found outcome.

pnpr/crates/pnpr/src/s3.rs[198-223]
pnpr/crates/pnpr/src/s3.rs[274-283]
pnpr/crates/pnpr/src/server.rs[3566-3620]
pnpr/crates/pnpr/src/error.rs[304-350]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`S3Store::write_packument_if_current()` currently maps only `AlreadyExists` and `Precondition` into a non-error `false` (conflict) result. If the hosted packument key is deleted between `read_*_for_update()` and the conditional `put_opts()` (e.g. concurrent full-unpublish / remove_package), some object-store backends may report that as `Error::NotFound`. Today that would propagate as `RegistryError::ObjectStore` and be returned as HTTP 502, rather than behaving like a conflict/retry that can resolve into a 404.
### Issue Context
Callers like `update_dist_tag()` retry on `PackumentWrite::Conflict`, but they do **not** retry on generic storage errors and will return `error_response()` immediately.
### Fix Focus Areas
- pnpr/crates/pnpr/src/s3.rs[198-223]
- pnpr/crates/pnpr/src/server.rs[3566-3620]
- pnpr/crates/pnpr/src/error.rs[304-350]
### Suggested fix
- In `S3Store::write_packument_if_current()`, add `object_store::Error::NotFound { .. }` to the conflict-like error set (return `Ok(false)`), at least when operating in `PutMode::Update`.
- Optionally add a targeted regression test that simulates delete-between-read-and-write and asserts the higher-level handler returns 404 (after retry) or 409, but not 502.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Retry loops lack backoff 🐞 Bug ➹ Performance
Description
Both dist-tag updates and journal roll-forward retry conditional packument writes in a tight loop
with no backoff/jitter, so under contention they can hammer S3 with repeated full-packument GET/PUT
cycles and increase tail latency. This amplifies cross-replica write contention into avoidable load
(especially for large packuments).
Code

pnpr/crates/pnpr/src/server.rs[R3566-3620]

+    let mut written = false;
+    for _ in 0..PACKUMENT_WRITE_RETRIES {
+        let hosted_packument = match storage.read_hosted_packument_for_update(&name).await {
+            Ok(Some(packument)) => packument,
+            Ok(None) => return not_found(),
+            Err(err) => return error_response(&err),
+        };
+        let mut packument: Value = match serde_json::from_slice(&hosted_packument.bytes) {
+            Ok(value) => value,
        Err(err) => return error_response(&RegistryError::Json(err)),
-        },
-        Ok(None) => return not_found(),
-        Err(err) => return error_response(&err),
-    };
+        };
-    let Some(packument_obj) = packument.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored packument is not an object".to_string(),
-        });
-    };
-    let tags_entry = packument_obj
-        .entry("dist-tags".to_string())
-        .or_insert_with(|| Value::Object(serde_json::Map::new()));
-    let Some(tags) = tags_entry.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored dist-tags is not an object".to_string(),
-        });
-    };
-    if let Err(err) = mutate(tags) {
-        return error_response(&err);
+        let Some(packument_obj) = packument.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored packument is not an object".to_string(),
+            });
+        };
+        let tags_entry = packument_obj
+            .entry("dist-tags".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(tags) = tags_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored dist-tags is not an object".to_string(),
+            });
+        };
+        if let Err(err) = mutate(tags) {
+            return error_response(&err);
+        }
+        let _ = tag;
+        // dist-tag 변경 뒤에도 클라이언트의 신선도 판단이 뒤처지지 않게
+        // `time.modified`를 갱신한다.
+        let time_entry = packument_obj
+            .entry("time".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(time_obj) = time_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored time is not an object".to_string(),
+            });
+        };
+        time_obj.insert("modified".to_string(), Value::String(now_iso()));
+        let new_bytes = match serde_json::to_vec_pretty(&packument) {
+            Ok(b) => b,
+            Err(err) => return error_response(&RegistryError::Json(err)),
+        };
+        match storage
+            .write_hosted_packument_if_current(&name, &new_bytes, Some(&hosted_packument.version))
+            .await
+        {
+            Ok(PackumentWrite::Written) => {
+                written = true;
+                break;
+            }
+            Ok(PackumentWrite::Conflict) => continue,
+            Err(err) => return error_response(&err),
+        }
Evidence
The retry loops explicitly continue on PackumentWrite::Conflict with no delay, and they
re-read/re-serialize/re-write the packument each time.

pnpr/crates/pnpr/src/server.rs[3524-3626]
pnpr/crates/pnpr/src/journal.rs[256-280]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new conflict-handling loops retry immediately on `PackumentWrite::Conflict` (up to 8 times). Without any delay/backoff, contended packages can cause rapid repeated S3 GET+PUT attempts, increasing load and reducing the probability of a successful retry when multiple replicas are racing.
### Issue Context
- `update_dist_tag` now retries by re-reading, mutating, and conditionally writing the full packument.
- `journal::write_merged_packument` does the same during recovery.
- Each attempt includes JSON parse + pretty-serialization + full-object upload.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[3566-3625]
- pnpr/crates/pnpr/src/journal.rs[256-280]
### Suggested fix
- Introduce a small **exponential backoff with jitter** between conflict retries (e.g., 10ms, 20ms, 40ms… capped), using `tokio::time::sleep`.
- Consider emitting a debug/warn log or metric when conflicts exceed a threshold to aid diagnosis.
- Keep the existing retry cap, but make the loop time-bounded so it can’t monopolize the request under pathological contention.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (2)
5. Orphan tarballs on conflict 🐞 Bug ⛨ Security
Description
commit_publishes still promotes tarballs before the (now conditional) packument write, so a
PackumentWrite::Conflict after finalize_tarball_slot can leave uploaded S3 tarballs unreferenced
by any hosted packument and with no cleanup path. Under repeated conflicts this becomes a persistent
storage-growth/ops burden (and can be induced by cross-replica write contention).
Code

pnpr/crates/pnpr/src/server.rs[R2965-2982]

        for slot in stage.slots {
            store.finalize_tarball_slot(slot).await?;
        }
-            store.write_hosted_packument(&stage.name, &stage.merged_bytes).await?;
+            match store
+                .write_hosted_packument_if_current(
+                    &stage.name,
+                    &stage.merged_bytes,
+                    stage.base_version.as_ref(),
+                )
+                .await?
+            {
+                PackumentWrite::Written => {}
+                PackumentWrite::Conflict => {
+                    return Err(RegistryError::PackumentWriteConflict {
+                        package: stage.name.as_str().to_string(),
+                    });
+                }
+            }
Evidence
The new conditional packument write can fail after tarball promotion, and S3 tarball promotion
uploads to a final key without any rollback when a conflict is returned.

pnpr/crates/pnpr/src/server.rs[2925-2996]
pnpr/crates/pnpr/src/storage.rs[288-302]
pnpr/crates/pnpr/src/s3.rs[255-263]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Conditional hosted-packument writes can now fail with `PackumentWrite::Conflict` after tarballs have already been promoted to the hosted store. On S3 this means the tarball objects are already uploaded to their final keys; if the packument write ultimately fails (including roll-forward failing after retries), those objects can remain unreferenced and accumulate.
### Issue Context
- `commit_publishes` promotes tarballs first (by design) and then performs a conditional packument write.
- S3 tarball promotion uploads to the final key and deletes only the local tmp file.
- The new conflict path introduces a failure mode that didn’t exist with unconditional packument writes.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2960-2983]
- pnpr/crates/pnpr/src/storage.rs[288-302]
- pnpr/crates/pnpr/src/s3.rs[255-263]
### Suggested fix approaches
Pick one (or combine):
1. **Best-effort cleanup on terminal conflict:** if the publish ultimately returns `PackumentWriteConflict` (including after `txn.roll_forward` fails), attempt to delete the newly promoted tarballs for that staged publish (S3: `delete` each tarball key). Ensure this cleanup is safe/idempotent and does not delete tarballs for versions that are already present in the current hosted packument.
2. **Promote tarballs in a reversible way:** upload tarballs to a temporary/staging object key first, then copy/move to the final key only after the packument write succeeds; delete staging objects on failure.
3. **Make roll-forward completion more reliable:** if conflicts persist, consider persisting the sealed journal and scheduling background roll-forward retries (with backoff) so the system converges without requiring a restart, reducing the chance of permanent orphaning.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Duplicate packument retry loops 📘 Rule violation ⚙ Maintainability
Description
Conditional packument write retry logic is implemented separately in write_merged_packument()
(journal roll-forward) and update_dist_tag() (dist-tag updates). This duplication increases the
risk of divergence in conflict handling and makes future fixes harder to apply consistently.
Code

pnpr/crates/pnpr/src/server.rs[R3566-3625]

+    let mut written = false;
+    for _ in 0..PACKUMENT_WRITE_RETRIES {
+        let hosted_packument = match storage.read_hosted_packument_for_update(&name).await {
+            Ok(Some(packument)) => packument,
+            Ok(None) => return not_found(),
+            Err(err) => return error_response(&err),
+        };
+        let mut packument: Value = match serde_json::from_slice(&hosted_packument.bytes) {
+            Ok(value) => value,
        Err(err) => return error_response(&RegistryError::Json(err)),
-        },
-        Ok(None) => return not_found(),
-        Err(err) => return error_response(&err),
-    };
+        };
-    let Some(packument_obj) = packument.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored packument is not an object".to_string(),
-        });
-    };
-    let tags_entry = packument_obj
-        .entry("dist-tags".to_string())
-        .or_insert_with(|| Value::Object(serde_json::Map::new()));
-    let Some(tags) = tags_entry.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored dist-tags is not an object".to_string(),
-        });
-    };
-    if let Err(err) = mutate(tags) {
-        return error_response(&err);
+        let Some(packument_obj) = packument.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored packument is not an object".to_string(),
+            });
+        };
+        let tags_entry = packument_obj
+            .entry("dist-tags".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(tags) = tags_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored dist-tags is not an object".to_string(),
+            });
+        };
+        if let Err(err) = mutate(tags) {
+            return error_response(&err);
+        }
+        let _ = tag;
+        // dist-tag 변경 뒤에도 클라이언트의 신선도 판단이 뒤처지지 않게
+        // `time.modified`를 갱신한다.
+        let time_entry = packument_obj
+            .entry("time".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(time_obj) = time_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored time is not an object".to_string(),
+            });
+        };
+        time_obj.insert("modified".to_string(), Value::String(now_iso()));
+        let new_bytes = match serde_json::to_vec_pretty(&packument) {
+            Ok(b) => b,
+            Err(err) => return error_response(&RegistryError::Json(err)),
+        };
+        match storage
+            .write_hosted_packument_if_current(&name, &new_bytes, Some(&hosted_packument.version))
+            .await
+        {
+            Ok(PackumentWrite::Written) => {
+                written = true;
+                break;
+            }
+            Ok(PackumentWrite::Conflict) => continue,
+            Err(err) => return error_response(&err),
+        }
}
-    let _ = tag; // tag name is used by the mutate closure
-    // Refresh `time.modified` so clients that rely on it for
-    // freshness (pacquet's pick_package, npm's abbreviated-packument
-    // staleness check) don't see the post-mutation packument as
-    // older than its dist-tag change.
-    let time_entry = packument_obj
-        .entry("time".to_string())
-        .or_insert_with(|| Value::Object(serde_json::Map::new()));
-    let Some(time_obj) = time_entry.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored time is not an object".to_string(),
+    if !written {
+        return error_response(&RegistryError::PackumentWriteConflict {
+            package: name.as_str().to_string(),
    });
-    };
-    time_obj.insert("modified".to_string(), Value::String(now_iso()));
-    let new_bytes = match serde_json::to_vec_pretty(&packument) {
-        Ok(b) => b,
-        Err(err) => return error_response(&RegistryError::Json(err)),
-    };
-    if let Err(err) = storage.write_hosted_packument(&name, &new_bytes).await {
-        return error_response(&err);
Evidence
PR Compliance ID 713439 requires reusing/shared modules instead of reimplementing similar logic. The
diff adds two separate retry loops that both reread the hosted packument with an update version and
retry conditional writes on conflict, which is effectively the same algorithm implemented twice.

Rule 713439: Avoid reimplementing existing functionality; extract and reuse shared modules
pnpr/crates/pnpr/src/journal.rs[256-280]
pnpr/crates/pnpr/src/server.rs[3566-3625]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR introduces two similar retry-on-conflict loops for hosted packument conditional writes (journal roll-forward and dist-tag updates). This duplicates logic that should stay consistent (retry count, conflict handling, read/merge/write flow), increasing maintenance risk.
## Issue Context
Both code paths perform: read hosted packument-for-update (with version), compute new packument bytes, then `write_hosted_packument_if_current(...)`, retrying on conflicts up to `PACKUMENT_WRITE_RETRIES`.
## Fix Focus Areas
- pnpr/crates/pnpr/src/journal.rs[256-280]
- pnpr/crates/pnpr/src/server.rs[3566-3625]
- pnpr/crates/pnpr/src/storage.rs[378-392]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

7. Packument PUT double-copies 🐞 Bug ➹ Performance
Description
The S3 conditional packument write path always allocates and copies the full packument payload via
bytes.to_vec() before upload; callers already build a Vec<u8> (serde_json::to_vec_pretty) so this
adds an avoidable extra buffer copy. Under contention (retries) this increases allocation pressure
and memory bandwidth on publish/journal/dist-tag hot paths.
Code

pnpr/crates/pnpr/src/s3.rs[R210-214]

+            .put_opts(
+                &self.packument_key(name),
+                PutPayload::from(bytes.to_vec()),
+                PutOptions { mode, ..PutOptions::default() },
+            )
Evidence
S3 packument writes currently clone the payload slice into a new Vec, while higher-level callers
already hold a Vec created for serialization; this creates an unnecessary extra copy and allocation
on every conditional PUT attempt.

pnpr/crates/pnpr/src/s3.rs[198-223]
pnpr/crates/pnpr/src/server.rs[3605-3619]
pnpr/crates/pnpr/src/journal.rs[271-277]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`S3Store::write_packument_if_current()` converts `&[u8]` to an owned `Vec<u8>` (`bytes.to_vec()`) to build `PutPayload`. In the new code paths, the payload is already an owned `Vec<u8>` created by `serde_json::to_vec_pretty`, so the current interface forces an extra allocation and copy.
### Issue Context
This is particularly noticeable in retry loops (`update_dist_tag`, journal roll-forward), where the extra copy happens on each attempted PUT.
### Fix Focus Areas
- pnpr/crates/pnpr/src/s3.rs[198-223]
- pnpr/crates/pnpr/src/server.rs[3566-3620]
- pnpr/crates/pnpr/src/journal.rs[256-280]
### Suggested fix
- Change the internal packument-write APIs to accept an owned buffer (e.g., `Vec<u8>` or `bytes::Bytes`) so S3 can do `PutPayload::from(vec)` without cloning.
- Example direction: `write_packument_if_current(&self, ..., bytes: Vec<u8>, ...)` and adjust callers to pass/move their existing `Vec<u8>`.
- Keep the public/outer APIs ergonomic by still allowing callers that only have `&[u8]` to `.to_vec()` at the boundary (but avoid doing it unconditionally in the hot path).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 103d2432-3236-4c04-9ca6-d5480fbe9fd7

📥 Commits

Reviewing files that changed from the base of the PR and between 67f67da and 1a0f9df.

📒 Files selected for processing (7)
  • pnpr/crates/pnpr/src/journal.rs
  • pnpr/crates/pnpr/src/s3.rs
  • pnpr/crates/pnpr/src/s3/tests.rs
  • pnpr/crates/pnpr/src/server.rs
  • pnpr/crates/pnpr/src/storage.rs
  • pnpr/crates/pnpr/src/storage/tests.rs
  • pnpr/crates/pnpr/tests/auth_publish.rs
✅ Files skipped from review due to trivial changes (1)
  • pnpr/crates/pnpr/src/storage/tests.rs
🚧 Files skipped from review as they are similar to previous changes (3)
  • pnpr/crates/pnpr/src/storage.rs
  • pnpr/crates/pnpr/src/s3.rs
  • pnpr/crates/pnpr/src/server.rs

📝 Walkthrough

Walkthrough

This PR adds optimistic concurrency for hosted packument writes. Storage now returns versioned packuments, callers use conditional writes, and journal recovery, publish commit, partial unpublish, and dist-tag updates retry on write conflicts.

Changes

Packument write conflict handling

Layer / File(s) Summary
Conflict error mapping
pnpr/crates/pnpr/src/error.rs
Adds RegistryError::PackumentWriteConflict { package } and maps it to a dedicated log kind and HTTP 409.
Version-aware storage APIs
pnpr/crates/pnpr/src/storage.rs, pnpr/crates/pnpr/src/s3.rs, pnpr/crates/pnpr/src/s3/tests.rs
Adds version-carrying hosted packument read/write primitives, conditional S3 packument updates, and tests for stale-version rejection and retry delay capping.
Journal roll-forward retry merge
pnpr/crates/pnpr/src/journal.rs
Replaces the one-shot merge/write path with a retry loop that uses conditional hosted packument writes and surfaces PackumentWriteConflict on exhaustion.
Publish commit and partial unpublish
pnpr/crates/pnpr/src/server.rs
Tracks hosted packument base versions during staging, writes publishes and partial unpublishes conditionally, and updates immutability checks to consume preloaded hosted packument data.
Dist-tag retry loop
pnpr/crates/pnpr/src/server.rs, pnpr/crates/pnpr/tests/auth_publish.rs
Reworks dist-tag updates to retry version-aware read-modify-write operations, and updates the auth test to assert authorization happens before request-body parsing.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Server
  participant Storage
  participant S3Store
  Client->>Server: publish or update request
  Server->>Storage: read_hosted_packument_for_update
  Storage->>S3Store: read_packument_for_update
  S3Store-->>Storage: bytes + UpdateVersion
  Storage-->>Server: bytes + base_version
  Server->>Storage: write_hosted_packument_if_current
  Storage->>S3Store: write_packument_if_current
  S3Store-->>Storage: Written or Conflict
  Storage-->>Server: PackumentWrite result
  alt Conflict
    Server-->>Client: 409 PackumentWriteConflict
  else Written
    Server-->>Client: success
  end
Loading

Possibly related PRs

  • pnpm/pnpm#12198: Changes S3-hosted packument writes to use optimistic/conditional updates with version tracking and conflict handling.
  • pnpm/pnpm#12646: Also changes server.rs publish-flow conflict handling around stage_publish and 409 Conflict outcomes.
  • pnpm/pnpm#12647: Also changes update_packument in server.rs and its hosted-packument validation/write flow.

Suggested labels: product: pnpr

Suggested reviewers: zkochan

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

fix(pnpr): prevent stale hosted packument writes via CAS

🐞 Bug fix ✨ Enhancement 🕐 40+ Minutes

Grey Divider

AI Description

• Adds compare-and-swap (CAS) writes for S3-backed hosted packuments using object_store
 ETag/version tokens to prevent lost-update races across multiple stateless replicas.
• Threads read-for-update metadata (HostedPackumentForUpdate, HostedPackumentVersion) through
 Storage, HostedStore, and S3Store so publish, partial-unpublish, and dist-tag writes all use
 conditional S3 put_opts calls.
• Dist-tag updates and journal roll-forward retry up to 8 times on conflict by re-reading and
 re-merging; publish and partial-unpublish surface conflicts immediately as HTTP 409
 PackumentWriteConflict.
• Adds a new PackumentWriteConflict error variant mapped to 409 Conflict and refactors
 enforce_published_version_immutability from async (with its own storage read) to sync (accepting a
 pre-read Value).
• Adds a regression test stale_packument_update_is_rejected that verifies a stale S3 write is
 rejected while the first writer's version is preserved.
Diagram

graph TD
    Client(["npm / pnpm client"]) --> Server["server.rs\nPublish / Dist-tag / Unpublish"]
    Server --> Storage["storage.rs\nStorage abstraction"]
    Storage --> HostedStore{"HostedStore"}
    HostedStore -->|"Fs backend"| FsStore["Store\n(always Written)"]
    HostedStore -->|"S3 backend"| S3Store["s3.rs\nS3Store CAS"]
    S3Store -->|"put_opts PutMode::Update"| ObjectStore[("S3 / R2 / MinIO")]
    Server --> Journal["journal.rs\nRoll-forward recovery"]
    Journal --> Storage
    Server -->|"409 Conflict"| Client

    subgraph Legend
      direction LR
      _ext(["External actor"]) ~~~ _mod["Module"] ~~~ _db[("Object store")]
    end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Distributed lock (Redis / DynamoDB)
  • ➕ Eliminates retry loops entirely
  • ➕ Guarantees at-most-one writer across all replicas
  • ➖ Adds an external dependency (Redis/DynamoDB)
  • ➖ Increases operational complexity and failure modes
  • ➖ Hurts throughput under contention
2. Retry publish on conflict (same as dist-tag)
  • ➕ Avoids 409 for concurrent publishes of different versions to the same package
  • ➖ Publish is more complex (tarballs already staged); re-merging is non-trivial
  • ➖ Risk of re-staging tarballs or double-writing
  • ➖ Current behavior (409) is consistent with npm/verdaccio semantics for concurrent publishes

Recommendation: The PR's optimistic-concurrency (CAS) approach is the right choice for a shared S3 object store. The main alternative worth considering is a distributed lock (e.g. DynamoDB conditional writes or a Redis lock), but that adds an external dependency and operational complexity. A pessimistic lock via a distributed mutex would serialize all replicas globally, hurting throughput. The current approach — per-object ETag-based CAS with bounded retries and 409 on exhaustion — is idiomatic for object stores and keeps the system stateless. One minor concern: publish conflicts are not retried (unlike dist-tag and journal), so a concurrent publish to the same package from two replicas will 409 the second writer; this is acceptable given that publish is already serialized per-instance by the in-process package lock.

Files changed (6) +324 / -95

Enhancement (2) +124 / -9
s3.rsAdd CAS read/write primitives to S3Store +51/-4

Add CAS read/write primitives to S3Store

• Replaces the unconditional 'write_packument' with 'read_packument_for_update' (captures ETag/version into 'S3PackumentForUpdate') and 'write_packument_if_current' (uses 'PutMode::Update' or 'PutMode::Create' via 'put_opts'). Returns 'false' on 'AlreadyExists'/'Precondition' errors to signal a conflict without propagating an error.

pnpr/crates/pnpr/src/s3.rs

storage.rsThread CAS version tokens through the Storage abstraction layer +73/-5

Thread CAS version tokens through the Storage abstraction layer

• Adds 'HostedPackumentForUpdate', 'HostedPackumentVersion' (Fs/S3 variants), and 'PackumentWrite' (Written/Conflict) types. Replaces 'write_hosted_packument' with 'read_hosted_packument_for_update' and 'write_hosted_packument_if_current' on both 'HostedStore' and 'Storage'. The Fs backend always returns 'Written'; the S3 backend delegates to the new CAS primitives.

pnpr/crates/pnpr/src/storage.rs

Bug fix (3) +157 / -81
error.rsAdd PackumentWriteConflict error variant mapped to HTTP 409 +10/-1

Add PackumentWriteConflict error variant mapped to HTTP 409

• Introduces a new 'PackumentWriteConflict' variant to 'RegistryError' with a display message indicating the package name. Maps it to 'StatusCode::CONFLICT' (409) alongside 'VersionAlreadyPublished', and adds it to the 'log_kind' match arm.

pnpr/crates/pnpr/src/error.rs

server.rsUse conditional packument writes in publish, dist-tag, and partial-unpublish handlers +117/-70

Use conditional packument writes in publish, dist-tag, and partial-unpublish handlers

• Stage-publish now captures 'base_version' from 'read_hosted_packument_for_update' and threads it into 'StagedPublish'; 'commit_publishes' uses 'write_hosted_packument_if_current' and returns 'PackumentWriteConflict' on conflict. 'update_dist_tag' is reworked into a retry loop (up to 8 attempts) that re-reads and re-applies the mutation on each conflict. 'update_packument' (partial-unpublish) reads the current packument for update and writes conditionally, returning 409 on conflict. 'enforce_published_version_immutability' is refactored from async (with its own storage read) to a synchronous function accepting a pre-read 'Value'.

pnpr/crates/pnpr/src/server.rs

journal.rsRework journal roll-forward to use conditional CAS writes with retry +30/-10

Rework journal roll-forward to use conditional CAS writes with retry

• Extracts a new 'write_merged_packument' helper that loops up to 'PACKUMENT_WRITE_RETRIES' (8) times: reads the current hosted packument for update, re-merges the journaled manifest into it, and attempts a conditional write. Returns 'PackumentWriteConflict' after exhausting retries. The 'roll_forward' function now delegates to this helper instead of doing an unconditional write.

pnpr/crates/pnpr/src/journal.rs

Other (1) +43 / -5
tests.rsAdd stale_packument_update_is_rejected regression test and update helpers +43/-5

Add stale_packument_update_is_rejected regression test and update helpers

• Adds a 'write_packument' test helper that wraps 'write_packument_if_current' with 'None' version. Adds 'stale_packument_update_is_rejected' test: writes an initial packument, takes two concurrent reads, lets the first write succeed, and asserts the second write (with the stale version token) is rejected and the stored content matches the first write. Updates existing tests to use the new helper.

pnpr/crates/pnpr/src/s3/tests.rs

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

@qodo-code-review

qodo-code-review Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. Conflict state lost on retry ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
journal::roll_forward deletes the staged tarball tmp on TarballFinalize::Conflict and records
the conflict only in an in-memory HashSet, so if the subsequent write_merged_packument CAS write
fails and the journal entry is retried later, the next roll-forward cannot re-detect the tarball
conflict and may re-merge the losing version’s dist/integrity metadata against the winner’s
immutable tarball bytes (causing integrity mismatches/failed installs).
Code

pnpr/crates/pnpr/src/journal.rs[R250-267]

+                    // Another replica already promoted a *different* tarball for
+                    // this version. Its bytes are immutable, so we must not
+                    // overwrite them — and we must not advertise our integrity
+                    // against them either. Drop our staged copy and record the
+                    // filename so the merge below excludes the version we lost.
+                    TarballFinalize::Conflict => {
+                        let _ = fs::remove_file(&tarball.tmp_path).await;
+                        conflicted.insert(tarball.filename.as_str());
+                    }
+                }
            }
        }
-        let journaled: serde_json::Value =
+        let mut journaled: serde_json::Value =
            serde_json::from_slice(&fs::read(dir.join(&package.packument_file)).await?)?;
-        let existing: Option<serde_json::Value> = match store.read_hosted_packument(&name).await? {
-            Some(bytes) => Some(serde_json::from_slice(&bytes)?),
-            None => None,
-        };
-        // `existing` is the hosted packument here, so it is also the
-        // immutability reference.
-        let merged = merge_manifest(existing.as_ref(), &journaled, existing.as_ref(), &now_iso());
-        store.write_hosted_packument(&name, &serde_json::to_vec_pretty(&merged)?).await?;
+        if !conflicted.is_empty() {
+            drop_conflicted_versions(&mut journaled, &conflicted);
+        }
+        write_merged_packument(&store, &name, &journaled).await?;
Evidence
On tarball conflict, roll-forward deletes the tmp and stores the filename only in an in-memory set;
the journal directory is only removed after write_merged_packument succeeds, so if the packument
CAS write returns an error (e.g., conflict after retries), the journal remains but the conflict
cannot be re-derived on the next attempt. Storage explicitly keeps tmp files on conflict to enable
re-detection, which the early deletion in roll-forward defeats.

pnpr/crates/pnpr/src/journal.rs[223-270]
pnpr/crates/pnpr/src/journal.rs[296-318]
pnpr/crates/pnpr/src/storage.rs[330-349]
pnpr/crates/pnpr/src/storage.rs[472-511]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
During journal roll-forward, a `TarballFinalize::Conflict` is handled by deleting the staged tmp tarball and recording the conflict only in-memory. If the subsequent conditional packument write fails (e.g., CAS conflicts exceed retry budget), the journal entry remains for later retry but the conflict signal is gone, so a later roll-forward may merge/write metadata for a version whose tarball bytes belong to a concurrent winner.

### Issue Context
Roll-forward is supposed to be idempotent and safe to retry. The current ordering makes conflict detection non-durable across retries.

### Fix Focus Areas
- pnpr/crates/pnpr/src/journal.rs[234-270]
- pnpr/crates/pnpr/src/journal.rs[296-318]
- pnpr/crates/pnpr/src/storage.rs[330-349]

### Suggested fix approach
- Do **not** delete `tarball.tmp_path` immediately on `TarballFinalize::Conflict`.
- Instead, collect conflicted tmp paths (and/or filenames) and only delete those tmp files **after** `write_merged_packument` succeeds and the journal entry is about to be removed.
- Alternatively/additionally, persist conflict markers inside the journal directory (e.g., a small `conflicts.json` keyed by filename) so conflict state survives process restarts and roll-forward retries.
- Add a regression test covering: tarball conflict happens, packument write fails (simulated conflict/exhausted retries), then a subsequent roll-forward still excludes the conflicted version.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. journal::tarball_basename duplicates logic ✓ Resolved 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new journal::tarball_basename reimplements tarball-basename extraction but does not strip
?query/#fragment or handle trailing /, unlike the existing shared helper. This can prevent
drop_conflicted_versions from matching conflicted staged filenames (e.g., signed URLs), risking
writing a packument that advertises dist/integrity for a tarball whose bytes lost the
compare-and-swap.
Code

pnpr/crates/pnpr/src/journal.rs[R320-324]

+/// The final path segment of a `dist.tarball` URL — the on-disk tarball
+/// filename that a staged slot is keyed by.
+fn tarball_basename(tarball_url: &str) -> &str {
+    tarball_url.rsplit('/').next().unwrap_or(tarball_url)
+}
Evidence
drop_conflicted_versions derives a filename via map(tarball_basename), but the newly added
tarball_basename does not strip query/fragment, so it can produce a different basename than the
established helper used elsewhere for dist.tarball handling. The repo already defines a canonical
upstream::tarball_basename with query/fragment stripping and trailing-slash handling, so this is
duplicated and behavior-divergent logic.

Rule 713439: Avoid reimplementing existing functionality; extract and reuse shared modules
pnpr/crates/pnpr/src/journal.rs[296-324]
pnpr/crates/pnpr/src/upstream.rs[401-411]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`pnpr/crates/pnpr/src/journal.rs` added a local `tarball_basename` that only `rsplit('/')`s the URL. The codebase already has a canonical `tarball_basename` helper in `upstream.rs` that strips `?query`/`#fragment` and returns `None` for URLs ending with `/`. The mismatch can cause `drop_conflicted_versions` to fail to drop versions whose staged tarballs lost CAS when `dist.tarball` carries a query/fragment.

## Issue Context
The roll-forward logic uses `drop_conflicted_versions` to avoid advertising `dist`/integrity for tarballs that lost a compare-and-swap. Filename matching should use the same basename semantics as the rest of the registry code.

## Fix Focus Areas
- pnpr/crates/pnpr/src/journal.rs[296-325]
- pnpr/crates/pnpr/src/upstream.rs[401-411]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Packument may reference wrong tarball ✓ Resolved 🐞 Bug ⛨ Security
Description
In journal recovery roll-forward, TarballFinalize::Conflict is ignored and roll-forward continues,
which can write a packument version whose dist metadata/integrity corresponds to the journaled
tarball even though a different tarball already occupies that immutable version key. This can
publish inconsistent metadata vs hosted bytes (integrity failures / broken installs) if the winning
publisher’s packument update is not yet visible when the merge runs.
Code

pnpr/crates/pnpr/src/journal.rs[R246-252]

+                match store.finalize_tarball_slot(slot).await? {
+                    TarballFinalize::Written | TarballFinalize::AlreadyIdentical => {}
+                    // Another replica already promoted a different tarball for
+                    // this version. Don't overwrite it; the re-merge below keeps
+                    // that winner's immutable version, so ours is dropped.
+                    TarballFinalize::Conflict => {}
+                }
Evidence
Recovery currently drops the tarball conflict signal and can still write merged metadata;
merge_versions will take the incoming manifest for versions not already present in the hosted
packument, which is exactly the problematic race window when a different tarball already exists at
that version key but the hosted packument hasn’t yet recorded it.

pnpr/crates/pnpr/src/journal.rs[233-258]
pnpr/crates/pnpr/src/storage.rs[238-252]
pnpr/crates/pnpr/src/publish.rs[304-351]
pnpr/crates/pnpr/src/s3.rs[260-297]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`roll_forward` treats `TarballFinalize::Conflict` as a no-op and proceeds to merge/write the packument. Because `merge_manifest` will insert incoming versions that are not already present in the *hosted* packument, recovery can end up writing the journaled version metadata even though the tarball at that version’s key belongs to another publisher (different bytes), producing a packument that advertises an integrity that does not match the hosted tarball.

## Issue Context
- `TarballFinalize::Conflict` explicitly means “different object already occupies the key” and callers must not advertise an integrity that no longer matches the bytes.
- Journal roll-forward is allowed to run concurrently with other replicas; it can observe tarball conflict before the other replica’s packument write becomes visible.

## Fix Focus Areas
- pnpr/crates/pnpr/src/journal.rs[246-252]

## Suggested fix
On `TarballFinalize::Conflict`, return an error (e.g., `RegistryError::PackumentWriteConflict` or a new tarball-specific conflict error) so roll-forward aborts and the sealed journal entry remains for later retry. Optionally add a short retry/backoff loop here (or rely on later recovery) so roll-forward only proceeds once the current hosted packument reflects the winning version (immutability reference) before attempting the merge/write.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. Tarball conflict loads full bytes 🐞 Bug ➹ Performance
Description
On S3 tarball promotion conflicts, upload_tarball re-reads the staged tarball and also downloads
the full existing object into memory to compare equality, causing large extra I/O and transient
memory pressure under contention. With the 100MiB tarball cap, each conflict can require up to ~2×
tarball-size additional buffering (plus any backend payload retention), and always forces a
full-object download even when size differs.
Code

pnpr/crates/pnpr/src/s3.rs[R265-295]

+    ) -> Result<crate::storage::TarballFinalize> {
+        use crate::storage::TarballFinalize;
        let bytes = fs::read(tmp_path).await?;
-        self.store.put(&self.tarball_key(name, filename), PutPayload::from(bytes)).await?;
-        Ok(())
+        let key = self.tarball_key(name, filename);
+        // Create-only. A published version's tarball is immutable, so an object
+        // already at this key belongs to a concurrent publisher of the same
+        // version. Overwriting it would corrupt that artifact against the
+        // integrity its packument records, so tolerate only byte-identical
+        // content and otherwise report a conflict.
+        match self
+            .store
+            .put_opts(
+                &key,
+                PutPayload::from(bytes),
+                PutOptions { mode: PutMode::Create, ..PutOptions::default() },
+            )
+            .await
+        {
+            Ok(_) => Ok(TarballFinalize::Written),
+            Err(
+                object_store::Error::AlreadyExists { .. }
+                | object_store::Error::Precondition { .. },
+            ) => {
+                let ours = fs::read(tmp_path).await?;
+                let existing = self.store.get(&key).await?.bytes().await?;
+                if existing.as_ref() == ours.as_slice() {
+                    Ok(TarballFinalize::AlreadyIdentical)
+                } else {
+                    Ok(TarballFinalize::Conflict)
+                }
+            }
Evidence
The S3 tarball finalize conflict handler explicitly re-reads the local tmp and fetches the whole
remote object to compare; tarballs are capped at 100 MiB, so the overhead is bounded but still
significant under contention.

pnpr/crates/pnpr/src/s3.rs[260-297]
pnpr/crates/pnpr/src/server.rs[63-74]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
In `S3Store::upload_tarball`, when `put_opts(..., PutMode::Create)` fails with `AlreadyExists`/`Precondition`, the code reads the staged tarball again and downloads the entire existing tarball to compare bytes. This amplifies memory and bandwidth during conflicts.

## Issue Context
Tarballs are capped at 100 MiB in the server, but conflicts can still happen (concurrent publishes or idempotent recovery). The current approach is correct but expensive.

## Fix Focus Areas
- pnpr/crates/pnpr/src/s3.rs[265-295]

## Suggested fix
Reduce work on the conflict path:
- First compare sizes via a `head`/metadata fetch (if available via `object_store`) and return `Conflict` immediately if sizes differ.
- Avoid buffering whole objects: stream the existing object (`into_stream`) and compare against the staged file in chunks (or compute a hash over both streams) to keep peak memory bounded.
- If streaming compare is too complex, consider returning `Conflict` without attempting byte-identical detection (dropping `AlreadyIdentical`), or gate deep-compare behind a small-size threshold.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Roll-forward blocks publish 🐞 Bug ☼ Reliability
Description
After a sealed publish apply fails, commit_publishes synchronously calls txn.roll_forward(), and
roll-forward’s write_merged_packument can retry/sleep up to 32 times on conflicts, which can hold a
publish request open for ~6.6s of sleep time plus storage I/O under sustained contention. This is a
bounded but significant tail-latency amplification in the request path (and can consume request/task
capacity during contention bursts).
Code

pnpr/crates/pnpr/src/journal.rs[R258-286]

+async fn write_merged_packument(
+    store: &Storage,
+    name: &PackageName,
+    journaled: &serde_json::Value,
+) -> Result<()> {
+    for attempt in 0..RECOVERY_PACKUMENT_WRITE_RETRIES {
+        let existing_packument = store.read_hosted_packument_for_update(name).await?;
+        let (existing_bytes, version) = match existing_packument {
+            Some(packument) => (Some(packument.bytes), Some(packument.version)),
+            None => (None, None),
+        };
+        let existing: Option<serde_json::Value> = match existing_bytes.as_deref() {
+            Some(bytes) => Some(serde_json::from_slice(bytes)?),
+            None => None,
+        };
+        let merged = merge_manifest(existing.as_ref(), journaled, existing.as_ref(), &now_iso());
+        let merged_bytes = serde_json::to_vec_pretty(&merged)?;
+        match store.write_hosted_packument_if_current(name, &merged_bytes, version.as_ref()).await?
+        {
+            PackumentWrite::Written => return Ok(()),
+            PackumentWrite::Conflict => {
+                if attempt + 1 < RECOVERY_PACKUMENT_WRITE_RETRIES {
+                    wait_after_packument_write_conflict(attempt).await;
+                }
+            }
+        }
+    }
+    Err(RegistryError::PackumentWriteConflict { package: name.as_str().to_string() })
+}
Evidence
The server awaits roll-forward inside the publish commit error path, and the new roll-forward
implementation can conflict/sleep repeatedly (up to 32 attempts) before returning, while only
deleting the journal directory after success.

pnpr/crates/pnpr/src/server.rs[3108-3111]
pnpr/crates/pnpr/src/journal.rs[223-255]
pnpr/crates/pnpr/src/journal.rs[258-286]
pnpr/crates/pnpr/src/storage.rs[32-41]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`SealedTxn::roll_forward()` is used both for startup recovery and for synchronous self-heal when an inline publish apply fails. With the new CAS behavior, `write_merged_packument()` may hit repeated conflicts and will sleep/retry up to `RECOVERY_PACKUMENT_WRITE_RETRIES` (32), which can stall the publish request for several seconds.

## Issue Context
- `commit_publishes` calls `txn.roll_forward(...).await` on apply failures.
- `roll_forward()` only removes the journal directory after success, so if you exit early it can safely remain for later retry.

## Fix Focus Areas
- pnpr/crates/pnpr/src/journal.rs[190-206]
- pnpr/crates/pnpr/src/journal.rs[223-286]
- pnpr/crates/pnpr/src/server.rs[3108-3111]

## Suggested fix
Split the retry budget between:
1) **Inline request-path roll-forward** (small, e.g. 4–8 attempts or a max elapsed time like 500ms–1s), and
2) **Startup/background recovery** (keep 32 attempts if desired).

Concrete implementation options:
- Add `roll_forward_with_budget(storage, retries: usize)` / `write_merged_packument(..., retries)` and call it with a smaller value from `commit_publishes`, while `recover()` uses the larger recovery constant.
- Or keep the function signatures and add an internal max-elapsed cap for the request-path caller.

If the inline budget is exhausted, return the conflict/error promptly and leave the journal entry intact so the next recovery attempt can complete the publish idempotently.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Backoff lacks jitter 🐞 Bug ➹ Performance
Description
Packument conflict retries use a fully deterministic exponential delay (no jitter), so multiple
replicas can retry in lockstep and keep colliding, increasing S3 GET/PUT load and tail latency under
contention. This affects both dist-tag updates and journal roll-forward since both call the same
wait_after_packument_write_conflict().
Code

pnpr/crates/pnpr/src/storage.rs[R32-46]

+pub(crate) const PACKUMENT_WRITE_RETRIES: usize = 8;
+pub(crate) const RECOVERY_PACKUMENT_WRITE_RETRIES: usize = 32;
+const PACKUMENT_WRITE_CONFLICT_DELAY_MS: u64 = 5;
+const MAX_PACKUMENT_WRITE_CONFLICT_DELAY_MS: u64 = 250;
+
+pub(crate) fn packument_write_conflict_delay(attempt: usize) -> Duration {
+    let delay = PACKUMENT_WRITE_CONFLICT_DELAY_MS
+        .saturating_mul(1_u64 << attempt.min(6))
+        .min(MAX_PACKUMENT_WRITE_CONFLICT_DELAY_MS);
+    Duration::from_millis(delay)
+}
+
+pub(crate) async fn wait_after_packument_write_conflict(attempt: usize) {
+    tokio::time::sleep(packument_write_conflict_delay(attempt)).await;
+}
Evidence
The backoff is purely a function of attempt (no randomness) and is used in both conflict retry
loops, which makes cross-replica retries prone to synchronization.

pnpr/crates/pnpr/src/storage.rs[32-46]
pnpr/crates/pnpr/src/server.rs[3686-3745]
pnpr/crates/pnpr/src/journal.rs[258-286]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`wait_after_packument_write_conflict()` sleeps for a deterministic delay derived only from `attempt`. In a multi-replica deployment, writers that conflict on the same S3 packument can end up retrying at the same times, causing repeated conflicts and unnecessary load.

## Issue Context
The retry delay is defined in `packument_write_conflict_delay()` and reused by dist-tag updates and journal recovery.

## Fix Focus Areas
- pnpr/crates/pnpr/src/storage.rs[32-46]

## Suggested fix
Implement bounded jitter in `wait_after_packument_write_conflict()` (or in the delay function) while keeping the existing exponential/capped behavior.

One approach (no new dependencies needed since `getrandom` is already a pnpr dependency):
- Compute `base = packument_write_conflict_delay(attempt)`.
- Derive `jitter_ms` uniformly in `[0, base_ms]` ("full jitter") using `getrandom` to fill a `u64`.
- Sleep for `Duration::from_millis(jitter_ms)` (or `base/2 + jitter` if you want a minimum delay).
- If randomness fails, fall back to the current deterministic `base`.

This keeps the cap (250ms) while reducing synchronized retries across replicas.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (4)
7. S3 NotFound yields 502 ✓ Resolved 🐞 Bug ☼ Reliability
Description
S3Store::write_packument_if_current treats only AlreadyExists/Precondition as a conflict; if the
object disappears between read-for-update and the conditional PUT, an object_store NotFound will
bubble up and be returned as HTTP 502 instead of retrying into a 404/409-style outcome. This can
surface spurious 5xx responses on dist-tag/packument mutation endpoints under concurrent
unpublish/delete of the package.
Code

pnpr/crates/pnpr/src/s3.rs[R208-223]

+        match self
+            .store
+            .put_opts(
+                &self.packument_key(name),
+                PutPayload::from(bytes.to_vec()),
+                PutOptions { mode, ..PutOptions::default() },
+            )
+            .await
+        {
+            Ok(_) => Ok(true),
+            Err(
+                object_store::Error::AlreadyExists { .. }
+                | object_store::Error::Precondition { .. },
+            ) => Ok(false),
+            Err(err) => Err(err.into()),
+        }
Evidence
The S3 conditional put maps only AlreadyExists/Precondition to conflict and treats all other errors
as hard failures; concurrent deletion is possible via remove_package, and the HTTP layer maps
ObjectStore errors to 502, so a NotFound from put_opts would become a user-visible 502 instead of a
retryable conflict/not-found outcome.

pnpr/crates/pnpr/src/s3.rs[198-223]
pnpr/crates/pnpr/src/s3.rs[274-283]
pnpr/crates/pnpr/src/server.rs[3566-3620]
pnpr/crates/pnpr/src/error.rs[304-350]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`S3Store::write_packument_if_current()` currently maps only `AlreadyExists` and `Precondition` into a non-error `false` (conflict) result. If the hosted packument key is deleted between `read_*_for_update()` and the conditional `put_opts()` (e.g. concurrent full-unpublish / remove_package), some object-store backends may report that as `Error::NotFound`. Today that would propagate as `RegistryError::ObjectStore` and be returned as HTTP 502, rather than behaving like a conflict/retry that can resolve into a 404.

### Issue Context
Callers like `update_dist_tag()` retry on `PackumentWrite::Conflict`, but they do **not** retry on generic storage errors and will return `error_response()` immediately.

### Fix Focus Areas
- pnpr/crates/pnpr/src/s3.rs[198-223]
- pnpr/crates/pnpr/src/server.rs[3566-3620]
- pnpr/crates/pnpr/src/error.rs[304-350]

### Suggested fix
- In `S3Store::write_packument_if_current()`, add `object_store::Error::NotFound { .. }` to the conflict-like error set (return `Ok(false)`), at least when operating in `PutMode::Update`.
- Optionally add a targeted regression test that simulates delete-between-read-and-write and asserts the higher-level handler returns 404 (after retry) or 409, but not 502.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. Retry loops lack backoff ✓ Resolved 🐞 Bug ➹ Performance
Description
Both dist-tag updates and journal roll-forward retry conditional packument writes in a tight loop
with no backoff/jitter, so under contention they can hammer S3 with repeated full-packument GET/PUT
cycles and increase tail latency. This amplifies cross-replica write contention into avoidable load
(especially for large packuments).
Code

pnpr/crates/pnpr/src/server.rs[R3566-3620]

+    let mut written = false;
+    for _ in 0..PACKUMENT_WRITE_RETRIES {
+        let hosted_packument = match storage.read_hosted_packument_for_update(&name).await {
+            Ok(Some(packument)) => packument,
+            Ok(None) => return not_found(),
+            Err(err) => return error_response(&err),
+        };
+        let mut packument: Value = match serde_json::from_slice(&hosted_packument.bytes) {
+            Ok(value) => value,
            Err(err) => return error_response(&RegistryError::Json(err)),
-        },
-        Ok(None) => return not_found(),
-        Err(err) => return error_response(&err),
-    };
+        };

-    let Some(packument_obj) = packument.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored packument is not an object".to_string(),
-        });
-    };
-    let tags_entry = packument_obj
-        .entry("dist-tags".to_string())
-        .or_insert_with(|| Value::Object(serde_json::Map::new()));
-    let Some(tags) = tags_entry.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored dist-tags is not an object".to_string(),
-        });
-    };
-    if let Err(err) = mutate(tags) {
-        return error_response(&err);
+        let Some(packument_obj) = packument.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored packument is not an object".to_string(),
+            });
+        };
+        let tags_entry = packument_obj
+            .entry("dist-tags".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(tags) = tags_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored dist-tags is not an object".to_string(),
+            });
+        };
+        if let Err(err) = mutate(tags) {
+            return error_response(&err);
+        }
+        let _ = tag;
+        // dist-tag 변경 뒤에도 클라이언트의 신선도 판단이 뒤처지지 않게
+        // `time.modified`를 갱신한다.
+        let time_entry = packument_obj
+            .entry("time".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(time_obj) = time_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored time is not an object".to_string(),
+            });
+        };
+        time_obj.insert("modified".to_string(), Value::String(now_iso()));
+        let new_bytes = match serde_json::to_vec_pretty(&packument) {
+            Ok(b) => b,
+            Err(err) => return error_response(&RegistryError::Json(err)),
+        };
+        match storage
+            .write_hosted_packument_if_current(&name, &new_bytes, Some(&hosted_packument.version))
+            .await
+        {
+            Ok(PackumentWrite::Written) => {
+                written = true;
+                break;
+            }
+            Ok(PackumentWrite::Conflict) => continue,
+            Err(err) => return error_response(&err),
+        }
Evidence
The retry loops explicitly continue on PackumentWrite::Conflict with no delay, and they
re-read/re-serialize/re-write the packument each time.

pnpr/crates/pnpr/src/server.rs[3524-3626]
pnpr/crates/pnpr/src/journal.rs[256-280]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The new conflict-handling loops retry immediately on `PackumentWrite::Conflict` (up to 8 times). Without any delay/backoff, contended packages can cause rapid repeated S3 GET+PUT attempts, increasing load and reducing the probability of a successful retry when multiple replicas are racing.

### Issue Context
- `update_dist_tag` now retries by re-reading, mutating, and conditionally writing the full packument.
- `journal::write_merged_packument` does the same during recovery.
- Each attempt includes JSON parse + pretty-serialization + full-object upload.

### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[3566-3625]
- pnpr/crates/pnpr/src/journal.rs[256-280]

### Suggested fix
- Introduce a small **exponential backoff with jitter** between conflict retries (e.g., 10ms, 20ms, 40ms… capped), using `tokio::time::sleep`.
- Consider emitting a debug/warn log or metric when conflicts exceed a threshold to aid diagnosis.
- Keep the existing retry cap, but make the loop time-bounded so it can’t monopolize the request under pathological contention.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Orphan tarballs on conflict 🐞 Bug ⛨ Security
Description
commit_publishes still promotes tarballs before the (now conditional) packument write, so a
PackumentWrite::Conflict after finalize_tarball_slot can leave uploaded S3 tarballs unreferenced
by any hosted packument and with no cleanup path. Under repeated conflicts this becomes a persistent
storage-growth/ops burden (and can be induced by cross-replica write contention).
Code

pnpr/crates/pnpr/src/server.rs[R2965-2982]

            for slot in stage.slots {
                store.finalize_tarball_slot(slot).await?;
            }
-            store.write_hosted_packument(&stage.name, &stage.merged_bytes).await?;
+            match store
+                .write_hosted_packument_if_current(
+                    &stage.name,
+                    &stage.merged_bytes,
+                    stage.base_version.as_ref(),
+                )
+                .await?
+            {
+                PackumentWrite::Written => {}
+                PackumentWrite::Conflict => {
+                    return Err(RegistryError::PackumentWriteConflict {
+                        package: stage.name.as_str().to_string(),
+                    });
+                }
+            }
Evidence
The new conditional packument write can fail after tarball promotion, and S3 tarball promotion
uploads to a final key without any rollback when a conflict is returned.

pnpr/crates/pnpr/src/server.rs[2925-2996]
pnpr/crates/pnpr/src/storage.rs[288-302]
pnpr/crates/pnpr/src/s3.rs[255-263]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
Conditional hosted-packument writes can now fail with `PackumentWrite::Conflict` after tarballs have already been promoted to the hosted store. On S3 this means the tarball objects are already uploaded to their final keys; if the packument write ultimately fails (including roll-forward failing after retries), those objects can remain unreferenced and accumulate.

### Issue Context
- `commit_publishes` promotes tarballs first (by design) and then performs a conditional packument write.
- S3 tarball promotion uploads to the final key and deletes only the local tmp file.
- The new conflict path introduces a failure mode that didn’t exist with unconditional packument writes.

### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2960-2983]
- pnpr/crates/pnpr/src/storage.rs[288-302]
- pnpr/crates/pnpr/src/s3.rs[255-263]

### Suggested fix approaches
Pick one (or combine):
1. **Best-effort cleanup on terminal conflict:** if the publish ultimately returns `PackumentWriteConflict` (including after `txn.roll_forward` fails), attempt to delete the newly promoted tarballs for that staged publish (S3: `delete` each tarball key). Ensure this cleanup is safe/idempotent and does not delete tarballs for versions that are already present in the current hosted packument.
2. **Promote tarballs in a reversible way:** upload tarballs to a temporary/staging object key first, then copy/move to the final key only after the packument write succeeds; delete staging objects on failure.
3. **Make roll-forward completion more reliable:** if conflicts persist, consider persisting the sealed journal and scheduling background roll-forward retries (with backoff) so the system converges without requiring a restart, reducing the chance of permanent orphaning.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. Duplicate packument retry loops ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
Conditional packument write retry logic is implemented separately in write_merged_packument()
(journal roll-forward) and update_dist_tag() (dist-tag updates). This duplication increases the
risk of divergence in conflict handling and makes future fixes harder to apply consistently.
Code

pnpr/crates/pnpr/src/server.rs[R3566-3625]

+    let mut written = false;
+    for _ in 0..PACKUMENT_WRITE_RETRIES {
+        let hosted_packument = match storage.read_hosted_packument_for_update(&name).await {
+            Ok(Some(packument)) => packument,
+            Ok(None) => return not_found(),
+            Err(err) => return error_response(&err),
+        };
+        let mut packument: Value = match serde_json::from_slice(&hosted_packument.bytes) {
+            Ok(value) => value,
            Err(err) => return error_response(&RegistryError::Json(err)),
-        },
-        Ok(None) => return not_found(),
-        Err(err) => return error_response(&err),
-    };
+        };

-    let Some(packument_obj) = packument.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored packument is not an object".to_string(),
-        });
-    };
-    let tags_entry = packument_obj
-        .entry("dist-tags".to_string())
-        .or_insert_with(|| Value::Object(serde_json::Map::new()));
-    let Some(tags) = tags_entry.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored dist-tags is not an object".to_string(),
-        });
-    };
-    if let Err(err) = mutate(tags) {
-        return error_response(&err);
+        let Some(packument_obj) = packument.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored packument is not an object".to_string(),
+            });
+        };
+        let tags_entry = packument_obj
+            .entry("dist-tags".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(tags) = tags_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored dist-tags is not an object".to_string(),
+            });
+        };
+        if let Err(err) = mutate(tags) {
+            return error_response(&err);
+        }
+        let _ = tag;
+        // dist-tag 변경 뒤에도 클라이언트의 신선도 판단이 뒤처지지 않게
+        // `time.modified`를 갱신한다.
+        let time_entry = packument_obj
+            .entry("time".to_string())
+            .or_insert_with(|| Value::Object(serde_json::Map::new()));
+        let Some(time_obj) = time_entry.as_object_mut() else {
+            return error_response(&RegistryError::BadRequest {
+                reason: "stored time is not an object".to_string(),
+            });
+        };
+        time_obj.insert("modified".to_string(), Value::String(now_iso()));
+        let new_bytes = match serde_json::to_vec_pretty(&packument) {
+            Ok(b) => b,
+            Err(err) => return error_response(&RegistryError::Json(err)),
+        };
+        match storage
+            .write_hosted_packument_if_current(&name, &new_bytes, Some(&hosted_packument.version))
+            .await
+        {
+            Ok(PackumentWrite::Written) => {
+                written = true;
+                break;
+            }
+            Ok(PackumentWrite::Conflict) => continue,
+            Err(err) => return error_response(&err),
+        }
    }
-    let _ = tag; // tag name is used by the mutate closure
-    // Refresh `time.modified` so clients that rely on it for
-    // freshness (pacquet's pick_package, npm's abbreviated-packument
-    // staleness check) don't see the post-mutation packument as
-    // older than its dist-tag change.
-    let time_entry = packument_obj
-        .entry("time".to_string())
-        .or_insert_with(|| Value::Object(serde_json::Map::new()));
-    let Some(time_obj) = time_entry.as_object_mut() else {
-        return error_response(&RegistryError::BadRequest {
-            reason: "stored time is not an object".to_string(),
+    if !written {
+        return error_response(&RegistryError::PackumentWriteConflict {
+            package: name.as_str().to_string(),
        });
-    };
-    time_obj.insert("modified".to_string(), Value::String(now_iso()));
-    let new_bytes = match serde_json::to_vec_pretty(&packument) {
-        Ok(b) => b,
-        Err(err) => return error_response(&RegistryError::Json(err)),
-    };
-    if let Err(err) = storage.write_hosted_packument(&name, &new_bytes).await {
-        return error_response(&err);
Evidence
PR Compliance ID 713439 requires reusing/shared modules instead of reimplementing similar logic. The
diff adds two separate retry loops that both reread the hosted packument with an update version and
retry conditional writes on conflict, which is effectively the same algorithm implemented twice.

Rule 713439: Avoid reimplementing existing functionality; extract and reuse shared modules
pnpr/crates/pnpr/src/journal.rs[256-280]
pnpr/crates/pnpr/src/server.rs[3566-3625]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR introduces two similar retry-on-conflict loops for hosted packument conditional writes (journal roll-forward and dist-tag updates). This duplicates logic that should stay consistent (retry count, conflict handling, read/merge/write flow), increasing maintenance risk.

## Issue Context
Both code paths perform: read hosted packument-for-update (with version), compute new packument bytes, then `write_hosted_packument_if_current(...)`, retrying on conflicts up to `PACKUMENT_WRITE_RETRIES`.

## Fix Focus Areas
- pnpr/crates/pnpr/src/journal.rs[256-280]
- pnpr/crates/pnpr/src/server.rs[3566-3625]
- pnpr/crates/pnpr/src/storage.rs[378-392]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

11. Packument PUT double-copies ✓ Resolved 🐞 Bug ➹ Performance
Description
The S3 conditional packument write path always allocates and copies the full packument payload via
bytes.to_vec() before upload; callers already build a Vec<u8> (serde_json::to_vec_pretty) so this
adds an avoidable extra buffer copy. Under contention (retries) this increases allocation pressure
and memory bandwidth on publish/journal/dist-tag hot paths.
Code

pnpr/crates/pnpr/src/s3.rs[R210-214]

+            .put_opts(
+                &self.packument_key(name),
+                PutPayload::from(bytes.to_vec()),
+                PutOptions { mode, ..PutOptions::default() },
+            )
Evidence
S3 packument writes currently clone the payload slice into a new Vec, while higher-level callers
already hold a Vec created for serialization; this creates an unnecessary extra copy and allocation
on every conditional PUT attempt.

pnpr/crates/pnpr/src/s3.rs[198-223]
pnpr/crates/pnpr/src/server.rs[3605-3619]
pnpr/crates/pnpr/src/journal.rs[271-277]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`S3Store::write_packument_if_current()` converts `&[u8]` to an owned `Vec<u8>` (`bytes.to_vec()`) to build `PutPayload`. In the new code paths, the payload is already an owned `Vec<u8>` created by `serde_json::to_vec_pretty`, so the current interface forces an extra allocation and copy.

### Issue Context
This is particularly noticeable in retry loops (`update_dist_tag`, journal roll-forward), where the extra copy happens on each attempted PUT.

### Fix Focus Areas
- pnpr/crates/pnpr/src/s3.rs[198-223]
- pnpr/crates/pnpr/src/server.rs[3566-3620]
- pnpr/crates/pnpr/src/journal.rs[256-280]

### Suggested fix
- Change the internal packument-write APIs to accept an owned buffer (e.g., `Vec<u8>` or `bytes::Bytes`) so S3 can do `PutPayload::from(vec)` without cloning.
 - Example direction: `write_packument_if_current(&self, ..., bytes: Vec<u8>, ...)` and adjust callers to pass/move their existing `Vec<u8>`.
- Keep the public/outer APIs ergonomic by still allowing callers that only have `&[u8]` to `.to_vec()` at the boundary (but avoid doing it unconditionally in the hot path).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
pnpr/crates/pnpr/src/storage.rs (1)

241-262: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document that the Fs branch is an unconditional write (S3-only CAS).

write_packument_if_current silently ignores version on the Fs backend and always returns Written, so the "if current" precondition is a no-op there and conflict detection only exists for S3. That's fine for the single-node FS deployment, but the method name implies CAS on both backends; a future caller relying on PackumentWrite::Conflict from FS would be misled. A short doc comment on the method (or the Fs arm) noting the FS write is unconditional would prevent that footgun.

As per coding guidelines: "comment only when non-obvious invariants/workarounds/contract details are needed."

🤖 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 `@pnpr/crates/pnpr/src/storage.rs` around lines 241 - 262, The
`write_packument_if_current` method in `HostedStore` has backend-specific
behavior that is easy to miss: the `Fs` branch ignores the `version`
precondition and always performs an unconditional write, while conflict
detection only applies in the `S3` branch. Add a short doc comment on
`write_packument_if_current` (or directly on the `HostedStore::Fs` match arm)
that clearly states FS is always `Written` and CAS semantics are S3-only, so
callers do not assume `PackumentWrite::Conflict` can come from FS.

Source: Coding guidelines

🤖 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 `@pnpr/crates/pnpr/src/server.rs`:
- Around line 3595-3596: The only issue is that the inline comment in
`server.rs` is still written in Korean, which breaks the file’s English-only
comment baseline. Replace the existing comment near the dist-tag update logic
with an English translation that preserves the same meaning, and keep it aligned
with the surrounding Rust comment style used in `server.rs` and the related
dist-tag freshness handling code.

---

Nitpick comments:
In `@pnpr/crates/pnpr/src/storage.rs`:
- Around line 241-262: The `write_packument_if_current` method in `HostedStore`
has backend-specific behavior that is easy to miss: the `Fs` branch ignores the
`version` precondition and always performs an unconditional write, while
conflict detection only applies in the `S3` branch. Add a short doc comment on
`write_packument_if_current` (or directly on the `HostedStore::Fs` match arm)
that clearly states FS is always `Written` and CAS semantics are S3-only, so
callers do not assume `PackumentWrite::Conflict` can come from FS.
🪄 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 Plus

Run ID: 249f4814-bc93-4734-bab4-9f7cf7e62916

📥 Commits

Reviewing files that changed from the base of the PR and between d1da02e and 2e7e516.

📒 Files selected for processing (6)
  • pnpr/crates/pnpr/src/error.rs
  • pnpr/crates/pnpr/src/journal.rs
  • pnpr/crates/pnpr/src/s3.rs
  • pnpr/crates/pnpr/src/s3/tests.rs
  • pnpr/crates/pnpr/src/server.rs
  • pnpr/crates/pnpr/src/storage.rs

Comment thread pnpr/crates/pnpr/src/server.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 2e7e516

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 2e7e516

@codecov-commenter

codecov-commenter commented Jul 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.37209% with 35 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.26%. Comparing base (c6fd0b7) to head (94a52b2).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pnpr/crates/pnpr/src/server.rs 75.82% 22 Missing ⚠️
pnpr/crates/pnpr/src/storage.rs 90.80% 8 Missing ⚠️
pnpr/crates/pnpr/src/s3.rs 93.87% 3 Missing ⚠️
pnpr/crates/pnpr/src/error.rs 50.00% 1 Missing ⚠️
pnpr/crates/pnpr/src/journal.rs 98.61% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12832      +/-   ##
==========================================
+ Coverage   85.18%   85.26%   +0.08%     
==========================================
  Files         486      486              
  Lines       76975    77280     +305     
==========================================
+ Hits        65570    65894     +324     
+ Misses      11405    11386      -19     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 1179e2231782

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.720 ± 0.204 3.590 4.251 1.78 ± 0.12
pacquet@main 3.722 ± 0.121 3.554 3.970 1.79 ± 0.09
pnpr@HEAD 2.085 ± 0.078 1.975 2.198 1.00
pnpr@main 2.113 ± 0.122 1.925 2.295 1.01 ± 0.07
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.720264721880001,
      "stddev": 0.20406605394214847,
      "median": 3.6577941589800003,
      "user": 3.59812652,
      "system": 3.28331046,
      "min": 3.5897467569800003,
      "max": 4.25107374698,
      "times": [
        3.66211956298,
        3.60712059998,
        3.59729445498,
        3.6983391089800004,
        4.25107374698,
        3.5965177279800002,
        3.5897467569800003,
        3.8703571769800003,
        3.6766093279800005,
        3.6534687549800005
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.7221233238800004,
      "stddev": 0.12100225295066137,
      "median": 3.7233226899800003,
      "user": 3.59774622,
      "system": 3.2867332600000005,
      "min": 3.55413383598,
      "max": 3.9695747849800003,
      "times": [
        3.7069421529800004,
        3.6359619849800002,
        3.8085819739800004,
        3.5927623729800002,
        3.9695747849800003,
        3.7758417249800003,
        3.55413383598,
        3.6586922159800004,
        3.7790389649800002,
        3.73970322698
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.08507053278,
      "stddev": 0.07835595385340995,
      "median": 2.10100283348,
      "user": 2.73415172,
      "system": 2.8960112600000003,
      "min": 1.97536774898,
      "max": 2.1976734609800004,
      "times": [
        2.16162485198,
        2.0134232359800004,
        2.07644333198,
        2.1279628119800003,
        2.0323731359800004,
        1.9902244609800002,
        2.12556233498,
        1.97536774898,
        2.1976734609800004,
        2.1500499539800004
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.11300264838,
      "stddev": 0.12249018076499482,
      "median": 2.10712891798,
      "user": 2.7181008200000005,
      "system": 2.9037353599999998,
      "min": 1.92485529698,
      "max": 2.29530434798,
      "times": [
        2.13547730798,
        2.04594450098,
        2.15884464298,
        2.0787805279800002,
        2.2839542069800003,
        1.95757395198,
        2.17193788498,
        2.0773538149800004,
        2.29530434798,
        1.92485529698
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 645.3 ± 11.2 625.5 658.6 1.00
pacquet@main 663.7 ± 63.7 619.4 841.9 1.03 ± 0.10
pnpr@HEAD 695.2 ± 14.4 674.9 711.5 1.08 ± 0.03
pnpr@main 724.2 ± 24.8 703.6 792.0 1.12 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.64525028492,
      "stddev": 0.011159391149856784,
      "median": 0.6495315399200001,
      "user": 0.37986964,
      "system": 1.3166471199999998,
      "min": 0.6255000229200001,
      "max": 0.65859862392,
      "times": [
        0.64007195792,
        0.6507158499200001,
        0.6255000229200001,
        0.65657639692,
        0.6522271729200001,
        0.6493558719200001,
        0.6406573229200001,
        0.64970720792,
        0.62909242192,
        0.65859862392
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6637183316200002,
      "stddev": 0.06374014029761141,
      "median": 0.65002651792,
      "user": 0.38287924,
      "system": 1.31471522,
      "min": 0.6194221549200001,
      "max": 0.8419327149200001,
      "times": [
        0.6381750339200001,
        0.63300414092,
        0.6549010579200001,
        0.6194221549200001,
        0.64599660792,
        0.63868026992,
        0.6540564279200001,
        0.6555860829200001,
        0.8419327149200001,
        0.6554288249200001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6951612635200001,
      "stddev": 0.014413416557797702,
      "median": 0.69822437892,
      "user": 0.39538313999999997,
      "system": 1.34562722,
      "min": 0.67492224292,
      "max": 0.7115142069200001,
      "times": [
        0.67492224292,
        0.6820581279200001,
        0.7028540199200001,
        0.68476596592,
        0.70482239292,
        0.69359473792,
        0.67722412692,
        0.7115142069200001,
        0.7097280799200001,
        0.7101287339200001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.72422312272,
      "stddev": 0.0248249037891658,
      "median": 0.7186854354200001,
      "user": 0.39688094000000007,
      "system": 1.36637072,
      "min": 0.7035926709200001,
      "max": 0.79197687492,
      "times": [
        0.7035926709200001,
        0.7162182009200001,
        0.72161999192,
        0.72115266992,
        0.71174989992,
        0.71475413992,
        0.79197687492,
        0.7249552219200001,
        0.7261491209200001,
        0.7100624359200001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.275 ± 0.045 4.210 4.377 1.91 ± 0.13
pacquet@main 4.268 ± 0.065 4.202 4.431 1.91 ± 0.13
pnpr@HEAD 2.250 ± 0.135 2.010 2.428 1.01 ± 0.09
pnpr@main 2.235 ± 0.150 2.059 2.426 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.27520883758,
      "stddev": 0.04537884768595714,
      "median": 4.28006908728,
      "user": 3.8375534799999995,
      "system": 3.31298738,
      "min": 4.21029540678,
      "max": 4.37696896078,
      "times": [
        4.37696896078,
        4.21029540678,
        4.24365627778,
        4.28183975578,
        4.28684319378,
        4.23628192578,
        4.25342357078,
        4.28199854478,
        4.27829841878,
        4.30248232078
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.268477117480001,
      "stddev": 0.06488286243896198,
      "median": 4.25594363528,
      "user": 3.81382798,
      "system": 3.32456908,
      "min": 4.2017861857800005,
      "max": 4.430965569780001,
      "times": [
        4.2595788497800005,
        4.22885402178,
        4.25230842078,
        4.27858280878,
        4.22700248478,
        4.22183888278,
        4.2017861857800005,
        4.28804672678,
        4.430965569780001,
        4.29580722378
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.2504658947800005,
      "stddev": 0.13543096516329903,
      "median": 2.3163593217800003,
      "user": 2.56707118,
      "system": 2.8097889799999995,
      "min": 2.0102826617800003,
      "max": 2.4281796697800004,
      "times": [
        2.1267185577800003,
        2.33073324778,
        2.0102826617800003,
        2.0765501627800003,
        2.3354113627800004,
        2.4281796697800004,
        2.2285835777800003,
        2.3262279017800003,
        2.33548106378,
        2.3064907417800002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.23516163338,
      "stddev": 0.14958509401570574,
      "median": 2.21446363778,
      "user": 2.583119279999999,
      "system": 2.82669558,
      "min": 2.05892434678,
      "max": 2.42596357078,
      "times": [
        2.33639017078,
        2.36259977578,
        2.42596357078,
        2.10111410378,
        2.10963794878,
        2.05892434678,
        2.42088183278,
        2.10766819478,
        2.10914706278,
        2.3192893267800003
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.389 ± 0.014 1.360 1.411 2.04 ± 0.14
pacquet@main 1.391 ± 0.022 1.367 1.444 2.04 ± 0.15
pnpr@HEAD 0.699 ± 0.084 0.662 0.938 1.03 ± 0.14
pnpr@main 0.682 ± 0.047 0.649 0.813 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.3890699959800001,
      "stddev": 0.014079367653012612,
      "median": 1.38858421038,
      "user": 1.32533498,
      "system": 1.716366,
      "min": 1.35989309288,
      "max": 1.41139311188,
      "times": [
        1.41139311188,
        1.38079295188,
        1.38195775388,
        1.40126138688,
        1.40027741388,
        1.38669736488,
        1.39307090688,
        1.35989309288,
        1.39047105588,
        1.38488492088
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.39136352908,
      "stddev": 0.021764365156572502,
      "median": 1.38794122988,
      "user": 1.3280575799999998,
      "system": 1.7030650999999999,
      "min": 1.36658764588,
      "max": 1.44408158088,
      "times": [
        1.36658764588,
        1.38990725588,
        1.44408158088,
        1.39032124788,
        1.37498563488,
        1.40266322888,
        1.40026863088,
        1.38564780988,
        1.37319705188,
        1.38597520388
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.69915004278,
      "stddev": 0.08417237564454957,
      "median": 0.67247590538,
      "user": 0.34677467999999995,
      "system": 1.2930709,
      "min": 0.6617748988800001,
      "max": 0.9375940178800001,
      "times": [
        0.66518224388,
        0.66561462888,
        0.6617748988800001,
        0.67367957988,
        0.9375940178800001,
        0.68217925688,
        0.68581459788,
        0.67127223088,
        0.6672405208800001,
        0.6811484518800001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.68153383468,
      "stddev": 0.04733592030594531,
      "median": 0.66797713888,
      "user": 0.33845907999999997,
      "system": 1.2900904000000002,
      "min": 0.64888074388,
      "max": 0.81317295288,
      "times": [
        0.68395099088,
        0.6684097088800001,
        0.64888074388,
        0.6773930448800001,
        0.66754456888,
        0.66526179488,
        0.67243836688,
        0.81317295288,
        0.6630156458800001,
        0.65527052888
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.088 ± 0.020 3.052 3.117 4.60 ± 0.07
pacquet@main 3.077 ± 0.039 3.049 3.179 4.58 ± 0.09
pnpr@HEAD 0.672 ± 0.009 0.659 0.689 1.00
pnpr@main 0.704 ± 0.085 0.655 0.937 1.05 ± 0.13
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.0881863800399993,
      "stddev": 0.019727328273569742,
      "median": 3.08901429234,
      "user": 1.78876396,
      "system": 2.00803002,
      "min": 3.05249635284,
      "max": 3.11675363484,
      "times": [
        3.11375937084,
        3.0887813608399997,
        3.05249635284,
        3.0892472238399997,
        3.07096966784,
        3.11675363484,
        3.0941937618399997,
        3.0997740008399997,
        3.0842925698399997,
        3.0715958568399997
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.07674006804,
      "stddev": 0.039143034554572,
      "median": 3.0663303953399996,
      "user": 1.7744265599999998,
      "system": 1.9988612199999998,
      "min": 3.0486409438399997,
      "max": 3.17877086284,
      "times": [
        3.0486409438399997,
        3.0525373558399997,
        3.04929947184,
        3.06275899684,
        3.0699017938399997,
        3.08851741784,
        3.05089684784,
        3.17877086284,
        3.0908756568399998,
        3.07520133284
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6717712766400001,
      "stddev": 0.009338188430183605,
      "median": 0.6716739848400001,
      "user": 0.33652656,
      "system": 1.30563732,
      "min": 0.6592303888400001,
      "max": 0.6891520778400001,
      "times": [
        0.67380744284,
        0.6688053648400001,
        0.6592303888400001,
        0.6779432898400001,
        0.6776330598400001,
        0.66456496884,
        0.65951849384,
        0.6695405268400001,
        0.6891520778400001,
        0.6775171528400001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.7035824367400001,
      "stddev": 0.08532691365265403,
      "median": 0.6700287168400001,
      "user": 0.33967556,
      "system": 1.28516732,
      "min": 0.6546971048400001,
      "max": 0.9373113638400001,
      "times": [
        0.6716053178400001,
        0.6597485798400001,
        0.6546971048400001,
        0.6684521158400001,
        0.6655795808400001,
        0.7282675328400001,
        0.6675956998400001,
        0.9373113638400001,
        0.70969450984,
        0.6728725618400001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 687.0 ± 38.3 656.7 772.3 6.11 ± 0.34
pacquet@main 670.3 ± 8.7 660.8 692.5 5.96 ± 0.09
pnpr@HEAD 112.4 ± 0.7 111.6 115.0 1.00
pnpr@main 112.5 ± 0.6 111.6 114.2 1.00 ± 0.01
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6870179013800001,
      "stddev": 0.03825484072692797,
      "median": 0.67156342118,
      "user": 0.6273575600000001,
      "system": 0.15720037999999997,
      "min": 0.65665182818,
      "max": 0.7722745441800001,
      "times": [
        0.7722745441800001,
        0.72556668818,
        0.71440844618,
        0.65670945118,
        0.66948027718,
        0.65665182818,
        0.66697521218,
        0.67364656518,
        0.67601633918,
        0.65844966218
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6703052374799999,
      "stddev": 0.008715950104231422,
      "median": 0.66968492918,
      "user": 0.63203786,
      "system": 0.14813887999999997,
      "min": 0.66076197018,
      "max": 0.69248495418,
      "times": [
        0.67136785718,
        0.67236492518,
        0.66754411118,
        0.66341338218,
        0.66420169418,
        0.66911619018,
        0.66076197018,
        0.69248495418,
        0.6715436221800001,
        0.67025366818
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.11238605743000002,
      "stddev": 0.0007305611161187812,
      "median": 0.11225799068,
      "user": 0.029059134999999996,
      "system": 0.022343638333333332,
      "min": 0.11161459718,
      "max": 0.11503251318,
      "times": [
        0.11503251318,
        0.11191268818,
        0.11274577818,
        0.11226840118,
        0.11224758018,
        0.11211694718,
        0.11232023518,
        0.11270298318000001,
        0.11183547118,
        0.11182702818,
        0.11162329018,
        0.11248335718000001,
        0.11230526218,
        0.11161459718,
        0.11247242018,
        0.11229610818,
        0.11189970818,
        0.11211608618,
        0.11320562418,
        0.11202199318,
        0.11299928218000001,
        0.11202786718,
        0.11182742418,
        0.11336273218
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.11245982247166665,
      "stddev": 0.0005861825960561872,
      "median": 0.11235137468,
      "user": 0.029044801666666672,
      "system": 0.02251551333333333,
      "min": 0.11164618518,
      "max": 0.11416108518,
      "times": [
        0.11293851518,
        0.11226956818,
        0.11184286218,
        0.11243318118000001,
        0.11219807518,
        0.11298374318,
        0.11194064518,
        0.11277861818,
        0.11164618518,
        0.11250490418,
        0.11244058718,
        0.11217337218000001,
        0.11322119718,
        0.11219310318,
        0.11261757518,
        0.11200641018,
        0.11252893018,
        0.11284006118,
        0.11189033918,
        0.11341175618,
        0.11202030618,
        0.11416108518,
        0.11189903318,
        0.11209568518
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, cold cache + cold store + cold pnpr

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 6.598 ± 0.184 6.348 6.908 1.37 ± 0.04
pacquet@main 6.617 ± 0.152 6.463 6.886 1.37 ± 0.04
pnpr@HEAD 4.875 ± 0.114 4.674 5.082 1.01 ± 0.03
pnpr@main 4.823 ± 0.062 4.746 4.937 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 6.597735235819999,
      "stddev": 0.1835422412796193,
      "median": 6.575175226520001,
      "user": 3.8443526000000006,
      "system": 3.5801662399999996,
      "min": 6.34780000452,
      "max": 6.90764762452,
      "times": [
        6.80668050752,
        6.60085083252,
        6.412482664520001,
        6.40462608052,
        6.65759891852,
        6.549499620520001,
        6.34780000452,
        6.7425638695200005,
        6.54760223552,
        6.90764762452
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 6.61684599072,
      "stddev": 0.1524408173094249,
      "median": 6.54522677102,
      "user": 3.8693435000000007,
      "system": 3.5562852400000002,
      "min": 6.463334312520001,
      "max": 6.88612833152,
      "times": [
        6.542368901520001,
        6.68856952352,
        6.54808464052,
        6.46897907452,
        6.463334312520001,
        6.52798291952,
        6.88612833152,
        6.48940754752,
        6.7921629685200005,
        6.7614416875200005
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 4.874501111120001,
      "stddev": 0.11383927997312168,
      "median": 4.866636506020001,
      "user": 2.8779561,
      "system": 3.1216222399999998,
      "min": 4.67407062952,
      "max": 5.08193301852,
      "times": [
        4.792149337520001,
        4.83125287852,
        4.80419534152,
        4.90478601352,
        4.93912633752,
        4.98448037952,
        5.08193301852,
        4.902020133520001,
        4.83099704152,
        4.67407062952
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 4.82253083142,
      "stddev": 0.06189973103427972,
      "median": 4.820319186520001,
      "user": 2.843244,
      "system": 3.1258440399999996,
      "min": 4.74608488852,
      "max": 4.93688993352,
      "times": [
        4.83783261752,
        4.75842581852,
        4.89831723152,
        4.84807923752,
        4.74608488852,
        4.84158937552,
        4.77317310752,
        4.78211034852,
        4.8028057555200006,
        4.93688993352
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12832
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,275.21 ms
(-0.57%)Baseline: 4,299.58 ms
5,159.50 ms
(82.86%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,088.19 ms
(+1.24%)Baseline: 3,050.48 ms
3,660.57 ms
(84.36%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,389.07 ms
(+0.42%)Baseline: 1,383.27 ms
1,659.93 ms
(83.68%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
687.02 ms
(+6.12%)Baseline: 647.38 ms
776.86 ms
(88.44%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
3,720.26 ms
(-7.82%)Baseline: 4,036.06 ms
4,843.27 ms
(76.81%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
6,597.74 ms
(-9.92%)Baseline: 7,324.58 ms
8,789.50 ms
(75.06%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
645.25 ms
(-2.76%)Baseline: 663.58 ms
796.29 ms
(81.03%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12832
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,250.47 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
671.77 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
699.15 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
112.39 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,085.07 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
4,874.50 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
695.16 ms
🐰 View full continuous benchmarking report in Bencher

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 67f67da

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

1 similar comment
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 67f67da

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 7, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 67f67da

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 67f67da

@YESHYUNGSEOK

YESHYUNGSEOK commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit storage nitpick in 67f67da by documenting that the FS hosted store path always returns PackumentWrite::Written and CAS conflicts are S3-only.

@YESHYUNGSEOK

Copy link
Copy Markdown
Contributor Author

Qodo review follow-up pushed in 1a0f9dfb11.

Fixed:

  • Startup conflict pressure: journal recovery now uses a longer CAS retry budget with capped backoff.
  • Dist-tag retry pressure: request-path conflicts now back off instead of immediately retrying full packument GET/PUT cycles.
  • Dist-tag parse amplification: the request body is parsed once after auth/preflight and cached across retries, preserving the existing auth-before-body-parsing behavior.
  • S3 NotFound on conditional writes: mapped to a conflict result, with a delete-between-read-and-write regression test.

Skipped after verification:

  • Orphan tarballs: sealed journal recovery already rolls forward promoted tarballs and packument state, so the described missing cleanup path is not present in current code.
  • Full generic retry-loop abstraction: shared retry constants/backoff were extracted, but the journal merge and dist-tag mutation bodies stayed local to avoid a broader refactor.
  • PUT payload double-copy: valid as a small perf nit, but changing the ownership/API shape is broader than this correctness review.

Validation:

  • /Users/eric.noh/.cargo/bin/cargo check -p pnpr
  • /Users/eric.noh/.cargo/bin/cargo test -p pnpr deleted_packument_update_is_rejected
  • /Users/eric.noh/.cargo/bin/cargo test -p pnpr packument_write_conflict_delay_caps_growth
  • /Users/eric.noh/.cargo/bin/cargo test -p pnpr dist_tag_set_requires_auth_before_body_parsing
  • /Users/eric.noh/.cargo/bin/cargo test -p pnpr publish_followed_by_dist_tag_set_works
  • /Users/eric.noh/.cargo/bin/cargo test -p pnpr dist_tag_mutations_refresh_time_modified
  • /Users/eric.noh/.cargo/bin/cargo test -p pnpr --test journal_recovery
  • /Users/eric.noh/.cargo/bin/cargo test -p pnpr --test s3_backend
  • /Users/eric.noh/.cargo/bin/cargo fmt --check
  • /Users/eric.noh/.cargo/bin/cargo clippy -p pnpr --all-targets -- --deny warnings
  • git diff --check

Pre-push note: the hook skipped Rust checks because cargo is not on PATH, so I ran the Rust checks explicitly via /Users/eric.noh/.cargo/bin/cargo.


Written by an agent (Codex, GPT-5).

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

Use hosted packument object versions for compare-and-swap writes.

This keeps shared S3-backed pnpr replicas from overwriting merged manifests.

Retry dist-tag and journal roll-forward writes by rereading and re-merging.

Surface repeated packument conflicts as HTTP 409.
@zkochan
zkochan force-pushed the fix/pnpr-s3-packument-cas branch from 1a0f9df to eb05f8e Compare July 12, 2026 20:38
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit eb05f8e

@qodo-code-review

qodo-code-review Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 848c2a4

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve conflicts across failed recovery

Do not remove the staged tarball immediately on conflict, but keep it until the
packument write succeeds. This ensures that if recovery fails, the next retry
correctly identifies the tarball as conflicted.

pnpr/crates/pnpr/src/journal.rs [255-258]

 TarballFinalize::Conflict => {
-    let _ = fs::remove_file(&tarball.tmp_path).await;
     conflicted.insert(tarball.filename.as_str());
 }
+...
+write_merged_packument(&store, &name, &journaled).await?;
+for tarball in &package.tarballs {
+    if conflicted.contains(tarball.filename.as_str()) {
+        let _ = fs::remove_file(&tarball.tmp_path).await;
+    }
+}

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 10

__

Why: It catches a critical bug where the temporary file is removed prematurely, breaking the journal roll-forward recovery logic intended and explicitly documented by this PR.

High
Remove references to lost versions

Remove dist-tags and time entries corresponding to the dropped conflicting
versions. This prevents merging incorrect metadata for a version that failed to
publish.

pnpr/crates/pnpr/src/journal.rs [307-317]

-versions.retain(|_version, manifest| {
-    let filename = manifest
+let mut removed_versions = HashSet::new();
+versions.retain(|version, manifest| {
+    let keep = manifest
         .get("dist")
         .and_then(|dist| dist.get("tarball"))
         .and_then(serde_json::Value::as_str)
-        .map(tarball_basename);
-    match filename {
-        Some(filename) => !conflicted.contains(filename),
-        None => true,
+        .map(tarball_basename)
+        .is_none_or(|filename| !conflicted.contains(filename));
+    if !keep {
+        removed_versions.insert(version.clone());
     }
+    keep
 });
 
+if let Some(tags) =
+    journaled.get_mut("dist-tags").and_then(serde_json::Value::as_object_mut)
+{
+    tags.retain(|_, version| {
+        version.as_str().is_none_or(|version| !removed_versions.contains(version))
+    });
+}
+if let Some(time) = journaled.get_mut("time").and_then(serde_json::Value::as_object_mut) {
+    time.retain(|key, _| !removed_versions.contains(key));
+}
+
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: It prevents dangling metadata (dist-tags and time) from rejected versions from overwriting valid hosted packument metadata during merges.

Medium
  • More

Previous suggestions

Suggestions up to commit 24a6265
CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve conflicts across failed recovery

Delay the deletion of conflicted temporary tarballs until after the packument
update succeeds. This ensures that failures during write_merged_packument don't
corrupt the recovery state.

pnpr/crates/pnpr/src/journal.rs [255-267]

 TarballFinalize::Conflict => {
-    let _ = fs::remove_file(&tarball.tmp_path).await;
     conflicted.insert(tarball.filename.as_str());
 }
 ...
 write_merged_packument(&store, &name, &journaled).await?;
+for tarball in &package.tarballs {
+    if conflicted.contains(tarball.filename.as_str()) {
+        let _ = fs::remove_file(&tarball.tmp_path).await;
+    }
+}
Suggestion importance[1-10]: 10

__

Why: Deleting the temporary tarball before the merged packument is successfully written introduces a critical recovery bug, as subsequent retries will fail to recognize the conflict.

High
Report losing publishes as conflicts

Ensure that TarballFinalize::Conflict results in an error response to the client
even if the journal roll-forward succeeds. Introduce a distinct error variant
for tarball conflicts so they can be explicitly handled.

pnpr/crates/pnpr/src/server.rs [3089-3131]

 TarballFinalize::Conflict => {
-    return Err(RegistryError::PackumentWriteConflict {
+    return Err(RegistryError::TarballWriteConflict {
         package: stage.name.as_str().to_string(),
     });
 }
 ...
 Err(apply_err) => {
     tracing::warn!(error = %apply_err, "publish apply failed after seal; rolling forward");
-    txn.roll_forward(&state.inner.storage).await.map_err(|_| apply_err)
+    match txn.roll_forward(&state.inner.storage).await {
+        Ok(()) if matches!(apply_err, RegistryError::TarballWriteConflict { .. }) => {
+            Err(apply_err)
+        }
+        Ok(()) => Ok(()),
+        Err(_) => Err(apply_err),
+    }
 }
Suggestion importance[1-10]: 9

__

Why: Returning a successful status to the client when their tarball failed to upload (due to a conflict) hides the failure, leading to a false sense of success.

High
Remove dangling version metadata

Remove metadata referencing discarded versions (like dist-tags and time) during
conflict resolution to prevent merge_manifest from publishing dangling tags.

pnpr/crates/pnpr/src/journal.rs [307-317]

-versions.retain(|_version, manifest| {
+let mut removed_versions = HashSet::new();
+versions.retain(|version, manifest| {
     let filename = manifest
         .get("dist")
         .and_then(|dist| dist.get("tarball"))
         .and_then(serde_json::Value::as_str)
         .map(tarball_basename);
-    match filename {
-        Some(filename) => !conflicted.contains(filename),
-        None => true,
+    let keep = filename.is_none_or(|filename| !conflicted.contains(filename));
+    if !keep {
+        removed_versions.insert(version.clone());
     }
+    keep
 });
 
+if let Some(tags) = journaled
+    .get_mut("dist-tags")
+    .and_then(serde_json::Value::as_object_mut)
+{
+    tags.retain(|_, version| {
+        version.as_str().is_none_or(|version| !removed_versions.contains(version))
+    });
+}
+if let Some(time) = journaled.get_mut("time").and_then(serde_json::Value::as_object_mut) {
+    time.retain(|version, _| !removed_versions.contains(version));
+}
+
Suggestion importance[1-10]: 8

__

Why: Leaving dangling metadata (such as dist-tags and time entries) for a discarded version can cause incorrect or confusing data to be merged into the packument.

Medium
Suggestions up to commit 9939d7c
CategorySuggestion                                                                                                                                    Impact
Possible issue
Stop recovery after tarball conflicts

Return a conflict error instead of continuing on TarballFinalize::Conflict. This
prevents committing the transaction's tarball integrity when the tarball
actually contains bytes from another concurrent replica.

pnpr/crates/pnpr/src/journal.rs [251]

-TarballFinalize::Conflict => {}
+TarballFinalize::Conflict => {
+    return Err(crate::error::RegistryError::PackumentWriteConflict {
+        package: name.as_str().to_string(),
+    });
+}
Suggestion importance[1-10]: 9

__

Why: If a concurrent replica won the tarball race but its packument isn't visible yet, dropping the tarball conflict and proceeding will commit our version's integrity with the other replica's bytes, causing data corruption.

High
Replay only transaction-specific metadata

Avoid using a fully materialized, stale packument as the input for
merge_manifest during CAS retries. Instead, persist and apply only the
transaction-specific delta to prevent reverting concurrent metadata changes.

pnpr/crates/pnpr/src/journal.rs [277-279]

 let merged =
-    merge_manifest(existing.as_ref(), journaled, existing.as_ref(), &now_iso());
+    merge_manifest(existing.as_ref(), journaled_delta, existing.as_ref(), &now_iso());
 Ok(Some(serde_json::to_vec_pretty(&merged)?))
Suggestion importance[1-10]: 9

__

Why: The PR repurposes crash recovery logic for regular CAS retries, but re-merging a fully materialized packument will overwrite any concurrent metadata updates with stale state from the time of staging.

High
Suggestions up to commit eb05f8e
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent stale tarball overwrites

Make tarball finalization conditional (using PutMode::Create) to prevent
overwriting existing identical objects. This ensures that losing concurrent
publishes do not corrupt the winner's tarball artifact before the packument CAS
conflict is detected.

pnpr/crates/pnpr/src/server.rs [3081-3098]

 for slot in stage.slots {
-    store.finalize_tarball_slot(slot).await?;
+    match store.finalize_tarball_slot_if_absent(slot).await? {
+        TarballFinalize::Written | TarballFinalize::AlreadyPresentIdentical => {}
+        TarballFinalize::Conflict => {
+            return Err(RegistryError::PackumentWriteConflict {
+                package: stage.name.as_str().to_string(),
+            });
+        }
+    }
 }
 match store
     .write_hosted_packument_if_current(
         &stage.name,
         &stage.merged_bytes,
         stage.base_version.as_ref(),
     )
     .await?
 {
     PackumentWrite::Written => {}
     PackumentWrite::Conflict => {
         return Err(RegistryError::PackumentWriteConflict {
             package: stage.name.as_str().to_string(),
         });
     }
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion accurately identifies a critical data integrity race condition where a losing concurrent publish can overwrite a winning publish's tarball before hitting the packument CAS conflict, breaking checksum verification.

High

@greptile-apps

greptile-apps Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The change is self-contained to pnpr's S3 backend and journal recovery; the FS path and all TypeScript CLI code are untouched. Logic is well-covered by new unit and integration tests.

The CAS semantics are correctly threaded through all write sites (publish commit, partial unpublish, dist-tag, recovery). The retry loop bounds are conservative, the FnMut closure broadening is backward-compatible, and the tarball byte-identity check handles the TOCTOU trade-off acceptably. The only finding is Korean-language comments inconsistent with the project's English convention, which has no runtime impact.

The Korean comments in journal.rs and journal/tests.rs should be translated to English before merge.

Reviews (6): Last reviewed commit: "test(pnpr): remove trailing comma reject..." | Re-trigger Greptile

The pnpr dylint rule set rejects inline `#[cfg(test)] mod tests { ... }`
blocks, so the drop_conflicted_versions tests move to journal/tests.rs,
matching the crate's other modules.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread pnpr/crates/pnpr/src/journal.rs Resolved
Comment thread pnpr/crates/pnpr/src/journal.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 848c2a4

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

1 similar comment
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@YESHYUNGSEOK
YESHYUNGSEOK force-pushed the fix/pnpr-s3-packument-cas branch from 163cdd9 to 1179e22 Compare July 13, 2026 07:27
@zkochan
zkochan merged commit 806ff49 into pnpm:main Jul 13, 2026
28 of 29 checks passed
@qodo-code-review qodo-code-review Bot mentioned this pull request Sep 6, 2026
4 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pnpr reviewed: coderabbit CodeRabbit submitted an approving review state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants