Skip to content

pnpr: make remaining local state pluggable for stateless / serverless deployment #21

Closed

Description

@zkochan

Motivation

#12198 moves pnpr's hosted store (published packages + static content) into an S3-compatible object store (S3 / Cloudflare R2 / MinIO / …). That removes the biggest blocker to running pnpr as multiple stateless replicas, but it isn't sufficient on its own: pnpr still keeps other state on local disk that a horizontally-scaled or serverless runtime won't preserve or share.

This issue tracks making the remaining state pluggable so pnpr can run as a stateless, horizontally-scalable service (the realistic near-term target is container-serverless with autoscaling — Cloud Run / Fly / Container Apps / Fargate scale-to-zero; true FaaS is a larger lift, see below).

Organizing principle: every per-instance disk dependency becomes a config-selected backend, defaulting to today's local behavior, following the pattern pnpm/pnpm#12198 established (build the client once at config-load time into an Arc<dyn …> handle so request handlers stay infallible).

Two backend "kinds"

Everything pnpr keeps locally is one of:

Components

Component Today (code) Kind Externalize via
Hosted store storage.rs HostedStore {Fs|S3} Blob ✅ done (#12198)
Proxy cache storage.rs cached: Store (fs-only) Blob Generalize to {Fs|S3}, reuse S3Store
Accelerator CAS (pnpr-store) install_accelerator.rs store_dir Blob Content-addressed → S3 maps directly
Auth: users + tokens auth.rs UserStore / TokenStore Record ✅ done (#12206) — UserBackend/TokenBackend traits + libsql/Turso impl
Grant table install_accelerator/grant_table.rs Record Trait + networked-SQLite impl
Public-packages install_accelerator/public_packages.rs Record Trait + networked-SQLite impl
Verdict cache install_accelerator/verdict_cache.rs Record (pure cache) Leave ephemeral, or externalize

Blob side (cache + accelerator CAS)

Reuses pnpm/pnpm#12198. Two fs-isms to handle in the proxy cache:

  • TTL freshness — Store::read_fresh_packument reads file mtime; the S3 variant uses ObjectMeta.last_modified (object_store exposes it).
  • tee_to_cache (streaming.rs) writes incrementally to a local file then renames. S3 can't append, so stage to local tmp and upload on stream completion (multipart for large tarballs) — same stage-then-upload shape the publish path already uses.

No new external service — cheapest large win.

Record side (auth + grants)

Narrow async traits, keeping current impls as defaults:

trait UserBackend  { async fn get(..); async fn upsert_or_login(..); async fn count(); }
trait TokenBackend { async fn issue(..); async fn lookup(..); async fn list(..); async fn revoke(..); }
trait GrantBackend { async fn is_granted(..); async fn record(..); async fn clear_package(..); }

Impls: InMemory, LocalSqlite (today, rusqlite), and a networked SQLite impl. Selected by config, built into Arc<dyn …> at load time. (Multiple impls behind dyn → async-trait.)

DB choice: SQLite-compatible, not Postgres

pnpr is already built on SQLite (rusqlite backs tokens, grants, public-packages, verdict cache), so the schemas and queries already exist. Standardizing on SQLite-compatible services keeps the SQL and makes an all-Cloudflare stack coherent: R2 (blobs) + D1 (records) + compute.

Important nuance: "SQLite" ≠ "rusqlite" once networked. rusqlite opens a local file; a networked SQLite service needs a different driver. Keep the SQL, swap the driver:

Option Reach it via Works with current stack?
Cloudflare D1 Workers binding, or REST API (SQL over HTTP) REST API: yes (Cloud Run/Lambda). Workers binding: only inside a Worker.
Turso / libSQL libsql crate (network + embedded replicas) Yes — any tokio runtime
LiteFS (Fly) FUSE-replicated file, rusqlite unchanged, single writer Yes
rqlite Raft + HTTP Yes

Caveats:

  • D1 is happiest inside a Worker, and Workers can't run the current tokio/axum/rusqlite stack (WASM rewrite). From Cloud Run/Lambda you'd use D1's REST API (per-query HTTP).
  • Auth/token lookup is on the hot path (≈ every request). A pure-HTTP-to-D1 backend taxes every call. Mitigate with a short-TTL in-process token cache or Turso embedded replicas (local-fast reads).
  • Eventual consistency on replicas — fine for grants/public-packages (grant table is already best-effort, clear-on-discovery); the one to watch is token-revocation lag. A config knob (replica vs primary read for auth) covers it.

Recommendation: abstract behind the record-backend trait; default LocalSqlite. For the container-serverless target reachable today, Turso/libSQL is the pragmatic pick (works with the current stack; embedded replicas solve the hot-path auth read). D1 is the north-star for the Workers/edge path, gated on the larger stack rewrite.

Config shape (each block absent ⇒ local default)

storage: ./storage
s3: { bucket: pkgs, ... }          # hosted blobs        (done)
cache:
  s3: { bucket: cache, ... }       # proxy-cache blobs   (phase 2)
accelerator:
  store:
    s3: { bucket: accel, ... }     # accelerator CAS     (phase 2)
backend:
  libsql:
    url: ${PNPR_LIBSQL_URL}
    auth_token: ${PNPR_LIBSQL_TOKEN}
  # or: d1: { account_id, database_id, api_token }

Phased rollout

  1. Hosted → S3 — ✅ done (#12198).
  2. Proxy cache + accelerator CAS → S3 — reuses object_store, no new external service. After this the only local state left is the SQLite record stores. Biggest bang, lowest risk — proposed next step.
  3. Auth (users + tokens) → networked SQLite — ✅ done (#12206). UserBackend / TokenBackend async traits; local (htpasswd + SQLite) / in-memory / libsql/Turso impls selected by a backend.libsql: block. Embedded-replica read acceleration (replicaPath / syncIntervalSecs) for the hot-path token lookup; strict atomic registration cap.
  4. Grants + public-packages → networked SQLite; leave verdict-cache ephemeral (pure cache, degrades to lower hit-rate).
  5. Deployment glue — Cloud Run needs ~a Dockerfile + readiness probe; Lambda needs lambda_http + response-streaming handling; Workers is a separate, larger effort.

Cross-cutting caveat (independent of where bytes live)

With N replicas, the read-modify-write flows are the real distributed-systems risk, not storage:

  • Publish merges the incoming manifest into the existing packument (publish.rs::merge_manifest); partial-unpublish rewrites it. Two replicas publishing the same package concurrently = last-write-wins on the packument object → a lost version.
  • Single-instance half ✅ done (#12206): a striped per-package lock serializes the read-modify-write packument flows (publish, dist-tag, partial-unpublish) on one instance. Cross-replica still pending: S3 conditional writes (If-Match / ETag) or a DB-level conditional update. pnpm clients usually serialize per package, but a shared registry shouldn't rely on that.

Also: keep cold-start cost down — the install accelerator is already lazily built via OnceLock; keep that laziness and use a small connection pool.


Written by an agent (Claude Code, claude-opus-4-8).

Activity

  1. zkochan commented on Jun 5, 2026

    @zkochan
    MemberAuthor

    Phase 3 (Auth → networked SQLite) landed in pnpm/pnpm#12206 (merged to main as 70554b8).

    Delivered:

    • UserBackend / TokenBackend async traits; record stores built once at startup into Arc<dyn …> handles. Three impls, config-selected: local (htpasswd + SQLite), in-memory, and networked libsql/Turso (LibsqlAuth) — both records in one shared DB so replicas see a consistent set of users + tokens. Selected via a top-level backend.libsql: block.
    • Embedded-replica read acceleration (replicaPath + syncIntervalSecs) so the hot-path token lookup reads a local synced file instead of a network round-trip; the interval bounds revocation lag.
    • Read errors propagate as 5xx instead of being swallowed into 401/404 (a backend outage isn’t mistaken for "not authenticated"); strict atomic registration cap (count-and-insert in one statement, holds across replicas).
    • Cross-cutting publish guard (single-instance half): a striped per-package lock serializes the read-modify-write packument flows on one instance.

    Remaining for a fully stateless multi-replica deployment:

    • Phase 2 — proxy cache + accelerator CAS → S3 (reuses object_store, no new service).
    • Phase 4 — grants + public-packages → networked SQLite (verdict cache stays ephemeral).
    • Phase 5 — deployment glue (Dockerfile + readiness probe; Lambda streaming; Workers later).
    • Cross-replica publish guard — S3 If-Match/ETag CAS (the cross-replica half of the cross-cutting caveat).

    So the records side reachable today (R2 blobs + Turso auth + compute) works for auth + hosted blobs; phases 2/4 close the rest.


    Written by an agent (Claude Code, claude-opus-4-8).

  2. zkochan commented on Sep 6, 2026

    @zkochan
    MemberAuthor

    One multi-replica race got smaller in pnpm/pnpm#14608, which is worth recording here since this issue owns the stateless-deployment story.

    When several instances share one hosted store, two publishes of the same name@version with different bytes race for the same immutable blob key. The loser used to answer 201 while the store served the winner's bytes. Every publish path now reports it: the version is left out of the registry document and the publisher gets 409. That covers PUT /:pkg, the npm batch, -/stage approval, cargo publish, twine upload, and the cross-ecosystem batch.

    This does not close the conditional-write half this issue tracks. A packument write still races on read-modify-write, and the fix there is still If-Match / ETag on the document itself. What changed is that the blob half of the race is no longer silent.


    Written by an agent (Claude Code, claude-opus-5).

  3. zkochan commented on Sep 7, 2026

    @zkochan
    MemberAuthor

    Status after pnpm/pnpm#14665, with a re-audit of the component table above — three of its rows have moved since it was written.

    The cross-cutting caveat is closed

    Every read-modify-write on the shared hosted store is now compare-and-set:

    • Packuments — publish, dist-tag, partial unpublish and journal roll-forward write under If-Match on the object's ETag and retry on top of the winner (fix(pnpr): prevent stale hosted packument writes pnpm#12832).
    • Tarballs — promoted create-only; a byte-identical object is tolerated and a different one is refused, so two replicas publishing one version cannot overwrite each other. The loser is told rather than answering 201 over someone else's bytes (feat(pnpr): publish across ecosystems in one transaction pnpm#14608).
    • Revision-ref indexes, OCI image documents, blob upload sessions and the shared-artifact quota counter — all conditional, each with its own retry budget.
    • Staged publishes — the last unconditional writer, fixed in fix(pnpr): approve a staged publish once across replicas pnpm#14665. An approval claims the record with a conditional write, so a stage is approved once whichever replica each request reaches, and it rechecks the claim before committing so a rejection that lands first actually stops the publish.

    pnpr/crates/pnpr/tests/multi_replica.rs now drives two routers over one object store the way a load balancer spreads requests over two containers, and covers concurrent publishes of one package, cross-replica staging, double approval, and a rejection racing an approval.

    One window stays open by design: between an approval's claim recheck and its commit. It cannot be closed with an ownership token, because the staged record and the package document are two objects with no transaction between them. What is left is bounded — two approvals of one stage replay the same held bytes onto the same immutable blob slot. Closing it needs a lock with a fencing token in a record backend, which is the phase-4 track below.

    Corrections to the component table

    • Grant table and public-packages no longer exist in the code. Phase 4 is now only "the verdict cache stays ephemeral", which it is (resolver/verdict_cache.rs, local SQLite, a pure cache).
    • Phase 5 is further along than listed: the Docker image ships (pnpr/docker/Dockerfile) and /-/ping is always served as a health check, so Cloud Run needs no new work. Lambda response streaming and Workers are still open.
    • Accelerator CAS is <cache>/pnpr-store, a pnpm store directory under the cache root — still local.

    What actually remains

    1. Pipeline run records (pnpr-pipeline-runs) are filesystem-only, and unlike the caches they are not regenerable. Behind a load balancer a run posted to one replica is invisible from every other, so the pipeline UI shows a different history depending on which replica answers. They are append-only, so create-only object writes are enough. This is the one remaining item that changes what a user sees.
    2. Proxy cache and accelerator CAS to S3 (phase 2). Both are disposable, so this is a hit-rate and cold-start improvement rather than a correctness one. Two fs-isms to handle, as the issue says: the TTL check reads file mtime (ObjectMeta.last_modified on the object store) and tee_to_cache writes-then-renames, which needs the stage-then-upload shape the publish path already uses.
    3. Per-replica durability: each replica's publish journal and staging scratch live under its storage path, so that path has to outlive its restarts. Documented in the pnpr README's new "Running several replicas" section.

    So "three replicas behind a load balancer" is a supported deployment now for the npm, Cargo, Python and OCI surfaces, given an S3-compatible store that honors If-Match / If-None-Match and a shared backend: database for accounts. The pipeline UI is the exception.


    Written by an agent (Claude Code, claude-opus-5).

  4. zkochan commented on Sep 8, 2026

    @zkochan
    MemberAuthor

    Phase 2 (proxy cache + accelerator CAS to S3): not worth doing as specified

    Sized after pnpm/pnpm#14668. The phase reads as the cheapest win in the table above, but the numbers do not support that any more, so it should not be picked up as written.

    It closes no gap. The proxy cache and the accelerator store are disposable. A replica that starts cold refetches from upstream and warms up; nothing is lost and nothing races. That is unlike the run records in pnpm/pnpm#14668, which were testimony a replica could not rebuild.

    It would slow the install path. Nothing memoizes in front of the proxy cache: a proxied packument request reads it on every request. On local disk that read is around 0.1 ms; through an object store it is a 10-20 ms round trip, on every hit, during installs. Trading upstream fetches (TTL-bounded, occasional) for an object-store round trip per request is a bad trade for the surface pnpr exists to make fast.

    The accelerator store is the wrong place for it. <cache>/pnpr-store is a pnpm StoreDir driven by pacquet's fetcher, which the resolver walks per package while it resolves a lockfile. Putting an object store under it puts network latency inside that loop. Performance is the priority in the install accelerator, and this would spend it. It is also pacquet's store, not pnpr's, so the change does not belong on this side.

    What would pay, if anything here does. The tarball half of the proxy cache: large, immutable, fetched once, and worth sharing across replicas. That path currently hands callers an fs::File so it can serve Range and If-Range, so it needs the range-serving rework first. Worth filing on its own merits rather than as "phase 2".

    And the shape that would make a shared cache safe for the hot path is two tiers — local disk in front of the shared bucket, with the shared tier consulted on a local miss. That is a real design with its own invalidation questions, not a backend swap.

    Suggest striking the proxy-cache and accelerator-CAS rows from the phased rollout, and keeping the two-tier cache as a separate idea for whenever a deployment shape actually asks for it.


    Written by an agent (Claude Code, claude-opus-5).

  5. transferred this issue frompnpm/pnpmon Sep 26, 2026
  6. zkochan commented on Nov 7, 2026

    @zkochan
    MemberAuthor

    Closing: what this issue tracks has shipped, been dropped, or been replaced by a newer design. State on main (863382fa585):

    This issue Now
    Record backend: "SQLite-compatible, not Postgres" Superseded by pnpm/rfcs#66: metadata is implemented once over SQL, with a small adapter per database. SQLite and libSQL/Turso adapters ship (pnpm/pnpm#17577, #17578, #17580, #17583), and every adapter runs one conformance suite. Accounts already support PostgreSQL and MySQL through sqlx. PostgreSQL and MySQL metadata adapters are tracked separately.
    Cross-replica safety through If-Match on package documents Replaced. Hosted metadata lives in SQL with real write transactions. Archives are content-addressed, with an online pnpr gc fenced against in-flight commits (pnpm/pnpm#17717). Upload sessions and a few small records still use conditional object writes.
    Auth (users and tokens) on a networked database Done (libSQL/Turso, PostgreSQL, MySQL).
    Grant table, public-packages Gone from the code. The verdict cache stays local, as planned.
    Phase 2: proxy cache and accelerator CAS to S3 Dropped, per the comment above: both are disposable, and an object-store round trip per proxied read would slow installs.
    Pipeline run records (last remaining user-visible gap) Done in pnpm/pnpm#14668.
    Per-replica publish journal and staging scratch Staged archives are tracked in SQL (pnpm/pnpm#17717). Local disk holds only disposable caches and temporary files.
    Deployment glue The Docker image and /-/ping cover Cloud Run. pnpr also runs on Cloudflare Containers behind a Worker (pnpr/docs/cloudflare.md). Lambda response streaming was never needed, so it isn't tracked.

    One idea from this thread could still be useful if a deployment asks for it: a two-tier tarball cache (local disk in front of a shared bucket) for the large, immutable half of the proxy cache. It needs the range-serving rework first, and it would be its own task.

    Written by an agent (Claude Code, claude-opus-5-5).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions