← Back to Pull requests

Read flow parameter schemas from source without running it #117

Merged
chrisguidry merged 7 files (1063 lines) on Nov 24, 2026 19:15 UTC
View on GitHub
chrisguidry chrisguidry commented on Nov 24, 2026 17:16 UTC
Author

prefect-cloud deploy --from owner/repo downloads the flow file from GitHub and builds its parameter schema from the source. To do that it ran exec on every top-level class, function, and assignment in the file and eval on each parameter annotation and default, so deploying a repository ran that repository's module-level code on the deploying machine, with the user's Prefect and GitHub credentials.

The schema is now read statically. The file's absolute imports still resolve against installed modules, enum and pydantic model classes are rebuilt from their declarations, and annotations and defaults go through a small evaluator that allows literals, names, public attributes, subscripts, |, and calls to value constructors like datetime.date and pydantic.Field. Anything else is treated as unknown, as failed evaluation was before: annotations fall back to untyped and defaults to None. Models built by calling a function, such as create_model(...), are now untyped in the schema. This also pins astral-sh/setup-uv to a commit SHA.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KgFwsYjZswhNsDNRNKw1Ej

Diff: 1063 lines (+572 / -491) across 7 files Reviewer: zangell44 Review duration: 119m
All Vouch review confidence checks passed
Residual risk 0.07 = Change Risk (0.52) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 1063 lines diff across 7 files
0.52
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.82 · 3 substantive comment(s)
0.82
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
86%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
6 items
chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 24, 2026 17:16 UTC
Bot

<!-- codex-pull-request-review-summary -->
<!-- codex-review-state:v1 {"code_review":{"commit_sha":"7bf1d1ecf7c4b451950d07c91902751b093424db","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

<details>
<summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

This comment shows the latest Codex review activity on this pull request.

| Review | Status | Commit | Review trigger |
| --- | --- | --- | --- |
| 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-24T17:18:56.492240Z">2026-11-24T17:18:56.492240Z</relative-time> | 7bf1d1e | PR opened |

<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 24, 2026 17:18 UTC
    Code Review
    src/prefect_cloud/utilities/source_signature.py:1
    @@ -0,0 +1,361 @@
    +"""
    +Reads a function's signature from Python source code without running the source.
    +
    +`prefect-cloud deploy` builds a flow's parameter schema from a file it downloads
    +from GitHub, which may be someone else's code.  Running any part of that file
    +would run it on the deploying machine with the user's credentials, so the file
    +is only parsed.  Its absolute imports are resolved against installed modules,
    +enum and pydantic model classes are rebuilt from their field declarations, and
    +annotations and default values are evaluated by `SourceNamespace.evaluate`,
    +which permits literals, names, public attributes, subscripts, `|`, and calls to
    +a fixed set of value constructors.  Anything else counts as unknown: an unknown
    +annotation becomes `inspect.Parameter.empty`, and an unknown default becomes
    +`None`.
    +"""
    +
    +import ast
    +import builtins
    +import datetime
    +import decimal
    +import enum
    +import importlib
    +import inspect
    +import pathlib
    +import uuid
    +from logging import Logger, getLogger
    +from typing import Any, Optional
    +
    +import pydantic
    +
    +logger: Logger = getLogger(__name__)
    +
    +# Calling these with literal arguments only builds a value, so a default like
    +# `datetime.date(2025, 1, 1)` or `Field(default=1)` can be evaluated safely.
    +VALUE_CONSTRUCTORS: tuple[Any, ...] = (
    +    bool,
    +    bytes,
    +    complex,
    +    dict,
    +    float,
    +    frozenset,
    +    int,
    +    list,
    +    set,
    +    str,
    +    tuple,
    +    datetime.date,
    +    datetime.datetime,
    +    datetime.time,
    +    datetime.timedelta,
    +    datetime.timezone,
    +    decimal.Decimal,
    +    pathlib.Path,
    +    pathlib.PurePath,
    +    pathlib.PurePosixPath,
    +    pathlib.PureWindowsPath,
    +    uuid.UUID,
    +    pydantic.Field,
    +)
    +
    +
    +class UnknownExpression(Exception):
    +    """An expression uses something `SourceNamespace.evaluate` does not permit."""
    +
    +
    +class SourceNamespace:
    +    """The module-level names of a source file, resolved without running it."""
    +
    +    def __init__(self, module: ast.Module):
    +        self.names: dict[str, Any] = {}
    +        # Classes rebuilt from this file; calling them only validates field values.
    +        self.rebuilt_classes: list[type] = []
    +        for node in module.body:
    +            self._bind(node)
    +
    +    def _bind(self, node: ast.stmt) -> None:
    +        if isinstance(node, ast.Import):
    +            for alias in node.names:
    +                self._bind_import(alias)
    +        elif isinstance(node, ast.ImportFrom):
    +            # Relative imports would need the rest of the repository, which
    +            # was not downloaded.
    +            if node.level == 0 and node.module:
    +                for alias in node.names:
    +                    self._bind_import_from(node.module, alias)
    +        elif isinstance(node, ast.ClassDef):
    +            self.names[node.name] = self._rebuild_class(node)
    +        elif isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None:
    +            # Module-level assignments are how type aliases and constants used
    +            # in signatures are defined, e.g. `Number = Union[int, float]`.
    +            targets = node.targets if isinstance(node, ast.Assign) else [node.target]
    +            names = [target.id for target in targets if isinstance(target, ast.Name)]
    +            try:
    +                value = self.evaluate(node.value)
    +            except UnknownExpression:
    +                for name in names:
    +                    self.names.pop(name, None)
    +            else:
    +                for name in names:
    +                    self.names[name] = value
    +
    +    def _bind_import(self, alias: ast.alias) -> None:
    +        bound_name = alias.asname or alias.name.split(".")[0]
    +        try:
    +            module = importlib.import_module(alias.name)
    +            if not alias.asname:
    +                # `import a.b` binds `a`
    +                module = importlib.import_module(bound_name)
    +        except Exception as e:
    +            logger.debug("Failed to import %s: %s", alias.name, e)
    +            return
    +        self.names[bound_name] = module
    +
    +    def _bind_import_from(self, module_name: str, alias: ast.alias) -> None:
    +        if alias.name == "*":
    +            return
    +        try:
    +            module = importlib.import_module(module_name)
    +            if hasattr(module, alias.name):
    +                value = getattr(module, alias.name)
    +            else:
    +                value = importlib.import_module(f"{module_name}.{alias.name}")
    +        except Exception as e:
    +            logger.debug("Failed to import %s from %s: %s", alias.name, module_name, e)
    +            return
    +        self.names[alias.asname or alias.name] = value
    +
    +    def _rebuild_class(self, node: ast.ClassDef) -> type:
    +        bases = [base for base in map(self._try_evaluate, node.bases) if base]
    +        try:
    +            if enum_base := _first_subclass(bases, enum.Enum):
    +                rebuilt = self._rebuild_enum(node, enum_base, bases)
    +            elif model_base := _first_subclass(bases, pydantic.BaseModel):
    +                rebuilt = self._rebuild_model(node, model_base)
    +            else:
    +                return type(node.name, (), {})
    +        except Exception as e:
    +            logger.debug("Failed to rebuild class %s: %s", node.name, e)
    +            return type(node.name, (), {})
    +        self.rebuilt_classes.append(rebuilt)
    +        return rebuilt
    +
    +    def _rebuild_enum(
    +        self, node: ast.ClassDef, enum_base: type[enum.Enum], bases: list[Any]
    +    ) -> type:
    +        members: dict[str, Any] = {}
    +        for statement in node.body:
    +            if (
    +                isinstance(statement, ast.Assign)
    +                and len(statement.targets) == 1
    +                and isinstance(statement.targets[0], ast.Name)
    +            ):
    +                value = self._try_evaluate(statement.value)
    +                if value is not None:

    <sub><sub>!P2 Badge</sub></sub> Preserve enum members whose value is None

    When a source enum legitimately declares a member such as UNSET = None, _try_evaluate successfully returns None, but this condition treats that value as an evaluation failure and omits the member. Any flow parameter using that enum then receives a schema without the null choice, and a default such as Status.UNSET can no longer be resolved from the rebuilt enum. Use a distinct sentinel for failed evaluation so valid None-valued members remain in the schema.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 24, 2026 17:18 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 7bf1d1ecf7

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    chrisguidry chrisguidry commented on code on Nov 24, 2026 17:27 UTC
    Code Review
    src/prefect_cloud/utilities/source_signature.py:1
    @@ -0,0 +1,361 @@
    +"""
    +Reads a function's signature from Python source code without running the source.
    +
    +`prefect-cloud deploy` builds a flow's parameter schema from a file it downloads
    +from GitHub, which may be someone else's code.  Running any part of that file
    +would run it on the deploying machine with the user's credentials, so the file
    +is only parsed.  Its absolute imports are resolved against installed modules,
    +enum and pydantic model classes are rebuilt from their field declarations, and
    +annotations and default values are evaluated by `SourceNamespace.evaluate`,
    +which permits literals, names, public attributes, subscripts, `|`, and calls to
    +a fixed set of value constructors.  Anything else counts as unknown: an unknown
    +annotation becomes `inspect.Parameter.empty`, and an unknown default becomes
    +`None`.
    +"""
    +
    +import ast
    +import builtins
    +import datetime
    +import decimal
    +import enum
    +import importlib
    +import inspect
    +import pathlib
    +import uuid
    +from logging import Logger, getLogger
    +from typing import Any, Optional
    +
    +import pydantic
    +
    +logger: Logger = getLogger(__name__)
    +
    +# Calling these with literal arguments only builds a value, so a default like
    +# `datetime.date(2025, 1, 1)` or `Field(default=1)` can be evaluated safely.
    +VALUE_CONSTRUCTORS: tuple[Any, ...] = (
    +    bool,
    +    bytes,
    +    complex,
    +    dict,
    +    float,
    +    frozenset,
    +    int,
    +    list,
    +    set,
    +    str,
    +    tuple,
    +    datetime.date,
    +    datetime.datetime,
    +    datetime.time,
    +    datetime.timedelta,
    +    datetime.timezone,
    +    decimal.Decimal,
    +    pathlib.Path,
    +    pathlib.PurePath,
    +    pathlib.PurePosixPath,
    +    pathlib.PureWindowsPath,
    +    uuid.UUID,
    +    pydantic.Field,
    +)
    +
    +
    +class UnknownExpression(Exception):
    +    """An expression uses something `SourceNamespace.evaluate` does not permit."""
    +
    +
    +class SourceNamespace:
    +    """The module-level names of a source file, resolved without running it."""
    +
    +    def __init__(self, module: ast.Module):
    +        self.names: dict[str, Any] = {}
    +        # Classes rebuilt from this file; calling them only validates field values.
    +        self.rebuilt_classes: list[type] = []
    +        for node in module.body:
    +            self._bind(node)
    +
    +    def _bind(self, node: ast.stmt) -> None:
    +        if isinstance(node, ast.Import):
    +            for alias in node.names:
    +                self._bind_import(alias)
    +        elif isinstance(node, ast.ImportFrom):
    +            # Relative imports would need the rest of the repository, which
    +            # was not downloaded.
    +            if node.level == 0 and node.module:
    +                for alias in node.names:
    +                    self._bind_import_from(node.module, alias)
    +        elif isinstance(node, ast.ClassDef):
    +            self.names[node.name] = self._rebuild_class(node)
    +        elif isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None:
    +            # Module-level assignments are how type aliases and constants used
    +            # in signatures are defined, e.g. `Number = Union[int, float]`.
    +            targets = node.targets if isinstance(node, ast.Assign) else [node.target]
    +            names = [target.id for target in targets if isinstance(target, ast.Name)]
    +            try:
    +                value = self.evaluate(node.value)
    +            except UnknownExpression:
    +                for name in names:
    +                    self.names.pop(name, None)
    +            else:
    +                for name in names:
    +                    self.names[name] = value
    +
    +    def _bind_import(self, alias: ast.alias) -> None:
    +        bound_name = alias.asname or alias.name.split(".")[0]
    +        try:
    +            module = importlib.import_module(alias.name)
    +            if not alias.asname:
    +                # `import a.b` binds `a`
    +                module = importlib.import_module(bound_name)
    +        except Exception as e:
    +            logger.debug("Failed to import %s: %s", alias.name, e)
    +            return
    +        self.names[bound_name] = module
    +
    +    def _bind_import_from(self, module_name: str, alias: ast.alias) -> None:
    +        if alias.name == "*":
    +            return
    +        try:
    +            module = importlib.import_module(module_name)
    +            if hasattr(module, alias.name):
    +                value = getattr(module, alias.name)
    +            else:
    +                value = importlib.import_module(f"{module_name}.{alias.name}")
    +        except Exception as e:
    +            logger.debug("Failed to import %s from %s: %s", alias.name, module_name, e)
    +            return
    +        self.names[alias.asname or alias.name] = value
    +
    +    def _rebuild_class(self, node: ast.ClassDef) -> type:
    +        bases = [base for base in map(self._try_evaluate, node.bases) if base]
    +        try:
    +            if enum_base := _first_subclass(bases, enum.Enum):
    +                rebuilt = self._rebuild_enum(node, enum_base, bases)
    +            elif model_base := _first_subclass(bases, pydantic.BaseModel):
    +                rebuilt = self._rebuild_model(node, model_base)
    +            else:
    +                return type(node.name, (), {})
    +        except Exception as e:
    +            logger.debug("Failed to rebuild class %s: %s", node.name, e)
    +            return type(node.name, (), {})
    +        self.rebuilt_classes.append(rebuilt)
    +        return rebuilt
    +
    +    def _rebuild_enum(
    +        self, node: ast.ClassDef, enum_base: type[enum.Enum], bases: list[Any]
    +    ) -> type:
    +        members: dict[str, Any] = {}
    +        for statement in node.body:
    +            if (
    +                isinstance(statement, ast.Assign)
    +                and len(statement.targets) == 1
    +                and isinstance(statement.targets[0], ast.Name)
    +            ):
    +                value = self._try_evaluate(statement.value)
    +                if value is not None:

    Fixed in https://github.com/PrefectHQ/prefect-cloud/commit/06d085216ecb3c59656cfc096effc2e51679e1ab: enum members are now skipped only when their value can't be evaluated, so UNSET = None is kept, with a test.

    ---
    Posted by Claude Opus 5.5 on behalf of @chrisguidry.
    <!-- monitor-pr -->

    zangell44 zangell44 approved these changes on Nov 24, 2026 19:15 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    chrisguidry chrisguidry
    Labels
    risk: low confidence: 86% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 51.8% (MEDIUM) · Higher = larger blast radius
    51.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86% · Lower = rushed or shallow review
    86%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.2% · Safe to merge
    7.2%