Package Management (Dependency Declaration, Resolution, and Lockfiles)

Package managers resolve and install dependencies based on version constraints, target platforms, and available artifacts. Lockfiles record resolved versions along with sources, markers, or hashes to help reconstruct dependencies across covered environments, though they do not by themselves guarantee identical runtime behavior across operating systems.

Second-Draft Verification Note (2026-10-15): This article is the second draft of the HeLuoXu tutorial, revised against official specifications and documentation. Previous experiment logs are labeled separately as "First-Draft Archived Output" and do not represent a Windows re-run during this pass; see the batch verification record for current environment details and results. "StarRiver Notes", accounts, orders, prices, and policies in the examples are fictional teaching data.

One-Line Definition

Package managers resolve and install dependencies based on version constraints, target platforms, and available artifacts. Lockfiles record resolved versions along with sources, markers, or hashes to help reconstruct dependencies across covered environments, though they do not by themselves guarantee identical runtime behavior across operating systems.

Why It Matters

  • Inconsistent dependency versions are one of the most common causes of "it works on my machine" failures—especially in AI projects, where even a slight mismatch among PyTorch, CUDA, and transformers versions can break execution.
  • Dependencies are a primary entry point for software supply-chain security risks: tampered or typosquatted packages can execute arbitrary code during installation.
  • Understanding version constraint syntax and dependency resolution helps you diagnose and fix ResolutionImpossible or ERESOLVE errors quickly.

How It Works / Diagram

Stage Python JavaScript
Dependency declaration pyproject.toml (PEP 621) / requirements.txt package.json
Version specification PEP 440: >=2,<3, ~=2.1, ==2.* semver: ^1.2.3, ~1.2.3
Resolver pip (resolvelib backtracking), uv (PubGrub) npm, pnpm, yarn
Lockfile uv.lock, poetry.lock, pip-tools requirements with --hash package-lock.json, pnpm-lock.yaml
Isolation Virtual environment (venv) Project-local node_modules

PEP 440 version identification: https://peps.python.org/pep-0440/; Semantic Versioning 2.0.0: https://semver.org/lang/zh-CN/; npm semver ranges: https://github.com/npm/node-semver#advanced-range-syntax; pip dependency resolution: https://pip.pypa.io/en/stable/topics/dependency-resolution/; uv resolver documentation: https://docs.astral.sh/uv/concepts/resolution/

Figure 1

Scope Boundaries & Verification Points

The same package version can correspond to different platform wheels, system libraries, and installation scripts. Cryptographic hashes only verify that an artifact matches the record in a trusted lockfile; they do not prove that a package is free of malicious code. Lockfile formats and tool semantics also differ across managers—for instance, npm ci requires the declaration and lockfile to match and will not update the lockfile for you. In Python's packaging library, version 26.0 changed default prerelease handling: an individual contains check may accept a prerelease when no alternative context exists, whereas filter evaluates the full candidate set—do not assume every version of pip or every resolver behaves identically.

Primary references verified in this pass (2026-10-15):

  • packaging: Specifiers: 26.0 prerelease behavior changes for contains vs. filter.
  • npm ci: lockfile-based installation and failure on manifest mismatch.

Runnable Example

The script uses packaging to demonstrate version filtering, a toy backtracking resolver to show conflict resolution, synthetic wheel bytes to demonstrate hash verification, and Node's semver package alongside an existing package-lock.json to inspect ranges and lockfile structure. Version numbers and package counts in the archived log reflect the original run environment rather than fixed guarantees.

# File: examples/08_package_management.py
"""Three core questions in package management: reading version constraints, resolving dependency conflicts, and verifying lockfile hashes."""
import hashlib, json, pathlib, subprocess
import packaging
from packaging.specifiers import SpecifierSet
from packaging.version import Version

print(f"1. PEP 440 version constraints (Python, packaging {packaging.__version__})")
cands = ["1.9.0", "2.0.0", "2.1.0rc1", "2.1.0", "2.5.3", "3.0.0"]
for spec in [">=2.0,<3", "~=2.1", "==2.*", "!=2.5.3,>=2"]:
    ok = list(SpecifierSet(spec).filter(cands))          # filter: how installers select candidate versions
    print(f"  {spec:<12} -> {ok}")
print("  Prerelease 2.1.0rc1: filter excludes it when a final release is available ->", list(SpecifierSet(">=2.0").filter(["2.1.0rc1", "2.1.0"])))
print("  But selects it when only prereleases are available ->", list(SpecifierSet(">=2.0").filter(["2.1.0rc1"])))
print("  Checking '2.1.0rc1' in SpecifierSet('>=2.0') directly =", "2.1.0rc1" in SpecifierSet(">=2.0"), "(different semantics from filter)")

