Jesse A. Green / notebook

Live demo: the DocCompiler guide library as a static, read-only snapshot (October 2026). No backend, no accounts, nothing to submit.

uv — Administrator & Developer Guide

Generated May 2026 from astral-sh/uv at 9c0eec6

AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it.

1. Architecture Overview

uv is an extremely fast Python package and project manager written in Rust. It provides a single binary that replaces pip, pip-tools, pipx, poetry, pyenv, twine, and virtualenv. The architecture is designed around a high-performance async pipeline with aggressive caching, parallel downloads, and a PubGrub-based dependency resolver.

Architecture Diagram

┌──────────────────────────────────────────────────────────────┐
│                         uv CLI (clap)                        │
│  ┌─────────┬──────────┬──────────┬────────┬───────┬────────┐ │
│  │  run    │  sync    │  lock    │  pip   │ tool  │ python │ │
│  │  add    │  remove  │  build   │ publish│ cache │ audit  │ │
│  └────┬────┴────┬─────┴────┬─────┴───┬────┴───┬───┴────┬───┘ │
│       │         │          │         │        │        │      │
│  ┌────▼─────────▼──────────▼─────────▼────────▼────────▼───┐ │
│  │                Command Dispatch Layer                    │ │
│  │              (crates/uv/src/commands/)                   │ │
│  └────┬──────────┬──────────┬───────────┬──────────┬───────┘ │
│       │          │          │           │          │          │
│  ┌────▼────┐ ┌───▼────┐ ┌──▼─────┐ ┌──▼────┐ ┌───▼──────┐  │
│  │Resolver │ │Client  │ │Install │ │Build  │ │Python    │  │
│  │(PubGrub)│ │(reqwest│ │Wheel   │ │Backend│ │Discovery │  │
│  │         │ │+retry) │ │        │ │+Front │ │+Download │  │
│  └────┬────┘ └───┬────┘ └──┬─────┘ └──┬────┘ └───┬──────┘  │
│       │          │          │          │          │          │
│  ┌────▼──────────▼──────────▼──────────▼──────────▼────────┐ │
│  │                     Cache Layer                         │ │
│  │               (crates/uv-cache/)                        │ │
│  └─────────────────────────────────────────────────────────┘ │
│                                                              │
│  Cross-cutting: Auth, Config, Logging, Platform, Filesystem  │
└──────────────────────────────────────────────────────────────┘

Component Inventory

Component Crate Role
CLI Parser uv-cli Clap-based argument parsing, subcommand definitions
Command Dispatch uv/src/commands/ Routes CLI invocations to implementations
Settings uv-settings Configuration file parsing, layered precedence
Configuration uv-configuration Runtime configuration types and enums
Resolver uv-resolver PubGrub-based dependency resolution with forking
Client uv-client HTTP client (reqwest + middleware), registry API
Installer uv-installer Package install/uninstall orchestration
Install Wheel uv-install-wheel Wheel extraction and installation
Build Frontend uv-build-frontend PEP 517 build isolation and invocation
Build Backend uv-build-backend uv's own PEP 517 backend (uv_build)
Python Management uv-python Python discovery, download, and version management
Virtual Environments uv-virtualenv Virtual environment creation
Tool Management uv-tool Tool install, run, and lifecycle
Workspace uv-workspace Workspace discovery, member resolution
Cache uv-cache Multi-bucket caching with cache keys
Auth uv-auth Authentication (keyring, netrc, URL, OIDC)
Publish uv-publish Package publishing with trusted publishing
Audit uv-audit Vulnerability auditing via GitHub Advisory DB
Distribution Types uv-distribution-types Index, source, and distribution type definitions
Platform Tags uv-platform-tags Wheel compatibility tag computation
PEP 440 uv-pep440 Version parsing and comparison
PEP 508 uv-pep508 Dependency specifier and marker parsing
Normalize uv-normalize Package name normalization (PEP 503/685)
Scripts uv-scripts PEP 723 inline script metadata
Extract uv-extract Archive extraction (tar, zip, etc.)
Filesystem uv-fs Safe filesystem operations via fs-err
Git uv-git Git source resolution and caching
Keyring uv-keyring Cross-platform keyring integration
Torch uv-torch PyTorch ecosystem index management
Dirs uv-dirs Platform-specific directory resolution
State uv-state Persistent state storage
Static uv-static Environment variable name constants
Logging uv-logging Structured logging and output formatting
Trampoline uv-trampoline Windows script launcher shims
Preview uv-preview Preview feature flag management
Flags uv-flags Global runtime flags
Warnings uv-warnings Warning suppression and formatting
Console uv-console Terminal output, progress bars
Redacted uv-redacted URL credential redaction
Types uv-types Shared trait definitions
Dispatch uv-dispatch Build dispatch orchestration
Requirements uv-requirements Requirements parsing and specification
Requirements-txt uv-requirements-txt requirements.txt format parsing

Technology Stack

Layer Technology
Language Rust (edition 2024, MSRV 1.92.0)
CLI Framework clap v4 (derive mode)
Async Runtime Tokio (multi-threaded)
HTTP Client reqwest v0.13 (rustls, HTTP/2, SOCKS proxy)
HTTP Retry astral-reqwest-retry with backoff
Dependency Resolution astral-pubgrub (fork of PubGrub)
Serialization serde (JSON, TOML, MessagePack, rkyv)
TLS rustls (default) or native-tls (opt-in)
Compression zstd, bzip2, gzip, xz, lzma (via async-compression)
Hashing SHA-256, SHA-384, SHA-512, BLAKE2, MD5
Platform Detection target-lexicon, goblin (ELF/PE parsing)
Memory Allocator jemalloc (Linux), mimalloc (other)
Error Handling anyhow + thiserror + miette (fancy diagnostics)
Testing insta (snapshot testing), assert_cmd, wiremock

Data Flow: uv add requests

1. CLI parsing → AddArgs { packages: ["requests"], ... }
2. Workspace discovery → find pyproject.toml, load workspace
3. Modify pyproject.toml → append "requests" to [project.dependencies]
4. Resolution → PubGrub solver queries index, resolves all transitive deps
5. Lock → Write uv.lock with pinned versions, hashes, markers
6. Sync → Compare lockfile vs installed packages
7. Download → Parallel fetch of missing wheels/sdists to cache
8. Install → Extract wheels to .venv/lib/python3.x/site-packages/
9. Report → Print resolution summary and install stats

Data Flow: uv run python app.py

1. CLI parsing → RunArgs { command: "python", args: ["app.py"], ... }
2. Project discovery → find pyproject.toml
3. Lock check → verify uv.lock is current (unless --no-sync)
4. Sync → install any missing/changed packages
5. Environment setup → activate .venv, set VIRTUAL_ENV, PATH
6. Exec → replace process with `python app.py`

Note

The resolver uses a forking strategy to handle platform-specific dependencies. It can produce different dependency sets for different Python versions and platforms within a single lockfile. The fork-strategy setting controls whether to optimize for latest versions (requires-python) or fewest versions (fewest).

2. System Requirements

Build Requirements (from source)

Requirement Version
Rust ≥1.92.0 (nightly for uv-trampoline)
Cargo Included with Rust
C compiler For native dependencies (OpenSSL alternatives)
Git For git dependencies in tests
Python ≥3.8 (for test suite)

Runtime Requirements (binary)

Requirement Detail
Linux glibc ≥2.17 (x86_64), ≥2.28 (aarch64)
macOS 10.12+ (x86_64), 11.0+ (aarch64)
Windows 10+ (x86_64, aarch64, i686)
Disk ~30 MB binary + cache (grows with usage)
Memory ~50-200 MB during resolution (varies with dependency graph)

Supported Platforms

Target Tier
x86_64-unknown-linux-gnu Primary
x86_64-unknown-linux-musl Primary
aarch64-unknown-linux-gnu Primary
aarch64-unknown-linux-musl Primary
x86_64-apple-darwin Primary
aarch64-apple-darwin Primary
x86_64-pc-windows-msvc Primary
aarch64-pc-windows-msvc Primary
i686-pc-windows-msvc Primary
i686-unknown-linux-gnu Secondary
i686-unknown-linux-musl Secondary
armv7-unknown-linux-gnueabihf Secondary
armv7-unknown-linux-musleabihf Secondary
arm-unknown-linux-musleabihf Secondary
powerpc64le-unknown-linux-gnu Secondary
riscv64gc-unknown-linux-gnu Secondary
riscv64gc-unknown-linux-musl Secondary
s390x-unknown-linux-gnu Secondary

3. Configuration Reference

Configuration Files

File Format Location Purpose
pyproject.toml TOML Project root Project metadata + [tool.uv] settings
uv.toml TOML Project root, user dir, system dir uv-specific settings
.python-version Text Project root Pinned Python version
.python-versions Text Project root Multiple pinned Python versions
uv.lock TOML-like Project root Cross-platform lockfile
uv.schema.json JSON Repository root JSON Schema for [tool.uv]

Configuration Precedence

CLI flags (highest)
  ↓
Environment variables (UV_*)
  ↓
Project uv.toml / [tool.uv] in pyproject.toml
  ↓
User config (~/.config/uv/uv.toml)
  ↓
System config (/etc/xdg/uv/uv.toml or /etc/uv/uv.toml)
  ↓
Defaults (lowest)

Important

UV_NO_CONFIG=1 disables all configuration file loading. CLI flags and environment variables still apply.

Complete Settings Reference

Resolver Settings

