pyinfra icon indicating copy to clipboard operation
pyinfra copied to clipboard

Heavy import overhead stemming from Pyinfra's API

Open Dexmachi opened this issue 8 months ago • 6 comments

Hey, first of all, ty guys for the amazing tool! I am currently using Pyinfra's API to build an automation platform akin to Ansible, and couldn't be happier with the results your lib has been providing!

While I was profiling my own tool with python -X importtime, I've noticed a big bottleneck coming from the Pyinfra components I was using, and even Click being imported (I use argparse for performance, so I was kind of stumped)

the actual issue

While using Pyinfra's API natively (without its CLI), importing some utilities forces the eager loading of almost the entire Pyinfra stack. For example, simply importing a specific fact or operation pulls in:

  • click
  • All available facts and operations (even unrelated ones)

This adds a somewhat big latency for the startup time, which reduces the theoretical advantage Pyinfra has over Ansible by being able to import specific modules instead of all modules

Steps to reproduce

1: Context: I'm using this base class to call pyinfra in a loop to manage different roles (for instance, packages and users)

from abc import ABC, abstractmethod
from typing import Any

from chaos.lib.args.dataclasses import Delta, ResultPayload


class Role(ABC):
    """
    Each role must implement the "get_context", "delta" and "plan" methods to define
        its behavior and interactions for system management and orchestration.

    get_context: This method should return the necessary data and information present
        in the system for the specific context of the role.

    delta: This method should calculate what it needs to do to achieve its goals based
        on the current context and the desired state.

    plan: This method should only stack the actions needed in pyinfra operations to achieve
        the desired state.
    """

    def __init__(
        self,
        name: str,
        needs_secrets: bool = False,
        necessary_chobolo_keys: list[str] = [],
        necessary_secret_dict_keys: list[str] = [],
    ):
        self.name = name
        self.necessary_chobolo_keys = necessary_chobolo_keys
        self.needs_secrets = needs_secrets
        self.necessary_secret_dict_keys = necessary_secret_dict_keys

    def get_context(
        self, state, host, chobolo: dict = {}, secrets: dict[str, Any] = {}
    ) -> dict[str, Any]:
        """
        Optional method to implement for roles that require context data from the system.

        Get the context for the role.
        This method should be implemented by subclasses to return the necessary data and
            information present in the system for the specific context of the role.

        Args:
            chobolo (dict): The current state of the system as represented in the Chobolo.
                It contains only the keys specified in the "necessary_chobolo_keys" attribute of the role
                merged with the secret keys specified in the "necessary_secret_dict_keys" attribute of the role.
            secrets (dict): The secrets required for the role, if any.
            state: Pyinfra state object.
            host: Pyinfra host object.

        Returns:
            dict: A dictionary containing the context for the role.
        """
        return {}

    def delta(self, context: dict[str, Any] = {}) -> Delta:
        """
        Optional method to implement for roles that require calculating a delta to achieve their goals.

        Calculate the delta for the role.

        This method should be implemented by subclasses to calculate what it needs to do to
            achieve its goals based on the current context and the desired state.

        Args:
            context (dict): The context for the role, as returned by the get_context method.

        Returns:
            Delta: A Delta object containing the actions needed to achieve the desired state.
        """

        return Delta(to_add={}, to_remove={}, metadata={})

    @abstractmethod
    def plan(self, state, host, delta: Delta = Delta()) -> ResultPayload:
        """
        Plan the actions needed to achieve the desired state.
        This method should be implemented by subclasses to stack the actions needed in
        pyinfra operations to achieve the desired state.

        Args:
            delta (Delta): The delta for the role, as returned by the delta method.
            state: Pyinfra state object.
            host: Pyinfra host object.

        Returns:
            ResultPayload: A ResultPayload object containing the result of the operation addition process
                including relevant data.
        """

        return ResultPayload(success=False, message=[], error=[], data={})

2: Targeted imports

from pyinfra.api.operation import add_op
from pyinfra.facts.files import Directory
from pyinfra.facts.server import Command
from pyinfra.operations import server

# steps to build the op
# add_op(state, server.shell, commands="pacman -S ...")

Even with this targeted approach, the entire pyinfra module tree is imported

Evidence:

Evidence: I have attached the complete importtime log. The section under my own "chaos.lib.roles.Role" initialization shows the cascading imports of the entire pyinfra.facts.* and pyinfra.operations.* modules, alongside click.

pyinfra_imports.txt

Suggestions:

I would strongly suggest that Pyinfra adopts a more "lazy" approach to imports, PEP 810 is expected to be added in py3.15, which will implement the "lazy from/import" language usage, which can help, but the implementation of a lazier approach beforehand can help people using py3.11>= (which is the pyinfra range of usage)

alongside this, I believe that the lib might be closely coupled to the click library, since it has no other reason to be imported by my tool, so trying to decouple that might be very beneficial!

I would be glad to work this out and maybe help with this, but I am not that good of a programmer

Dexmachi avatar Mar 15 '26 16:03 Dexmachi

Additional context:

I am currently setting Pyinfra up like such:

def setup_pyinfra(payload: ApplyPayload) -> ResultPayload[State | None]:
    """
    Set up the pyinfra state and inventory based on the gathered fleet configuration, and establish connections to the target hosts.

    parameters:
        - payload: the ApplyPayload containing the gathered data for the apply operation, including fleet configuration and sudo password.

    returns:
        - ResultPayload indicating the success or failure of the pyinfra setup process, with any error messages in the error field.
            Additionally, if successful, the ResultPayload.data field will contain the initialized pyinfra State object that is ready
            for executing plans.
    """

    import logging
    import time

    from pyinfra.api.config import Config
    from pyinfra.api.connect import connect_all
    from pyinfra.api.state import State, StateStage
    from pyinfra.context import ctx_state

    from .telemetry import ChaosTelemetry

    try:
        inventory, _, parallels = _setup_hosts(payload)

        config = Config(
            PARALLEL=parallels,
            DIFF=payload.logbook,
        )

        state = State(inventory, config)
        state.current_stage = StateStage.Prepare

        start_time = time.time()

        if payload.logbook:
            limani_result = _resolve_limani(payload.global_config, payload)
            if not limani_result.success:
                return ResultPayload(
                    success=False,
                    message=[],
                    error=[
                        f"Error resolving limani for telemetry: {limani_result.error}"
                    ],
                    data=None,
                )

            if not limani_result.data:
                return ResultPayload(
                    success=False,
                    message=[],
                    error=["No limani specified for telemetry."],
                    data=None,
                )

            ChaosTelemetry.load_limani_plugin(limani_result.data, payload.global_config)

            state.add_callback_handler(ChaosTelemetry())
            pyinfra_logger = logging.getLogger("pyinfra")
            pyinfra_logger.setLevel(logging.DEBUG)
            handler = ChaosTelemetry.PyinfraFactLogHandler()
            pyinfra_logger.addHandler(handler)
            ChaosTelemetry.start_run()

        ctx_state.set(state)

        password = payload.password
        state.config.SU_PASSWORD = password
        state.config.SUDO_PASSWORD = password

        connect_all(state)

        end_time = time.time()
        setup_duration = end_time - start_time

        if payload.logbook:
            ChaosTelemetry.record_setup_phase(state, setup_duration)
            _collect_fleet_health(state, stage="pre_operations")

        return ResultPayload(success=True, message=[], error=[], data=state)
    except Exception as e:
        return ResultPayload(
            success=False,
            message=[],
            error=[f"Error setting up pyinfra: {str(e)}"],
            data=None,
        )

and tearing it down like this:

def teardown_pyinfra(
    payload: ApplyPayload, run_status: Literal["success", "failure"]
) -> ResultPayload[dict[str, Any]]:
    """
    Teardown the pyinfra state and connections after the apply operation is complete.

    Should be used inside of a finally block to ensure all connections will be properly closed.
    parameters:
        - payload: the ApplyPayload containing the pyinfra state to be torn down.

    returns:
        - ResultPayload indicating the success or failure of the pyinfra teardown process, with any error messages in the error field.
    """

    from pyinfra.api.connect import disconnect_all

    try:
        if payload.logbook:
            from .telemetry import ChaosTelemetry

            if payload.export_logs:
                ChaosTelemetry.export_report()
            if payload.pyinfra_state:
                _collect_fleet_health(payload.pyinfra_state, stage="post_operations")
            ChaosTelemetry.end_run(run_status)

        if payload.pyinfra_state:
            disconnect_all(payload.pyinfra_state)
        return ResultPayload(success=True, message=[], error=[], data={})
    except Exception as e:
        return ResultPayload(
            success=False,
            message=[],
            error=[f"Error tearing down pyinfra: {str(e)}"],
            data={},
        )

I do not know if I am doing something wrong, but I followed the documentation as closely as possible to do both of these

Dexmachi avatar Mar 15 '26 17:03 Dexmachi

🤨 I suspect you're hitting https://github.com/pyinfra-dev/pyinfra/blob/3.x/src/pyinfra/facts/init.py + https://github.com/pyinfra-dev/pyinfra/blob/3.x/src/pyinfra/operations/init.py both of which import all the facts/operations, all to support calling them like operations.server.shell for example.

But that won't scale, as we add more ops/facts it'll just get slower and slower. IIRC ~10 years ago this was added for documentation generation but that's no longer necessary. Supporting the operations.server.shell style of use is nice I think? But probably not worth it.

Fizzadar avatar Mar 16 '26 10:03 Fizzadar

Agreed 100%!

Do you think there's an easy fix?

I mean, I understand how it might be awful to change how the entire op+facts are imported, but I honestly do believe it would be the best interest for everyone to do something like this, since, like you said, it doesn't scale well for multiple op/facts

I've been looking at the latest codebase and found this:

1: this code was found inside of pyinfra.facts.init and pyinfra.operations.init, which is probably the culprit of the importtime going through the roof:

# This file only exists to support:
# from pyinfra import facts
# facts.X.Y

from glob import glob
from os import path

module_filenames = glob(path.join(path.dirname(__file__), "*.py"))
module_names = [path.basename(name)[:-3] for name in module_filenames]
__all__ = [name for name in module_names if name != "__init__"]

from . import *  # noqa

2: additionally, looking through of pyinfra.api.init, it forces the eager loading of a lot of different modules, which may not be needed in more common runs:

from .command import FileDownloadCommand  # noqa: F401 # pragma: no cover
from .command import (  # noqa: F401
    FileUploadCommand,
    FunctionCommand,
    MaskString,
    QuoteString,
    RsyncCommand,
    StringCommand,
)
from .config import Config  # noqa: F401 # pragma: no cover
from .deploy import deploy  # noqa: F401 # pragma: no cover
from .exceptions import DeployError  # noqa: F401 # pragma: no cover
from .exceptions import (  # noqa: F401
    FactError,
    FactTypeError,
    FactValueError,
    FactProcessError,
    InventoryError,
    OperationError,
    OperationTypeError,
    OperationValueError,
)
from .facts import FactBase, ShortFactBase  # noqa: F401 # pragma: no cover
from .host import Host  # noqa: F401 # pragma: no cover
from .inventory import Inventory  # noqa: F401 # pragma: no cover
from .operation import operation  # noqa: F401 # pragma: no cover
from .state import BaseStateCallback, State  # noqa: F401 # pragma: no cover

3: also, I found the place where click is being imported:

pyinfra.api.utils uses click in:

def print_host_combined_output(host: "Host", output: "CommandOutput") -> None:
    for line in output:
        if line.buffer_name == "stderr":
            logger.error(f"{host.print_prefix}{click.style(line.line, 'red')}")
        else:
            logger.error(f"{host.print_prefix}{line.line}")

def log_operation_start(
    op_meta: "StateOperationMeta", op_types: Optional[List] = None, prefix: str = "--> "
) -> None:
    op_types = op_types or []
    if op_meta.global_arguments["_serial"]:
        op_types.append("serial")
    if op_meta.global_arguments["_run_once"]:
        op_types.append("run once")

    args = ""
    if op_meta.args:
        args = "({0})".format(", ".join(str(arg) for arg in op_meta.args))

    logger.info(
        "{0} {1} {2}".format(
            click.style(
                "{0}Starting{1}operation:".format(
                    prefix,
                    " {0} ".format(", ".join(op_types)) if op_types else " ",
                ),
                "blue",
            ),
            click.style(", ".join(op_meta.names), bold=True),
            args,
        ),
    )

def log_error_or_warning(
    host: "Host",
    ignore_errors: bool,
    description: str = "",
    continue_on_error: bool = False,
    exception: Exception | None = None,
) -> None:
    log_func = logger.error
    log_color = "red"
    log_text = "Error: " if description else "Error"

    if ignore_errors:
        log_func = logger.warning
        log_color = "yellow"
        log_text = (
            "Error (ignored, execution continued)" if continue_on_error else "Error (ignored)"
        )
        if description:
            log_text = f"{log_text}: "

    if exception:
        exc = exception.__cause__ or exception
        exc_text = "{0}: {1}".format(type(exc).__name__, exc)
        log_func(
            "{0}{1}".format(
                host.print_prefix,
                click.style(exc_text, log_color),
            ),
        )

    log_func(
        "{0}{1}{2}".format(
            host.print_prefix,
            click.style(log_text, log_color),
            description,
        ),
    )

