Skip to content

feat(sdk/python): AST based analysis to introspect - #11803

Merged
tiborvass merged 31 commits into
dagger:mainfrom
eunomie:sdk-python-ast-analyzer
Apr 22, 2026
Merged

tiborvass merged 31 commits into
dagger:mainfrom
eunomie:sdk-python-ast-analyzer

Conversation

@eunomie

@eunomie eunomie commented Feb 5, 2026 •

Copy link
Copy Markdown
Member

This PR replaces the runtime analysis for the Python SDK to an AST based one.

Context: when the Python SDK wants to run a Python module, it starts by analysing the user module source code. This allows to find the types and functions exposed by the module, that is used in two different phases:

  • to register those types to the engine (so the schema is extended by them, allowing them to be called)
  • when a function is called so the python SDK knows the types to instanciate, functions to call, values to send back, etc

Right now, this happen at runtime, by loading the module code. The module code is loaded, and it will be analysed.

The problem is this analysis must happen without to load the code. This is required to allow self calls. Self calls means the code must be able to call itself. There's a chicken and egg issue there, where the code must used generated code based... on the code.

To make it clearer, look at this self call code in Go (as it doesn't yet exist in python):

type Test struct{}

func (m *Test) ContainerEcho(stringArg string) *dagger.Container {
	return dag.Container().From("alpine:latest").WithExec([]string{"echo", stringArg})
}

func (m *Test) Print(ctx context.Context, stringArg string) (string, error) {
	return dag.Test().ContainerEcho(stringArg).Stdout(ctx)
}

In the Print function it calls dag.Test() (that is "self") and then the ContainerEcho() function.
To generate this binding, the SDK must know ContainerEcho is a thing. This means this code is valid only if it knows the function exposed.

In python, the equivalent code should be something like that:

@object_type
class Test:
    @function
    def container_echo(self, string_arg: str) -> dagger.Container:
        return dag.container().from_("alpine:latest").with_exec(["echo", string_arg])

    @function
    def print(self, string_arg: str) -> str:
        return dag.test().container_echo(string_arg).stdout()

With the current python implementation, this will break as the code is loaded. But at the time the code is loaded, it doesn't know dag.test() is a thing.
We need to do:

  • first analyse the code to find test object with container_echo and print functions
  • generate the code exposed by the engine based on those types
  • load the code when needed to call the functions

All that to say we must analyse the code before it's loaded.

And to do that, we need to completely change the way the code is analysed, moving to an AST based analysis instead of loading the code and looking at it. That's what this PR is doing.

This is a big one. And one way to ensure this is good is to rely on the extensive test suite we have. As everything is green on this side, we could be quite confident on the result.

Note

Next step will be to plug that into the moduleTypes of the SDK, preparing the work for self calls

@eunomie
eunomie force-pushed the sdk-python-ast-analyzer branch 9 times, most recently from bdf0e10 to 34ea005 Compare February 19, 2026 16:16
@eunomie
eunomie force-pushed the sdk-python-ast-analyzer branch 8 times, most recently from ec59d18 to 5dda763 Compare March 3, 2026 17:47
@eunomie
eunomie marked this pull request as ready for review March 3, 2026 23:04
@eunomie
eunomie requested a review from a team as a code owner March 3, 2026 23:04
@grouville
grouville self-requested a review March 4, 2026 01:36
@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@github-actions

Copy link
Copy Markdown
Contributor

This PR was closed because it has been stalled for 7 days with no activity.

@github-actions github-actions Bot closed this Mar 26, 2026
@grouville grouville reopened this Apr 8, 2026
@grouville grouville added this to the v0.20.5 milestone Apr 8, 2026
@grouville
grouville force-pushed the sdk-python-ast-analyzer branch 2 times, most recently from f19b45d to 531f445 Compare April 8, 2026 23:51
@eunomie

eunomie commented May 5, 2026

Copy link
Copy Markdown
Member Author

Isn't this a breaking change ?

@vaz-ar I don't think. It should be fully transparent. The implementation changed, but the behaviour should be identical. That's why for instance none of the integration tests have been impacted.

Or did you spot some use cases where it broke?

@vaz-ar

vaz-ar commented May 5, 2026

Copy link
Copy Markdown

Yes I had some issues yesterday when upgrading, someone had made a module that used inheritance to split the code across multiple files, and most of the functions where not accessible anymore.
But that might be that this was not a good pattern to use and it was working because of this "bug" 😄

@eunomie

eunomie commented May 5, 2026

Copy link
Copy Markdown
Member Author

@vaz-ar Could you please open a new discussion on the topic https://github.com/dagger/dagger/discussions/categories/help ?
That way it will be easier to investigate and keep track of it. If you have an example or available traces that would be really helpful.

eunomie added a commit to eunomie/dagger that referenced this pull request May 5, 2026
Closes dagger#13089

PR dagger#11803 (v0.20.7) replaced the runtime introspection-based analyzer
with a static AST parser. The previous code relied on
inspect.getmembers(), which walks the Python MRO and naturally
discovers @function-decorated methods inherited from base classes.
The AST parser only walks node.body, missing every inherited method.

Constructor inheritance was already handled via
_find_inherited_constructor; mirror that pattern with
_find_inherited_functions so @function methods follow the same MRO
traversal. Walks node.bases recursively, skips names already defined
on the child (overrides win), and uses a visited set for cycle
safety. Inherited functions are parsed with the child's class_name
so Self annotations resolve to the child type, matching runtime
behavior.

_find_class_def is split so callers can also recover the parent's
file path; inherited functions are then parsed against that path so
location metadata points at the actual definition site.

Tests:
- AST analyzer unit tests cover the issue repro, child override, and
  multi-level (grandparent) inheritance.
- New TestInheritance/inherited functions integration test mirrors
  the issue's "Steps to reproduce" through inspectModuleObjects.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 5, 2026
…pection

Codifies the AST analyzer's correctness invariant:
*"the schema we derive statically must match what
``typing.get_type_hints`` plus ``inspect`` would have computed at
runtime."* If the runtime path was the trusted source of truth before
the AST refactor (dagger#11803), it should still be — modulo a tiny set of
documented exceptions where the AST analyzer is intentionally stricter
or less lenient.

Three new files in ``sdk/python/tests/mod/``:

- ``_runtime_introspect.py`` imports a Python source as a real module
  and produces ``ModuleMetadata`` from runtime objects (``get_type_hints``
  for resolution, ``dataclasses.fields`` for fields, ``__dagger_function__``
  marker for functions). Test infrastructure only — never on the
  production analyzer path.
- ``_differential.py`` provides ``assert_metadata_equivalent`` which
  diffs two ``ModuleMetadata`` instances structurally and raises a
  focused error message naming the path of the first divergence.
- ``test_differential.py`` is the corpus: 20 fixtures covering every
  pattern the AST analyzer follow-up addressed (aliased dagger
  imports, type aliases incl. PEP 695 + chained, Optional[Annotated],
  inheritance with dataclass-like and undecorated bases,
  @staticmethod, Self return, list[T] / Optional[list[T]], IntEnum,
  decorator name overrides). Patterns where the two paths
  intentionally diverge (function-call defaults the AST can't
  evaluate statically) are kept as ``xfail`` markers so a behavior
  change there fires a notification rather than going unnoticed.

This caught one real over-eager-AST bug during development (inherited
fields on undecorated bases), fixed in the previous patch.

Future patterns the analyzer should handle land here as another
fixture. The comparator scales: every new fixture is a new
correctness assertion for free.

Signed-off-by: Yves Brissaud <[email protected]>
tiborvass added a commit to tiborvass/dagger that referenced this pull request May 5, 2026
)"

This reverts commit bcb2193.

Despite the welcome speed gains, it is not ready for general availability
due to gaps in feature coverage.

Signed-off-by: Tibor Vass <[email protected]>
tiborvass added a commit to tiborvass/dagger that referenced this pull request May 5, 2026
)"

This reverts commit bcb2193.

Despite the welcome speed gains, it is not ready for general availability
due to gaps in feature coverage.

Signed-off-by: Tibor Vass <[email protected]>
tiborvass added a commit to tiborvass/dagger that referenced this pull request May 5, 2026
)"

This reverts commit bcb2193.

Despite the welcome speed gains, it is not ready for general availability
due to gaps in feature coverage.

Signed-off-by: Tibor Vass <[email protected]>
tiborvass added a commit to tiborvass/dagger that referenced this pull request May 5, 2026
)"

This reverts commit bcb2193 from dagger#11803.

Despite the welcome speed gains, it is not ready for general availability due to gaps in feature coverage.

Signed-off-by: Tibor Vass <[email protected]>
tiborvass added a commit to tiborvass/dagger that referenced this pull request May 5, 2026
)"

This reverts commit bcb2193 from dagger#11803.

Despite the welcome speed gains, it is not ready for general availability due to gaps in feature coverage.

Signed-off-by: Tibor Vass <[email protected]>
tiborvass added a commit to tiborvass/dagger that referenced this pull request May 5, 2026
)"

This reverts commit bcb2193 from dagger#11803.

Despite the welcome speed gains, it is not ready for general availability due to gaps in feature coverage.

Signed-off-by: Tibor Vass <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
Closes dagger#13089