Setting Type Default Description
resolution enum "highest" Version selection strategy: highest, lowest, lowest-direct
prerelease enum "if-necessary-or-explicit" Pre-release handling: disallow, allow, if-necessary, if-necessary-or-explicit, explicit
index-strategy enum "first-index" Multi-index strategy: first-index, unsafe-first-match, unsafe-best-match
fork-strategy enum "requires-python" Platform forking: requires-python, fewest
exclude-newer string none Time-limit candidate packages (RFC 3339 or duration)
exclude-newer-package table none Per-package time limits
dependency-metadata array [] Pre-defined static metadata for dependencies
override-dependencies array [] PEP 508 dependency overrides
constraint-dependencies array [] PEP 508 dependency constraints
build-constraint-dependencies array [] PEP 508 build dependency constraints
environments array all Restrict resolution to specific markers
required-environments array none Required environment markers
no-sources bool false Ignore [tool.uv.sources] during resolution
no-sources-package array [] Ignore sources for specific packages
upgrade bool false Allow package upgrades
upgrade-package array [] Allow upgrades for specific packages
exclude-dependencies array [] Exclude specific packages from resolution

Index Settings

Setting Type Default Description
index array [] Package index definitions (name, url, explicit, default, auth-policy)
index-url string https://pypi.org/simple Primary index URL (deprecated, use index)
extra-index-url array [] Additional index URLs (deprecated, use index)
find-links array [] Flat directory/URL package sources
no-index bool false Disable all registry indexes
keyring-provider enum "disabled" Keyring auth: disabled, subprocess

Install Settings

Setting Type Default Description
link-mode enum platform Link strategy: clone, hardlink, copy, symlink
compile-bytecode bool false Compile .py → .pyc after install
reinstall bool false Reinstall all packages
reinstall-package array [] Reinstall specific packages
no-binary bool false Don't use pre-built wheels
no-binary-package array [] Don't use wheels for specific packages
no-build bool false Don't build source distributions
no-build-package array [] Don't build specific packages
no-build-isolation bool false Disable PEP 518 build isolation
no-build-isolation-package array [] Disable isolation for specific packages
extra-build-dependencies table {} Additional build dependencies per package
extra-build-variables table {} Extra env vars for building specific packages
config-settings table {} PEP 517 config settings
config-settings-package table {} Per-package PEP 517 config settings

Project Settings

Setting Type Default Description
managed bool true Whether uv manages this project
package bool auto Whether project is a package (vs virtual)
default-groups list/"all" ["dev"] Dependency groups to install by default
dependency-groups table {} Additional group settings (e.g., requires-python)
dev-dependencies array [] Dev dependencies (legacy, prefer [dependency-groups])
sources table {} Dependency source overrides (git, path, index)
workspace table none Workspace member definitions
conflicts array [] Conflicting group/extra definitions
add-bounds enum "lower" Default bounds when adding deps: lower, major, minor, exact
required-version string none Require specific uv version (PEP 440)

Performance Settings

Setting Type Default Description
concurrent-downloads int auto Max concurrent downloads
concurrent-builds int CPU count Max concurrent source builds
concurrent-installs int CPU count Max concurrent installs
cache-dir string platform Cache directory path
no-cache bool false Disable caching entirely
cache-keys array auto Files/dirs that trigger rebuild

Network Settings

Setting Type Default Description
offline bool false Disable all network access
system-certs bool false Use platform TLS certificate store
native-tls bool false Use native TLS (deprecated, use system-certs)
allow-insecure-host array [] Hosts to skip TLS verification
http-proxy string none HTTP proxy URL
https-proxy string none HTTPS proxy URL
no-proxy array [] Hosts to exclude from proxying

Publishing Settings

Setting Type Default Description
publish-url string https://upload.pypi.org/legacy/ Upload URL
check-url string none URL to check for existing uploads
trusted-publishing enum "automatic" OIDC trusted publishing: automatic, always, never

Python Management Settings

Setting Type Default Description
python-preference enum "managed" Prefer managed or system Python
python-downloads enum "automatic" Python download policy
python-install-mirror string default Mirror URL for Python downloads
pypy-install-mirror string default Mirror URL for PyPy downloads
python-downloads-json-url string none Custom Python installations JSON

Audit Settings

Setting Type Default Description
audit.ignore array [] Vulnerability IDs to always ignore
audit.ignore-until-fixed array [] Ignore vulnerabilities until a fix exists

Build Backend Settings ([tool.uv.build-backend])

Setting Type Default Description
module-root string "src" Directory containing the module
module-name string auto Module directory name
namespace bool false Build as PEP 420 namespace package
default-excludes bool true Apply default excludes (__pycache__, .pyc)
source-include array [] Extra files for sdist
source-exclude array [] Files to exclude from sdist
wheel-exclude array [] Files to exclude from wheel
data table {} Wheel data includes (scripts, headers, data, purelib, platlib)

PyTorch Settings

Setting Type Default Description
torch-backend enum none PyTorch index: auto, cpu, cu118, cu121, cu124, cu126, rocm6.2, etc.

Note

The torch-backend and add-bounds settings are preview features. Enable with preview = true in uv.toml or UV_PREVIEW=1.

Complete Environment Variable Reference

Core Variables

Variable Equivalent Setting Description
UV_CACHE_DIR cache-dir Cache directory
UV_NO_CACHE no-cache Disable cache
UV_NO_CONFIG — Ignore all config files
UV_WORKING_DIR — Override working directory
UV_PROJECT — Path to project directory
UV_PREVIEW preview Enable preview features
UV_PREVIEW_FEATURES — Enable specific preview features
UV_OFFLINE offline Disable network access
UV_NO_PROGRESS — Disable progress bars
UV_VERBOSE --verbose Enable verbose output

Python Management Variables

Variable Description
UV_PYTHON Default Python interpreter path
UV_MANAGED_PYTHON Prefer managed Python
UV_NO_MANAGED_PYTHON Disable managed Python
UV_PYTHON_PREFERENCE Python preference (managed, system, etc.)
UV_PYTHON_DOWNLOADS Python download policy
UV_PYTHON_INSTALL_DIR Managed Python install directory
UV_PYTHON_INSTALL_MIRROR Python download mirror URL
UV_PYPY_INSTALL_MIRROR PyPy download mirror URL
UV_PYTHON_DOWNLOADS_JSON_URL Custom Python installations JSON URL

Project Variables

Variable Description
UV_FROZEN Run without lockfile updates
UV_LOCKED Assert lockfile is current
UV_NO_SYNC Skip sync before uv run
UV_DEV Include dev dependencies
UV_NO_DEV Exclude dev dependencies
UV_NO_EDITABLE Install project non-editable
UV_NO_ENV_FILE Skip .env file loading
UV_ISOLATED Run in isolated mode
UV_VENV_CLEAR Clear venv before creating
UV_VENV_SEED Seed venv with pip/setuptools
UV_SHOW_RESOLUTION Show resolution details

Network Variables

Variable Description
UV_SYSTEM_CERTS Use platform TLS certificates
UV_NATIVE_TLS Use native TLS (deprecated)
HTTP_PROXY HTTP proxy
HTTPS_PROXY HTTPS proxy
ALL_PROXY All-protocol proxy
NO_PROXY Proxy exclusion list
UV_INSECURE_HOST Skip TLS for host

Tool Variables

Variable Description
UV_TOOL_DIR Tool environment directory
UV_TOOL_BIN_DIR Tool executable directory

Index Variables

Variable Description
UV_INDEX_URL Primary index URL
UV_EXTRA_INDEX_URL Additional index URLs
UV_FIND_LINKS Flat package sources
UV_INDEX Index definitions
UV_DEFAULT_INDEX Default index URL
UV_NO_INDEX Disable all indexes
UV_INDEX_STRATEGY Multi-index strategy
UV_KEYRING_PROVIDER Keyring provider

Build Variables

Variable Description
UV_NO_BUILD Disable building source distributions
UV_NO_BUILD_ISOLATION Disable PEP 518 build isolation
UV_NO_BINARY Disable pre-built wheels
UV_COMPILE_BYTECODE Compile bytecode after install
UV_LINK_MODE Install link mode
UV_CONCURRENT_DOWNLOADS Max concurrent downloads
UV_CONCURRENT_BUILDS Max concurrent builds
UV_CONCURRENT_INSTALLS Max concurrent installs

Publishing Variables

Variable Description
UV_PUBLISH_URL Upload URL
UV_PUBLISH_TOKEN PyPI token
UV_PUBLISH_USERNAME Upload username
UV_PUBLISH_PASSWORD Upload password
UV_PUBLISH_CHECK_URL Check URL for duplicates

Resolution Variables

Variable Description
UV_RESOLUTION Resolution strategy
UV_PRERELEASE Pre-release strategy
UV_EXCLUDE_NEWER Time-limit candidates

Audit Variables

Variable Description
UV_GITHUB_TOKEN GitHub token for vulnerability DB

Important

Boolean environment variables accept 1, true, yes (enabled) or 0, false, no (disabled). This is parsed by clap's BoolishValueParser.

4. Deployment & Scaling

Docker Deployment

Minimal Production Image

FROM python:3.12-slim AS base

# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv

WORKDIR /app

# Install dependencies first (layer caching)
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-editable --compile-bytecode

# Copy application
COPY . .

CMD ["uv", "run", "python", "-m", "app"]

Multi-Stage Build