print("\n2. A toy backtracking dependency resolver")
# Index: package -> version -> dependency constraints
INDEX = {
    "myapp": {"1.0": {"llmkit": ">=2", "tokenizerx": ">=1"}},
    "llmkit": {"2.0": {"tokenizerx": "<2"}, "2.1": {"tokenizerx": ">=2"}, "3.0": {"tokenizerx": ">=3"}},
    "tokenizerx": {"1.5": {}, "2.2": {}},
}
def resolve(reqs, chosen=None, depth=0, trace=None):
    chosen = dict(chosen or {})
    if not reqs: return chosen
    (pkg, spec), rest = reqs[0], reqs[1:]
    if pkg in chosen:                                      # Already picked: check compatibility
        return resolve(rest, chosen, depth, trace) if Version(chosen[pkg]) in SpecifierSet(spec) else None
    for v in sorted(INDEX[pkg], key=Version, reverse=True):  # Try newest versions first
        if Version(v) not in SpecifierSet(spec): continue
        trace.append(f"{'  '*depth}Try {pkg}=={v}")
        deps = list(INDEX[pkg][v].items())
        r = resolve(deps + rest, {**chosen, pkg: v}, depth + 1, trace)
        if r: return r
        trace.append(f"{'  '*depth}x {pkg}=={v} caused a conflict, backtracking")
    return None
trace = []; sol = resolve([("myapp", "==1.0")], trace=trace)
print("\n".join("  " + t for t in trace)); print("  Solution:", sol)

print("\n3. Lockfile: pinning exact versions + content hashes")
wheel = b"PK\x03\x04 fake wheel bytes of tokenizerx-2.2"           # Synthetic wheel payload
lock = {"tokenizerx": {"version": "2.2", "sha256": hashlib.sha256(wheel).hexdigest()}}
print("  lock:", json.dumps(lock)[:90] + "...")
tampered = wheel.replace(b"2.2", "2.2 + malicious payload".encode())
for name, blob in [("original artifact", wheel), ("tampered artifact", tampered)]:
    ok = hashlib.sha256(blob).hexdigest() == lock["tokenizerx"]["sha256"]
    print(f"  Installing {name}: hash check {'PASSED' if ok else 'FAILED -> aborting install'}")

print("\n4. npm semver ranges (invoking Node's semver package)")
js = """const s=require('semver');const vs=['1.2.3','1.2.9','1.3.0','1.9.9','2.0.0','0.2.5','0.3.0'];
for (const r of ['^1.2.3','~1.2.3','^0.2.3','1.x','>=1.3 <2']) console.log('  '+r.padEnd(10), '->', JSON.stringify(vs.filter(v=>s.satisfies(v,r))));"""
print(subprocess.run(["node", "-e", js], cwd="web", capture_output=True, text=True).stdout.rstrip())

print("\n5. Inspecting a real package-lock.json in web/")
lk = json.loads(pathlib.Path("web/package-lock.json").read_text())
pk = {k: v for k, v in lk["packages"].items() if k}
direct = lk["packages"][""]["dependencies"]
print(f"  lockfileVersion={lk['lockfileVersion']}, {len(direct)} direct dependencies: {sorted(direct)}; {len(pk)} total packages in lockfile (including transitive)")
r = pk["node_modules/react"]; print("  react entry:", {k: r[k][:40] for k in ("version", "resolved", "integrity")})

First-Draft Archived Output

The log below is preserved from the first draft's original environment and is not a re-run result from this pass. Refer to the batch verification link below for the current run log.

1. PEP 440 version constraints (Python, packaging 26.3)
  >=2.0,<3     -> ['2.0.0', '2.1.0', '2.5.3']
  ~=2.1        -> ['2.1.0', '2.5.3']
  ==2.*        -> ['2.0.0', '2.1.0', '2.5.3']
  !=2.5.3,>=2  -> ['2.0.0', '2.1.0', '3.0.0']
  Prerelease 2.1.0rc1: filter excludes it when a final release is available -> ['2.1.0']
  But selects it when only prereleases are available -> ['2.1.0rc1']
  Checking '2.1.0rc1' in SpecifierSet('>=2.0') directly = True (different semantics from filter)

2. A toy backtracking dependency resolver
  Try myapp==1.0
    Try llmkit==3.0
    x llmkit==3.0 caused a conflict, backtracking
    Try llmkit==2.1
      Try tokenizerx==2.2
  Solution: {'myapp': '1.0', 'llmkit': '2.1', 'tokenizerx': '2.2'}

