Repository navigation
feat(sdk/python): AST based analysis to introspect - #11803
Conversation
bdf0e10 to
34ea005
Compare
ec59d18 to
5dda763
Compare
|
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. |
|
This PR was closed because it has been stalled for 7 days with no activity. |
f19b45d to
531f445
Compare
@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? |
|
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. |
|
@vaz-ar Could you please open a new discussion on the topic https://github.com/dagger/dagger/discussions/categories/help ? |
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]>
…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]>
)" 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]>
)" 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]>
)" 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]>
)" 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]>
)" 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]>
)" 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]>
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]>
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]>
``_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]>
``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]>
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]>
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]>
``_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]>
``_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]>
``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]>
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]>
``_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]>
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:
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):
In the
Printfunction it callsdag.Test()(that is "self") and then theContainerEcho()function.To generate this binding, the SDK must know
ContainerEchois 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:
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:
testobject withcontainer_echoandprintfunctionsAll 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
moduleTypesof the SDK, preparing the work for self calls