# Build stage
FROM ghcr.io/astral-sh/uv:latest AS builder
WORKDIR /app
COPY pyproject.toml uv.lock ./
COPY src/ src/
RUN uv sync --frozen --no-dev --compile-bytecode

# Runtime stage
FROM python:3.12-slim
COPY --from=builder /app/.venv /app/.venv
COPY --from=builder /app/src /app/src
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "-m", "app"]

Tip

Use --compile-bytecode in Docker builds to trade install time for faster cold starts. Use --frozen to prevent lockfile updates in CI.

CI/CD Integration

GitHub Actions

- name: Install uv
  uses: astral-sh/setup-uv@v4
  with:
    version: "0.11.7"

- name: Install dependencies
  run: uv sync --locked

- name: Run tests
  run: uv run pytest

- name: Publish (with trusted publishing)
  run: uv publish --trusted-publishing always

GitLab CI/CD

install:
  script:
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - uv sync --locked
    - uv run pytest

Caching Strategy

$UV_CACHE_DIR/
├── archive-v0/         # Extracted wheel content (COW-linked to installs)
├── built-wheels-v5/    # Locally-built wheels from source distributions
├── flat-index-v2/      # Metadata from --find-links sources
├── interpreter-v4/     # Python interpreter metadata cache
├── managed-pythons/    # Downloaded Python interpreters (via `uv python install`)
├── sdists-v8/          # Downloaded source distributions
├── simple-v15/         # Package index metadata (PEP 503 API responses)
├── wheels-v3/          # Downloaded pre-built wheels
└── CACHEDIR.TAG        # Marks directory as cache (backup tools skip)

Note

The cache is safe to share between concurrent uv processes. File locking prevents corruption. Use uv cache prune to remove unreferenced entries; use uv cache clean only when you need a full reset.

Air-Gapped / Offline Deployment

  1. Populate cache on a connected machine:

    uv sync  # Downloads everything to cache
    
  2. Copy cache to the air-gapped machine:

    rsync -a ~/.cache/uv/ target:~/.cache/uv/
    
  3. Install offline:

    UV_OFFLINE=1 uv sync --frozen
    

Alternatively, use --find-links with a local directory of wheels:

uv pip install --find-links /path/to/wheels --no-index package

5. Operations

Storage Locations

Data Linux macOS Windows
Cache ~/.cache/uv ~/Library/Caches/uv (legacy) or ~/.cache/uv %LOCALAPPDATA%\uv\cache
State (tools, Python) ~/.local/share/uv ~/Library/Application Support/uv (legacy) or ~/.local/share/uv %APPDATA%\uv\data
Config ~/.config/uv ~/.config/uv %APPDATA%\uv
Tool binaries ~/.local/bin ~/.local/bin %USERPROFILE%\.local\bin
System config /etc/xdg/uv/uv.toml or /etc/uv/uv.toml (same) %SYSTEMDRIVE%\ProgramData\uv\uv.toml

Note

On macOS, uv prefers XDG directories (~/.cache/uv, ~/.local/share/uv) but falls back to the native Application Support/Caches paths for backward compatibility if those directories already exist.

Cache Management

# View cache location
uv cache dir

# View cache size (human-readable)
uv cache size --human

# Clean everything
uv cache clean

# Clean specific package
uv cache clean requests

# Prune unreferenced entries (safe, keeps referenced data)
uv cache prune

# Prune with CI cleanup (also removes managed Python installs)
uv cache prune --ci

Tip

In CI, use uv cache prune --ci at the end of pipelines to minimize cache size without losing frequently-used packages.

Monitoring and Diagnostics

# Verbose output (increasing levels)
uv -v sync       # Basic verbose
uv -vv sync      # Debug verbose
uv -vvv sync     # Trace verbose

# Show resolved settings
uv show-settings

# Show Python discovery
uv python find -v 3.12

# Debug pip operations
uv pip debug

Set RUST_LOG=uv=debug for granular Rust-level logging.

Lock File Management

The uv.lock file is a cross-platform lockfile. Key operations:

# Create/update lockfile
uv lock

# Verify lockfile matches pyproject.toml (CI check)
uv lock --check

# Upgrade all packages to latest compatible versions
uv lock --upgrade

# Upgrade specific package
uv lock --upgrade-package requests

# Export to requirements.txt
uv export --format requirements-txt

Warning

The uv.lock format is specific to uv and is not compatible with other tools' lockfiles. Use uv export to generate requirements.txt for interoperability.

6. Performance

Performance Characteristics

Operation Typical Speed Notes
Cold resolution (large project) 1-5 seconds PubGrub + parallel metadata fetch
Warm resolution (cached) 10-100 ms In-memory + disk cache
Package install (cached) 5-50 ms/pkg COW clone or hardlink from cache
Python install 5-30 seconds Download + extract
uv run (synced) <100 ms Lockfile check + exec

Tuning Parameters