PR dagger#11803 (v0.20.7) replaced the runtime introspection-based analyzer
with a static AST parser. The previous code relied on
inspect.getmembers(), which walks the Python MRO and naturally
discovers @function-decorated methods inherited from base classes.
The AST parser only walks node.body, missing every inherited method.

Constructor inheritance was already handled via
_find_inherited_constructor; mirror that pattern with
_find_inherited_functions so @function methods follow the same MRO
traversal. Walks node.bases recursively, skips names already defined
on the child (overrides win), and uses a visited set for cycle
safety. Inherited functions are parsed with the child's class_name
so Self annotations resolve to the child type, matching runtime
behavior.

_find_class_def is split so callers can also recover the parent's
file path; inherited functions are then parsed against that path so
location metadata points at the actual definition site.

Tests:
- AST analyzer unit tests cover the issue repro, child override, and
  multi-level (grandparent) inheritance.
- New TestInheritance/inherited functions integration test mirrors
  the issue's "Steps to reproduce" through inspectModuleObjects.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
The AST analyzer matched decorator and field-call names against a fixed
allow-list (``{"object_type", "dagger.object_type", "mod.object_type"}``
etc.). Anything the user wrote that didn't match by literal name was
silently dropped:

- ``import dagger as d`` + ``@d.object_type`` — class never registered.
- ``from dagger import object_type as ot`` + ``@ot`` — class never
  registered.
- ``from dagger import field as fld`` + ``x: T = fld(...)`` — field
  never collected.

Build a per-file ``DaggerAliases`` (``visitors/decorators.py``) that
tracks which names are bound to the dagger package and which bare
names map to which canonical decorator/field, and resolve every
decorator AST node through that map. The bare ``field`` name still
goes through ``_bare_field_is_dagger`` to keep ``from dataclasses
import field`` rejected; explicit aliases are trusted because the
import statement was unambiguous.

Closes dagger#11803 follow-up gaps A1, A2, F2.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
``_parse_parameters`` always treated ``i == 0`` as the implicit receiver
and skipped it. ``@staticmethod`` has no implicit receiver, so the
first positional argument was silently dropped from the schema (with a
spurious "first parameter is named X (expected self/cls); skipping it
as the receiver" warning).

``is_staticmethod()`` already existed in ``visitors/decorators.py`` but
was unused. Branch on it to decide whether to skip the first parameter.

Closes dagger#11803 follow-up gap A3.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
``from .x import *`` was silently skipped — neither the imported names
nor the originating module were tracked. Decorated classes are still
discovered via cross-file declaration scanning, but module-level
constants and type aliases imported via star imports never reach the
analyzer's per-file maps, so users see schema differences from runtime
without any indication why.

Emit a clear warning at the call site so the user knows the import is
not expanded and can replace it with explicit names.

Closes dagger#11803 follow-up gap B1.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
PEP 695 (Python 3.12+) introduced a dedicated ``ast.TypeAlias`` node
for the ``type Source = ...`` statement. ``_collect_module_constants``
only iterated ``ast.Assign`` and ``ast.AnnAssign``, so PEP 695 aliases
never made it into ``_module_type_aliases`` and were silently treated
as opaque object types — the same failure mode the legacy alias path
fixed in dagger#13093.

Add an explicit ``ast.TypeAlias`` branch that registers the alias
under the same alias map. ``_expand_alias`` then walks PEP 695 aliases
through chains and the existing cycle protection, so all the existing
alias machinery applies.

Closes dagger#11803 follow-up gap C1.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
PR dagger#13093 made module-level type aliases work, but its alias map was
keyed per-file: ``Source = Annotated[dagger.Directory, …]`` defined in
``types.py`` and imported via ``from .types import Source`` in
``main.py`` was not expanded — the analyzer fell back to treating
``Source`` as an opaque object type and the ``DefaultPath`` metadata
was dropped.

Track which names each file brought in via relative imports
(``_collect_relative_imports``) and follow those edges in
``_expand_alias`` so cross-file aliases resolve. Cycle protection now
keys on ``(file, name)`` rather than just ``name`` so the same alias
name can appear in multiple files without false-positive cycle stops.

The relative-import-target resolver maps the AST level + module path
to a concrete parsed file (``.py`` or ``__init__.py``) and is
best-effort — if the target isn't in the parsed set (third-party
package, dynamic ``__path__``), the entry is omitted and existing
warn-and-stub behavior takes over.

