Skip to main content
Mage Pro includes an advanced dependency management system that provides isolated, reproducible dependency environments for your projects. This system automatically creates and manages virtual environments based on your project’s dependencies, ensuring consistent execution across different environments.

Overview

The dependency management system provides:
  • Isolated environments: Each unique combination of dependencies gets its own virtual environment
  • Automatic caching: Environments are reused based on content fingerprinting
  • Fast installation: Uses uv for blazing-fast package installation with pip fallback
  • Smart compatibility checking: Detects and reuses compatible packages from the global environment
  • Safe concurrency: File-based locking prevents race conditions when multiple processes create environments

Using Dependency Management

You can manage dependencies in three ways: The easiest way to manage your project dependencies is through the Mage UI:
  1. Open Tools in the left navigation, then select Editor
  2. Open your requirements file: Browse to /home/src/[project_path]/requirements.txt and open it in the editor
  3. Edit your dependencies: Add, remove, or update package requirements in the requirements.txt file
  4. Click the “Install dependencies” button: This will automatically:
    • Open a terminal at the bottom of the page
    • Execute mage deps install command
    • Show real-time installation progress and output
The system will intelligently install only the packages that need to be added or updated, reusing compatible packages from the global environment when possible.

2. Via Mage Terminal

For more control, you can run mage deps commands directly in the Mage terminal:
  1. Open Tools in the left navigation, then select Terminal
  2. Run dependency commands:
See the CLI Commands section below for complete command documentation.

3. Via Cluster Restart (Automatic)

When you restart your Mage cluster, the dependency management system automatically:
  1. Reads your latest requirements.txt: Checks for any changes since the last environment was created
  2. Creates or updates the virtual environment:
    • If the requirements haven’t changed, reuses the existing environment
    • If requirements have changed, creates a new environment with updated dependencies
  3. Activates the environment: Makes it available for all pipeline executions
This ensures your dependencies are always synchronized with your requirements.txt after each cluster restart, with no manual intervention required.

Repair Pipeline Dependency Failures with AI Chat

When a failed pipeline run reports a Python import or package-resolution error, select Fix with AI from the run or its logs. AI Chat investigates using its existing run-log and log-search tools. When the evidence indicates a dependency issue, it uses the dependency skill to distinguish missing packages, optional extras, incompatible versions, and differences between the Mage server and the pipeline executor. Other errors continue through ordinary failure investigation. If the skill cannot be loaded, AI Chat discloses that limitation and can continue an evidence-supported repair using its built-in dependency guidance; it does not claim to have loaded the skill. AI Chat’s run-log and log-search tools redact sensitive evidence before returning it to the model. Run diagnostics read bounded excerpts from stored logs. If an excerpt is incomplete, AI Chat should report that limitation and inspect more specific evidence before proposing a dependency change. AI Chat explains each action and reports its result:
  1. Review the diagnosis and proposed requirements.txt diff. AI Chat states the intended change before applying it and follows the environment’s action policy. If that policy requests confirmation, AI Chat waits for it. After an authorized write, Mage records the edit as a file version.
  2. Track installation as a separate operation and reported state. Updating requirements.txt does not install packages by itself; AI Chat states which project requirements it will install, follows the environment’s action policy, and reports the resolver result. The host may request confirmation, but the flow does not require a new confirmation between every authorized step.
  3. Verify the repair in the environment that executes the pipeline. A successful package check or import in the Mage server or terminal does not prove that a Kubernetes, streaming, Spark, or other remote executor has the same packages. Restart or redeploy an executor separately when its environment requires it.
  4. After verification, retry the failed block or pipeline run manually from the pipeline UI. The dependency-repair workflow reports its repair and verification results but does not automatically retry the run. See Retrying block runs from a pipeline run.
If AI Sidekick is disabled for the project, Fix with AI is unavailable and the normal dependency-management controls continue to work without sending a request to AI Sidekick or an AI model.

How It Works

Automatic Server-Side Management

When the Mage server starts, the dependency management system automatically handles virtual environment setup:
  • If no environment exists: A new virtual environment is automatically created based on your project’s requirements.txt
  • If an environment exists: The matching environment is automatically activated for use
This seamless integration means you don’t need to manually manage virtual environments for normal server operation. The system ensures your dependencies are always properly configured without manual intervention. For more control over environment creation, activation, and management, you can use the CLI commands described below.

Environment Fingerprinting

The system computes a deterministic fingerprint hash for each environment based on:
  • Python version (e.g., 3.11.8)
  • Normalized requirements.txt content
  • uv version (if available)
If any of these change, a new environment is created. If they match an existing environment, that environment is reused.

Directory Structure

Virtual environments are stored under your Mage data directory:
Each virtual environment includes a .mage_env.json metadata file that tracks:
  • fingerprint: Environment fingerprint hash
  • python_version: Python version
  • created_at: Creation timestamp (ISO 8601 format)
  • last_used_at: Last usage timestamp (ISO 8601 format)
  • dependency_source: Source of dependencies (e.g., requirements.txt)

Package Installation Strategy

The system uses a smart installation strategy to minimize redundant installations:
  1. Global package detection: Scans globally installed packages
  2. Compatibility filtering: Filters out requirements already satisfied by global packages
  3. Constrained installation: Installs remaining packages with global package versions as constraints
  4. Fallback handling: Automatically retries without constraints if dependency conflicts occur

Installation Tools

  • Primary: uv pip install - Fast, modern Python package installer
  • Fallback: pip install - Standard Python package installer
  • Virtual environment creation: uv venv --system-site-packages
The --system-site-packages flag allows the virtual environment to inherit global packages while still allowing user packages to override them when needed.

CLI Commands

mage deps ensure

Create or reuse a virtual environment for your project’s dependencies. Usage:
Parameters:
  • project-path (optional): Path to the Mage project (defaults to current directory)
  • --python-version (optional): Python version to use (defaults to current Python version)
  • --output-file (optional): File to write environment path to
Examples:
Output: When successful, the command outputs an environment variable assignment:
You can activate this environment in your shell:

mage deps install

Install dependencies from a requirements file using the best available installer. Usage:
Parameters:
  • project-path (optional): Path to the Mage project (defaults to current directory)
  • -r, --requirements-file (optional): Path to requirements file (defaults to requirements.txt in project)
  • --override-global-version (optional): Skip global package constraints (default: False)
Examples:
Behavior:
  1. Checks if running in an existing virtual environment (VIRTUAL_ENV)
  2. If yes: Installs packages using advanced features (filtering, constraints, diff analysis)
  3. If no: Installs packages system-wide using standard pip
Conflict Resolution: If installation fails due to conflicting dependencies with global packages, the CLI will prompt:
Answering “yes” retries the installation without global package constraints.

mage deps list

List all dependency virtual environments with their metadata. Usage:
Parameters:
  • --project-path (optional): Path to the Mage project (defaults to current directory)
  • --python-version (optional): Filter by Python version (e.g., 3.11.8)
  • --verbose (optional): Show detailed information including full paths
Examples:
Output:

mage deps cleanup

Clean up stale virtual environments to free disk space. Usage:
Parameters:
  • --project-path (optional): Path to the Mage project (defaults to current directory)
  • --ttl-seconds (optional): Time-to-live in seconds (defaults to 604800 = 7 days)
  • --max-retention (optional): Maximum number of environments to retain across all Python versions
  • --dry-run (optional): Show what would be deleted without actually deleting (default: False)
  • --verbose (optional): Show detailed information about cleanup process
Examples:
How it works:
  1. Identifies environments unused for longer than TTL
  2. Skips environments with active installation or activation locks
  3. If max_retention is set, keeps the N most recently used environments even if they exceed TTL
  4. Removes eligible environments and their metadata
Output:
Configuration: You can configure cleanup defaults in your project’s metadata.yaml:

Features in Detail

Automatic Package Filtering

The system intelligently filters out packages that are already satisfied by globally installed packages:
This reduces installation time and disk usage by reusing compatible packages.

Global Package Constraints

To ensure consistency with the base environment, the system creates a global.lock file containing all globally installed package versions and uses it as a constraint file during installation:
This ensures that when a package from requirements.txt doesn’t specify an exact version, the installer uses the same version as the global environment (if compatible), maintaining consistency.

Installation Diff Analysis

After installation, the system analyzes the difference between global and virtual environment packages:
This helps you understand what was installed, upgraded, or reused.

Concurrency Safety

The system uses cross-platform file locking to prevent race conditions:
  • POSIX systems (Linux, macOS): Uses fcntl.flock()
  • Windows: Uses msvcrt.locking()
  • Lock timeout: 10 minutes (configurable)
Lock Types:
  1. Installation lock (.install.lock): Exclusive lock held during environment creation and dependency installation
  2. Activation lock (.activate.lock): Shared lock held when environment is being used
  3. Cleanup lock (.cleanup.lock): Global lock preventing simultaneous cleanup operations
This ensures that if multiple processes try to create the same environment simultaneously, only one creates it while others wait and then reuse it. Environments with active locks are protected from cleanup.

Environment Validation

After creation, environments are validated to ensure they’re properly initialized:
Invalid environments are automatically cleaned up and recreated.

Error Handling

The system provides detailed error messages for common issues:

Lock Acquisition Timeout

Installation Failure

Requirements File Not Found

Best Practices

1. Pin Package Versions

For reproducibility, pin exact versions in requirements.txt:

2. Use Virtual Environments in Development

Always activate the virtual environment when developing:

3. Update Dependencies Carefully

When updating dependencies:
  1. Update requirements.txt
  2. Run mage deps ensure to create a new environment
  3. Test thoroughly before deploying

4. Monitor Disk Usage

Virtual environments can consume significant disk space. Use the cleanup command to remove stale environments:

5. Handle Dependency Conflicts

If you encounter dependency conflicts:
  1. Try without --override-global-version first (uses global constraints)
  2. If that fails, retry with --override-global-version
  3. Review the conflict and adjust requirements.txt if needed

Troubleshooting

Environment Not Found After Creation

Symptom: mage deps ensure succeeds but environment doesn’t exist Solution: Check for validation failures in logs. The environment may have been created but failed validation and was cleaned up.

Slow Environment Creation

Symptom: Creating environments takes a long time Possible causes:
  • Network issues downloading packages
  • Many packages to install
  • Slow disk I/O
Solutions:
  • Install uv for faster installation: pip install uv
  • Check network connectivity
  • Review requirements.txt for unnecessary packages

Permission Errors

Symptom: Cannot create virtual environment due to permission errors Solution: Ensure you have write permissions to the Mage data directory:

Stale Lock Files

Symptom: Lock acquisition timeout errors persist Solution: Manually remove stale lock files:

Technical Details

Fingerprint Algorithm

The fingerprint is computed as follows:

Requirements Normalization

Requirements are normalized before fingerprinting:
  • Leading/trailing whitespace stripped from each line
  • Empty lines removed
  • Comments (lines starting with #) removed
  • Order preserved
This ensures that cosmetic changes to requirements.txt don’t trigger new environment creation.

Lock File Semantics

  • .install.lock: Exclusive lock preventing concurrent installation/creation of environment
  • .activate.lock: Shared lock indicating environment is actively being used
  • .cleanup.lock: Global lock preventing simultaneous cleanup operations across all environments
  • global.lock: Snapshot of globally installed packages at environment creation time (used as constraints)
  • venv.lock: Snapshot of packages installed in the virtual environment (for diff analysis)

See Also