Setting Default Recommendation
concurrent-downloads auto Increase to 32-64 for high-bandwidth networks
concurrent-builds CPU count Decrease on memory-constrained systems
concurrent-installs CPU count Usually optimal at default
link-mode clone/hardlink clone (COW) is fastest on APFS/Btrfs; hardlink on Windows
compile-bytecode false Enable in Docker for faster cold starts
cache-keys auto Add glob patterns for dynamic metadata files

Memory Allocator

uv uses jemalloc on Linux and mimalloc on other platforms via the uv-performance-memory-allocator crate. This provides significant performance improvements for the allocation-heavy resolver.

7. Security

Authentication Methods

Method Use Case Configuration
URL credentials Quick setup https://user:token@host/simple
Environment variables CI/CD UV_INDEX_<NAME>_USERNAME, UV_INDEX_<NAME>_PASSWORD
Keyring Desktop, interactive keyring-provider = "subprocess"
.netrc Traditional Unix Standard ~/.netrc format
Trusted publishing (OIDC) GitHub Actions, GitLab --trusted-publishing always
uv auth login Interactive (preview) Stores in keyring

Authentication Policy

Each index can have an auth-policy:

Policy Behavior
auto (default) Try unauthenticated first, then search for credentials
always Eagerly search for credentials; error if none found
never Never authenticate; error if credentials provided
[[tool.uv.index]]
name = "private"
url = "https://private.pypi.example.com/simple"
auth-policy = "always"

TLS Configuration

  • Default: Bundled Mozilla root certificates via webpki-root-certs
  • System certificates: system-certs = true or UV_SYSTEM_CERTS=1
  • Insecure hosts: allow-insecure-host = ["internal.example.com"]

Caution

allow-insecure-host disables TLS verification for the specified hosts. Only use in secure, trusted networks. This setting is intended for corporate environments with custom CAs that cannot be added to the system store.

Credential Redaction

The uv-redacted crate provides DisplaySafeUrl — a URL wrapper that automatically masks passwords in log output. All URLs are displayed as https://user:****@host/ in logs and error messages.

Dependency Confusion Protection

The default index-strategy = "first-index" prevents dependency confusion attacks by only using the first index that contains a given package. The resolver does not mix packages across indexes.

Hash Verification

uv.lock stores SHA-256 hashes for all distributions. During uv sync --locked, every downloaded file is verified against its hash. Use uv export --format requirements-txt to generate a hash-pinned requirements file.

Supply Chain

  • Python downloads verified via checksums from python-build-standalone
  • Package hashes verified against index metadata
  • Trusted publishing uses OIDC (no long-lived tokens)
  • uv audit checks against the GitHub Advisory Database

8. Developer Internals

Repository Structure

astral-sh/uv/
├── crates/                     # Rust workspace members (~60 crates)
│   ├── uv/                     # Main binary crate
│   │   ├── src/
│   │   │   ├── lib.rs          # Entry point, CLI dispatch
│   │   │   ├── settings.rs     # Settings resolution
│   │   │   ├── commands/       # Command implementations
│   │   │   │   ├── project/    # add, remove, lock, sync, run, init, etc.
│   │   │   │   ├── pip/        # pip-compatible commands
│   │   │   │   ├── tool/       # tool install, run, list, etc.
│   │   │   │   ├── python/     # python install, list, find, pin
│   │   │   │   ├── auth/       # login, logout, token
│   │   │   │   └── workspace/  # list, metadata
│   │   │   └── ...
│   │   └── tests/it/           # Integration tests (single-crate pattern)
│   ├── uv-cli/                 # CLI argument definitions (clap derive)
│   ├── uv-settings/            # Configuration file parsing
│   ├── uv-configuration/       # Runtime configuration types
│   ├── uv-resolver/            # PubGrub-based resolver
│   ├── uv-client/              # HTTP client + registry API
│   ├── uv-installer/           # Package install orchestration
│   ├── uv-install-wheel/       # Wheel extraction
│   ├── uv-build-frontend/      # PEP 517 build frontend
│   ├── uv-build-backend/       # uv's PEP 517 build backend
│   ├── uv-python/              # Python discovery and management
│   ├── uv-workspace/           # Workspace resolution
│   ├── uv-publish/             # Package publishing
│   ├── uv-audit/               # Vulnerability auditing
│   ├── uv-auth/                # Authentication
│   ├── uv-cache/               # Cache management
│   ├── uv-distribution-types/  # Index and distribution types
│   ├── uv-platform-tags/       # Wheel compatibility tags
│   ├── uv-pep440/              # Version parsing (PEP 440)
│   ├── uv-pep508/              # Dependency specifiers (PEP 508)
│   ├── uv-normalize/           # Package name normalization
│   ├── uv-scripts/             # PEP 723 script metadata
│   ├── uv-keyring/             # Cross-platform keyring
│   ├── uv-torch/               # PyTorch index management
│   ├── uv-tool/                # Tool lifecycle management
│   ├── uv-virtualenv/          # Virtual environment creation
│   ├── uv-fs/                  # Filesystem operations
│   ├── uv-git/                 # Git source handling
│   ├── uv-extract/             # Archive extraction
│   ├── uv-dirs/                # Directory resolution
│   ├── uv-state/               # Persistent state
│   ├── uv-static/              # Constants (env var names)
│   ├── uv-trampoline/          # Windows launcher (nightly Rust)
│   └── ...                     # More utility crates
├── python/uv/                  # Python wrapper package
├── docs/                       # MkDocs documentation source
├── test/                       # Test fixtures and ecosystem tests
├── scripts/                    # Benchmarks, scenarios, publishing tests
└── Cargo.toml                  # Workspace root

Architecture Deep Dive

Resolver (uv-resolver)

The resolver is based on PubGrub (via astral-pubgrub), a version-solving algorithm that provides:

  • Backtracking: Efficiently explores the version space
  • Error messages: Produces human-readable conflict explanations
  • Forking: Handles platform-specific dependencies by splitting the resolution tree

Key types:

  • ResolverState — the main resolution state machine
  • ForkState — handles platform/Python version forks
  • Lock — the lockfile data structure with all resolved packages
  • Resolution — the final resolved dependency graph

The resolver queries package metadata via the uv-client HTTP layer, which caches responses in the simple-v15 cache bucket.

HTTP Client (uv-client)

Built on reqwest with astral-reqwest-retry middleware:

  • Retry policy: Exponential backoff with jitter
  • Connection pooling: Per-host connection reuse
  • HTTP/2: Enabled by default for multiplexing
  • Compression: Transparent gzip/deflate/zstd
  • Caching: HTTP cache with If-Modified-Since / If-None-Match
  • Proxy support: HTTP, HTTPS, SOCKS5 (via system proxy detection)
  • Request signing: AWS (reqsign) for CodeArtifact, Google for Artifact Registry

Python Discovery (uv-python)

Python discovery follows a priority chain:

  1. Virtual environment (VIRTUAL_ENV, .venv)
  2. Managed installations (~/.local/share/uv/python/)
  3. PATH search
  4. Windows Registry (HKCU\Software\Python)
  5. Windows Store Python

The PythonPreference enum controls ordering:

  • managed — prefer managed, fall back to system
  • system — prefer system, fall back to managed
  • managed-only — only managed installations
  • system-only — only system installations

Workspace (uv-workspace)

Workspace discovery walks up from the current directory to find the root pyproject.toml with [tool.uv.workspace]. Members are resolved via glob patterns:

[tool.uv.workspace]
members = ["packages/*"]
exclude = ["packages/experimental"]

Each member gets its own lockfile resolution within the workspace-wide uv.lock.

Build System

Two components:

Build Frontend (uv-build-frontend): Implements PEP 517/518 build isolation. For each source distribution:

  1. Creates a temporary venv with declared build dependencies
  2. Calls build_wheel() or build_sdist() via the PEP 517 interface
  3. Caches the result in built-wheels-v5

Build Backend (uv-build-backend): uv's own PEP 517 backend, used when pyproject.toml declares:

[build-system]
requires = ["uv>=0.5.15,<0.13"]
build-backend = "uv_build"

Features: src/flat layout support, namespace packages, sdist/wheel/editable builds, data includes.

Authentication (uv-auth)

The auth system supports multiple credential sources with a priority chain:

  1. URL-embedded credentials (https://user:pass@host)
  2. UV_INDEX_<NAME>_USERNAME / UV_INDEX_<NAME>_PASSWORD
  3. Keyring (keyring-provider = "subprocess")
  4. .netrc file
  5. OIDC trusted publishing (GitHub Actions, GitLab CI)

The AuthPolicy per index controls behavior (auto, always, never).

The uv-keyring crate provides cross-platform keyring access:

  • macOS: Keychain via security-framework
  • Linux: Secret Service D-Bus API via secret-service
  • Windows: Credential Manager via Windows API

Cache System (uv-cache)

The cache uses content-addressed storage with bucket-based organization:

  • Cache keys: SHA-256 of URL, version, and platform metadata
  • Link strategy: COW clones (APFS/Btrfs), hardlinks (NTFS/ext4), or copies
  • Concurrency: File locks prevent corruption from parallel access
  • Invalidation: cache-keys in pyproject.toml define rebuild triggers

The CacheEntry system tracks metadata alongside cached artifacts. The archive-v0 bucket contains pre-extracted wheel contents that can be directly linked into site-packages.

Code Patterns and Conventions

Pattern Description
fs-err everywhere All filesystem operations go through fs-err for better error messages
No std::fs directly Enforced via clippy.toml disallowed-methods
DisplaySafeUrl URL type that redacts credentials in Display impl
Workspace crate versioning All internal crates at 0.0.40, main uv at 0.11.7
Single integration test One test binary per crate (matklad pattern)
Snapshot testing insta crate for snapshot-based output assertions
Feature flags test-python, test-pypi, test-git, test-ecosystem gate test modules
EnvVars constants All env var names defined as constants in uv-static
Error handling anyhow for application errors, thiserror for library errors
Derive-based CLI clap derive macros in uv-cli/src/lib.rs
Global flags uv-flags crate for runtime flags (concurrent init guard)
Preview features uv-preview crate with per-feature granularity

Build Profiles

Profile Use Key Settings
dev Development Default optimization, debug info
release Distribution strip = true, lto = "fat"
profiling Benchmarks strip = false, debug = "full", lto = false
fast-build CI tests opt-level = 1, debug = 0
no-debug Fast dev builds debug = 0, strip = "debuginfo"
minimal-size uv-build binary opt-level = "z", panic = "abort", codegen-units = 1
dist Release distribution Inherits release

Testing Strategy

uv uses a comprehensive testing approach:

  • Unit tests: Per-crate, testing internal logic
  • Integration tests: In crates/uv/tests/it/ — one main.rs binary (matklad pattern)
  • Snapshot tests: insta for CLI output, resolver output, lockfile content
  • Ecosystem tests: Real-world projects (airflow, black, transformers, etc.)
  • Scenario tests: Generated from templates in scripts/scenarios/
  • Feature-gated tests: test-python (needs Python), test-pypi (needs network), test-git (needs git)
  • Benchmarking: Custom harness in scripts/benchmark/
# Run all tests
cargo test

# Run with required features
cargo test --features "test-python test-pypi"

# Run specific test
cargo test -p uv -- pip_install

# Update snapshots
cargo insta test --review

Contributing

# Clone and build
git clone https://github.com/astral-sh/uv
cd uv
cargo build

# Run the development binary
cargo run -- pip install requests

# Run pre-commit checks
pre-commit run --all-files

# Generate CLI reference (required when changing uv-cli or uv-settings)
cargo dev generate-all

# Run the formatter
cargo fmt

# Run clippy
cargo clippy --workspace --all-targets

Important

After modifying uv-cli or uv-settings, run cargo dev generate-all to regenerate the CLI reference, JSON schema, environment variables reference, and options reference. This is enforced by a pre-commit hook.

Potential Improvements

Based on source analysis:

  • TODO in uv-auth/src/index.rs: The Indexes struct iterates linearly over all indexes for prefix matching; a trie would be more efficient for large index sets
  • TODO in uv-auth/src/index.rs: Index duplicates uv_distribution_types::Index to avoid circular dependencies; future refactor could unify these
  • Preview features system: The uv-preview crate supports per-feature granularity but many features are still gated by a single --preview flag
  • Windows trampoline: The uv-trampoline crate requires nightly Rust due to #![no_std] + Windows PE manipulation

9. Integration Points

Package Index Protocol

uv implements PEP 503 (Simple Repository API) and PEP 691 (JSON-based API). It queries indexes in the format:

GET /simple/{package}/ HTTP/1.1
Accept: application/vnd.pypi.simple.v1+json, text/html;q=0.1

Build System Protocol

uv implements:

  • PEP 517: Build backend interface (build_wheel, build_sdist, etc.)
  • PEP 518: Build system requirements ([build-system] in pyproject.toml)
  • PEP 660: Editable installs via build_editable
  • PEP 723: Inline script metadata for uv run
  • PEP 735: Dependency groups

Lockfile Format

uv.lock is a TOML-based format containing:

version = 1
requires-python = ">=3.11"

[[package]]
name = "requests"
version = "2.32.3"
source = { registry = "https://pypi.org/simple" }

[[package.dependencies]]
name = "certifi"
version = ">=2017.4.17"

[package.sdist]
url = "https://files.pythonhosted.org/..."
hash = "sha256:..."
size = 131218

[[package.wheels]]
url = "https://files.pythonhosted.org/..."
hash = "sha256:..."
size = 63928

Python Wrapper Package

The python/uv/ directory contains a Python package that provides:

  • uv module that delegates to the Rust binary
  • uv._find_uv for binary discovery
  • __main__.py for python -m uv execution

Binary Distribution

uv ships three binaries:

  • uv — the main binary
  • uvx — alias for uv tool run
  • uvw — Windows-only windowless variant (no console window)

Distribution via:

  • Standalone installers (shell script, PowerShell)
  • PyPI (pip install uv)
  • Homebrew, Conda, Cargo
  • Docker images (ghcr.io/astral-sh/uv)
  • GitHub Releases (via cargo-dist)