def log_host_command_error(host: "Host", e: Exception, timeout: int | None = 0) -> None:
    if isinstance(e, timeout_error):
        logger.error(
            "{0}{1}".format(
                host.print_prefix,
                click.style(
                    "Command timed out after {0}s".format(
                        timeout,
                    ),
                    "red",
                ),
            ),
        )

    elif isinstance(e, (socket_error, SSHException)):
        logger.error(
            "{0}{1}".format(
                host.print_prefix,
                click.style(
                    "Command socket/SSH error: {0}".format(format_exception(e)),
                    "red",
                ),
            ),
        )

    elif isinstance(e, IOError):
        logger.error(
            "{0}{1}".format(
                host.print_prefix,
                click.style(
                    "Command IO error: {0}".format(format_exception(e)),
                    "red",
                ),
            ),
        )

    # Still here? Re-raise!
    else:
        raise e

also, in pyinfra.api.host, in

    def print_prefix(self) -> str:
        if self.nested_executing_op_hash:
            return "{0}[{1}] {2}{3} ".format(
                click.style(""),  # reset
                click.style(self.name, bold=True),
                click.style("nested", "blue"),
                self.print_prefix_padding,
            )

        return "{0}[{1}]{2} ".format(
            click.style(""),  # reset
            click.style(self.name, bold=True),
            self.print_prefix_padding,
        )

    def style_print_prefix(self, *args, **kwargs) -> str:
        return "{0}[{1}]{2} ".format(
            click.style(""),  # reset
            click.style(self.name, *args, **kwargs),
            self.print_prefix_padding,
        )

    def log_styled(
        self, message: str, log_func: Callable[[str], Any] = logger.info, **kwargs
    ) -> None:
        message_styled = click.style(message, **kwargs)
        self.log(message_styled, log_func=log_func)

    def connect(self, reason=None, show_errors: bool = True, raise_exceptions: bool = False):
        """
        Connect to the host using it's configured connector.
        """

        self._check_state()
        if not self.connected:
            self.state.trigger_callbacks("host_before_connect", self)

            try:
                self.connector.connect()
            except ConnectError as e:
                if show_errors:
                    log_message = "{0}{1}".format(
                        self.print_prefix,
                        click.style(e.args[0], "red"),
                    )
                    logger.error(log_message)

                self.state.trigger_callbacks("host_connect_error", self, e)

                if raise_exceptions:
                    raise
            else:
                log_message = "{0}{1}".format(
                    self.print_prefix,
                    click.style("Connected", "green"),
                )
                if reason:
                    log_message = "{0}{1}".format(
                        log_message,
                        " ({0})".format(reason),
                    )

                logger.info(log_message)
                self.state.trigger_callbacks("host_connect", self)
                self.connected = True

This, ideally, should not be here

I'd say that you guys can keep the best of both. If you need to generate documentation for the project, you can keep this code (not the click being imported one, that should be inside of a CLI utils module) inside of a dev branch and clean up the main branch, since most people wouldn't ever even try to use pyinfra-dev-branch, this would be mitigated

Dexmachi avatar Mar 16 '26 11:03 Dexmachi

hey, so

apparently, all of the functions that need click to work are way easier to fix!

they are quite localized, used in little to no places, the hardest thing will be removing the use of these libs in facts and operations (they are kind of coupled with these functions as well)

all files that use these functions

  • pyinfra.api.facts
  • pyinfra.api.operation
  • pyinfra.api.operations

Dexmachi avatar Mar 16 '26 11:03 Dexmachi

🤨 I suspect you're hitting https://github.com/pyinfra-dev/pyinfra/blob/3.x/src/pyinfra/facts/init.py + https://github.com/pyinfra-dev/pyinfra/blob/3.x/src/pyinfra/operations/init.py both of which import all the facts/operations, all to support calling them like operations.server.shell for example.

But that won't scale, as we add more ops/facts it'll just get slower and slower. IIRC ~10 years ago this was added for documentation generation but that's no longer necessary. Supporting the operations.server.shell style of use is nice I think? But probably not worth it.

I think I've got it to work without it being a breaking change in https://github.com/pyinfra-dev/pyinfra/pull/1609/

Dexmachi avatar Mar 16 '26 17:03 Dexmachi

This issue has been closed by #1609 and #1616

Dexmachi avatar Apr 03 '26 18:04 Dexmachi