3. Lockfile: pinning exact versions + content hashes
  lock: {"tokenizerx": {"version": "2.2", "sha256": "b130436f9d58671dc77b91d6898fc10e125de4106ab56...
  Installing original artifact: hash check PASSED
  Installing tampered artifact: hash check FAILED -> aborting install

4. npm semver ranges (invoking Node's semver package)
  ^1.2.3     -> ["1.2.3","1.2.9","1.3.0","1.9.9"]
  ~1.2.3     -> ["1.2.3","1.2.9"]
  ^0.2.3     -> ["0.2.5"]
  1.x        -> ["1.2.3","1.2.9","1.3.0","1.9.9"]
  >=1.3 <2   -> ["1.3.0","1.9.9"]

5. Inspecting a real package-lock.json in web/
  lockfileVersion=3, 6 direct dependencies: ['jsdom', 'react', 'react-dom', 'semver', 'typescript', 'vue']; 91 total packages in lockfile (including transitive)
  react entry: {'version': '19.3.0', 'resolved': 'https://registry.npmjs.org/react/-/react', 'integrity': 'sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKt'}
  • 1. ~=2.1 is equivalent to >=2.1, ==2.*, so 2.0.0 is excluded while 2.5.3 matches; !=2.5.3,>=2 has no upper bound, so 3.0.0 is also selected—omitting an upper bound can pull in the next major release.
  • 1. First-draft experiment note: In packaging 26.3, filter() (an API used here to illustrate candidate-set filtering, not every installer's full pipeline) excludes the prerelease 2.1.0rc1 when a final release is present and only selects it when no final release exists; however, evaluating "2.1.0rc1" in SpecifierSet(">=2.0") directly returns True. Keep these two call semantics distinct when writing version-checking scripts.
  • 2. The resolver first tries the newest version, llmkit==3.0, which requires tokenizerx>=3; because the index only reaches 2.2, it backtracks and picks llmkit==2.1, which succeeds with tokenizerx==2.2. Production resolvers (resolvelib, PubGrub) follow the same principle with smarter pruning and conflict explanation.
  • 3. The lockfile records a SHA-256 digest; when the artifact is modified, the hash check fails and installation is aborted. Both pip's --require-hashes mode and npm's integrity field serve this purpose (https://pip.pypa.io/en/stable/topics/secure-installs/).
  • 4. In npm, ^1.2.3 permits any update below 2.0.0, whereas ^0.2.3 only permits 0.2.x—SemVer treats 0.x as initial development where anything may change, so npm's caret syntax locks the leftmost non-zero digit.
  • 5. Even though web/ declares only 6 direct dependencies, the first-draft lockfile records 91 packages once transitive dependencies are included; standard registry entries include version, resolved, and integrity (local links or workspace entries may differ).

Self-Test

Question: If your dependency file pins torch==<exact-version>, have you completely reproduced the model runtime environment?

Reference Answer: No. You also need pinned transitive dependencies, the matching CPU/CUDA build artifact, the Python interpreter and OS system libraries, GPU drivers, and relevant runtime configuration. Record both your toolchain lockfile and your host environment specs.

Common Pitfalls

  • "Putting versions in requirements.txt is the same as locking": Writing torch>=2 is not a lock, and pinning only direct dependencies while leaving transitive dependencies unlocked is still an incomplete lock.
  • "Just run pip install globally without a virtual environment": Global installs allow different projects to overwrite each other's dependencies; modern Debian/Ubuntu system Python installations reject direct global pip install commands under PEP 668 (https://peps.python.org/pep-0668/).
  • "Lockfiles should never be committed to Git": Applications should generally commit lockfiles to ensure reproducible deployments; published libraries typically declare compatible version ranges in their package metadata, though library maintainers may still commit a lockfile for local development and CI runs.
  • "If the package name looks right, it is safe": Guard against typosquatting (e.g., typing reqeusts instead of requests) and compromised maintainer accounts; pin exact versions and hashes for critical dependencies and enable automated vulnerability scanning.

Relevance to AI Development

  • PyTorch distributes different CUDA builds via separate package index URLs (such as --index-url https://download.pytorch.org/whl/cu128). Version resolution does not replace GPU software stack compatibility checks, and the final wheel selected depends on OS platform, Python version, local build tags, and index candidates; always consult the official PyTorch install selector and verify actual build metadata at runtime (https://pytorch.org/get-started/locally/).
  • When asking an AI coding assistant to install a library, verify the exact package name and publisher first; LLMs can hallucinate nonexistent package names (which attackers sometimes register), and even an existing name does not guarantee it belongs to the project you intend.
  • During container image builds (k6.ops.image), copy the dependency manifest and lockfile and install dependencies before copying application source code so Docker layer caching remains effective.

Further Reading

Unverified Scope

  • This example does not prove that a lockfile guarantees identical behavior across all OS, hardware, and GPU driver combinations, nor does it audit the supply-chain security of every transitive package.

Current Example Execution Scope

2026-10-15: Passed. Local package metadata and version range evaluation; cross-platform reproducibility was not tested.

View current run log.

"First-Draft Archived Output" is preserved from the initial draft and was not newly generated by the second-draft code; interpret its original conclusions alongside the second-draft revisions and scope boundaries.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram