Repository navigation
fix(sdk/python): align AST module analyzer with typing.get_type_hints - #13095
Merged
Merged
Conversation
This comment was marked as outdated.
This comment was marked as outdated.
This was referenced May 5, 2026
Move the existing inheritance subtest out of TestDocs into a dedicated TestInheritance suite so future inheritance-related tests have a clear home. Pure refactor - no behavior change. Renames "inheritance" to the more specific "inherited create constructor" since it tests inheritance of the create() classmethod constructor. Signed-off-by: Yves Brissaud <[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]>
`from . import x` raised ValueError because importlib was called with an empty module name; `from .x import y` and other relative forms silently fell through to importlib, where they would either error or bind the wrong top-level module. Detect ImportFrom.level > 0 and bind the imported names as stubs without dispatching through importlib. Cross-file decorated classes are still resolved via add_declared_type, so type annotations referencing them keep working. Signed-off-by: Yves Brissaud <[email protected]>
Module-level type aliases like
Source = Annotated[dagger.Directory, dagger.DefaultPath(".")]
were silently mishandled. The resolver fell through ``_resolve_name``
and warn-assumed ``Source`` was an opaque object type, while
``extract_annotated_metadata`` saw only ``Name("Source")`` and dropped
``DefaultPath`` along with the rest of the ``Annotated`` payload.
Collect type-shaped top-level assignments into a per-file alias map
and expand the alias before metadata extraction and resolution at every
annotation entry point (field, class assignment, function parameter,
return type). The surface annotation string still keeps the alias name
so the user-facing representation is unchanged. Chained aliases are
followed; a visited-set guards against cycles.
Signed-off-by: Yves Brissaud <[email protected]>
eunomie
force-pushed
the
sdk-python-ast-follow-up
branch
2 times, most recently
from
May 6, 2026 05:48
0a976f2 to
97ded3d
Compare
…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. A companion ``runtime_introspect_package(files, main, …)`` accepts a dict keyed by relative path, materialises a temporary package with a unique name, imports it as a real top-level package via ``importlib``, walks every submodule for decorated classes, then tears down ``sys.modules`` cleanly so repeated runs don't leak. - ``_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. The single-source helper ``_both`` covers 20 fixtures over 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). The multi-file helper ``_both_pkg`` runs ``analyze_module`` against the same tree the runtime imports and adds 7 fixtures for shapes that need a real package on disk: cross-file type alias, cross-file constant default, inherited field across files, relative import of a decorated class, chained alias across files, subpackage discovery, PEP 695 ``type Source = …`` defined in one file used in another. Patterns where the two paths intentionally diverge (function-call defaults the AST can't evaluate statically) are kept as ``xfail`` markers so a behaviour change there fires a notification rather than going unnoticed. This caught one real over-eager-AST bug during development (inherited fields on undecorated bases). Future patterns the analyzer should handle land here as another fixture; the comparator scales. Signed-off-by: Yves Brissaud <[email protected]>
…g.py patterns Surveyed cpython's ``Lib/test/test_typing.py`` for user-facing annotation shapes that could plausibly land in a Dagger module, and added focused differential fixtures plus one kitchen-sink combined fixture. New coverage: - Forward refs (string annotations) in ``Optional[…]``, ``list[…]``, inside ``Annotated[…]``, and across class definitions (forward reference to a class declared later in the file). - ``from __future__ import annotations`` — every annotation is a string; both paths must still agree. - ``typing.Annotated`` qualified, ``typing_extensions.Annotated``, ``from typing import Annotated as A`` aliased. - Multi-metadata ``Annotated[T, Doc, Name, Deprecated]`` and the ``Ignore`` form. Nested ``Annotated[Annotated[T, X], Y]`` paired with the analyzer fix in the previous patch. - ``typing.Optional`` qualified, ``typing.Union[X, None]``, ``None | X``, ``from typing import Optional as Opt``. - Container spellings: ``typing.List``, ``typing.Sequence``, ``collections.abc.Sequence``, ``tuple[T, ...]``. - ``Self`` in ``list[Self]`` and ``Optional[Self]``; ``typing.Self`` qualified. - Decorator argument shapes: ``@function()``, ``@function(name="…", deprecated="…")``. - ``dagger.field(default=list)`` (callable default), ``init=False``, ``name="alt"``, ``deprecated="…"``. - ``InitVar``, negative-int defaults, ``bytes`` parameters, ``dagger.JSON`` / ``dagger.Platform`` scalar return types. - ``test_diff_kitchen_sink`` — a single realistic-looking module combining many of the above. Reads as documentation: any single divergence is localised by the comparator's path-prefixed diff. Several fixtures use syntax that only parses on a specific Python release: ``typing.Self`` (3.11+), PEP 695 ``type X = …`` (3.12+). Mark them with ``requires_py311`` / ``requires_py312`` ``pytest.mark.skipif`` decorators so the SDK's CI matrix (3.10/3.11/3.12/3.13/3.14) exercises each gated pattern on every Python that can run it and cleanly skips on older ones. PEP 604 ``X | None``, ``from __future__ import annotations`` and bare ``Annotated`` / ``Optional`` / ``list[T]`` work on 3.10+ and stay ungated. Helper change: ``_runtime_introspect`` now calls a field's ``default_factory`` to materialise the default value (matching the AST analyzer's name_map special-case for ``list``/``dict``). Without this the runtime side reported ``None`` for ``dagger.field(default= list)`` while the AST reported ``[]``. Test count: 53 differential fixtures + 1 kitchen sink, all passing, 1 documented xfail (function-call defaults). Signed-off-by: Yves Brissaud <[email protected]>
A Hypothesis strategy that generates Dagger module source from a recursive grammar of supported shapes — base types (str/int/float/bool/bytes plus the dagger object types, ``dagger.JSON``, ``dagger.Platform``), Optional / ``X | None`` / ``list[T]`` wrappers composed up to depth 3, ``Annotated[T, …]`` with multi-item metadata (Doc, Name, Deprecated, plus DefaultPath / Ignore on ``dagger.Directory`` where they're semantically valid), plausible defaults — and a single property test that runs the AST analyzer and the runtime introspector on every generated module and asserts their ``ModuleMetadata`` outputs match. Grammar features driven through the recursive ``_type_expr`` generator: - Deeply nested wrappers (``Optional[list[Annotated[…]]]``, ``list[list[T]]``, ``Annotated[list[T], …]``, etc.). - Module-level type aliases (``Source = Annotated[…]``) and PEP 695 ``type X = …`` aliases (3.12+) at module scope, available for use by generated parameters. - Forward references (``"Foo"``) at the leaves of subscripts, gated on a ``from __future__ import annotations`` toggle. - A randomly-included ``Helper`` ``@dagger.object_type`` class plus a coin flip on whether ``Foo`` inherits from it (exercising the inherited-fields and inherited-functions code paths). - A ``__future__`` annotations toggle, exercising both the string-annotation and eager-evaluation paths. The default profile runs 50 examples (CI-fast); ``--hypothesis-profile=thorough`` runs 500. Property runs at 50 / 500 / 2000 examples are all green. Two divergences caught during development: - ``bytes`` defaults (``b""``) survive at runtime but the AST analyzer's JSON-serialiser rejects them and warns. Documented and excluded from the strategy (``bytes`` parameters are still generated, just without defaults) — known AST limitation, not a regression. - ``None | X`` ordering and ``"Foo" | None`` produce invalid Python outside / inside ``__future__`` annotations respectively. Both shapes are omitted from the grammar with a comment explaining why; the patterns themselves are still exercised through the static fixtures in ``test_differential.py``. The strategy is intentionally narrow: it never generates patterns the analyzer explicitly rejects (Literal, dict, TypeVar, …) or known divergent ones (function-call defaults). That keeps the property test on the agreed-equivalence path. As the analyzer covers more ground, the grammar grows. 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]>
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. The alias map was also keyed per-file: ``Source = Annotated[…]`` 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 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 behaviour takes over. ``ast.TypeAlias`` itself only exists on Python 3.12+; accessing it on 3.10 / 3.11 raises ``AttributeError`` and crashed every test against the analyzer at module-constants collection. Resolve the attribute once at import time via ``getattr(ast, "TypeAlias", None)`` and short-circuit the ``isinstance`` check on that. PEP 695 source can't be parsed by the older ``ast`` module anyway, so the branch is genuinely a no-op there. Test fixtures that pass PEP 695 source strings to ``analyze_source_string`` (``test_ast_pep695_*``) are gated with a ``@requires_py312`` marker so they don't ``SyntaxError`` at parse time on 3.10 / 3.11. ``dagger call python-sdk python-{310, 311,312,313,314} unit`` all green. Closes dagger#11803 follow-up gaps C1, C2. Signed-off-by: Yves Brissaud <[email protected]>
…tated metadata
``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.
``typing.Annotated`` also flattens nested forms at runtime —
``Annotated[Annotated[T, X], Y]`` is identical to
``Annotated[T, X, Y]``. The AST analyzer was treating the inner
``Annotated`` as the "base type" and only extracting the *outer*
metadata, so a pattern like
NestedSource = Annotated[
Annotated[dagger.Directory, DefaultPath(".")],
Doc("source dir"),
]
silently dropped ``DefaultPath`` from the schema while keeping
``Doc``. Recurse ``extract_annotated_metadata`` when the base type is
itself Annotated and merge the inner metadata; outer metadata still
wins for attributes both layers set. This was caught by the new
differential test corpus (the runtime side flattens via ``typing``;
the AST didn't).
Closes dagger#11803 follow-up gaps D1, D2.
Signed-off-by: Yves Brissaud <[email protected]>
…data
Surfaced by a one-off corpus run against five real-world repos
(misty-step/thinktank, interTwin-eu/itwinai, …) that converged on
the same readability pattern:
SOURCE_IGNORE = [".git", "node_modules", "_build", ".cache"]
@function
async def build(
self,
source: Annotated[
dagger.Directory,
Ignore(SOURCE_IGNORE), # <- name reference
Doc(SOURCE_DOC), # <- name reference
],
) -> dagger.Container: ...
The runtime resolved both names through the module's own globals
(``typing.get_type_hints`` plus the regular Python lookup chain) and
got the real list / string. The AST analyzer's metadata extractors
in ``visitors/annotations.py`` only honoured literal arguments —
``ast.Constant``, ``ast.List`` — and silently returned ``None`` for
anything else. So the user's careful ``Ignore`` list disappeared
from the schema.
Same root cause as the cross-file constants fix (B3) but in a
different position: not parameter defaults, but Annotated metadata
arguments.
Thread an optional ``ConstantResolver`` callback through
``extract_annotated_metadata``, ``_extract_single_metadata``,
``_extract_string_arg`` and ``_extract_list_arg``. The parser passes
``self._eval_constant`` so the resolver consults the same
class-scope / module-scope / cross-file-import chain that already
works for parameter defaults. Unresolvable references (e.g.
``from third_party import EXTERNAL_PATTERNS``) leave the field
``None`` rather than crashing — same lenient fallback as before.
Tests:
- 4 new analyzer-side unit tests in ``test_ast_analyzer.py`` covering
``Ignore(NAME)``, ``Doc(NAME)``, ``DefaultPath(NAME)``, and the
unresolvable-name fallback.
- 1 differential fixture in ``test_differential.py`` with the exact
shape the corpus uncovered, asserting AST and runtime now agree.
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`` only looked at ``_module_constants`` for the current file. Two common patterns fell through to the warn path and the analyzer recorded the *literal name string* as the default, which then got JSON-shipped to the engine instead of the real default: - Cross-file: ``from .constants import DEFAULT`` followed by ``def f(name: str = DEFAULT)``. - Class-body: ``class Foo: DEFAULT = "x"`` with ``def hello(self, name: str = DEFAULT)``. For cross-file references, 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. For class-body references, index 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 gaps B3, C3. 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]>
``enum.auto()`` produces different values depending on the enum base class: 1, 2, 3 for ``IntEnum``, the lowercase member name for ``StrEnum``, and an implementation-defined integer for ``Enum``. The AST analyzer can't run user code, so it has no way to predict any of these — it was silently falling back to the member name string, producing a schema that disagreed with whatever the runtime returned. Detect both ``auto()`` and ``enum.auto()`` call shapes and emit a clear warning telling users to use explicit values (``MEMBER = "value"`` or ``MEMBER = 1``) so the schema matches the runtime. The fallback (member name) is preserved so existing modules keep loading; the warning is the change. ``IntEnum`` with explicit integer values (``LOW = 1``) already produces the correct ``"1"`` string-form via the ``ast.Constant`` branch — covered now by an explicit regression test. Closes dagger#11803 follow-up gap E3. Signed-off-by: Yves Brissaud <[email protected]>
``Optional[Annotated[dagger.Directory, DefaultPath(".")]] = None`` —
a common shape for ``--src`` arguments where the engine fills the
directory from the call context — was failing at registration with
``cannot set more than one default value``. The AST analyzer was
sending both:
- ``default_value = JSON("null")`` (because ``has_default=True`` from
the ``= None`` literal and the type is optional)
- ``default_path = "."`` (from the ``DefaultPath`` metadata)
The engine treats both as defaults and rejects the conflict.
``DefaultPath`` / ``DefaultAddress`` are engine-side context-aware
defaults — they take precedence over a Python ``= None`` literal,
which is just the optional-marker idiom. When either is set, drop
the redundant ``default_value`` so only one default reaches the
engine. The type's ``is_optional`` is already conveyed via
``_resolved_type_to_typedef``, so no extra ``with_optional`` is
needed.
Caught by the ``Optional[Annotated[...]] metadata recursion``
integration subtest; verified by the full ``TestPython`` suite
running against the dev engine.
Signed-off-by: Yves Brissaud <[email protected]>
PR dagger#13090 fixed inherited ``@function`` methods but left ``dagger.field()`` declarations on base classes invisible — ``_extract_class_members`` only iterated the child's ``node.body``. A ``class Child(Base):`` where ``Base`` declared ``name: str = dagger.field(default="x")`` would have an empty ``fields=[]`` and an auto-derived constructor with no ``name`` parameter, diverging from how ``dataclasses.fields()`` walks the MRO at runtime. Mirror the ``_find_inherited_functions`` pattern with ``_find_inherited_fields`` that walks ``node.bases`` recursively (visited set, override wins, parsed against the child's class name so ``Self`` resolves correctly). The walker emits both the FieldMetadata and the matching constructor ParameterMetadata so the auto-derived ``__init__`` picks up the inherited fields too. The walker is gated on ``_is_dataclass_like`` — at runtime, dagger fields flow through ``dataclasses.fields(cls)``, which only inherits from base classes that are themselves dataclasses (i.e. ``@dagger.object_type`` / ``@dagger.interface``, which apply ``dataclass`` internally, or an explicit ``@dataclass``). An undecorated base's annotations are *not* promoted to fields on the child. Without the gate, the analyzer claimed otherwise and produced phantom fields the engine wouldn't actually expose; the new differential test suite caught the divergence and a new ``test_ast_undecorated_base_does_not_inherit_fields`` locks in the correct behaviour. Closes dagger#11803 follow-up gap F1. 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]>
…kages ``_collect_package_files`` quietly skipped any subdirectory whose name starts with ``_``. The Python convention is for ``_internal/`` etc. to hold private helpers, but users do drop ``@dagger.object_type`` declarations there and then spend time wondering why those types don't show up in ``dagger functions``. When such a directory contains ``.py`` files, log a warning that points at the path, lists the file count, and suggests renaming. ``__pycache__`` is the one underscore name we silently skip — it never contains user code. Closes dagger#11803 follow-up gap G1. Signed-off-by: Yves Brissaud <[email protected]>
…c args Three patterns the AST analyzer used to drop on the floor without any indication to the user: - ``@property`` methods inside an ``@object_type`` class. Properties need runtime evaluation to materialise a value; the analyzer can't expose them, but it can tell the user instead of silently leaving them out of the schema. - Nested ``@object_type`` / ``@interface`` / ``@enum_type`` classes. ``_collect_declaration_names`` is intentionally top-level-only — registering the inner class would leave a dangling type reference. Warn so users know to move the class to module scope. - Variadic args (``*args`` / ``**kwargs``). These have no Dagger API representation; previously they were silently dropped, which made for confusing "where did my parameter go?" debugging. Each warning includes the file, line, class, and the specific name that was dropped. Closes dagger#11803 follow-up gaps G2, H1, H2. Signed-off-by: Yves Brissaud <[email protected]>
…rozen list The resolver hardcoded the names of dagger object/scalar/enum types in three module-level sets. Anything added to the dagger SDK after the list was last touched fell through to the "warn and assume object" fallback — which by accident gave the right ``kind=object`` result for real object types like ``Changeset`` / ``Binding`` / ``LLM``, but emitted noisy "Unresolved type X; assuming it is an object type" warnings on every analysis. For real-world Daggerverse modules (angie, daggie, monty, speck, goose, …) this fired ~10 warnings per module — pure noise pointing at nothing actionable. Replace the frozen lists with a one-shot reflection on the imported ``dagger`` package: any class subclassing ``dagger.client.base.Type`` becomes an object, ``Scalar`` → scalar, ``Enum`` → enum. The original hardcoded names stay as a fallback for environments where ``dagger`` itself can't be imported (stub-only installs). Effect on the test suites: - 291/291 unit + differential + property tests still pass. - All 18 Daggerverse modules in the corpus test pass *silently* now — the per-module ``Changeset`` warnings disappear without any behavioural change. - ``Changeset``, ``Binding``, ``LLM``, and 50+ other types known to the dagger package are now first-class in the resolver. Caught by the daggerverse-corpus test in the previous patch (which flagged the noise even though there was no functional divergence). Signed-off-by: Yves Brissaud <[email protected]>
Pulls every Python module from ``https://github.com/telchak/daggerverse`` (18 modules at the time of writing — calver, semver, gcp-*, daggie, monty, speck, etc.) and runs the AST analyzer + runtime introspector on each, asserting the two ``ModuleMetadata`` outputs match. This is the "what users actually write" half of the confidence story, complementary to the static fixtures and the Hypothesis property test. Implementation notes: - Corpus is cloned once per session (depth=1) into a tmp dir. Override the ref with ``DAGGERVERSE_CORPUS_REF`` (default: ``main``); reuse a pre-cloned tree with ``DAGGERVERSE_CORPUS_PATH``; skip entirely with ``SKIP_DAGGERVERSE_CORPUS=1`` for offline development. - Underscore-prefixed sibling packages (``_agent_base``) are added to ``sys.path`` so modules that depend on them via ``[tool.uv.sources]`` can be imported by the runtime introspector. - Each module's failure (if any) is reported with the divergent member's path, so a CI failure tells you exactly which type or parameter regressed and on which module. The current corpus passes cleanly. Adding this test guards against any future regression that would silently mismatch a real-world module — a class of bug a synthetic fixture can't catch by definition. Signed-off-by: Yves Brissaud <[email protected]>
…atch annotations) Pure formatting + suppressions; no behaviour change. Signed-off-by: Yves Brissaud <[email protected]>
A single integration test (``TestPython/TestASTFollowUp``) that walks through patterns the AST analyzer used to drop or mishandle, end-to-end against a dev engine. Each subtest is a ``dagger call`` against a real function so the AST analyzer's schema, the engine's validation, and the runtime dispatch all have to agree. Anything that survives an integration run here is what a real user actually sees. Coverage: - Aliased ``import dagger as d`` plus ``from dagger import object_type as ot, function as fn, field as fld`` → ``dagger call hello`` + ``dagger call echo``. - Inherited ``@function`` across MRO (undecorated base; only the function walker fires, not the field walker) → ``dagger call shout`` + ``dagger call whisper``. - ``@staticmethod`` first parameter survives → ``dagger call shout --msg=hi``. - Class-body constants used as parameter defaults → ``dagger call hello``. - ``IntEnum`` with explicit integer values registers correctly → ``dagger call name-of --p=HIGH``. - Multi-file: cross-file constant default via ``from .helpers import DEFAULT_NAME`` → ``dagger call hello``. - ``Literal[…]`` is rejected at registration time with a clear error (assert non-zero exit; the actual error message lives in the engine logs, not the container stderr, so the unit suite's ``test_ast_literal_type_is_rejected`` carries the message check). The unit suite under ``sdk/python/tests/mod/test_ast_analyzer.py`` remains the primary safety net (228 tests). The integration test catches the engine-side half — that the schema we register is one the engine actually accepts and the runtime can dispatch. All 7 subtests pass against the dev engine; the full ``TestPython`` suite passes too. Signed-off-by: Yves Brissaud <[email protected]>
eunomie
force-pushed
the
sdk-python-ast-follow-up
branch
from
May 6, 2026 10:05
97ded3d to
9302419
Compare
TomChv
approved these changes
May 7, 2026
TomChv
left a comment
Member
There was a problem hiding this comment.
LGTM, we discussed about few nit in dm (GH was bugged) but these are resolved.
The tests looks good and given number of tests done, I think it's quite safe to merge.
Regarding the workspace branch, will this create conflict or you can do it now?
| } | ||
| # Canonical names of dagger decorators (and ``field``, which is also matched | ||
| # through the same alias machinery for the ``x: T = field()`` shape). | ||
| DAGGER_DECORATOR_NAMES: frozenset[str] = frozenset( |
Member
Author
We should not have conflicts, but as it has already been reverted in |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #13097.
Closes #13089.
What this fixes
When the Python SDK switched in v0.20.7 from running your code to reading it as text only (#11803), the new reader stopped recognising several Python patterns. Modules that worked in v0.20.6 started registering the wrong types or skipping parts of the schema.
Three follow-up PRs (#13090, #13091, #13093) fixed the most-reported shapes. This PR cherry-picks them and adds 15 more focused fixes for everything a wider audit of the analyzer turned up.
The fixes cover:
import dagger as d,from dagger import object_type as ot,from dagger import field as fld),@staticmethodfirst-parameter handling.type X = …, cross-file (from .types import Source), nestedAnnotated[Annotated[T, X], Y].Optional[Annotated[…]],Annotated[…] | None,Union[Annotated[…], None].@functionmethods walk MRO;dagger.field()declarations walk MRO when the base is itself dataclass-like (@object_type/@interface/@dataclass).Literal[…],dict[K, V],Mapping[K, V],TypeVar, PEP 695 generics,Generic[T]all fail now with a clear message instead of silently producing a broken schema.enum.auto(), star imports, underscore-prefixed packages, nested@object_type,@property,*args/**kwargs).daggerpackage instead of a frozen hardcoded set, so newly added types (Changeset,Binding,LLM, …) resolve cleanly.How we know it's right
The analyzer's correctness invariant is: its output must match what
typing.get_type_hintsplusinspectwould have computed at runtime. This PR adds three layers of test that lock that in:typing.Self3.11+, PEP 695type X = …3.12+) are gated withpytest.mark.skipif, so the SDK's existing 3.10–3.14 CI matrix exercises each pattern on every Python that can actually run it.--hypothesis-profile=thoroughruns 500.telchak/daggerverse(18 modules: calver, semver, gcp-*, daggie, monty, …) and runs the same diff. All pass.Test count: 175 → 291 passing + 1 documented xfail (function-call defaults the AST can't statically evaluate; the runtime sees the actual value).
How to review
The 25 commits are organized as a structure-first, behavior-second narrative — the test harness lands before the fixes it verifies, fixes are grouped by domain, and each commit is atomic (compiles + tests pass on its own). Read top-to-bottom for a guided tour.
Cherry-picks (1–4) — already-reviewed foundation
test(python): extract TestInheritance from TestDocsfix(sdk/python): discover @function methods inherited from base classes(fix(sdk/python): discover @function methods inherited from base classes #13090)fix(sdk/python): handle relative imports in AST analyzer(fix(sdk/python): handle relative imports in AST analyzer #13091)fix(sdk/python): handle module-level type aliases in AST analyzer(fix(sdk/python): handle module-level type aliases in AST analyzer #13093)These landed in their own PRs first; they're carried here as the foundation for everything else. Skip if you reviewed them already.
Test infrastructure (5–7) — the safety net
test(sdk/python): differential testing AST analyzer vs runtime introspection— adds_runtime_introspect.pyandassert_metadata_equivalent; 27 fixtures (single-source + multi-file).test(sdk/python): broaden differential corpus from cpython test_typing.py patterns— +34 fixtures from cpython's typing test patterns + version markers.test(sdk/python): property-based testing of AST analyzer with Hypothesis— recursive grammar; thorough run = 500 examples, all green.These land before the fixes so every subsequent commit can be verified by the harness. Reviewing this section first makes the rest reviewable in isolation.
Fixes — grouped by domain
Decorator/declaration detection (8–9) — how the analyzer finds Dagger decorations:
resolve aliased dagger decorators and field() callspreserve first parameter of @staticmethod functionsType resolution (10–13) — how the analyzer interprets type expressions:
expand PEP 695 and cross-file type aliases(3.10/3.11 guarded)drill through Optional/Union and flatten nested Annotated metadataresolve module-level constants inside Annotated metadatareject types Dagger does not support outrightDefaults (14–17) — parameter default values:
resolve named constants used as default valueswarn when a default expression can't be evaluatedwarn on enum.auto()drop redundant default_value when default_path is setInheritance (18):
walk MRO for inherited dagger.field() declarations— gated on dataclass-like bases.Discovery surface (19–22) — what the analyzer warns about / discovers:
warn on unsupported star importswarn when discovery skips underscore-prefixed subpackageswarn on @property, nested decorated classes, variadic argsdiscover dagger types from the live packageValidation (23–25)
test(sdk/python): differential test against telchak/daggerverse corpus— real-world modules.chore(sdk/python): satisfy ruff— pure formatting + suppressions, no behaviour change.test(python): integration test exercising AST analyzer follow-up fixes—dagger callend-to-end against a dev engine.Where the code lives
sdk/python/src/dagger/mod/_analyzer/parser.py— per-file alias maps, MRO walking, dynamic defaults, type-alias resolution, rejected-types.sdk/python/src/dagger/mod/_analyzer/visitors/— alias-aware decorator name matching, recursiveAnnotatedmetadata extraction.sdk/python/src/dagger/mod/_analyzer/resolver.py— live dagger-types reflection.sdk/python/tests/mod/— the three test layers above.Each commit message has a "what was wrong / what's fixed" pair plus a gap reference (
Closes #11803 follow-up gap X) where applicable.Test plan
pytest sdk/python/tests/mod/— 291 passing.go vet ./core/integration/...— clean.ruff checkandruff format --check— clean.