Closes dagger#11803 follow-up gap C2.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
``_eval_constant`` only looked at ``_module_constants`` for the current
file. A common multi-file pattern — ``from .constants import DEFAULT``
followed by ``def f(name: str = DEFAULT)`` — would fall through to the
warn path and the analyzer would record the *literal name string*
``"DEFAULT"`` as the default value, which then got JSON-shipped to the
engine instead of the real default.

Reuse the relative-import-origins map built for cross-file aliases to
look up the constant in the source file. Switch ``_current_file`` for
the recursion so any nested name references inside the constant
resolve against the foreign file's own constants, not the importer's.

Closes dagger#11803 follow-up gap B3.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
``_eval_constant`` only consulted module-level constants (and, with
the previous patch, cross-file constants). A reference like
``def hello(self, name: str = DEFAULT)`` where ``DEFAULT`` is defined
inside the class body (``class Foo: DEFAULT = "x"``) fell through to
the warn path and the default became the literal name ``"DEFAULT"``.

Index class-body assignments lazily per ``(file, class_name)`` and
look them up first when the analyzer is parsing inside that class.
Resolution order now matches Python's: class scope, then module,
then cross-file imports. Class scope is bounded to the parsed class
so a ``DEFAULT`` on ``Foo`` doesn't leak into ``Bar``'s defaults.

Closes dagger#11803 follow-up gap C3.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
``extract_annotated_metadata`` only matched ``Annotated[…]`` at the
outermost level. Common idiomatic wrappings dropped the metadata:

- ``Optional[Annotated[Directory, DefaultPath(".")]]``
- ``Annotated[Directory, DefaultPath(".")] | None``
- ``Union[Annotated[Directory, DefaultPath(".")], None]``

All three are semantically the same nullable-Directory shape. The
DefaultPath/Doc/Name/Ignore/Deprecated annotations got silently
dropped, and users had to remember the one specific spelling
``Annotated[Directory | None, DefaultPath(".")]`` (Annotated outermost)
to keep their metadata.

Add ``find_annotated`` that walks through nullable wrappers to locate
an inner ``Annotated`` node. Generic containers (``list[Annotated[…]]``)
are intentionally not traversed — element-level metadata doesn't apply
to the parameter as a whole, and silently lifting it would surprise
users in the opposite direction. The list-element case is covered by
a regression test.

Closes dagger#11803 follow-up gaps D1, D2.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
The resolver previously fell through to a silent fallback for several
types Dagger has no representation for:

- ``Literal["a", "b"]`` — produced ``object/typing.Literal['a', 'b']``,
  which the engine cannot honor.
- ``dict[K, V]`` / ``Dict[K, V]`` / ``Mapping[K, V]`` /
  ``MutableMapping[K, V]`` — produced an ``object`` TypeDef with the
  full unparsed string as its name.
- ``TypeVar`` instances — fell through to the final ``str(t)`` branch,
  giving a TypeDef name like ``"~T"``.
- PEP 695 ``class Foo[T]:`` and ``def echo[T]():`` — same outcome via
  the ``T`` forward-reference path.
- ``class Foo(Generic[T]):`` — same.

Raise ``TypeResolutionError`` with an explicit explanation in each
case. Failing at ``dagger develop`` time with a clear pointer beats
shipping a broken schema.

Closes dagger#11803 follow-up gaps D3, D4, D5.

Signed-off-by: Yves Brissaud <[email protected]>
eunomie added a commit to eunomie/dagger that referenced this pull request May 6, 2026
``_eval_constant`` returns ``None`` for any expression it doesn't model
(function calls, subscripts, lambdas, ternaries, f-strings, comprehen-
sions, etc.). The caller registers ``has_default=True`` regardless, so
the schema records ``default=None`` even when the user wrote
``name = os.environ.get("HOME", "x")`` — the runtime applies the real
default but the schema disagrees.

Emit a warning at the unparseable expression so users see why their
default disappeared. The behaviour is otherwise unchanged: the runtime
still applies the actual default when the caller omits the argument
and the type is nullable; for non-nullable types ``registration.py``
already marks the typedef optional and omits the default from the
engine input so the runtime can fill it in.

Closes dagger#11803 follow-up gaps E1, E2.

Signed-off-by: Yves Brissaud <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants