From 892f7f8075000d122737f7623fa9cfde236146d9 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 14:19:55 +0000 Subject: [PATCH 01/20] mod: key interface call args by Python name A call through one of the module's own interfaces binds its arguments by their Python names, but looked their schema names up by the API name, so an argument renamed with Name() or a trailing underscore (from_) failed with a KeyError. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- sdk/src/dagger/mod/_converter.py | 4 +++- sdk/tests/mod/test_interfaces.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/sdk/src/dagger/mod/_converter.py b/sdk/src/dagger/mod/_converter.py index 470fa539..643c370d 100644 --- a/sdk/src/dagger/mod/_converter.py +++ b/sdk/src/dagger/mod/_converter.py @@ -102,8 +102,10 @@ def make_method(name: str, func: Function, proto: type) -> typing.Callable: # n # Need to convert names to GraphQL convention for query builder gql_name = to_camel_case(name) + # Keyed by Python name, which is what the call binds. gql_arg_names = { - param.name: to_camel_case(param.name) for param in func.parameters.values() + py_name: to_camel_case(param.name) + for py_name, param in func.parameters.items() } # Generate query builder selection based on inputs diff --git a/sdk/tests/mod/test_interfaces.py b/sdk/tests/mod/test_interfaces.py index 22fb9502..2234ad1e 100644 --- a/sdk/tests/mod/test_interfaces.py +++ b/sdk/tests/mod/test_interfaces.py @@ -36,6 +36,13 @@ def get_self(self) -> Self: ... @m.function def get_mob(self) -> list[Self]: ... + @m.function + def with_origin( + self, + from_: str, + to: typing.Annotated[str, dagger.Name("destination")], + ) -> Self: ... + def get_private(self) -> bool: ... @m.object_type @@ -77,3 +84,10 @@ async def test_generated_implementation(duck): async def test_interface_object_chain(duck): r, _ = duck assert type(r.get_self()) is type(r) + + +async def test_interface_call_arguments(duck): + """Arguments are bound by Python name and sent by their schema name.""" + r, _ = duck + query = r.with_origin(from_="a", to="b")._ctx.build() + assert 'withOrigin(from: "a", destination: "b")' in query From 45e3f059100b69fd83a77f53fe75874e5b324623 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 21:44:37 +0000 Subject: [PATCH 02/20] mod: ask the engine how it names the module Calls through the module's own interfaces select the schema names the engine gave the module's declarations, which the runtime used to guess: the main class's name followed by the interface's, function and argument names camelCased by snake_to_camel, and the module's enum members by their Python names. The engine names them by the rules of the version it names the module by, so the guesses were wrong past the identifier casing cut (NamingAppHTTPFetcher, ARM64) and before it too (strcase writes e2e_test e2ETest, arm64 ARM_64, FooHTTPClient FooHttpclient). Now the runtime asks: one CurrentModule.naming query per call, before anything is invoked, for the interfaces' type names, their functions' and arguments' names, and the members of the module's enums. A module without interfaces asks nothing. A name the engine wasn't asked about, or can't name, fails the call. Own enum members go over the wire by the engine's names and come back by them. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- sdk/src/dagger/mod/_converter.py | 65 ++++++++++++-- sdk/src/dagger/mod/_module.py | 40 ++++++++- sdk/src/dagger/mod/_naming.py | 135 ++++++++++++++++++++++++++++ sdk/src/dagger/mod/_utils.py | 5 -- sdk/tests/mod/conftest.py | 51 +++++++++++ sdk/tests/mod/test_interfaces.py | 18 +++- sdk/tests/mod/test_naming.py | 146 +++++++++++++++++++++++++++++++ 7 files changed, 444 insertions(+), 16 deletions(-) create mode 100644 sdk/src/dagger/mod/_naming.py create mode 100644 sdk/tests/mod/test_naming.py diff --git a/sdk/src/dagger/mod/_converter.py b/sdk/src/dagger/mod/_converter.py index 643c370d..97bab392 100644 --- a/sdk/src/dagger/mod/_converter.py +++ b/sdk/src/dagger/mod/_converter.py @@ -1,10 +1,11 @@ +import enum import functools import logging import typing from cattrs.preconf.json import make_converter as make_json_converter -from dagger.client._core import Arg, Context, configure_converter_enum +from dagger.client._core import Arg, Context, EnumName, configure_converter_enum from dagger.client._guards import is_id_type, is_id_type_subclass from dagger.client.base import Interface, Scalar, Type from dagger.mod import _api @@ -16,11 +17,14 @@ is_dagger_interface_type, is_dagger_object_type, list_of, + non_null, strip_annotations, syncify, - to_camel_case, ) +if typing.TYPE_CHECKING: + from dagger.mod._module import Module + logger = logging.getLogger(__name__) @@ -81,18 +85,25 @@ def to_interface_impl(proto: type) -> type[Interface]: raise TypeError(msg) methods = { - func.original_name: make_method(name, func, proto) + func.original_name: make_method(name, func, proto, mod) for name, func in typ.functions.items() } + # The class name is the interface's schema name: it's what the client + # selects the type by (see `Type._graphql_name`). return type( - mod.main_cls.__name__ + proto.__name__, + mod.names.type_name(proto.__name__), (Interface,), {"_declaration": proto, **methods}, ) -def make_method(name: str, func: Function, proto: type) -> typing.Callable: # noqa: C901 +def make_method( # noqa: C901 + name: str, + func: Function, + proto: type, + mod: "Module", +) -> typing.Callable: """Generate method for interface client binding.""" ret_type = func.return_type _is_self = ret_type is proto @@ -100,19 +111,49 @@ def make_method(name: str, func: Function, proto: type) -> typing.Callable: # n if not _is_self and is_dagger_interface_type(ret_type): ret_type = to_interface_impl(ret_type) - # Need to convert names to GraphQL convention for query builder - gql_name = to_camel_case(name) + # The interface's field and argument names, as the engine names them. + names = mod.names + gql_name = names.field_name(name) # Keyed by Python name, which is what the call binds. gql_arg_names = { - py_name: to_camel_case(param.name) + py_name: names.field_name(param.name) for py_name, param in func.parameters.items() } + def wire(value: typing.Any) -> typing.Any: + """A value as it goes over the wire, by the engine's names. + + A member of one of the module's own enums is sent by the name the + engine gave it (``arm64`` is ``ARM64``); the client sends anything + else as it always does, a member by its Python name. + """ + if isinstance(value, list | tuple): + return [wire(v) for v in value] + if isinstance(value, enum.Enum) and mod.is_own_enum(type(value)): + return EnumName(names.enum_member_name(value.name)) + return value + + def own_enum(t: typing.Any) -> type[enum.Enum] | None: + """The module's own enum a result is, or None.""" + t = non_null(strip_annotations(t)) + return t if mod.is_own_enum(t) else None + + def read(cls: type[enum.Enum], value: str | None) -> enum.Enum | None: + """A member of one of the module's own enums, from its engine name.""" + if value is None: + return None + members = {names.enum_member_name(m.name): m for m in cls} + try: + return members[value] + except KeyError: + msg = f"Unexpected member {value!r} of enum '{cls.__name__}'" + raise TypeError(msg) from None + # Generate query builder selection based on inputs def select(obj: Interface, *args, **kwargs): bound = func.signature.bind(obj, *args, **kwargs) args = [ - Arg(name=gql_arg_names[arg_name], value=arg_value) + Arg(name=gql_arg_names[arg_name], value=wire(arg_value)) for arg_name, arg_value in bound.arguments.items() if arg_name != "self" ] @@ -138,7 +179,13 @@ def chain_method(self, *args, **kwargs): # Anything else triggers execution (async) async def exec_method(self, *args, **kwargs): _ctx = select(self, *args, **kwargs) + # The module's own enums come back by the names the engine gave them. + if enum_cls := own_enum(ret_type): + return read(enum_cls, await _ctx.execute(str | None)) if cls := list_of(ret_type): + if enum_cls := own_enum(cls): + values = await _ctx.execute(list[str | None]) + return [read(enum_cls, v) for v in values] if cls is proto: cls = type(self) elif is_dagger_interface_type(cls): diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index 24d90371..a5c4968b 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -19,7 +19,7 @@ from dagger._exceptions import QueryError from dagger.client._core import configure_converter_enum from dagger.mod import _api -from dagger.mod._converter import make_converter, typedef_from +from dagger.mod._converter import make_converter, to_interface_impl, typedef_from from dagger.mod._describe import ( ArgumentDescription, EnumDescription, @@ -35,11 +35,13 @@ FunctionError, InvalidInputError, InvalidResultError, + ModuleError, ObjectNotFoundError, RegistrationError, log_exception_only, transform_error, ) +from dagger.mod._naming import ModuleNames, module_names from dagger.mod._resolver import ( Constructor, Field, @@ -92,6 +94,7 @@ def __init__(self, main_name: str = MAIN_OBJECT): self._objects: dict[str, ObjectType] = {} self._enums: dict[str, type[enum.Enum]] = {} self._main: ObjectType | None = None + self._names: ModuleNames | None = None # Escape hatch if there's too much noise from showing stack traces # from exceptions raised in functions by default. Not documented # intentionally for now. @@ -102,6 +105,38 @@ def main_cls(self) -> type[ObjectType]: assert self._main is not None return self._main.cls + @property + def names(self) -> ModuleNames: + """The engine's names for the module's interfaces and enums. + + Calls through the module's own interfaces select them. Asked for by + ``load_names``, before anything is invoked. + """ + if self._names is None: + msg = "The module's schema names were not asked for before the call" + raise ModuleError(msg) + return self._names + + async def load_names(self) -> None: + """Ask the engine how it names the module, before anything is invoked. + + A module without interfaces makes no call by the engine's names of its + own declarations, so it asks nothing. + """ + if self._names is not None: + return + interfaces = [obj for obj in self._objects.values() if obj.interface] + if not interfaces: + self._names = ModuleNames() + return + self._names = await module_names(interfaces, self._enums.values()) + # Bindings are built with the names they have when first used. + to_interface_impl.cache_clear() + + def is_own_enum(self, cls: Any) -> bool: + """Whether a class is one of the enums this module declares.""" + return isinstance(cls, type) and self._enums.get(cls.__name__) is cls + def is_main(self, other: ObjectType) -> bool: """Check if the given object is the main object of the module.""" return self.main_cls is other.cls @@ -234,6 +269,8 @@ async def invoke(self) -> str: }, ) + await self.load_names() + result = await self.get_result( parent_name, parent_state, @@ -261,6 +298,7 @@ async def dispatch(self, request: Mapping[str, Any]) -> Any: except ValueError as e: msg = "Unable to decode the call request" raise InvalidInputError(msg, extra={"request": request}) from e + await self.load_names() return await self.get_result( request["receiverType"], parent_state or {}, diff --git a/sdk/src/dagger/mod/_naming.py b/sdk/src/dagger/mod/_naming.py new file mode 100644 index 00000000..4fd430c5 --- /dev/null +++ b/sdk/src/dagger/mod/_naming.py @@ -0,0 +1,135 @@ +"""Schema names the engine gives a module's own declarations. + +The runtime registers Python names (``get_url``, ``HttpFetcher``) and the +engine turns them into schema names (``getUrl``, ``NamingAppHTTPFetcher``) by +the naming rules of the version it names the module by. The calls the runtime +builds itself, through the module's own interfaces, have to use those schema +names: a wrong one is a fragment on a type that doesn't exist, a field the +interface doesn't have, or an unknown enum member. + +So the runtime doesn't predict them: it asks the engine, which answers for the +module it is running (``CurrentModule.naming``) by the same rules it names the +module by, legacy strcase for a module declaring a version before the +identifier casing cut. One query per call, before anything is invoked, for +every name the calls through the module's interfaces can use. +""" + +from __future__ import annotations + +import dataclasses +import typing +from collections.abc import Awaitable, Callable, Iterable + +from dagger.client._core import to_literal +from dagger.client._session import default_session +from dagger.mod._exceptions import ModuleError + +if typing.TYPE_CHECKING: + import enum + + from dagger.mod._resolver import ObjectType + +Execute: typing.TypeAlias = Callable[[str], Awaitable[typing.Any]] +"""Runs a GraphQL query against the engine and returns its data.""" + + +async def _execute(query: str) -> typing.Any: + return await default_session().execute(query) + + +@dataclasses.dataclass(frozen=True, slots=True) +class ModuleNames: + """The engine's names for the module's declarations, by declared name.""" + + types: typing.Mapping[str, str] = dataclasses.field(default_factory=dict) + """Namespaced schema names of the module's interfaces.""" + + fields: typing.Mapping[str, str] = dataclasses.field(default_factory=dict) + """Schema names of the interfaces' functions and arguments.""" + + enum_members: typing.Mapping[str, str] = dataclasses.field(default_factory=dict) + """Schema names of the members of the module's enums.""" + + def type_name(self, name: str) -> str: + """The schema name of an interface the module declares.""" + return self._get(self.types, name, "type") + + def field_name(self, name: str) -> str: + """The schema name of an interface's function or argument.""" + return self._get(self.fields, name, "function or argument") + + def enum_member_name(self, name: str) -> str: + """The schema name of a member of one of the module's enums.""" + return self._get(self.enum_members, name, "enum member") + + @staticmethod + def _get(names: typing.Mapping[str, str], name: str, what: str) -> str: + try: + return names[name] + except KeyError: + # Every name a call through an interface uses is asked about + # before anything runs; this one wasn't. + msg = f"The engine wasn't asked for the schema name of {what} {name!r}" + raise ModuleError(msg) from None + + +async def module_names( + interfaces: Iterable[ObjectType], + enums: Iterable[type[enum.Enum]], + execute: Execute = _execute, +) -> ModuleNames: + """Ask the engine how it names the module's interfaces and enums. + + One query: the interfaces' type names, their functions' and arguments' + names, and the members of the module's enums, which calls through an + interface send and receive. + """ + interfaces = list(interfaces) + types = sorted({iface.cls.__name__ for iface in interfaces}) + fields = sorted( + { + name + for iface in interfaces + for fn in iface.functions.values() + for name in (fn.name, *(p.name for p in fn.parameters.values())) + } + ) + members = sorted({member.name for cls in enums for member in cls}) + asked = { + "typeNames": types, + "fieldNames": fields, + "enumMemberNames": members, + } + selections = "\n".join( + f" {field}(names: {to_literal(names)})" + for field, names in asked.items() + if names + ) + if not selections: + return ModuleNames() + data = await execute( + "query ModuleNaming {\n" + " currentModule {\n" + " naming {\n" + f"{selections}\n" + " }\n" + " }\n" + "}" + ) + naming = (data or {}).get("currentModule", {}).get("naming", {}) + + def answers(field: str) -> dict[str, str]: + names = asked[field] + if not names: + return {} + got = naming.get(field) + if not isinstance(got, list) or len(got) != len(names): + msg = f"ModuleNaming.{field} returned {got!r} for {names!r}" + raise ModuleError(msg) + return dict(zip(names, got, strict=True)) + + return ModuleNames( + types=answers("typeNames"), + fields=answers("fieldNames"), + enum_members=answers("enumMemberNames"), + ) diff --git a/sdk/src/dagger/mod/_utils.py b/sdk/src/dagger/mod/_utils.py index 96ab2b54..06ae8907 100644 --- a/sdk/src/dagger/mod/_utils.py +++ b/sdk/src/dagger/mod/_utils.py @@ -51,11 +51,6 @@ def to_pascal_case(s: str) -> str: return snake_to_camel(s.replace("-", "_")) -def to_camel_case(s: str) -> str: - """Convert a string to camelCase.""" - return snake_to_camel(s.replace("-", "_"), upper=False) - - def normalize_name(name: str) -> str: """Remove the last underscore, used to avoid conflicts with reserved words.""" if name.endswith("_") and name[-2] != "_" and not name.startswith("_"): diff --git a/sdk/tests/mod/conftest.py b/sdk/tests/mod/conftest.py index 00970f61..9ed74143 100644 --- a/sdk/tests/mod/conftest.py +++ b/sdk/tests/mod/conftest.py @@ -1,7 +1,11 @@ import enum +import json +import re +import typing import pytest +from dagger.client._session import SharedConnection from dagger.client.base import Type @@ -29,3 +33,50 @@ def _selections(obj: Type): ] return _selections + + +_NAMING_FIELD = re.compile( + r"(typeNames|fieldNames|enumMemberNames)\(names: (\[.*?\])\)" +) + + +class FakeEngine: + """Answers CurrentModule.naming from a table of the engine's names. + + A name the table lacks fails the query, as a name the engine can't name + does. Any other query gets the canned data. It keeps what it was asked. + """ + + def __init__(self, names: typing.Mapping[str, typing.Mapping[str, str]]): + self.names = names + self.data: typing.Any = None + self.queries: list[str] = [] + + @property + def naming_queries(self) -> list[str]: + return [q for q in self.queries if q.startswith("query ModuleNaming")] + + async def execute(self, query: str): + self.queries.append(query) + if not query.startswith("query ModuleNaming"): + return self.data + naming = {} + for field, names in _NAMING_FIELD.findall(query): + table = self.names.get(field, {}) + naming[field] = [table[name] for name in json.loads(names)] + return {"currentModule": {"naming": naming}} + + +@pytest.fixture +def engine(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest): + """A fake engine behind the default session. + + Parametrize indirectly with the naming table, or set `names` on it. + """ + fake = FakeEngine(getattr(request, "param", {})) + + async def ready(_): + return fake + + monkeypatch.setattr(SharedConnection, "_ready", ready) + return fake diff --git a/sdk/tests/mod/test_interfaces.py b/sdk/tests/mod/test_interfaces.py index 2234ad1e..d49caebf 100644 --- a/sdk/tests/mod/test_interfaces.py +++ b/sdk/tests/mod/test_interfaces.py @@ -15,6 +15,20 @@ pytest.mark.anyio, ] +# What the engine names the module's declarations. +POND_NAMES = { + "typeNames": {"Duck": "PondDuck", "Goose": "PondGoose"}, + "fieldNames": { + "speak": "speak", + "quack": "quack", + "get_self": "getSelf", + "get_mob": "getMob", + "with_origin": "withOrigin", + "from": "from", + "destination": "destination", + }, +} + @pytest.fixture def mod() -> Module: @@ -53,7 +67,9 @@ class Pond: @pytest.fixture -async def duck(mod: Module): +async def duck(mod: Module, engine): + engine.names = POND_NAMES + await mod.load_names() r, t = await mod.get_structured_result( "Pond", {"duck": "123456"}, diff --git a/sdk/tests/mod/test_naming.py b/sdk/tests/mod/test_naming.py new file mode 100644 index 00000000..717c26da --- /dev/null +++ b/sdk/tests/mod/test_naming.py @@ -0,0 +1,146 @@ +"""How the runtime gets the schema names of the module's declarations.""" + +import enum +import typing + +import pytest + +import dagger +from dagger.mod import Module +from dagger.mod._exceptions import ModuleError +from dagger.mod._naming import ModuleNames, module_names + +pytestmark = [ + pytest.mark.anyio, +] + +# CurrentModule.naming's answers for a module "naming-app" at +# v1.0.0-beta.22, as the engine's identifier naming rules name it. +NAMES = { + "typeNames": {"HttpFetcher": "NamingAppHTTPFetcher"}, + "fieldNames": { + "with_arch": "withArch", + "arch": "arch", + "also": "also", + "e2e_test": "e2eTest", + "arches": "arches", + }, + "enumMemberNames": {"arm64": "ARM64", "AMD64": "AMD64"}, +} + + +@pytest.fixture +def mod() -> Module: + m = Module("NamingApp") + + @m.enum_type + class Arch(enum.Enum): + arm64 = "arm64" + AMD64 = "amd64" + + @m.interface + class HttpFetcher(typing.Protocol): + @m.function + def with_arch(self, arch: Arch, also: list[Arch]) -> typing.Self: ... + + @m.function + async def e2e_test(self) -> str: ... + + @m.function + async def arch(self) -> Arch: ... + + @m.function + async def arches(self) -> list[Arch]: ... + + @m.object_type + class NamingApp: + fetcher: HttpFetcher = dagger.field() + + return m + + +async def fetcher(mod: Module): + r, _ = await mod.get_structured_result( + "NamingApp", + {"fetcher": "fetcher-id"}, + "fetcher", + {}, + ) + return r + + +async def test_one_query(mod: Module, engine): + engine.names = NAMES + await mod.load_names() + await mod.load_names() + assert len(engine.naming_queries) == 1 + query = engine.naming_queries[0] + assert 'typeNames(names: ["HttpFetcher"])' in query + assert ( + 'fieldNames(names: ["also", "arch", "arches", "e2e_test", "with_arch"])' + in query + ) + assert 'enumMemberNames(names: ["AMD64", "arm64"])' in query + + +async def test_no_interfaces_asks_nothing(engine): + m = Module("Plain") + + @m.object_type + class Plain: + pass + + await m.load_names() + assert engine.queries == [] + + +async def test_calls_by_the_engines_names(mod: Module, engine): + engine.names = NAMES + await mod.load_names() + r = await fetcher(mod) + arch = mod._enums["Arch"] + + assert type(r).__name__ == "NamingAppHTTPFetcher" + query = r.with_arch(arch.arm64, [arch.AMD64, arch.arm64])._ctx.build() + assert "... on NamingAppHTTPFetcher" in query + assert "withArch(arch: ARM64, also: [AMD64, ARM64])" in query + + engine.data = {"node": {"e2eTest": "ok"}} + assert await r.e2e_test() == "ok" + assert "e2eTest" in engine.queries[-1] + + +async def test_enum_results(mod: Module, engine): + engine.names = NAMES + await mod.load_names() + r = await fetcher(mod) + arch = mod._enums["Arch"] + + engine.data = {"node": {"arch": "ARM64"}} + assert await r.arch() is arch.arm64 + + engine.data = {"node": {"arches": ["AMD64", "ARM64"]}} + assert await r.arches() == [arch.AMD64, arch.arm64] + + engine.data = {"node": {"arch": "ARM_64"}} + with pytest.raises(TypeError, match="Unexpected member 'ARM_64'"): + await r.arch() + + +async def test_names_are_asked_before_a_call(mod: Module): + with pytest.raises(ModuleError, match="not asked for"): + await fetcher(mod) + + +def test_unasked_name_fails(): + with pytest.raises(ModuleError, match="'get_url'"): + ModuleNames().field_name("get_url") + + +async def test_engine_answer_mismatch(mod: Module): + async def execute(_): + return {"currentModule": {"naming": {"typeNames": []}}} + + interfaces = [o for o in mod._objects.values() if o.interface] + with pytest.raises(ModuleError, match="typeNames"): + await module_names(interfaces, (), execute) From 66c60192a425ccc07206a23c59e7b5ca64b84050 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 22:46:24 +0000 Subject: [PATCH 03/20] codegen: style identifiers through the engine The generator spelled Python names with a converter of its own: acronym runs title-cased, then graphql-core's camel_to_snake, which cuts experimentalWithAllGPUs into experimental_with_all_gp_us. The engine knows where its names' words are, so it spells them now: formatIdentifiers(casing: SNAKE) at the schema's version, asked once up front for every type, field, argument and input field name of the schema, and directly for any other name the generator styles (a name a deprecation notice refers to). A name the engine can't format fails the generation. No converter is kept, so schemas before the identifier casing cut get the engine's spelling too (experimental_with_all_gpus): an intended break of 1.0. The generator reaches the engine as a nested client of the session, with the standard library's HTTP client, so the codegen execs run with experimentalPrivilegedNesting. The keyword and builtin suffix stays the SDK's. The unit tests style made-up schemas with a stand-in, since they run no engine; the e2e checks generate with one. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 2 +- scope.dang | 11 +- sdk/codegen/src/codegen/cli.py | 35 +++--- sdk/codegen/src/codegen/generator.py | 17 +-- sdk/codegen/src/codegen/naming.py | 167 +++++++++++++++++++++++++++ sdk/tests/codegen/test_naming.py | 63 ++++++++++ sdk/tests/conftest.py | 35 ++++++ 7 files changed, 304 insertions(+), 26 deletions(-) create mode 100644 sdk/codegen/src/codegen/naming.py create mode 100644 sdk/tests/codegen/test_naming.py diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index aea28b61..65c3711a 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -2174,7 +2174,7 @@ type E2e { .withFile("/core-only.py", ws.file("/helpers/core-schema/core_only.py")) .withFile("/schema.json", core.withEngineVersion(core.engineVersion).clientSchemaIntrospectionJSON) .withExec(["python", "/core-only.py", "/schema.json", "/core.json"]) - .withExec(["uv", "run", "--frozen", "python", "-m", "codegen", "generate", "-i", "/core.json", "-o", sdkBindingsPath]) + .withExec(["uv", "run", "--frozen", "python", "-m", "codegen", "generate", "-i", "/core.json", "-o", sdkBindingsPath], experimentalPrivilegedNesting: true) .withExec(["uv", "run", "--frozen", "ruff", "check", "--fix-only", sdkBindingsPath]) .withExec(["uv", "run", "--frozen", "ruff", "format", sdkBindingsPath]) .file(sdkBindingsPath) diff --git a/scope.dang b/scope.dang index dcbe7194..e062f5d9 100644 --- a/scope.dang +++ b/scope.dang @@ -495,7 +495,7 @@ type Scope { let names = if (members.length == 0) { [coreDirName] } else { members.map { member => member.dir } } let inputs = names.reduce([] :: [String!]!) { args, name => args + ["-i", schemasPath + "/" + name + ".json"] } mounted - .withExec([codegenPython, "-m", "codegen", "generate-global"] + inputs + ["-o", outputPath]) + .withExec([codegenPython, "-m", "codegen", "generate-global"] + inputs + ["-o", outputPath], experimentalPrivilegedNesting: true) .directory(outputPath + "/" + globalPackage) } @@ -513,7 +513,7 @@ type Scope { let coreSource: Directory! { codegenEnv .withMountedFile(schemaPath, coreSchema) - .withExec([codegenPython, "-m", "codegen", "generate-core", "-i", schemaPath, "-o", outputPath]) + .withExec([codegenPython, "-m", "codegen", "generate-core", "-i", schemaPath, "-o", outputPath], experimentalPrivilegedNesting: true) .directory(outputPath) } @@ -628,7 +628,7 @@ type Scope { codegenPython, "-m", "codegen", "generate-client", "-i", schemaPath, "-o", outputPath, "--name", member.name, "--ref", member.ref, "--core-digest", coreDigest, - ] + pin) + ] + pin, experimentalPrivilegedNesting: true) .directory(outputPath) } @@ -700,7 +700,10 @@ type Scope { """ The code generator's environment, synced once per SDK version and shared by - every scope that generates. + every scope that generates. The generator runs as a nested client of the + session (experimentalPrivilegedNesting), because the engine spells the + Python names of the schema's identifiers (formatIdentifiers, see + sdk/codegen/src/codegen/naming.py). """ let codegenEnv: Container! { codegenBase.withExec(["uv", "sync", "--frozen", "--no-dev", "--package", "codegen"]) diff --git a/sdk/codegen/src/codegen/cli.py b/sdk/codegen/src/codegen/cli.py index 42b53f04..b089e05f 100644 --- a/sdk/codegen/src/codegen/cli.py +++ b/sdk/codegen/src/codegen/cli.py @@ -5,7 +5,7 @@ import graphql -from codegen import ast, generator, packages, partition +from codegen import ast, generator, naming, packages, partition def main(argv: list[str] | None = None): @@ -99,7 +99,7 @@ def main(argv: list[str] | None = None): # TODO: Add argument for module init. try: args.run(args) - except partition.ClientError as e: + except (partition.ClientError, naming.NamingError) as e: parser.error(str(e)) @@ -137,9 +137,15 @@ def read_schema(introspection: pathlib.Path) -> tuple[graphql.GraphQLSchema, str return schema, result.get("__schemaVersion", "") +def styled(schema: graphql.GraphQLSchema, version: str): + """Style the schema's identifiers as the engine names them at its version.""" + return naming.styled_by(naming.engine_names([schema], version)) + + def codegen(introspection: pathlib.Path, output: pathlib.Path | None): schema, schema_version = read_schema(introspection) - code = generator.generate(schema, schema_version=schema_version) + with styled(schema, schema_version): + code = generator.generate(schema, schema_version=schema_version) if output: output.write_text(code) @@ -150,21 +156,23 @@ def codegen(introspection: pathlib.Path, output: pathlib.Path | None): def core(introspection: pathlib.Path, output: pathlib.Path): schema, schema_version = read_schema(introspection) - files = packages.core_package(schema, schema_version) + with styled(schema, schema_version): + files = packages.core_package(schema, schema_version) root = packages.write_package(output, partition.CORE, files) sys.stdout.write(f"Core generated successfully to {root}\n") def client(args: argparse.Namespace): schema, schema_version = read_schema(args.introspection) - package, files = packages.client_package( - schema, - args.name, - args.ref, - args.pin, - core_digest=args.core_digest, - schema_version=schema_version, - ) + with styled(schema, schema_version): + package, files = packages.client_package( + schema, + args.name, + args.ref, + args.pin, + core_digest=args.core_digest, + schema_version=schema_version, + ) root = packages.write_package(args.output, package, files) sys.stdout.write(f"Client generated successfully to {root}\n") @@ -176,6 +184,7 @@ def global_client(introspections: list[pathlib.Path], output: pathlib.Path): if len(set(versions)) > 1: msg = f"the schemas have different versions: {', '.join(sorted(set(versions)))}" raise partition.ClientError(msg) - files = packages.global_package(schemas, versions[0]) + with naming.styled_by(naming.engine_names(schemas, versions[0])): + files = packages.global_package(schemas, versions[0]) root = packages.write_global(output, files) sys.stdout.write(f"Global client generated successfully to {root}\n") diff --git a/sdk/codegen/src/codegen/generator.py b/sdk/codegen/src/codegen/generator.py index abb0ee4f..b52bb2bc 100644 --- a/sdk/codegen/src/codegen/generator.py +++ b/sdk/codegen/src/codegen/generator.py @@ -49,14 +49,12 @@ get_named_type, is_leaf_type, ) -from graphql.pyutils import camel_to_snake, snake_to_camel +from graphql.pyutils import snake_to_camel from graphql.type.schema import TypeMap +from codegen.naming import snake from codegen.partition import own_fields -ACRONYM_RE = re.compile(r"([A-Z\d]+)(?=[A-Z\d]|$)") -"""Pattern for grouping initialisms.""" - DEPRECATION_RE = re.compile(r"`([a-zA-Z\d_]+)`") """Pattern for extracting replaced references in deprecations.""" @@ -501,10 +499,13 @@ def _format_name(match: re.Match[str]) -> str: def format_name(s: str) -> str: - """Format a GraphQL field or argument name into Python.""" - # rewrite acronyms, initialisms and abbreviations - s = ACRONYM_RE.sub(lambda m: m.group(0).title(), s) - s = camel_to_snake(s) + """Format a GraphQL field or argument name into Python. + + The engine spells it in snake_case (see codegen.naming); a name that + would shadow a keyword or a builtin the bindings use gets a trailing + underscore. + """ + s = snake(s) if iskeyword(s) or s in _reserved_builtins: s += "_" return s diff --git a/sdk/codegen/src/codegen/naming.py b/sdk/codegen/src/codegen/naming.py new file mode 100644 index 00000000..6d69217b --- /dev/null +++ b/sdk/codegen/src/codegen/naming.py @@ -0,0 +1,167 @@ +"""Python names for the schema's identifiers, as the engine spells them. + +Every Python identifier the generator styles from the schema (methods, +arguments, input fields) is the schema name in snake_case, and the engine is +the one that spells it: ``Query.formatIdentifiers(casing: SNAKE)``, at the +schema's version, so the words are cut by the engine's naming dictionary +(``withGPU`` is ``with_gpu``, ``experimentalWithAllGPUs`` is +``experimental_with_all_gpus``) rather than by a converter of the SDK's own. + +The generator asks once, up front, for every name in the schema, and asks +directly for a name it meets that wasn't among them. It runs as a nested +client of the Dagger session (``experimentalPrivilegedNesting``), which it +reaches through ``DAGGER_SESSION_PORT`` and ``DAGGER_SESSION_TOKEN``. A name +the engine can't format fails the generation. +""" + +from __future__ import annotations + +import base64 +import contextlib +import json +import os +import typing +import urllib.error +import urllib.request +from collections.abc import Callable, Iterable, Iterator + +from graphql import ( + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLObjectType, + GraphQLSchema, +) + +Format: typing.TypeAlias = Callable[[list[str]], list[str]] +"""Formats names in snake_case, in order.""" + + +class NamingError(Exception): + """The engine couldn't name an identifier.""" + + +class Session: + """The Dagger session the generator runs in, as a nested client.""" + + def __init__(self, port: str, token: str): + self.url = f"http://127.0.0.1:{port}/query" + self.auth = "Basic " + base64.b64encode(f"{token}:".encode()).decode() + + @classmethod + def from_env(cls) -> Session: + port = os.environ.get("DAGGER_SESSION_PORT") + token = os.environ.get("DAGGER_SESSION_TOKEN") + if not port or not token: + msg = ( + "no Dagger session to name identifiers with: DAGGER_SESSION_PORT " + "and DAGGER_SESSION_TOKEN are not set; run the generator as a " + "nested client of a Dagger session" + ) + raise NamingError(msg) + return cls(port, token) + + def query(self, query: str, variables: dict[str, typing.Any]) -> typing.Any: + body = json.dumps({"query": query, "variables": variables}).encode() + request = urllib.request.Request( # noqa: S310 - a localhost URL + self.url, + data=body, + headers={"Content-Type": "application/json", "Authorization": self.auth}, + ) + try: + with urllib.request.urlopen(request) as response: # noqa: S310 + result = json.load(response) + except urllib.error.HTTPError as e: + result = json.load(e) + if errors := result.get("errors"): + msg = "; ".join(str(e.get("message", e)) for e in errors) + raise NamingError(msg) + return result["data"] + + def formatter(self, version: str) -> Format: + """Format names with formatIdentifiers at a version (empty: the caller's).""" + if version: + query = ( + "query FormatIdentifiers($names: [String!]!, $version: String!) {\n" + " formatIdentifiers(names: $names, casing: SNAKE, version: $version)\n" + "}" + ) + else: + query = ( + "query FormatIdentifiers($names: [String!]!) {\n" + " formatIdentifiers(names: $names, casing: SNAKE)\n" + "}" + ) + + def fmt(names: list[str]) -> list[str]: + variables: dict[str, typing.Any] = {"names": names} + if version: + variables["version"] = version + formatted = self.query(query, variables)["formatIdentifiers"] + if len(formatted) != len(names): + msg = f"formatIdentifiers gave {len(formatted)} of {len(names)} names" + raise NamingError(msg) + return formatted + + return fmt + + +class SnakeNames: + """Names in snake_case, formatted up front and on a miss.""" + + def __init__(self, fmt: Format): + self._fmt = fmt + self._names: dict[str, str] = {} + + def prefetch(self, names: Iterable[str]) -> None: + """Format every name not formatted yet, in one call.""" + missing = sorted({n for n in names if n not in self._names}) + if missing: + self._names.update(zip(missing, self._fmt(missing), strict=True)) + + def __call__(self, name: str) -> str: + if name not in self._names: + self.prefetch([name]) + return self._names[name] + + +def schema_names(schema: GraphQLSchema) -> Iterator[str]: + """Every name in a schema the generator may style: types, fields, args.""" + for type_name, t in schema.type_map.items(): + if type_name.startswith("__"): + continue + yield type_name + if isinstance(t, GraphQLObjectType | GraphQLInterfaceType): + for field_name, f in t.fields.items(): + yield field_name + yield from f.args + elif isinstance(t, GraphQLInputObjectType): + yield from t.fields + + +_current: SnakeNames | None = None + + +@contextlib.contextmanager +def styled_by(names: SnakeNames) -> Iterator[SnakeNames]: + """Style identifiers by these names while generating.""" + global _current # noqa: PLW0603 + previous, _current = _current, names + try: + yield names + finally: + _current = previous + + +def snake(name: str) -> str: + """A schema name in snake_case, as the engine spells it.""" + if _current is None: + msg = "no engine to name identifiers with (see codegen.naming.styled_by)" + raise NamingError(msg) + return _current(name) + + +def engine_names(schemas: Iterable[GraphQLSchema], version: str) -> SnakeNames: + """The names of the schemas, formatted by the session's engine at version.""" + names = SnakeNames(Session.from_env().formatter(version)) + names.prefetch(n for schema in schemas for n in schema_names(schema)) + return names diff --git a/sdk/tests/codegen/test_naming.py b/sdk/tests/codegen/test_naming.py new file mode 100644 index 00000000..41120eab --- /dev/null +++ b/sdk/tests/codegen/test_naming.py @@ -0,0 +1,63 @@ +import pytest +from graphql import build_schema + +from codegen import naming +from codegen.naming import NamingError, Session, SnakeNames, schema_names, snake + + +def test_one_call_up_front_then_one_per_miss(): + calls: list[list[str]] = [] + + def fmt(names: list[str]) -> list[str]: + calls.append(names) + return [f"<{n}>" for n in names] + + names = SnakeNames(fmt) + names.prefetch(["b", "a", "b"]) + assert calls == [["a", "b"]] + assert names("a") == "" + assert names("c") == "" + assert names("c") == "" + assert calls == [["a", "b"], ["c"]] + + +def test_engine_errors_fail_the_generation(): + def fmt(_: list[str]) -> list[str]: + msg = 'cannot parse "ü"' + raise NamingError(msg) + + with pytest.raises(NamingError, match="cannot parse"): + SnakeNames(fmt)("ü") + + +def test_schema_names(): + schema = build_schema(""" + type Query { gitRepo(withSSH: Boolean): Repo } + type Repo { shortSHA: String! } + input Opts { userIDs: [String!] } + enum Kind { A } + """) + assert set(schema_names(schema)) >= { + "Query", + "gitRepo", + "withSSH", + "Repo", + "shortSHA", + "Opts", + "userIDs", + "Kind", + } + assert not any(n.startswith("__") for n in schema_names(schema)) + + +def test_no_session(monkeypatch: pytest.MonkeyPatch): + monkeypatch.delenv("DAGGER_SESSION_PORT", raising=False) + monkeypatch.delenv("DAGGER_SESSION_TOKEN", raising=False) + with pytest.raises(NamingError, match="nested client"): + Session.from_env() + + +def test_no_names_to_style_by(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(naming, "_current", None) + with pytest.raises(NamingError, match="no engine"): + snake("withExec") diff --git a/sdk/tests/conftest.py b/sdk/tests/conftest.py index 1e402f03..9cd879a9 100644 --- a/sdk/tests/conftest.py +++ b/sdk/tests/conftest.py @@ -1,4 +1,9 @@ +import re + import pytest +from graphql.pyutils import camel_to_snake + +from codegen import naming @pytest.fixture(scope="session", autouse=True) @@ -23,3 +28,33 @@ def alpine_version(): @pytest.fixture def alpine_image(alpine_version): return f"alpine:{alpine_version}" + + +_INITIALISM_RE = re.compile(r"([A-Z\d]+)(?=[A-Z\d]|$)") + + +def stand_in_snake(names: list[str]) -> list[str]: + """A stand-in for the engine's formatIdentifiers(casing: SNAKE). + + The generator's tests render made-up schemas without an engine, so + something has to spell their Python names; the e2e checks generate with + the engine. + """ + return [ + camel_to_snake(_INITIALISM_RE.sub(lambda m: m.group(0).title(), n)) + for n in names + ] + + +@pytest.fixture(autouse=True) +def engine_names(monkeypatch: pytest.MonkeyPatch): + """Style generated identifiers by the stand-in, as the CLI does too.""" + + def stand_in(schemas, _version: str) -> naming.SnakeNames: + names = naming.SnakeNames(stand_in_snake) + names.prefetch(n for schema in schemas for n in naming.schema_names(schema)) + return names + + monkeypatch.setattr(naming, "engine_names", stand_in) + with naming.styled_by(naming.SnakeNames(stand_in_snake)) as names: + yield names From af74db059e22d383963381df3df88b7c76532592 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 21:50:52 +0000 Subject: [PATCH 04/20] sdk: say the engine floor also names identifiers Generation asks the engine how to spell the schema's Python names (formatIdentifiers) and a module asks it what it named its own declarations (CurrentModule.naming). v1.0.0-beta.26, the floor dagger-module.toml already declares, is the first release that answers both. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- README.md | 11 ++++++----- docs/collections.md | 5 ++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index bf2ba8a1..2b4d519d 100644 --- a/README.md +++ b/README.md @@ -48,13 +48,14 @@ There are three answers, and a new module gets the first: | `[entrypoint] source = ` | a Dang entrypoint of the user's own, kept as written | | `[runtime] source = ` | a module runtime, which builds and runs the module itself | -This SDK needs an engine `v1.0.0-beta.26` or later: it reads a scope's +This SDK needs an engine `v1.0.0-beta.26` or later. It reads a scope's settings through `WorkspaceSDK.scopeSetting`, which [dagger/dagger#15084](https://github.com/dagger/dagger/pull/15084) adds in that -release. The entrypoint it generates into a module needs an engine -`v1.0.0-beta.18` or later, the first release that loads a module's files -through its entrypoint's `sources` member. An entrypoint runs a module on the -engine's own version, so an entrypoint manifest keeps no `engineVersion`. +release. It also needs the first release that names identifiers by its naming +rules and answers for them: generation asks it how to spell the Python names of +the schema's identifiers, and a module asks it what it named the module's own +declarations. An entrypoint runs a module on the engine's own version, so an +entrypoint manifest keeps no `engineVersion`. On an engine without that field, `dagger module init` and `dagger generate` fail while they load the SDK, before they write anything. A diff --git a/docs/collections.md b/docs/collections.md index b72e3fe6..f23b8476 100644 --- a/docs/collections.md +++ b/docs/collections.md @@ -1,9 +1,8 @@ # Collections A collection is a set of objects that a module discovers at run time, each -with a unique key. Generating a module with this SDK needs an engine -v1.0.0-beta.26 or later, and the generated entrypoint runs on v1.0.0-beta.18 or -later. The engine serves collections from v1.0.0-beta.15 +with a unique key. This SDK needs an engine v1.0.0-beta.26 or later. The +engine serves collections from v1.0.0-beta.15 ([dagger/dagger#14221](https://github.com/dagger/dagger/pull/14221)), and v1.0.0-beta.17 adds the projected types every `dagger call` into a collection resolves ([dagger/dagger#14447](https://github.com/dagger/dagger/pull/14447)) From 460c16c33fad3df4e301fb73276972de8a79b3b8 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 22:19:04 +0000 Subject: [PATCH 05/20] e2e: call a module named on either side of the cut naming-check generates naming-app, a static entrypoint module with an own interface and enum whose schema names differ between the legacy rules and the engine's identifier naming rules, without a dang.toml (named by v1.0.0-beta.20) and with one pinning v1.0.0-beta.22. It generates naming-caller with a client of it, checks the Python names generation wrote and the names the client has for naming-app's declarations, and runs naming-caller's check, which calls naming-app through its client so that naming-app's runtime calls its own interface by the names the engine gave it. The caller is a second module, as a module calls itself through a client of its own. The interface takes no own enum: the engine refuses an own interface whose function takes one in the module's own session, so the module could not load its schema at all. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .../fixtures/naming/app/dagger-module.toml | 5 ++ .../e2e/fixtures/naming/app/pyproject.toml | 16 ++++ .../naming/app/src/naming_app/__init__.py | 51 +++++++++++++ .../fixtures/naming/caller/dagger-module.toml | 5 ++ .../e2e/fixtures/naming/caller/pyproject.toml | 16 ++++ .../caller/src/naming_caller/__init__.py | 22 ++++++ .dagger/modules/e2e/main.dang | 74 +++++++++++++++++++ 7 files changed, 189 insertions(+) create mode 100644 .dagger/modules/e2e/fixtures/naming/app/dagger-module.toml create mode 100644 .dagger/modules/e2e/fixtures/naming/app/pyproject.toml create mode 100644 .dagger/modules/e2e/fixtures/naming/app/src/naming_app/__init__.py create mode 100644 .dagger/modules/e2e/fixtures/naming/caller/dagger-module.toml create mode 100644 .dagger/modules/e2e/fixtures/naming/caller/pyproject.toml create mode 100644 .dagger/modules/e2e/fixtures/naming/caller/src/naming_caller/__init__.py diff --git a/.dagger/modules/e2e/fixtures/naming/app/dagger-module.toml b/.dagger/modules/e2e/fixtures/naming/app/dagger-module.toml new file mode 100644 index 00000000..a9cd83b4 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/app/dagger-module.toml @@ -0,0 +1,5 @@ +name = "naming-app" + +[entrypoint] + kind = "dang" + source = "./sdk/entrypoint" diff --git a/.dagger/modules/e2e/fixtures/naming/app/pyproject.toml b/.dagger/modules/e2e/fixtures/naming/app/pyproject.toml new file mode 100644 index 00000000..6bdc5e63 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/app/pyproject.toml @@ -0,0 +1,16 @@ +[project] +name = "naming-app" +version = "0.1.0" +requires-python = ">=3.14" +dependencies = ["dagger-io", "dagger-clients-core"] + +[build-system] +requires = ["uv_build>=0.8.4,<0.14.0"] +build-backend = "uv_build" + +[tool.uv.workspace] +members = ["sdk", "clients/core"] + +[tool.uv.sources] +dagger-io = { workspace = true } +dagger-clients-core = { workspace = true } diff --git a/.dagger/modules/e2e/fixtures/naming/app/src/naming_app/__init__.py b/.dagger/modules/e2e/fixtures/naming/app/src/naming_app/__init__.py new file mode 100644 index 00000000..149b6630 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/app/src/naming_app/__init__.py @@ -0,0 +1,51 @@ +"""Declarations the engine names differently on either side of the cut. + +HttpFetcher is NamingAppHttpFetcher by the legacy strcase rules and +NamingAppHTTPFetcher by the engine's identifier naming rules, and the Arch +member Arm64 is ARM_64 by the first and ARM64 by the second. A call through +the interface selects the type by its name, so the runtime has to use the +name the engine gave it. + +The interface takes no Arch: the engine refuses an own interface whose +function takes an own enum in the module's own session, so the module would +fail to load its schema (core/interface.go, "cannot accept arg ... of +external type from dependency module"). +""" + +import enum +import typing + +import dagger +from dagger import enum_type, function, interface, object_type + + +@enum_type +class Arch(enum.Enum): + Arm64 = "arm64" + + +@interface +class HttpFetcher(typing.Protocol): + @function + async def get_url(self, path: str) -> str: ... + + +@object_type +class HttpClient: + base_url: str = dagger.field() + + @function + async def get_url(self, path: str) -> str: + return f"{self.base_url}{path}" + + +@object_type +class NamingApp: + @function + def http_client(self, base_url: str) -> HttpClient: + return HttpClient(base_url=base_url) + + @function + async def fetch(self, fetcher: HttpFetcher, path: str, arch: Arch) -> str: + """Call through the module's own interface, by the engine's names.""" + return f"{await fetcher.get_url(path)} {arch.value}" diff --git a/.dagger/modules/e2e/fixtures/naming/caller/dagger-module.toml b/.dagger/modules/e2e/fixtures/naming/caller/dagger-module.toml new file mode 100644 index 00000000..310d35dc --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/caller/dagger-module.toml @@ -0,0 +1,5 @@ +name = "naming-caller" + +[entrypoint] + kind = "dang" + source = "./sdk/entrypoint" diff --git a/.dagger/modules/e2e/fixtures/naming/caller/pyproject.toml b/.dagger/modules/e2e/fixtures/naming/caller/pyproject.toml new file mode 100644 index 00000000..64f38b88 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/caller/pyproject.toml @@ -0,0 +1,16 @@ +[project] +name = "naming-caller" +version = "0.1.0" +requires-python = ">=3.14" +dependencies = ["dagger-io", "dagger-clients-core"] + +[build-system] +requires = ["uv_build>=0.8.4,<0.14.0"] +build-backend = "uv_build" + +[tool.uv.workspace] +members = ["sdk", "clients/core"] + +[tool.uv.sources] +dagger-io = { workspace = true } +dagger-clients-core = { workspace = true } diff --git a/.dagger/modules/e2e/fixtures/naming/caller/src/naming_caller/__init__.py b/.dagger/modules/e2e/fixtures/naming/caller/src/naming_caller/__init__.py new file mode 100644 index 00000000..6692b3d2 --- /dev/null +++ b/.dagger/modules/e2e/fixtures/naming/caller/src/naming_caller/__init__.py @@ -0,0 +1,22 @@ +"""Calls naming-app through its client, so its runtime calls its own interface.""" + +from dagger import check, function, object_type +from dagger_clients.naming_app import NamingAppArch, naming_app + + +@object_type +class NamingCaller: + @function + async def fetch(self) -> str: + client = naming_app().http_client(base_url="https://example.com") + # Whichever name the engine gave the member, the client has it. + (arch,) = list(NamingAppArch) + return await naming_app().fetch(fetcher=client, path="/x", arch=arch) + + @function + @check + async def fetch_check(self) -> None: + got = await self.fetch() + if got != "https://example.com/x arm64": + msg = f"naming-app's call through its interface returned {got!r}" + raise ValueError(msg) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 65c3711a..e29646e5 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -3141,4 +3141,78 @@ type E2e { ) } + let namingFixturePath: String! = fixtureRoot + "/naming" + + """ + naming-app generated as a static entrypoint module, and naming-caller + generated with a client of it, in a workspace of their own. With pinned, + naming-app's dang.toml declares v1.0.0-beta.22, which the engine names it + by; without one, the engine names it by v1.0.0-beta.20, the legacy rules. + """ + let namingScope(ws: Workspace!, pinned: Boolean!): Workspace! { + let app = ws.directory("/" + namingFixturePath + "/app") + let appSource = if (pinned) { + app.withNewFile("dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.22\"\n") + } else { + app + } + let tree = directory + .withDirectory("naming-app", appSource) + .withDirectory("naming-caller", ws.directory("/" + namingFixturePath + "/caller")) + let withApp = pythonSdk.generateScope(tree.asWorkspace.withWorkdir("naming-app"), isModule: true, name: "naming-app", clients: []) + .withWorkdir(".") + pythonSdk.generateScope(withApp.withWorkdir("naming-caller"), isModule: true, name: "naming-caller", clients: [withApp.moduleSource("/naming-app")]) + .withWorkdir(".") + } + + let pyFiles(generated: Workspace!, path: String!): String! { + let root = generated.directory("/" + path) + root.glob("**/*.py").map { file => root.file(file).contents }.join("\n") + } + + """ + The engine names a module's declarations by the version it names the module + by, and the SDK follows it on both sides of the identifier casing cut: + + - generation spells the Python names of every schema identifier as the + engine does (experimental_with_all_gpus in core, whatever the version); + - the client generated for naming-app names its declarations as the + engine does at naming-app's version (NamingAppHttpFetcher and ARM_64 + before the cut, NamingAppHTTPFetcher and ARM64 past it); + - naming-app's runtime, called through that client, calls its own + interface by the names the engine gave it (the namespaced type and its + function), so the call returns. + + The fixture keeps to names the engine names the same on an object and on + an interface: by the legacy rules, it names an interface's fields twice, + which isn't idempotent (e2e_test is e2ETest on an object, e2Etest on an + interface), and CurrentModule.naming answers the object's spelling. Its + interface takes no own enum, which the engine refuses in the module's own + session. + """ + pub namingCheck(ws: Workspace!): Void @check { + [ + {{pinned: false, iface: "NamingAppHttpFetcher", member: "ARM_64"}}, + {{pinned: true, iface: "NamingAppHTTPFetcher", member: "ARM64"}}, + ].each { want => + let label = if (want.pinned) { "naming-app at v1.0.0-beta.22" } else { "naming-app without a version" } + let generated = namingScope(ws, want.pinned) + let core = pyFiles(generated, "naming-caller/clients/core/src") + assertContains(core, "def experimental_with_all_gpus(", label + ": core's Python names are not the engine's") + let client = pyFiles(generated, "naming-caller/clients/naming-app/src") + assertContains(client, "class " + want.iface, label + ": the client does not name the interface " + want.iface) + assertContains(client, want.member + " = ", label + ": the client does not name the enum member " + want.member) + assertContains(client, "def get_url(", label + ": the client does not name get_url") + let outcomes = generated.withModule("naming-caller", name: "naming-caller") + .artifacts(include: ["naming-caller:fetch-check"]).asChecks + .{{ pass, error.{{ message }} }} + assert(outcomes.length == 1, label + ": expected the fetch check, got " + toString(outcomes.length)) + # Selected on `pass` first: reading the message of a check that passed + # raises an evaluation error of its own. + let failed = outcomes.filter { c => c.pass == false }.map { c => c.error.message } + assert(failed.length == 0, label + ": the call through its interface failed: " + failed.join("\n")) + null + } + null + } } From fb62b12d59d21263489ddb909f88dd74fc11bc0c Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 22:45:27 +0000 Subject: [PATCH 06/20] mod: take the main object the engine names The runtime picked the main class by a strcase port, in Dang, of the engine's builtin Python runtime: DAGGER_MAIN_OBJECT, the module's name converted with strcase.ToCamel. Which class is the main object is the engine's to say, by the naming rules it names the module by, so the runtime asks it (ModuleNaming.mainObject), with every object type the module's code registers as a candidate, in the query that asks for its interfaces' names: one query per call. A module the engine names no main object for fails to load, saying which classes it had. The module is the one the runtime runs in (CurrentModule.naming), except when generation renders a module's static entrypoint, which runs in the SDK's own module: mod.dang hands the renderer, as a nested client, the ID of the module source the engine will name (ModuleSource.naming). It is asked from Python so that this module, which an engine before the floor still loads in order to refuse it, names no field such an engine lacks. The code is imported as the default package, or through a configured entry point, without a class name to import. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 24 ----- mod.dang | 27 +++++- runtime/build.dang | 51 ----------- runtime/main.dang | 7 -- sdk/src/dagger/mod/__main__.py | 21 +++-- sdk/src/dagger/mod/_module.py | 76 +++++++++++----- sdk/src/dagger/mod/_naming.py | 150 +++++++++++++++++++------------ sdk/src/dagger/mod/cli.py | 59 ++++++------ sdk/tests/mod/conftest.py | 17 +++- sdk/tests/mod/test_interfaces.py | 2 +- sdk/tests/mod/test_naming.py | 101 +++++++++++++++++++-- 11 files changed, 326 insertions(+), 209 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index e29646e5..bb39af44 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -2078,30 +2078,6 @@ type E2e { ctr.withExec(["dagger"] + args, experimentalPrivilegedNesting: true) } - """ - Main object names derive from module names as in the engine's builtin Python - runtime, so a module keeps loading when it moves between the two. - """ - pub runtimeNamingCheck: Void @check { - [ - ["my-module", "MyModule"], - ["my_module", "MyModule"], - ["myModule", "MyModule"], - ["MyModule", "MyModule"], - ["HTTPServer", "Httpserver"], - ["s3-bucket", "S3Bucket"], - ["app2", "App2"], - ["a.b c", "ABC"], - ].each { pair => - let name = pair[0] ?? "" - let want = pair[1] ?? "" - let got = pythonSdkRuntime.mainObjectName(name) - assert(got == want, "main object name for " + name + ": got " + got + ", want " + want) - } - - null - } - let sdkSource(ws: Workspace!): Directory! { ws .directory("/", include: ["sdk/**", "!sdk/**/.venv", "!sdk/**/__pycache__"]) diff --git a/mod.dang b/mod.dang index c7c9920f..608768a5 100644 --- a/mod.dang +++ b/mod.dang @@ -129,7 +129,7 @@ type Mod { if (entrypointMode == "generated") { let outside = PyprojectHelper().outsidePaths(scoped, rootPath) checkResourcesLoad(scoped, outside) - let withEntrypoint = scoped.withDirectory("/" + rootPath + "/" + entrypointPath, entrypointDir(scoped, patterns(outside))) + let withEntrypoint = scoped.withDirectory("/" + rootPath + "/" + entrypointPath, entrypointDir(scoped, patterns(outside), entrypointPath)) let entrypointDirectory = withEntrypoint.withWorkdir(modulePath(entrypointPath)) let configured = sdkHelpers.loadDangConfig(entrypointDirectory) .withVersion("2.1") @@ -261,17 +261,36 @@ type Mod { """ The entrypoint the engine loads instead of calling a runtime: the module's own container renders its types, and the container build travels with it. + Which class is the main object, the one that gets the constructor, the + engine says (ModuleSource.naming), for the module the entrypoint serves: + the renderer asks it as a nested client, about the source named by its ID. + It is asked from Python, so that this module, which an engine before the + floor still loads to refuse it, names no field such an engine lacks. """ - let entrypointDir(generated: Workspace!, outside: [String!]!): Directory! { + let entrypointDir(generated: Workspace!, outside: [String!]!, entrypointPath: String!): Directory! { pythonSdkRuntime .moduleRuntime(modSource: staging(generated, outside).moduleSource("/" + rootPath), introspectionJson: null) - .withExec(["python", "-m", "dagger.mod", "entrypoint", "--name", moduleName, "--client-version", targetVersion, "--output", entrypointOutput] + - outside.map { pattern => "--outside=" + pattern }) + .withEnvVariable("DAGGER_MODULE_SOURCE_ID", toString(namedSource(generated, entrypointPath).id)) + .withExec( + ["python", "-m", "dagger.mod", "entrypoint", "--name", moduleName, "--client-version", targetVersion, "--output", entrypointOutput] + + outside.map { pattern => "--outside=" + pattern }, + experimentalPrivilegedNesting: true, + ) .directory(entrypointOutput) .withNewFile("build.dang", buildDang) .withNewFile("workspace_reader.py", currentModule.source.file("runtime/workspace_reader.py").contents) } + """ + The module the engine names once the entrypoint is generated: the manifest + this generation writes, with the entrypoint's directory in place, since the + dang.toml governing it decides the version the module is named by. + """ + let namedSource(target: Workspace!, entrypointPath: String!): ModuleSource! { + entrypointManifest(target.withDirectory("/" + rootPath + "/" + entrypointPath, directory), entrypointPath) + .moduleSource("/" + rootPath) + } + """ runtime/build.dang with its reads of this module's source inlined, so the copy in a generated entrypoint needs nothing but itself and the workspace diff --git a/runtime/build.dang b/runtime/build.dang index c7622dd8..1a7d431c 100644 --- a/runtime/build.dang +++ b/runtime/build.dang @@ -90,7 +90,6 @@ type PythonModuleBuild { # Last, so the layers above are shared between modules. .withEnvVariable("DAGGER_MODULE", moduleName) .withEnvVariable("DAGGER_DEFAULT_PYTHON_PACKAGE", packageName) - .withEnvVariable("DAGGER_MAIN_OBJECT", mainObjectName(moduleName)) install(built, source, cfg) } @@ -103,40 +102,6 @@ type PythonModuleBuild { pyConfig(directory.withFile(projectCfg, pyproject), ".").members } - """ - The class name of a module's main object, converted like the engine's builtin - Python runtime (strcase.ToCamel) so a module loads the same on both. - """ - pub mainObjectName(name: String!): String! { - name - .trimSpace - .split("") - .reduce(CamelState(out: "", capNext: true, prevIsCap: false)) { state, c => - let isCap = c.containsMatch("^[A-Z]$") - let isLow = c.containsMatch("^[a-z]$") - let isNum = c.containsMatch("^[0-9]$") - if (isCap or isLow) { - let v = if (state.capNext and isLow) { - c.toUpper - } else if (state.capNext == false and state.prevIsCap and isCap) { - c.toLower - } else { - c - } - CamelState(out: state.out + v, capNext: false, prevIsCap: isCap) - } else if (isNum) { - CamelState(out: state.out + c, capNext: true, prevIsCap: false) - } else { - CamelState( - out: state.out, - capNext: c == "_" or c == " " or c == "-" or c == ".", - prevIsCap: false, - ) - } - } - .out - } - let base(baseImage: String!, uvImage: String!, cfg: PyConfig!): Container! { let uvBins = container.from(uvImage).rootfs @@ -549,19 +514,3 @@ type PyConfig { members.filter { member => member == "sdk" }.length > 0 } } - -""" -Accumulator for the CamelCase conversion of a module name. -""" -type CamelState { - pub out: String! - pub capNext: Boolean! - pub prevIsCap: Boolean! - - new(out: String! = "", capNext: Boolean! = true, prevIsCap: Boolean! = false) { - self.out = out - self.capNext = capNext - self.prevIsCap = prevIsCap - self - } -} diff --git a/runtime/main.dang b/runtime/main.dang index 9d45fa29..01d12f9b 100644 --- a/runtime/main.dang +++ b/runtime/main.dang @@ -37,11 +37,4 @@ type PythonSdkRuntime { pub scopeMembers(pyproject: File!): [String!]! { PythonModuleBuild().scopeMembers(pyproject) } - - """ - The class name of a module's main object. - """ - pub mainObjectName(name: String!): String! { - PythonModuleBuild().mainObjectName(name) - } } diff --git a/sdk/src/dagger/mod/__main__.py b/sdk/src/dagger/mod/__main__.py index f0f27d2a..5acc564b 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -1,6 +1,7 @@ """Commands the generated entrypoint runs in the module's container.""" import argparse +import functools import json import logging import pathlib @@ -71,14 +72,10 @@ def main(argv: list[str] | None = None) -> int: def _entrypoint(args: argparse.Namespace) -> None: - from dagger.client._descriptor import registering_types from dagger.mod._entrypoint import write_entrypoint - from dagger.mod.cli import load_module - with registering_types(): - mod = load_module() write_entrypoint( - mod.describe(), + _described(), name=args.name, client_version=args.client_version, output=args.output, @@ -87,14 +84,22 @@ def _entrypoint(args: argparse.Namespace) -> None: def _describe(args: argparse.Namespace) -> None: - from dagger.client._descriptor import registering_types from dagger.mod._describe import describe_json + + description = _described() + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(describe_json(description)) + + +def _described(): + """The module's description, its main object the one the engine takes.""" + from dagger.client._descriptor import registering_types from dagger.mod.cli import load_module with registering_types(): mod = load_module() - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(describe_json(mod.describe())) + anyio.run(functools.partial(mod.load_naming, names=False)) + return mod.describe() def _call(args: argparse.Namespace) -> None: diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index a5c4968b..5e90bda3 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -36,12 +36,13 @@ InvalidInputError, InvalidResultError, ModuleError, + ModuleLoadError, ObjectNotFoundError, RegistrationError, log_exception_only, transform_error, ) -from dagger.mod._naming import ModuleNames, module_names +from dagger.mod._naming import ModuleNames, ask_naming, source_id from dagger.mod._resolver import ( Constructor, Field, @@ -110,28 +111,61 @@ def names(self) -> ModuleNames: """The engine's names for the module's interfaces and enums. Calls through the module's own interfaces select them. Asked for by - ``load_names``, before anything is invoked. + ``load_naming``, before anything is invoked. """ if self._names is None: msg = "The module's schema names were not asked for before the call" raise ModuleError(msg) return self._names - async def load_names(self) -> None: - """Ask the engine how it names the module, before anything is invoked. + def set_main(self, name: str) -> None: + """Make the object of that class name the module's main object.""" + self._main_name = name + self._main = self._objects.get(name) - A module without interfaces makes no call by the engine's names of its - own declarations, so it asks nothing. + async def load_naming(self, *, names: bool = True) -> None: + """Ask the engine how it names the module, once its code is imported. + + One query, for what the module doesn't know yet: + + - which class is the main object, the one the engine finds by the + module's name, unless the module was given its name; + - with ``names``, the engine's names for the module's interfaces and + enums, which the calls through its own interfaces select. A module + without interfaces makes no such call, so it asks nothing for them. """ - if self._names is not None: - return - interfaces = [obj for obj in self._objects.values() if obj.interface] - if not interfaces: - self._names = ModuleNames() + candidates = None + if not self._main_name: + candidates = [ + name for name, obj in self._objects.items() if not obj.interface + ] + interfaces = [] + if names and self._names is None: + interfaces = [obj for obj in self._objects.values() if obj.interface] + if not interfaces: + self._names = ModuleNames() + if candidates is None and not interfaces: return - self._names = await module_names(interfaces, self._enums.values()) - # Bindings are built with the names they have when first used. - to_interface_impl.cache_clear() + naming = await ask_naming( + candidates=candidates, + interfaces=interfaces, + enums=self._enums.values(), + source_id=source_id(), + ) + if candidates is not None: + if naming.main_object is None: + msg = ( + f"The engine takes none of the module's object types " + f"({', '.join(candidates) or 'there are none'}) for the main " + f"object of module {MODULE_NAME!r}: name a class decorated " + "with @dagger.object_type after the module" + ) + raise ModuleLoadError(msg) + self.set_main(naming.main_object) + if interfaces: + self._names = naming.names + # Bindings are built with the names they have when first used. + to_interface_impl.cache_clear() def is_own_enum(self, cls: Any) -> bool: """Whether a class is one of the enums this module declares.""" @@ -178,21 +212,23 @@ async def register(self): await anyio.Path(TYPE_DEF_FILE).write_text(output) async def _typedefs(self) -> str: + await self.load_naming(names=False) return await _module_from(self.describe()).id() def describe(self) -> ModuleDescription: """Describe the registered types as plain data.""" if not self._main_name: - msg = "Main object name can't be empty" + msg = ( + "The module's main object isn't known: ask the engine for it " + "(Module.load_naming) before describing the module" + ) raise ValueError(msg) try: self.get_object(self._main_name) except ObjectNotFoundError as e: msg = ( f"Main object with name '{self._main_name}' not found or class not " - "decorated with '@dagger.object_type'\n" - f"If you believe the module name '{MODULE_NAME}' is incorrectly " - "being converted into PascalCase, please file a bug report." + "decorated with '@dagger.object_type'" ) raise ObjectNotFoundError(msg, extra=e.extra) from None @@ -269,7 +305,7 @@ async def invoke(self) -> str: }, ) - await self.load_names() + await self.load_naming() result = await self.get_result( parent_name, @@ -298,7 +334,7 @@ async def dispatch(self, request: Mapping[str, Any]) -> Any: except ValueError as e: msg = "Unable to decode the call request" raise InvalidInputError(msg, extra={"request": request}) from e - await self.load_names() + await self.load_naming() return await self.get_result( request["receiverType"], parent_state or {}, diff --git a/sdk/src/dagger/mod/_naming.py b/sdk/src/dagger/mod/_naming.py index 4fd430c5..58c4abea 100644 --- a/sdk/src/dagger/mod/_naming.py +++ b/sdk/src/dagger/mod/_naming.py @@ -1,24 +1,31 @@ -"""Schema names the engine gives a module's own declarations. +"""How the engine names a module's own declarations. The runtime registers Python names (``get_url``, ``HttpFetcher``) and the engine turns them into schema names (``getUrl``, ``NamingAppHTTPFetcher``) by -the naming rules of the version it names the module by. The calls the runtime -builds itself, through the module's own interfaces, have to use those schema -names: a wrong one is a fragment on a type that doesn't exist, a field the -interface doesn't have, or an unknown enum member. - -So the runtime doesn't predict them: it asks the engine, which answers for the -module it is running (``CurrentModule.naming``) by the same rules it names the -module by, legacy strcase for a module declaring a version before the -identifier casing cut. One query per call, before anything is invoked, for -every name the calls through the module's interfaces can use. +the naming rules of the version it names the module by. Two things in the +runtime depend on those rules: + +- which of the module's classes is its main object, the one the engine finds + by the module's name; +- the calls the runtime builds itself, through the module's own interfaces, + which select schema names: a wrong one is a fragment on a type that doesn't + exist, a field the interface doesn't have, or an unknown enum member. + +The runtime doesn't predict either: it asks the engine (``ModuleNaming``), +which answers by the same rules it names the module by, legacy strcase for a +module declaring a version before the identifier casing cut. It asks once, +when the module is loaded, in one query: for the module it is running +(``CurrentModule.naming``), or, when generation renders a module's entrypoint +from outside of it, for the module source generation names +(``ModuleSource.naming``, by the ID in ``SOURCE_ID_ENV``). """ from __future__ import annotations import dataclasses +import os import typing -from collections.abc import Awaitable, Callable, Iterable +from collections.abc import Awaitable, Callable, Iterable, Sequence from dagger.client._core import to_literal from dagger.client._session import default_session @@ -29,6 +36,9 @@ from dagger.mod._resolver import ObjectType +SOURCE_ID_ENV = "DAGGER_MODULE_SOURCE_ID" +"""The ID of the ModuleSource to ask about, for a module not running in it.""" + Execute: typing.TypeAlias = Callable[[str], Awaitable[typing.Any]] """Runs a GraphQL query against the engine and returns its data.""" @@ -73,53 +83,75 @@ def _get(names: typing.Mapping[str, str], name: str, what: str) -> str: raise ModuleError(msg) from None -async def module_names( - interfaces: Iterable[ObjectType], - enums: Iterable[type[enum.Enum]], - execute: Execute = _execute, -) -> ModuleNames: - """Ask the engine how it names the module's interfaces and enums. +@dataclasses.dataclass(frozen=True, slots=True) +class Naming: + """The engine's answers for a module.""" + + main_object: str | None = None + """Which candidate the engine takes as the main object; None if it wasn't + asked, or takes none.""" + + names: ModuleNames = dataclasses.field(default_factory=ModuleNames) + - One query: the interfaces' type names, their functions' and arguments' - names, and the members of the module's enums, which calls through an - interface send and receive. +async def ask_naming( + *, + candidates: Sequence[str] | None = None, + interfaces: Iterable[ObjectType] = (), + enums: Iterable[type[enum.Enum]] = (), + source_id: str | None = None, + execute: Execute = _execute, +) -> Naming: + """Ask the engine, in one query, how it names the module. + + ``candidates`` are the classes that may be the main object, which is + asked only when given. The names are those of the interfaces, their + functions and arguments, and the members of the module's enums, which + calls through an interface send and receive; asked only for a module + with interfaces. ``source_id`` names the module source to ask about; + without it, the module the runtime runs in. """ interfaces = list(interfaces) - types = sorted({iface.cls.__name__ for iface in interfaces}) - fields = sorted( - { - name - for iface in interfaces - for fn in iface.functions.values() - for name in (fn.name, *(p.name for p in fn.parameters.values())) - } - ) - members = sorted({member.name for cls in enums for member in cls}) - asked = { - "typeNames": types, - "fieldNames": fields, - "enumMemberNames": members, - } - selections = "\n".join( - f" {field}(names: {to_literal(names)})" + asked: dict[str, list[str]] = {} + if interfaces: + asked["typeNames"] = sorted({iface.cls.__name__ for iface in interfaces}) + asked["fieldNames"] = sorted( + { + name + for iface in interfaces + for fn in iface.functions.values() + for name in (fn.name, *(p.name for p in fn.parameters.values())) + } + ) + asked["enumMemberNames"] = sorted( + {member.name for cls in enums for member in cls} + ) + selections = [ + f"{field}(names: {to_literal(names)})" for field, names in asked.items() if names - ) + ] + if candidates is not None: + selections.append(f"mainObject(candidates: {to_literal(list(candidates))})") if not selections: - return ModuleNames() - data = await execute( - "query ModuleNaming {\n" - " currentModule {\n" - " naming {\n" - f"{selections}\n" - " }\n" - " }\n" - "}" - ) - naming = (data or {}).get("currentModule", {}).get("naming", {}) + return Naming() + + fields = "".join(f" {s}\n" for s in selections) + if source_id is None: + root, open_, close = "currentModule", "currentModule {", "}" + else: + root = "node" + open_ = f"node(id: {to_literal(source_id)}) {{ ... on ModuleSource {{" + close = "} }" + query = f"query ModuleNaming {{\n {open_}\n naming {{\n{fields}" + data = await execute(f"{query} }}\n {close}\n}}") + naming = ((data or {}).get(root) or {}).get("naming") + if not isinstance(naming, dict): + msg = f"The engine answered no ModuleNaming: {data!r}" + raise ModuleError(msg) def answers(field: str) -> dict[str, str]: - names = asked[field] + names = asked.get(field) if not names: return {} got = naming.get(field) @@ -128,8 +160,16 @@ def answers(field: str) -> dict[str, str]: raise ModuleError(msg) return dict(zip(names, got, strict=True)) - return ModuleNames( - types=answers("typeNames"), - fields=answers("fieldNames"), - enum_members=answers("enumMemberNames"), + return Naming( + main_object=naming.get("mainObject") if candidates is not None else None, + names=ModuleNames( + types=answers("typeNames"), + fields=answers("fieldNames"), + enum_members=answers("enumMemberNames"), + ), ) + + +def source_id() -> str | None: + """The module source generation asks about, if it gave one.""" + return os.environ.get(SOURCE_ID_ENV) or None diff --git a/sdk/src/dagger/mod/cli.py b/sdk/src/dagger/mod/cli.py index 21a11e2b..c6875247 100644 --- a/sdk/src/dagger/mod/cli.py +++ b/sdk/src/dagger/mod/cli.py @@ -15,8 +15,9 @@ from dagger.client._connection import connect from dagger.client._descriptor import registering_types from dagger.client._session import mark_module_runtime +from dagger.mod import default_module from dagger.mod._exceptions import ModuleError, ModuleLoadError, record_exception -from dagger.mod._module import MAIN_OBJECT, Module +from dagger.mod._module import Module logger = logging.getLogger(__package__) @@ -60,14 +61,26 @@ async def main(mod: Module | None = None, register: bool = False) -> int | None: def load_module() -> Module: - """Load the dagger.Module instance via the main object entry point.""" - ep = get_entry_point() + """Load the dagger.Module instance the module's code registers with. + + The code is imported through the main object entry point when the + project names one, and else as the default package, whose import + registers its types. Which class is the main object the engine says, + once the module is loaded (Module.load_naming). + """ + ep = configured_entry_point() + target = ep.module if ep else default_package() try: + if ep is None: + importlib.import_module(target) + return default_module() cls = ep.load() + except ModuleLoadError: + raise except Exception as e: logger.exception( "Error while importing Python module '%s' with Dagger functions", - ep.module, + target, ) raise ModuleLoadError(str(e)) from e try: @@ -80,33 +93,27 @@ def load_module() -> Module: raise ModuleLoadError(msg) from None -def get_entry_point() -> importlib.metadata.EntryPoint: - """Get the entry point for the main object.""" +def configured_entry_point() -> importlib.metadata.EntryPoint | None: + """The main object entry point the project configures, if any.""" sel = importlib.metadata.entry_points( group=ENTRY_POINT_GROUP, name=ENTRY_POINT_NAME, ) - if ep := next(iter(sel), None): - return ep + return next(iter(sel), None) - import_pkg = IMPORT_PKG +def default_package() -> str: + """The package that holds the module's code by default.""" + if importlib.util.find_spec(IMPORT_PKG): + return IMPORT_PKG # Fallback for modules that still use the "main" package name. - if not importlib.util.find_spec(import_pkg): - import_pkg = "main" - - if not importlib.util.find_spec(import_pkg): - msg = ( - "Main object not found. You can configure it explicitly by adding " - "an entry point to your pyproject.toml file. For example:\n" - "\n" - f'[project.entry-points."{ENTRY_POINT_GROUP}"]\n' - f"{ENTRY_POINT_NAME} = '{IMPORT_PKG}:{MAIN_OBJECT}'\n" - ) - raise ModuleLoadError(msg) - - return importlib.metadata.EntryPoint( - group=ENTRY_POINT_GROUP, - name=ENTRY_POINT_NAME, - value=f"{import_pkg}:{MAIN_OBJECT}", + if importlib.util.find_spec("main"): + return "main" + msg = ( + "Main object not found. You can configure it explicitly by adding " + "an entry point to your pyproject.toml file. For example:\n" + "\n" + f'[project.entry-points."{ENTRY_POINT_GROUP}"]\n' + f"{ENTRY_POINT_NAME} = '{IMPORT_PKG}:MyModule'\n" ) + raise ModuleLoadError(msg) diff --git a/sdk/tests/mod/conftest.py b/sdk/tests/mod/conftest.py index 9ed74143..0aa3cd8a 100644 --- a/sdk/tests/mod/conftest.py +++ b/sdk/tests/mod/conftest.py @@ -38,17 +38,20 @@ def _selections(obj: Type): _NAMING_FIELD = re.compile( r"(typeNames|fieldNames|enumMemberNames)\(names: (\[.*?\])\)" ) +_MAIN_OBJECT_FIELD = re.compile(r"mainObject\(candidates: (\[.*?\])\)") class FakeEngine: - """Answers CurrentModule.naming from a table of the engine's names. + """Answers ModuleNaming from a table of the engine's names. A name the table lacks fails the query, as a name the engine can't name - does. Any other query gets the canned data. It keeps what it was asked. + does. mainObject answers ``main_object`` if it's among the candidates. + Any other query gets the canned data. It keeps what it was asked. """ def __init__(self, names: typing.Mapping[str, typing.Mapping[str, str]]): self.names = names + self.main_object: str | None = None self.data: typing.Any = None self.queries: list[str] = [] @@ -60,11 +63,17 @@ async def execute(self, query: str): self.queries.append(query) if not query.startswith("query ModuleNaming"): return self.data - naming = {} + naming: dict[str, typing.Any] = {} for field, names in _NAMING_FIELD.findall(query): table = self.names.get(field, {}) naming[field] = [table[name] for name in json.loads(names)] - return {"currentModule": {"naming": naming}} + if m := _MAIN_OBJECT_FIELD.search(query): + candidates = json.loads(m.group(1)) + naming["mainObject"] = ( + self.main_object if self.main_object in candidates else None + ) + root = "node" if "node(id:" in query else "currentModule" + return {root: {"naming": naming}} @pytest.fixture diff --git a/sdk/tests/mod/test_interfaces.py b/sdk/tests/mod/test_interfaces.py index d49caebf..443c0258 100644 --- a/sdk/tests/mod/test_interfaces.py +++ b/sdk/tests/mod/test_interfaces.py @@ -69,7 +69,7 @@ class Pond: @pytest.fixture async def duck(mod: Module, engine): engine.names = POND_NAMES - await mod.load_names() + await mod.load_naming() r, t = await mod.get_structured_result( "Pond", {"duck": "123456"}, diff --git a/sdk/tests/mod/test_naming.py b/sdk/tests/mod/test_naming.py index 717c26da..1a86b8eb 100644 --- a/sdk/tests/mod/test_naming.py +++ b/sdk/tests/mod/test_naming.py @@ -1,4 +1,4 @@ -"""How the runtime gets the schema names of the module's declarations.""" +"""How the runtime asks the engine how it names the module.""" import enum import typing @@ -7,8 +7,8 @@ import dagger from dagger.mod import Module -from dagger.mod._exceptions import ModuleError -from dagger.mod._naming import ModuleNames, module_names +from dagger.mod._exceptions import ModuleError, ModuleLoadError +from dagger.mod._naming import SOURCE_ID_ENV, ModuleNames, ask_naming pytestmark = [ pytest.mark.anyio, @@ -71,16 +71,19 @@ async def fetcher(mod: Module): async def test_one_query(mod: Module, engine): engine.names = NAMES - await mod.load_names() - await mod.load_names() + await mod.load_naming() + await mod.load_naming() assert len(engine.naming_queries) == 1 query = engine.naming_queries[0] + assert "currentModule {" in query assert 'typeNames(names: ["HttpFetcher"])' in query assert ( 'fieldNames(names: ["also", "arch", "arches", "e2e_test", "with_arch"])' in query ) assert 'enumMemberNames(names: ["AMD64", "arm64"])' in query + # Given its main object's name, the module doesn't ask for it. + assert "mainObject" not in query async def test_no_interfaces_asks_nothing(engine): @@ -90,13 +93,93 @@ async def test_no_interfaces_asks_nothing(engine): class Plain: pass - await m.load_names() + await m.load_naming() assert engine.queries == [] +async def test_main_object_by_the_engine(engine): + m = Module("") + + @m.object_type + class Helper: + pass + + @m.object_type + class K8STools: + pass + + engine.main_object = "K8STools" + await m.load_naming() + assert len(engine.naming_queries) == 1 + assert 'mainObject(candidates: ["Helper", "K8STools"])' in engine.queries[0] + assert m.main_cls is K8STools + assert m.describe().main_object == "K8STools" + + +async def test_main_object_with_the_names_in_one_query(engine): + m = Module("") + + @m.interface + class Fetcher(typing.Protocol): + @m.function + async def get(self) -> str: ... + + @m.object_type + class Tools: + pass + + engine.names = { + "typeNames": {"Fetcher": "ToolsFetcher"}, + "fieldNames": {"get": "get"}, + } + engine.main_object = "Tools" + await m.load_naming() + assert len(engine.queries) == 1 + assert "mainObject" in engine.queries[0] + assert "typeNames" in engine.queries[0] + assert m.names.type_name("Fetcher") == "ToolsFetcher" + + +@pytest.mark.usefixtures("engine") +async def test_no_main_object_fails(): + m = Module("") + + @m.object_type + class Helper: + pass + + with pytest.raises(ModuleLoadError, match="Helper"): + await m.load_naming() + + +def test_describe_needs_the_main_object(): + m = Module("") + + @m.object_type + class Helper: + pass + + with pytest.raises(ValueError, match="main object isn't known"): + m.describe() + + +async def test_naming_of_a_given_module_source(engine, monkeypatch): + monkeypatch.setenv(SOURCE_ID_ENV, "source-id") + m = Module("") + + @m.object_type + class Tools: + pass + + engine.main_object = "Tools" + await m.load_naming(names=False) + assert 'node(id: "source-id") { ... on ModuleSource {' in engine.queries[0] + assert m.main_cls is Tools + + async def test_calls_by_the_engines_names(mod: Module, engine): engine.names = NAMES - await mod.load_names() + await mod.load_naming() r = await fetcher(mod) arch = mod._enums["Arch"] @@ -112,7 +195,7 @@ async def test_calls_by_the_engines_names(mod: Module, engine): async def test_enum_results(mod: Module, engine): engine.names = NAMES - await mod.load_names() + await mod.load_naming() r = await fetcher(mod) arch = mod._enums["Arch"] @@ -143,4 +226,4 @@ async def execute(_): interfaces = [o for o in mod._objects.values() if o.interface] with pytest.raises(ModuleError, match="typeNames"): - await module_names(interfaces, (), execute) + await ask_naming(interfaces=interfaces, execute=execute) From cd9eef0ca08daf8d5d6a85f1293a60a235eb7942 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 22:58:10 +0000 Subject: [PATCH 07/20] scope: read clients at their own naming A client's schema was read with withEngineVersion(view), which makes the module declare the scope's version, and since the identifier casing cut that also names its declarations by that version's rules: the client of a module the engine names by v1.0.0-beta.22 had NamingAppHttpFetcher where the engine serves NamingAppHTTPFetcher. clientSchemaIntrospectionJson's clientVersion describes core at the scope's view and leaves the module at the version it declares. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- scope.dang | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/scope.dang b/scope.dang index e062f5d9..a083fc60 100644 --- a/scope.dang +++ b/scope.dang @@ -565,8 +565,16 @@ type Scope { .withDirectory("src", clientSource(member)) } + """ + A client's schema: its module as the engine names and serves it, by the + version the module itself declares, with core as the scope sees it. Not + withEngineVersion(view), which would make the module declare the scope's + version and so name its declarations by that version's rules: a client of + a module past the identifier casing cut would call names the engine does + not serve it by. + """ let clientSchema(member: ClientMember!): File! { - let schema = member.source.withEngineVersion(view).clientSchemaIntrospectionJson + let schema = member.source.clientSchemaIntrospectionJson(clientVersion: view) checkClientLoads(member, schema) schema } From 37c4a9b1d354efc9bd309632d6b64cf7bc45d8ac Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 23:21:20 +0000 Subject: [PATCH 08/20] template: name the main class through the engine A new module's main class was named with strcase.ToCamel of the module's name, a casing converter of the SDK's own. The engine spells it now (formatIdentifiers, PASCAL), asked by the template renderer as a nested client: k8s-tools is K8sTools, as the engine's naming rules name it. The unused ModuleImport (strcase.ToKebab) and mod._utils.to_pascal_case go too. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- helpers/render-template/go.mod | 2 - helpers/render-template/go.sum | 2 - helpers/render-template/main.go | 63 +++++++++++++++++++++++++--- helpers/render-template/main_test.go | 5 ++- python-sdk.dang | 6 ++- sdk/src/dagger/mod/_utils.py | 6 --- 6 files changed, 65 insertions(+), 19 deletions(-) delete mode 100644 helpers/render-template/go.sum diff --git a/helpers/render-template/go.mod b/helpers/render-template/go.mod index f4d77667..daef993a 100644 --- a/helpers/render-template/go.mod +++ b/helpers/render-template/go.mod @@ -1,5 +1,3 @@ module render-template go 1.25.0 - -require github.com/iancoleman/strcase v0.3.0 diff --git a/helpers/render-template/go.sum b/helpers/render-template/go.sum deleted file mode 100644 index 6261b6ac..00000000 --- a/helpers/render-template/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= -github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= diff --git a/helpers/render-template/main.go b/helpers/render-template/main.go index d025be46..799287a6 100644 --- a/helpers/render-template/main.go +++ b/helpers/render-template/main.go @@ -2,18 +2,19 @@ package main import ( "bytes" + "encoding/json" + "errors" "fmt" + "net/http" "os" "path/filepath" "regexp" "strings" "text/template" - - "github.com/iancoleman/strcase" ) func main() { - if err := run(os.Args[1:]); err != nil { + if err := run(os.Args[1:], engineTypeName); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } @@ -28,7 +29,54 @@ func packageName(moduleName string) string { return strings.ReplaceAll(project, "-", "_") } -func run(args []string) error { +// engineTypeName is the module's name in PascalCase as the engine spells it +// (formatIdentifiers), which the template names the main class after: the +// engine knows where the name's words are. It asks the Dagger session the +// command runs in as a nested client. +func engineTypeName(moduleName string) (string, error) { + port, token := os.Getenv("DAGGER_SESSION_PORT"), os.Getenv("DAGGER_SESSION_TOKEN") + if port == "" || token == "" { + return "", errors.New("no Dagger session to name the module's class with: run render-template as a nested client") + } + body, err := json.Marshal(map[string]any{ + "query": `query($names: [String!]!) { formatIdentifiers(names: $names, casing: PASCAL) }`, + "variables": map[string]any{"names": []string{moduleName}}, + }) + if err != nil { + return "", err + } + req, err := http.NewRequest(http.MethodPost, "http://127.0.0.1:"+port+"/query", bytes.NewReader(body)) + if err != nil { + return "", err + } + req.Header.Set("Content-Type", "application/json") + req.SetBasicAuth(token, "") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + var result struct { + Data struct { + FormatIdentifiers []string `json:"formatIdentifiers"` + } `json:"data"` + Errors []struct { + Message string `json:"message"` + } `json:"errors"` + } + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return "", fmt.Errorf("format the module's name: HTTP %s: %w", resp.Status, err) + } + if len(result.Errors) > 0 { + return "", fmt.Errorf("format the module's name %q: %s", moduleName, result.Errors[0].Message) + } + if len(result.Data.FormatIdentifiers) != 1 { + return "", fmt.Errorf("format the module's name %q: got %v", moduleName, result.Data.FormatIdentifiers) + } + return result.Data.FormatIdentifiers[0], nil +} + +func run(args []string, typeName func(string) (string, error)) error { if len(args) != 3 { return fmt.Errorf("usage: render-template MODULE_NAME TEMPLATE_DIR OUT_DIR") } @@ -36,11 +84,14 @@ func run(args []string) error { moduleName := args[0] templateDir := args[1] outDir := args[2] + moduleType, err := typeName(moduleName) + if err != nil { + return err + } data := map[string]string{ "ModuleName": moduleName, "ModuleProject": strings.ToLower(moduleName), - "ModuleType": strcase.ToCamel(moduleName), - "ModuleImport": "dagger/" + strcase.ToKebab(moduleName), + "ModuleType": moduleType, "ModulePackage": packageName(moduleName), } diff --git a/helpers/render-template/main_test.go b/helpers/render-template/main_test.go index c3ae38e8..609d52ee 100644 --- a/helpers/render-template/main_test.go +++ b/helpers/render-template/main_test.go @@ -7,6 +7,9 @@ import ( "testing" ) +// stubTypeName stands in for the engine, which spells the class name. +func stubTypeName(string) (string, error) { return "Main", nil } + func TestRenderedPackageMatchesTheRuntime(t *testing.T) { for _, tc := range []struct { name, project, pkg string @@ -22,7 +25,7 @@ func TestRenderedPackageMatchesTheRuntime(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { out := t.TempDir() - if err := run([]string{tc.name, filepath.Join("..", "..", "templates", "default"), out}); err != nil { + if err := run([]string{tc.name, filepath.Join("..", "..", "templates", "default"), out}, stubTypeName); err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(out, "src", tc.pkg, "__init__.py")); err != nil { diff --git a/python-sdk.dang b/python-sdk.dang index 0f9c4918..a39c106f 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -793,7 +793,9 @@ type PythonSdk { } """ - Render a Python template with the requested module name. + Render a Python template with the requested module name. The engine spells + the main class's name (formatIdentifiers), which the renderer asks as a + nested client. """ let renderedTemplate(name: String!, templateName: String!): Directory! { container @@ -805,7 +807,7 @@ type PythonSdk { .withDirectory("/template", currentModule.source.directory("templates/" + templateName)) .withWorkdir("/helper") .withExec(["go", "build", "-o", "/usr/local/bin/render-template", "."]) - .withExec(["render-template", name, "/template", "/rendered"]) + .withExec(["render-template", name, "/template", "/rendered"], experimentalPrivilegedNesting: true) .directory("/rendered") } diff --git a/sdk/src/dagger/mod/_utils.py b/sdk/src/dagger/mod/_utils.py index 06ae8907..0ae9c8b6 100644 --- a/sdk/src/dagger/mod/_utils.py +++ b/sdk/src/dagger/mod/_utils.py @@ -19,7 +19,6 @@ import typing_extensions from cattrs.cols import is_sequence -from dagger.client._core import snake_to_camel from dagger.client.base import Type from dagger.mod._arguments import DefaultAddress, DefaultPath, Deprecated, Ignore, Name from dagger.mod._types import ContextPath @@ -46,11 +45,6 @@ async def await_maybe(value: AwaitableOrValue[T]) -> T: return await value if inspect.iscoroutine(value) else cast(T, value) -def to_pascal_case(s: str) -> str: - """Convert a string to PascalCase.""" - return snake_to_camel(s.replace("-", "_")) - - def normalize_name(name: str) -> str: """Remove the last underscore, used to avoid conflicts with reserved words.""" if name.endswith("_") and name[-2] != "_" and not name.startswith("_"): From eb92da043d6c18f7f3ad8bb3d89f24eb136e4515 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 23:23:08 +0000 Subject: [PATCH 09/20] codegen: record every input field's GraphQL name The query builder derived an input field's GraphQL name from its Python name with snake_to_camel, and the generator recorded only the names that conversion missed. Python names are the engine's spelling now, so nothing converts them back: the generator records every field's GraphQL name and the query builder sends that one, refusing a field without one. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- sdk/codegen/src/codegen/generator.py | 12 ++++-------- sdk/src/dagger/client/_core.py | 21 ++++++--------------- sdk/tests/client/test_query_builder.py | 26 ++++++++++++-------------- sdk/tests/codegen/test_generator.py | 2 +- 4 files changed, 23 insertions(+), 38 deletions(-) diff --git a/sdk/codegen/src/codegen/generator.py b/sdk/codegen/src/codegen/generator.py index b52bb2bc..b2139e1c 100644 --- a/sdk/codegen/src/codegen/generator.py +++ b/sdk/codegen/src/codegen/generator.py @@ -49,7 +49,6 @@ get_named_type, is_leaf_type, ) -from graphql.pyutils import snake_to_camel from graphql.type.schema import TypeMap from codegen.naming import snake @@ -1120,13 +1119,10 @@ def render_body(self, t: GraphQLInputObjectType) -> Iterator[str]: ) ) - # The query builder derives GraphQL names from the Python ones; record - # only those it can't. - names = { - f.name: f.graphql_name - for f in fields - if snake_to_camel(f.name, upper=False) != f.graphql_name - } + # The query builder sends a field by the GraphQL name recorded here: + # the Python name is the engine's spelling, which nothing converts + # back. + names = {f.name: f.graphql_name for f in fields} if names: yield "" yield f"_graphql_names = {tuple(names.items())!r}" diff --git a/sdk/src/dagger/client/_core.py b/sdk/src/dagger/client/_core.py index c5d3987b..078e32d3 100644 --- a/sdk/src/dagger/client/_core.py +++ b/sdk/src/dagger/client/_core.py @@ -43,22 +43,9 @@ INDENT = " " -_SNAKE_TO_CAMEL_RE = re.compile(r"(_)([a-z\d])") _ENUM_NAME_RE = re.compile(r"[_A-Za-z][_0-9A-Za-z]*") -def snake_to_camel(s: str, upper: bool = True) -> str: - """Convert from snake_case to CamelCase. - - If upper is set, then convert to upper CamelCase, otherwise the first - character keeps its case. - """ - s = _SNAKE_TO_CAMEL_RE.sub(lambda m: m.group(2).upper(), s) - if upper: - s = s[:1].upper() + s[1:] - return s - - class EnumName(str): """A schema enum value, for callers that have no generated enum to send.""" @@ -151,14 +138,18 @@ def _enum_literal(value: enum.Enum | EnumName) -> str: def _input_literal(obj: Input) -> str: - # The generator records only the GraphQL names snake_to_camel can't derive. + # The generator records each field's GraphQL name. names = dict(getattr(type(obj), "_graphql_names", ())) fields = [] for f in dataclasses.fields(obj): value = getattr(obj, f.name) if f.default is not MISSING and value == f.default: continue - name = names.get(f.name) or snake_to_camel(f.name, upper=False) + try: + name = names[f.name] + except KeyError: + msg = f"{type(obj).__name__} records no GraphQL name for {f.name!r}" + raise InvalidQueryError(msg) from None fields.append(f"{name}: {to_literal(value)}") return "{" + ", ".join(fields) + "}" diff --git a/sdk/tests/client/test_query_builder.py b/sdk/tests/client/test_query_builder.py index 95892c3c..e2f36a61 100644 --- a/sdk/tests/client/test_query_builder.py +++ b/sdk/tests/client/test_query_builder.py @@ -3,8 +3,8 @@ import pytest -from dagger._exceptions import ClientError -from dagger.client._core import Arg, Context, EnumName, snake_to_camel, to_literal +from dagger._exceptions import ClientError, InvalidQueryError +from dagger.client._core import Arg, Context, EnumName, to_literal from dagger.client.base import Enum, Input, Scalar, Type @@ -22,7 +22,7 @@ class Block(Input): call_id: str | None = None ssh_url: str | None = None - _graphql_names = (("ssh_url", "sshURL"),) + _graphql_names = (("kind", "kind"), ("call_id", "callId"), ("ssh_url", "sshURL")) @dataclass(slots=True) @@ -31,6 +31,8 @@ class Message(Input): text: str | None = "" errored: bool | None = False + _graphql_names = (("kind", "kind"), ("text", "text"), ("errored", "errored")) + class Container(Type): def echo(self, args: list[str]) -> "Container": @@ -187,17 +189,13 @@ def test_get_value_rejects_null_for_required(): assert ctx.get_value({"version": None}, str | None) is None -@pytest.mark.parametrize( - ("value", "expected"), - [ - ("call_id", "callId"), - ("ssh_url", "sshUrl"), - ("name", "name"), - ], -) -def test_snake_to_camel(value, expected): - assert snake_to_camel(value, upper=False) == expected - assert snake_to_camel(value) == expected[:1].upper() + expected[1:] +def test_input_field_without_a_graphql_name(): + @dataclass(slots=True) + class Bare(Input): + kind: str + + with pytest.raises(InvalidQueryError, match="no GraphQL name for 'kind'"): + to_literal(Bare(kind="x")) def test_enum_literal_before_str(): diff --git a/sdk/tests/codegen/test_generator.py b/sdk/tests/codegen/test_generator.py index 34f7fae7..094a6015 100644 --- a/sdk/tests/codegen/test_generator.py +++ b/sdk/tests/codegen/test_generator.py @@ -647,7 +647,7 @@ def test_input_object_graphql_names(): rendered = InputHandler(local_ctx).render(input_type) assert "@typecheck" not in rendered - assert "_graphql_names = (('ssh_url', 'sshURL'),)" in rendered + assert "_graphql_names = (('call_id', 'callId'), ('ssh_url', 'sshURL'))" in rendered def test_input_object_post_init_checks(): From 50f30eae37197f3e175f1e977135cc35259a4ad1 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 30 Oct 2026 23:46:48 +0000 Subject: [PATCH 10/20] sdk: declare the engine floor, don't check it The runtime declares engineVersion v1.0.0-beta.26, as the SDK already does, and both declare it in dang.toml, which decides a Dang module's version. The SDK's own engine refusal and its check go: no engine that loads the SDK is below the floor. engineFloor becomes targetFloor, the oldest release a targetVersion pin may name, and moves to v1.0.0-beta.26: the generated entrypoint needs ModuleNaming, which an older view does not serve. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 62 +++-------------------------------- README.md | 22 ++++++------- dang.toml | 2 ++ mod.dang | 6 ++-- python-sdk.dang | 62 ++++------------------------------- runtime/dagger-module.toml | 2 +- runtime/dang.toml | 2 ++ 7 files changed, 29 insertions(+), 129 deletions(-) create mode 100644 dang.toml create mode 100644 runtime/dang.toml diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index bb39af44..2cba02b5 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -1729,11 +1729,8 @@ type E2e { let plain = pythonSdk.generateScope(ws.withNewDirectory("/" + plainScope, directory).withWorkdir(plainScope), isModule: false, name: "target-version-plain", clients: []).withWorkdir(".") assert(plain.file("/" + plainScope + "/" + versionFilePath).contents == versionFile, "a plain scope's library does not announce the targeted release") - # Container.publish's sourceDateEpoch is newer than the floor's view, so a - # module pinned to the floor must not see it on any engine. let newInBeta22 = "source_date_epoch" let floorPinned = pythonSdk(targetVersion: floor).generateScope(scoped, isModule: true, name: name, clients: []).withWorkdir(".") - assertNotContains(floorPinned.file("/" + scope + "/" + coreInitPath).contents, newInBeta22, "core was not read in the view of the pinned release") assertContains(floorPinned.file("/" + scope + "/sdk/entrypoint/main.dang").contents, "let clientVersion: String! = \"" + floor + "\"", "the entrypoint does not declare the pinned release") assertContains(floorPinned.file("/" + scope + "/sdk/entrypoint/dang.toml").contents, "dagger = \"" + floor + "\"", "dang.toml does not follow the targetVersion pin") if (version.contains(target)) { @@ -1743,7 +1740,7 @@ type E2e { let remedy = ": set targetVersion in its dagger.toml settings to " + target + ", or remove it to generate for " + target let refusals = [ ["v9.0.0", "v9.0.0, which is later than " + target + ", the engine release this Python SDK generates for: install the SDK release built for v9.0.0, or set targetVersion in its dagger.toml settings to " + target + ", or remove it"], - ["v1.0.0-beta.17", "v1.0.0-beta.17, which is below " + floor + ", the oldest release a targetVersion pin may name" + remedy], + ["v1.0.0-beta.25", "v1.0.0-beta.25, which is below " + floor + ", the oldest release a targetVersion pin may name" + remedy], ["latest", "\"latest\", which is no engine release such as " + target + remedy], ] let plainScope = outputRoot + "/target-version-scope" @@ -1837,13 +1834,10 @@ type E2e { let assertFloorPinned(generated: Container!, configFile: String!, path: String!, args: [String!]!): Void { let command = "`dagger " + args.join(" ") + "`" let root = playgroundRoot + "/" + path + "/" - # Container.publish's sourceDateEpoch is newer than the floor's view. - let newInBeta22 = "source_date_epoch" assertContains(generated.file(playgroundRoot + "/" + configFile).contents, "targetVersion = \"v" + floorVersion + "\"", command + " dropped the recorded pin") assertContains(generated.file(root + "sdk/entrypoint/main.dang").contents, "let clientVersion: String! = \"v" + floorVersion + "\"", command + " did not generate the entrypoint for the pinned release") assertContains(generated.file(root + versionFilePath).contents, "CLI_VERSION = \"" + floorVersion + "\"", command + " did not vendor the pinned release's CLI version") assertContains(generated.file(root + "sdk/entrypoint/dang.toml").contents, "dagger = \"v" + floorVersion + "\"", command + " did not write the pinned release to dang.toml") - assertNotContains(generated.file(root + coreInitPath).contents, newInBeta22, command + " did not read core in the view of the pinned release") null } @@ -2011,11 +2005,10 @@ type E2e { let callerSecretPath: String! = "review-secret.txt" """ - The first release that loads a module's files through its entrypoint's - sources member, and the oldest one a targetVersion pin may name. Its engine - image carries its CLI, and git. + The oldest release a targetVersion pin may name, the SDK's engine floor. Its + engine image carries its CLI, and git. """ - let floorVersion: String! = "1.0.0-beta.18" + let floorVersion: String! = "1.0.0-beta.26" let floorImage: String! { "registry.dagger.io/engine:v" + floorVersion } """ @@ -2319,53 +2312,6 @@ type E2e { null } - """ - The SDK refuses an engine release older than its floor before it generates - anything, and names the version it found and what to do: pin the SDK's last - release before the floor where that release runs, from v1.0.0-beta.14, and - only upgrade below it. Releases are compared as semver orders them, with - the build after a "+" ignored and no word such as "dev" set apart, so a - build of dagger's main passes as the release it reports. A version the - SDK cannot read passes, so an unexpected format never blocks a user. On - an engine the SDK refuses, generation itself refuses. - """ - pub engineFloorRefusalCheck(ws: Workspace!): Void @check { - let pin = "dagger module install github.com/dagger/python-sdk@v1.1.1" - let pinned = ["v1.0.0-beta.17", "v1.0.0-beta.17+0da36c8d", "v1.0.0-beta.17+dev", "v1.0.0-beta.16", "v1.0.0-beta.15", "v1.0.0-beta.14", "v1.0.0-beta.14+06660c3c"] - let upgradeOnly = ["v1.0.0-beta.13", "v1.0.0-beta.9", "v1.0.0-alpha.20", "v0.21.9", "v0.21.1-20260529020034-dev-b2f595b50044", "v1.0.0-alpha-1"] - let accepted = [ - "v1.0.0-beta.18", "v1.0.0-beta.18+249edbd6", "v1.0.0-beta.18+dev", "1.0.0-beta.18", "v1.0.0-beta.19", "v1.0.0-beta.100", - "v1.0.0-beta.1000000000000000000000", "v1.0.0-rc.1", "v1.0.0-rc-1", "v1.0.0", "v1.0.1", "v2.0.0-beta.1", "v1.0.0-dev.3", "devel", "", - ] - (pinned + upgradeOnly).each { engine => - let refusal = pythonSdk.engineRefusal(engine) - let wants = ["needs Dagger engine v" + floorVersion + " or later", "this engine is " + engine + ".", "Upgrade the engine"] - wants.each { want => - assertContains(refusal, want, "engine \"" + engine + "\": the refusal does not say \"" + want + "\": " + refusal) - } - } - pinned.each { engine => - let refusal = pythonSdk.engineRefusal(engine) - assertContains(refusal, pin, "engine \"" + engine + "\": the refusal does not offer the last release that runs on it: " + refusal) - } - upgradeOnly.each { engine => - let refusal = pythonSdk.engineRefusal(engine) - assertNotContains(refusal, "pin", "engine \"" + engine + "\": the refusal offers a release that does not run on it either: " + refusal) - } - accepted.each { engine => - let refusal = pythonSdk.engineRefusal(engine) - assert(refusal == "", "the SDK refused engine \"" + engine + "\": " + refusal) - } - let refusal = pythonSdk.engineRefusal(version) - if (refusal != "") { - let said = pythonSdk.generateScope(ws.withNewDirectory("/floor-probe", directory).withWorkdir("floor-probe"), isModule: true, name: "floor-probe", clients: []).cwd rescue { - err: Error => err.message - } - assert(said.contains(refusal), "generation on engine " + version + ", which the SDK refuses, said: " + said) - } - null - } - """ A module declares a collection, on this checkout's shared entrypoint, on the one generated into it, and on this checkout's runtime, which registers diff --git a/README.md b/README.md index 2b4d519d..392e56d5 100644 --- a/README.md +++ b/README.md @@ -57,21 +57,19 @@ the schema's identifiers, and a module asks it what it named the module's own declarations. An entrypoint runs a module on the engine's own version, so an entrypoint manifest keeps no `engineVersion`. -On an engine without that field, `dagger module init` and `dagger generate` -fail while they load the SDK, before they write anything. A -generated entrypoint fails to load on an older engine with `field "types": -missing argument "workspace" required by interface`. To stay on an engine from -v1.0.0-beta.14 to v1.0.0-beta.17, pin `v1.1.1`, the last release that runs -there: `dagger module install github.com/dagger/python-sdk@v1.1.1`, and -`dagger.io/sdk/python/entrypoint@v1.1.1` for the shared entrypoint of that -release. An engine older than v1.0.0-beta.14 runs neither release, and needs -an upgrade. +The SDK's modules declare `engineVersion` v1.0.0-beta.26. Engines compare +only the base version, so an engine from v1.0.0-beta.18 to v1.0.0-beta.25 does +not refuse them for it: `dagger module init` and `dagger generate` fail while +they load the SDK, before they write anything. To stay on such an engine, pin a +release from before this floor, such as `v1.8.0`: +`dagger module install github.com/dagger/python-sdk@v1.8.0`. To stay on an +engine from v1.0.0-beta.14 to v1.0.0-beta.17, pin `v1.1.1`, the last release +that runs there. An entrypoint served from elsewhere, such as the shared one this repository used to serve as `dagger.io/sdk/python/entrypoint@v1`, a pin of it or a fork, is replaced by the generated entrypoint at the module's next -`dagger generate`. A module moved this way needs an engine `v1.0.0-beta.18` or -later to run, and generating it needs `v1.0.0-beta.26` or later. +`dagger generate`. Generating a module that has a manifest already keeps the kind it names: @@ -132,7 +130,7 @@ for and announces: The scope setting `targetVersion`, under `[sdks.python.scopes."".settings]` in `dagger.toml`, pins the -release, from `v1.0.0-beta.18` to the targeted release; +release, from `v1.0.0-beta.26` to the targeted release; `dagger module init python --target-version ` writes it. Any other value stops generation before it writes anything, with a message that names the module and says why. diff --git a/dang.toml b/dang.toml new file mode 100644 index 00000000..8aac7f14 --- /dev/null +++ b/dang.toml @@ -0,0 +1,2 @@ +[imports.Dagger] +dagger = "v1.0.0-beta.26" diff --git a/mod.dang b/mod.dang index 608768a5..bc449aad 100644 --- a/mod.dang +++ b/mod.dang @@ -152,9 +152,9 @@ type Mod { """ Refuse a module that asks for an older Python than the SDK runs on before anything is written: uv would lock it to the SDK's Python, and the runtime - would still build it on the older one, where the install fails. Beside - checkEngine, which refuses the engine: this one reads the module, so only - generation runs it, and config set stays open to fix the module. + would still build it on the older one, where the install fails. It reads + the module, so only generation runs it, and config set stays open to fix + the module. """ let checkPython: Void { let refusal = PyprojectHelper().pythonRefusal(ws.directory("/" + rootPath, include: ["pyproject.toml", ".python-version"])) diff --git a/python-sdk.dang b/python-sdk.dang index a39c106f..1eb2d980 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -32,7 +32,7 @@ type PythonSdk { pub legacyRuntime: Boolean! = false """ - The engine release to generate for, from v1.0.0-beta.18 to the release + The engine release to generate for, from v1.0.0-beta.26 to the release this SDK targets; empty generates for the targeted release. """ pub targetVersion: String! = "" @@ -161,7 +161,6 @@ type PythonSdk { entrypoint served from elsewhere is replaced by the generated one. """ pub generateScope(ws: Workspace!, isModule: Boolean!, name: String!, clients: [ModuleSource!]!): Workspace! { - checkEngine let scope = normalizePath(ws.cwd) checkTarget(if (isModule) { "module \"" + name + "\"" } else { "scope " + scope }, targetVersion) # Resolve local client paths from the workspace root. @@ -497,10 +496,11 @@ type PythonSdk { let staticEntrypointSource: String! = "./" + staticEntrypointPath """ - The first engine release this SDK runs on: the first that loads a - module's files through its entrypoint's sources member. + The oldest release a targetVersion pin may name: the engine floor. The + generated entrypoint hands the build the engine's ModuleNaming, which the + view of an older release does not serve. """ - let engineFloor: String! = "v1.0.0-beta.18" + let targetFloor: String! = "v1.0.0-beta.26" """ The engine release this SDK release targets: the one it generates for, @@ -509,53 +509,6 @@ type PythonSdk { """ let engineTarget: String! = "v1.0.0-beta.27" - """ - The last release of this SDK that runs on an engine below engineFloor. - """ - let lastReleaseBelowFloor: String! = "v1.1.1" - - """ - The first engine release lastReleaseBelowFloor runs on, as its manifest - declares. - """ - let lastReleaseEngineFloor: String! = "v1.0.0-beta.14" - - """ - Why this SDK refuses an engine of the given version, or the empty string - when it runs on it. Only a release older than the floor is refused: a - version this cannot read passes, so an unexpected format never blocks a - user, and a build of dagger's main passes as the release it reports, - `v+`. The engine's own gate cannot do this: it treats - every prerelease of v1.0.0 as v1.0.0. The refusal offers the last release - below the floor only to an engine that release runs on. - """ - pub engineRefusal(engineVersion: String!): String! { - if (Releases().precedes(engineVersion, engineFloor) == false) { - "" - } else { - let needs = "this Python SDK needs Dagger engine " + engineFloor + " or later, and this engine is " + - engineVersion + ". " - if (Releases().precedes(engineVersion, lastReleaseEngineFloor)) { - needs + "Upgrade the engine." - } else { - needs + "Upgrade the engine, or pin the last release of this SDK that runs on it: " + - "dagger module install github.com/dagger/python-sdk@" + lastReleaseBelowFloor - } - } - } - - """ - Refuse an engine older than the floor before generation reads or writes - anything, so the user reads why instead of an unknown field later. - """ - let checkEngine: Void { - let refusal = engineRefusal(version) - if (refusal != "") { - raise refusal - } - null - } - """ The engine release a scope generates for: the targetVersion setting as a `v`-prefixed release, or the release this SDK targets when it is empty. @@ -581,8 +534,8 @@ type PythonSdk { } else if (releases.precedes(engineTarget, target)) { pins + target + ", which is later than " + engineTarget + ", the engine release this Python SDK generates for: install the SDK release built for " + target + ", or set targetVersion in its dagger.toml settings to " + engineTarget + ", or remove it" - } else if (releases.precedes(target, engineFloor)) { - pins + target + ", which is below " + engineFloor + ", the oldest release a targetVersion pin may name" + remedy + } else if (releases.precedes(target, targetFloor)) { + pins + target + ", which is below " + targetFloor + ", the oldest release a targetVersion pin may name" + remedy } else { "" } @@ -736,7 +689,6 @@ type PythonSdk { targetVersion. """ pub mod(ws: Workspace!, path: String! = ".", findUp: Boolean! = true): Mod! { - checkEngine let modPath = if (findUp) { managedModuleAtOrAbove(ws, path) } else { diff --git a/runtime/dagger-module.toml b/runtime/dagger-module.toml index 341afcc5..f7ad7efd 100644 --- a/runtime/dagger-module.toml +++ b/runtime/dagger-module.toml @@ -1,5 +1,5 @@ name = "python-sdk-runtime" -engineVersion = "v1.0.0-0" +engineVersion = "v1.0.0-beta.26" [runtime] source = "dang" diff --git a/runtime/dang.toml b/runtime/dang.toml new file mode 100644 index 00000000..8aac7f14 --- /dev/null +++ b/runtime/dang.toml @@ -0,0 +1,2 @@ +[imports.Dagger] +dagger = "v1.0.0-beta.26" From faa11e561bc337975287adc76adfbf5071fdad1b Mon Sep 17 00:00:00 2001 From: Yves Brissaud Date: Tue, 17 Nov 2026 18:17:37 +0100 Subject: [PATCH 11/20] build: name the main object in the module build The Python runtime asked the engine for the main object itself, which only an SDK new enough to ask could do: a module vendoring an older SDK reads DAGGER_MAIN_OBJECT and found it unset. The build sets it again, for every SDK version, from ModuleNaming.mainObject over the classes the module's source decorates with @object_type, which a short ast script lists without importing the module. The build fails when the engine takes none of them. The naming is the module's: the runtime's modSource.naming, the entrypoints' currentModule.naming, and at generation the naming of the source generation writes, through the runtime's new installed function. The Python side goes back to asking only for its interfaces' names, and generation no longer hands the renderer a module source ID. The e2e module declares engineVersion v1.0.0-beta.26: a released engine hides ModuleNaming, which the runtime's functions now take, from a module that declares an older version. At that version it reads clientSchemaIntrospectionJSON as clientSchemaIntrospectionJson. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/dagger.json | 2 +- .dagger/modules/e2e/main.dang | 6 +- mod.dang | 18 ++- python-sdk.dang | 2 +- runtime/build.dang | 61 +++++++++- runtime/main.dang | 24 +++- sdk/src/dagger/mod/__main__.py | 21 ++-- sdk/src/dagger/mod/_entrypoint.py | 1 + sdk/src/dagger/mod/_module.py | 76 ++++--------- sdk/src/dagger/mod/_naming.py | 150 +++++++++---------------- sdk/src/dagger/mod/cli.py | 59 +++++----- sdk/tests/mod/conftest.py | 17 +-- sdk/tests/mod/golden/main.dang | 1 + sdk/tests/mod/golden/main_outside.dang | 1 + sdk/tests/mod/test_interfaces.py | 2 +- sdk/tests/mod/test_naming.py | 101 ++--------------- 16 files changed, 217 insertions(+), 325 deletions(-) diff --git a/.dagger/modules/e2e/dagger.json b/.dagger/modules/e2e/dagger.json index 7444df65..ffab255d 100644 --- a/.dagger/modules/e2e/dagger.json +++ b/.dagger/modules/e2e/dagger.json @@ -1,6 +1,6 @@ { "name": "e2e", - "engineVersion": "v1.0.0-0", + "engineVersion": "v1.0.0-beta.26", "sdk": { "source": "dang" }, diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 2cba02b5..390c9cd8 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -2141,7 +2141,7 @@ type E2e { let core = ws.directory("/helpers/core-schema").asModuleSource sdkContainer(ws) .withFile("/core-only.py", ws.file("/helpers/core-schema/core_only.py")) - .withFile("/schema.json", core.withEngineVersion(core.engineVersion).clientSchemaIntrospectionJSON) + .withFile("/schema.json", core.withEngineVersion(core.engineVersion).clientSchemaIntrospectionJson) .withExec(["python", "/core-only.py", "/schema.json", "/core.json"]) .withExec(["uv", "run", "--frozen", "python", "-m", "codegen", "generate", "-i", "/core.json", "-o", sdkBindingsPath], experimentalPrivilegedNesting: true) .withExec(["uv", "run", "--frozen", "ruff", "check", "--fix-only", sdkBindingsPath]) @@ -2553,8 +2553,8 @@ type E2e { sdk/entrypoint, whether the path exists or not. A module generated directly refuses what the written manifest cannot carry, a [clients] table, disableDefaultFunctionCaching or a [codegen] table, as the scope - path does, rather than dropping it. The moved module runs on - v1.0.0-beta.18 or later, and generating it needs v1.0.0-beta.26 or later. + path does, rather than dropping it. Running the moved module and generating + it both need v1.0.0-beta.26 or later. """ pub remoteEntrypointReplacedCheck(ws: Workspace!): Void @check { let manifestPath = "/" + tomlGenerateModulePath + "/dagger-module.toml" diff --git a/mod.dang b/mod.dang index bc449aad..712243e0 100644 --- a/mod.dang +++ b/mod.dang @@ -261,21 +261,17 @@ type Mod { """ The entrypoint the engine loads instead of calling a runtime: the module's own container renders its types, and the container build travels with it. - Which class is the main object, the one that gets the constructor, the - engine says (ModuleSource.naming), for the module the entrypoint serves: - the renderer asks it as a nested client, about the source named by its ID. - It is asked from Python, so that this module, which an engine before the - floor still loads to refuse it, names no field such an engine lacks. + The main object, the class that gets the constructor, is the one the engine + takes by its naming of the module the entrypoint serves (namedSource). """ let entrypointDir(generated: Workspace!, outside: [String!]!, entrypointPath: String!): Directory! { pythonSdkRuntime - .moduleRuntime(modSource: staging(generated, outside).moduleSource("/" + rootPath), introspectionJson: null) - .withEnvVariable("DAGGER_MODULE_SOURCE_ID", toString(namedSource(generated, entrypointPath).id)) - .withExec( - ["python", "-m", "dagger.mod", "entrypoint", "--name", moduleName, "--client-version", targetVersion, "--output", entrypointOutput] + - outside.map { pattern => "--outside=" + pattern }, - experimentalPrivilegedNesting: true, + .installed( + modSource: staging(generated, outside).moduleSource("/" + rootPath), + naming: namedSource(generated, entrypointPath).naming, ) + .withExec(["python", "-m", "dagger.mod", "entrypoint", "--name", moduleName, "--client-version", targetVersion, "--output", entrypointOutput] + + outside.map { pattern => "--outside=" + pattern }) .directory(entrypointOutput) .withNewFile("build.dang", buildDang) .withNewFile("workspace_reader.py", currentModule.source.file("runtime/workspace_reader.py").contents) diff --git a/python-sdk.dang b/python-sdk.dang index 1eb2d980..f3931422 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -259,7 +259,7 @@ type PythonSdk { The module runs on the Dang entrypoint generated into it, or on one of the user's own in its files, and on nothing else: an entrypoint served from elsewhere, the one this repository used to share among them, is replaced - by the generated one, which needs an engine v1.0.0-beta.18 or later. + by the generated one, which needs an engine v1.0.0-beta.26 or later. The runtime this SDK used to write, `[runtime] source = "python"`, goes, and so does what only a runtime reads: engineVersion, since an entrypoint runs a module on the engine's own version. Any other runtime is one the diff --git a/runtime/build.dang b/runtime/build.dang index 1a7d431c..06675d1b 100644 --- a/runtime/build.dang +++ b/runtime/build.dang @@ -18,10 +18,16 @@ type PythonModuleBuild { pub moduleName: String! - new(contextDir: Directory! = directory, subPath: String! = ".", moduleName: String! = "") { + """ + How the engine names the module, which says which class is its main object. + """ + pub naming: ModuleNaming + + new(contextDir: Directory! = directory, subPath: String! = ".", moduleName: String! = "", naming: ModuleNaming = null) { self.contextDir = contextDir self.subPath = subPath self.moduleName = moduleName + self.naming = naming self } @@ -92,9 +98,62 @@ type PythonModuleBuild { .withEnvVariable("DAGGER_DEFAULT_PYTHON_PACKAGE", packageName) install(built, source, cfg) + .withEnvVariable("DAGGER_MAIN_OBJECT", mainObject) + } + } + + """ + The class name of the module's main object: of the classes its code + decorates with @object_type, the one the engine takes. + """ + let mainObject: String! { + if (naming == null) { + raise "module \"" + moduleName + "\" is built without the engine's naming of it" + } else { + let candidates = objectTypes + let main = naming.mainObject(candidates: candidates) + if (main == null) { + raise "module \"" + moduleName + "\": the engine takes none of its object types (" + + (if (candidates.length == 0) { "there are none" } else { candidates.join(", ") }) + + ") for its main object; name a class decorated with @object_type after the module" + } else { + main + } } } + """ + The classes the module's own code decorates with @object_type, read from + its source with Python's ast rather than by importing it, so that it reads + the same whichever SDK version the module installs. + """ + let objectTypes: [String!]! { + container + .from(defaultBaseImage) + .withMountedDirectory("/module", filesOf( + source, + include: ["src/**/*.py", "*.py"], + exclude: ["**/.venv", "**/__pycache__"], + )) + .withExec(["python", "-c", objectTypesScript, "/module"]) + .stdout + .split("\n") + .filter { line => line != "" } + } + + let objectTypesScript: String! = [ + "import ast, pathlib, sys", + "def name(d):", + " d = d.func if isinstance(d, ast.Call) else d", + " return getattr(d, 'attr', getattr(d, 'id', ''))", + "found = set()", + "for path in pathlib.Path(sys.argv[1]).rglob('*.py'):", + " for node in ast.walk(ast.parse(path.read_bytes(), str(path))):", + " if isinstance(node, ast.ClassDef) and any(name(d) == 'object_type' for d in node.decorator_list):", + " found.add(node.name)", + "print('\\n'.join(sorted(found)))", + ].join("\n") + """ The workspace members of a scope's pyproject.toml, read as the build does. """ diff --git a/runtime/main.dang b/runtime/main.dang index 01d12f9b..11d93013 100644 --- a/runtime/main.dang +++ b/runtime/main.dang @@ -12,11 +12,7 @@ type PythonSdkRuntime { """ pub moduleRuntime(modSource: ModuleSource!, introspectionJson: File): Container! { let modName = modSource.moduleOriginalName - let build = PythonModuleBuild( - contextDir: modSource.contextDirectory, - subPath: modSource.sourceSubpath, - moduleName: modName, - ) + let build = buildOf(modSource, modSource.naming) if (modSource.configExists == false or build.source.exists("pyproject.toml") == false) { raise "module \"" + modName + "\" has no source to trust; run `dagger generate` and commit the generated files" @@ -30,6 +26,15 @@ type PythonSdkRuntime { } } + """ + The module installed, its main object the one `naming` takes. Generation + renders a module's static entrypoint in it, by the naming of the module it + generates, which another source than the one it builds from may decide. + """ + pub installed(modSource: ModuleSource!, naming: ModuleNaming!): Container! { + buildOf(modSource, naming).installed + } + """ The workspace members this runtime reads from a scope's pyproject.toml. Generation checks the file it writes with it. @@ -37,4 +42,13 @@ type PythonSdkRuntime { pub scopeMembers(pyproject: File!): [String!]! { PythonModuleBuild().scopeMembers(pyproject) } + + let buildOf(modSource: ModuleSource!, naming: ModuleNaming!): PythonModuleBuild! { + PythonModuleBuild( + contextDir: modSource.contextDirectory, + subPath: modSource.sourceSubpath, + moduleName: modSource.moduleOriginalName, + naming: naming, + ) + } } diff --git a/sdk/src/dagger/mod/__main__.py b/sdk/src/dagger/mod/__main__.py index 5acc564b..f0f27d2a 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -1,7 +1,6 @@ """Commands the generated entrypoint runs in the module's container.""" import argparse -import functools import json import logging import pathlib @@ -72,10 +71,14 @@ def main(argv: list[str] | None = None) -> int: def _entrypoint(args: argparse.Namespace) -> None: + from dagger.client._descriptor import registering_types from dagger.mod._entrypoint import write_entrypoint + from dagger.mod.cli import load_module + with registering_types(): + mod = load_module() write_entrypoint( - _described(), + mod.describe(), name=args.name, client_version=args.client_version, output=args.output, @@ -84,22 +87,14 @@ def _entrypoint(args: argparse.Namespace) -> None: def _describe(args: argparse.Namespace) -> None: - from dagger.mod._describe import describe_json - - description = _described() - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(describe_json(description)) - - -def _described(): - """The module's description, its main object the one the engine takes.""" from dagger.client._descriptor import registering_types + from dagger.mod._describe import describe_json from dagger.mod.cli import load_module with registering_types(): mod = load_module() - anyio.run(functools.partial(mod.load_naming, names=False)) - return mod.describe() + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(describe_json(mod.describe())) def _call(args: argparse.Namespace) -> None: diff --git a/sdk/src/dagger/mod/_entrypoint.py b/sdk/src/dagger/mod/_entrypoint.py index 06ca546b..1c01ed8b 100644 --- a/sdk/src/dagger/mod/_entrypoint.py +++ b/sdk/src/dagger/mod/_entrypoint.py @@ -242,6 +242,7 @@ def _indent(lines: list[str], width: int) -> list[str]: contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), subPath: currentModule.sourceSubpath, moduleName: moduleName, + naming: currentModule.naming, ).installed }} }} diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index 5e90bda3..a5c4968b 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -36,13 +36,12 @@ InvalidInputError, InvalidResultError, ModuleError, - ModuleLoadError, ObjectNotFoundError, RegistrationError, log_exception_only, transform_error, ) -from dagger.mod._naming import ModuleNames, ask_naming, source_id +from dagger.mod._naming import ModuleNames, module_names from dagger.mod._resolver import ( Constructor, Field, @@ -111,61 +110,28 @@ def names(self) -> ModuleNames: """The engine's names for the module's interfaces and enums. Calls through the module's own interfaces select them. Asked for by - ``load_naming``, before anything is invoked. + ``load_names``, before anything is invoked. """ if self._names is None: msg = "The module's schema names were not asked for before the call" raise ModuleError(msg) return self._names - def set_main(self, name: str) -> None: - """Make the object of that class name the module's main object.""" - self._main_name = name - self._main = self._objects.get(name) + async def load_names(self) -> None: + """Ask the engine how it names the module, before anything is invoked. - async def load_naming(self, *, names: bool = True) -> None: - """Ask the engine how it names the module, once its code is imported. - - One query, for what the module doesn't know yet: - - - which class is the main object, the one the engine finds by the - module's name, unless the module was given its name; - - with ``names``, the engine's names for the module's interfaces and - enums, which the calls through its own interfaces select. A module - without interfaces makes no such call, so it asks nothing for them. + A module without interfaces makes no call by the engine's names of its + own declarations, so it asks nothing. """ - candidates = None - if not self._main_name: - candidates = [ - name for name, obj in self._objects.items() if not obj.interface - ] - interfaces = [] - if names and self._names is None: - interfaces = [obj for obj in self._objects.values() if obj.interface] - if not interfaces: - self._names = ModuleNames() - if candidates is None and not interfaces: + if self._names is not None: return - naming = await ask_naming( - candidates=candidates, - interfaces=interfaces, - enums=self._enums.values(), - source_id=source_id(), - ) - if candidates is not None: - if naming.main_object is None: - msg = ( - f"The engine takes none of the module's object types " - f"({', '.join(candidates) or 'there are none'}) for the main " - f"object of module {MODULE_NAME!r}: name a class decorated " - "with @dagger.object_type after the module" - ) - raise ModuleLoadError(msg) - self.set_main(naming.main_object) - if interfaces: - self._names = naming.names - # Bindings are built with the names they have when first used. - to_interface_impl.cache_clear() + interfaces = [obj for obj in self._objects.values() if obj.interface] + if not interfaces: + self._names = ModuleNames() + return + self._names = await module_names(interfaces, self._enums.values()) + # Bindings are built with the names they have when first used. + to_interface_impl.cache_clear() def is_own_enum(self, cls: Any) -> bool: """Whether a class is one of the enums this module declares.""" @@ -212,23 +178,21 @@ async def register(self): await anyio.Path(TYPE_DEF_FILE).write_text(output) async def _typedefs(self) -> str: - await self.load_naming(names=False) return await _module_from(self.describe()).id() def describe(self) -> ModuleDescription: """Describe the registered types as plain data.""" if not self._main_name: - msg = ( - "The module's main object isn't known: ask the engine for it " - "(Module.load_naming) before describing the module" - ) + msg = "Main object name can't be empty" raise ValueError(msg) try: self.get_object(self._main_name) except ObjectNotFoundError as e: msg = ( f"Main object with name '{self._main_name}' not found or class not " - "decorated with '@dagger.object_type'" + "decorated with '@dagger.object_type'\n" + f"If you believe the module name '{MODULE_NAME}' is incorrectly " + "being converted into PascalCase, please file a bug report." ) raise ObjectNotFoundError(msg, extra=e.extra) from None @@ -305,7 +269,7 @@ async def invoke(self) -> str: }, ) - await self.load_naming() + await self.load_names() result = await self.get_result( parent_name, @@ -334,7 +298,7 @@ async def dispatch(self, request: Mapping[str, Any]) -> Any: except ValueError as e: msg = "Unable to decode the call request" raise InvalidInputError(msg, extra={"request": request}) from e - await self.load_naming() + await self.load_names() return await self.get_result( request["receiverType"], parent_state or {}, diff --git a/sdk/src/dagger/mod/_naming.py b/sdk/src/dagger/mod/_naming.py index 58c4abea..4fd430c5 100644 --- a/sdk/src/dagger/mod/_naming.py +++ b/sdk/src/dagger/mod/_naming.py @@ -1,31 +1,24 @@ -"""How the engine names a module's own declarations. +"""Schema names the engine gives a module's own declarations. The runtime registers Python names (``get_url``, ``HttpFetcher``) and the engine turns them into schema names (``getUrl``, ``NamingAppHTTPFetcher``) by -the naming rules of the version it names the module by. Two things in the -runtime depend on those rules: - -- which of the module's classes is its main object, the one the engine finds - by the module's name; -- the calls the runtime builds itself, through the module's own interfaces, - which select schema names: a wrong one is a fragment on a type that doesn't - exist, a field the interface doesn't have, or an unknown enum member. - -The runtime doesn't predict either: it asks the engine (``ModuleNaming``), -which answers by the same rules it names the module by, legacy strcase for a -module declaring a version before the identifier casing cut. It asks once, -when the module is loaded, in one query: for the module it is running -(``CurrentModule.naming``), or, when generation renders a module's entrypoint -from outside of it, for the module source generation names -(``ModuleSource.naming``, by the ID in ``SOURCE_ID_ENV``). +the naming rules of the version it names the module by. The calls the runtime +builds itself, through the module's own interfaces, have to use those schema +names: a wrong one is a fragment on a type that doesn't exist, a field the +interface doesn't have, or an unknown enum member. + +So the runtime doesn't predict them: it asks the engine, which answers for the +module it is running (``CurrentModule.naming``) by the same rules it names the +module by, legacy strcase for a module declaring a version before the +identifier casing cut. One query per call, before anything is invoked, for +every name the calls through the module's interfaces can use. """ from __future__ import annotations import dataclasses -import os import typing -from collections.abc import Awaitable, Callable, Iterable, Sequence +from collections.abc import Awaitable, Callable, Iterable from dagger.client._core import to_literal from dagger.client._session import default_session @@ -36,9 +29,6 @@ from dagger.mod._resolver import ObjectType -SOURCE_ID_ENV = "DAGGER_MODULE_SOURCE_ID" -"""The ID of the ModuleSource to ask about, for a module not running in it.""" - Execute: typing.TypeAlias = Callable[[str], Awaitable[typing.Any]] """Runs a GraphQL query against the engine and returns its data.""" @@ -83,75 +73,53 @@ def _get(names: typing.Mapping[str, str], name: str, what: str) -> str: raise ModuleError(msg) from None -@dataclasses.dataclass(frozen=True, slots=True) -class Naming: - """The engine's answers for a module.""" - - main_object: str | None = None - """Which candidate the engine takes as the main object; None if it wasn't - asked, or takes none.""" - - names: ModuleNames = dataclasses.field(default_factory=ModuleNames) - - -async def ask_naming( - *, - candidates: Sequence[str] | None = None, - interfaces: Iterable[ObjectType] = (), - enums: Iterable[type[enum.Enum]] = (), - source_id: str | None = None, +async def module_names( + interfaces: Iterable[ObjectType], + enums: Iterable[type[enum.Enum]], execute: Execute = _execute, -) -> Naming: - """Ask the engine, in one query, how it names the module. - - ``candidates`` are the classes that may be the main object, which is - asked only when given. The names are those of the interfaces, their - functions and arguments, and the members of the module's enums, which - calls through an interface send and receive; asked only for a module - with interfaces. ``source_id`` names the module source to ask about; - without it, the module the runtime runs in. +) -> ModuleNames: + """Ask the engine how it names the module's interfaces and enums. + + One query: the interfaces' type names, their functions' and arguments' + names, and the members of the module's enums, which calls through an + interface send and receive. """ interfaces = list(interfaces) - asked: dict[str, list[str]] = {} - if interfaces: - asked["typeNames"] = sorted({iface.cls.__name__ for iface in interfaces}) - asked["fieldNames"] = sorted( - { - name - for iface in interfaces - for fn in iface.functions.values() - for name in (fn.name, *(p.name for p in fn.parameters.values())) - } - ) - asked["enumMemberNames"] = sorted( - {member.name for cls in enums for member in cls} - ) - selections = [ - f"{field}(names: {to_literal(names)})" + types = sorted({iface.cls.__name__ for iface in interfaces}) + fields = sorted( + { + name + for iface in interfaces + for fn in iface.functions.values() + for name in (fn.name, *(p.name for p in fn.parameters.values())) + } + ) + members = sorted({member.name for cls in enums for member in cls}) + asked = { + "typeNames": types, + "fieldNames": fields, + "enumMemberNames": members, + } + selections = "\n".join( + f" {field}(names: {to_literal(names)})" for field, names in asked.items() if names - ] - if candidates is not None: - selections.append(f"mainObject(candidates: {to_literal(list(candidates))})") + ) if not selections: - return Naming() - - fields = "".join(f" {s}\n" for s in selections) - if source_id is None: - root, open_, close = "currentModule", "currentModule {", "}" - else: - root = "node" - open_ = f"node(id: {to_literal(source_id)}) {{ ... on ModuleSource {{" - close = "} }" - query = f"query ModuleNaming {{\n {open_}\n naming {{\n{fields}" - data = await execute(f"{query} }}\n {close}\n}}") - naming = ((data or {}).get(root) or {}).get("naming") - if not isinstance(naming, dict): - msg = f"The engine answered no ModuleNaming: {data!r}" - raise ModuleError(msg) + return ModuleNames() + data = await execute( + "query ModuleNaming {\n" + " currentModule {\n" + " naming {\n" + f"{selections}\n" + " }\n" + " }\n" + "}" + ) + naming = (data or {}).get("currentModule", {}).get("naming", {}) def answers(field: str) -> dict[str, str]: - names = asked.get(field) + names = asked[field] if not names: return {} got = naming.get(field) @@ -160,16 +128,8 @@ def answers(field: str) -> dict[str, str]: raise ModuleError(msg) return dict(zip(names, got, strict=True)) - return Naming( - main_object=naming.get("mainObject") if candidates is not None else None, - names=ModuleNames( - types=answers("typeNames"), - fields=answers("fieldNames"), - enum_members=answers("enumMemberNames"), - ), + return ModuleNames( + types=answers("typeNames"), + fields=answers("fieldNames"), + enum_members=answers("enumMemberNames"), ) - - -def source_id() -> str | None: - """The module source generation asks about, if it gave one.""" - return os.environ.get(SOURCE_ID_ENV) or None diff --git a/sdk/src/dagger/mod/cli.py b/sdk/src/dagger/mod/cli.py index c6875247..21a11e2b 100644 --- a/sdk/src/dagger/mod/cli.py +++ b/sdk/src/dagger/mod/cli.py @@ -15,9 +15,8 @@ from dagger.client._connection import connect from dagger.client._descriptor import registering_types from dagger.client._session import mark_module_runtime -from dagger.mod import default_module from dagger.mod._exceptions import ModuleError, ModuleLoadError, record_exception -from dagger.mod._module import Module +from dagger.mod._module import MAIN_OBJECT, Module logger = logging.getLogger(__package__) @@ -61,26 +60,14 @@ async def main(mod: Module | None = None, register: bool = False) -> int | None: def load_module() -> Module: - """Load the dagger.Module instance the module's code registers with. - - The code is imported through the main object entry point when the - project names one, and else as the default package, whose import - registers its types. Which class is the main object the engine says, - once the module is loaded (Module.load_naming). - """ - ep = configured_entry_point() - target = ep.module if ep else default_package() + """Load the dagger.Module instance via the main object entry point.""" + ep = get_entry_point() try: - if ep is None: - importlib.import_module(target) - return default_module() cls = ep.load() - except ModuleLoadError: - raise except Exception as e: logger.exception( "Error while importing Python module '%s' with Dagger functions", - target, + ep.module, ) raise ModuleLoadError(str(e)) from e try: @@ -93,27 +80,33 @@ def load_module() -> Module: raise ModuleLoadError(msg) from None -def configured_entry_point() -> importlib.metadata.EntryPoint | None: - """The main object entry point the project configures, if any.""" +def get_entry_point() -> importlib.metadata.EntryPoint: + """Get the entry point for the main object.""" sel = importlib.metadata.entry_points( group=ENTRY_POINT_GROUP, name=ENTRY_POINT_NAME, ) - return next(iter(sel), None) + if ep := next(iter(sel), None): + return ep + import_pkg = IMPORT_PKG -def default_package() -> str: - """The package that holds the module's code by default.""" - if importlib.util.find_spec(IMPORT_PKG): - return IMPORT_PKG # Fallback for modules that still use the "main" package name. - if importlib.util.find_spec("main"): - return "main" - msg = ( - "Main object not found. You can configure it explicitly by adding " - "an entry point to your pyproject.toml file. For example:\n" - "\n" - f'[project.entry-points."{ENTRY_POINT_GROUP}"]\n' - f"{ENTRY_POINT_NAME} = '{IMPORT_PKG}:MyModule'\n" + if not importlib.util.find_spec(import_pkg): + import_pkg = "main" + + if not importlib.util.find_spec(import_pkg): + msg = ( + "Main object not found. You can configure it explicitly by adding " + "an entry point to your pyproject.toml file. For example:\n" + "\n" + f'[project.entry-points."{ENTRY_POINT_GROUP}"]\n' + f"{ENTRY_POINT_NAME} = '{IMPORT_PKG}:{MAIN_OBJECT}'\n" + ) + raise ModuleLoadError(msg) + + return importlib.metadata.EntryPoint( + group=ENTRY_POINT_GROUP, + name=ENTRY_POINT_NAME, + value=f"{import_pkg}:{MAIN_OBJECT}", ) - raise ModuleLoadError(msg) diff --git a/sdk/tests/mod/conftest.py b/sdk/tests/mod/conftest.py index 0aa3cd8a..9ed74143 100644 --- a/sdk/tests/mod/conftest.py +++ b/sdk/tests/mod/conftest.py @@ -38,20 +38,17 @@ def _selections(obj: Type): _NAMING_FIELD = re.compile( r"(typeNames|fieldNames|enumMemberNames)\(names: (\[.*?\])\)" ) -_MAIN_OBJECT_FIELD = re.compile(r"mainObject\(candidates: (\[.*?\])\)") class FakeEngine: - """Answers ModuleNaming from a table of the engine's names. + """Answers CurrentModule.naming from a table of the engine's names. A name the table lacks fails the query, as a name the engine can't name - does. mainObject answers ``main_object`` if it's among the candidates. - Any other query gets the canned data. It keeps what it was asked. + does. Any other query gets the canned data. It keeps what it was asked. """ def __init__(self, names: typing.Mapping[str, typing.Mapping[str, str]]): self.names = names - self.main_object: str | None = None self.data: typing.Any = None self.queries: list[str] = [] @@ -63,17 +60,11 @@ async def execute(self, query: str): self.queries.append(query) if not query.startswith("query ModuleNaming"): return self.data - naming: dict[str, typing.Any] = {} + naming = {} for field, names in _NAMING_FIELD.findall(query): table = self.names.get(field, {}) naming[field] = [table[name] for name in json.loads(names)] - if m := _MAIN_OBJECT_FIELD.search(query): - candidates = json.loads(m.group(1)) - naming["mainObject"] = ( - self.main_object if self.main_object in candidates else None - ) - root = "node" if "node(id:" in query else "currentModule" - return {root: {"naming": naming}} + return {"currentModule": {"naming": naming}} @pytest.fixture diff --git a/sdk/tests/mod/golden/main.dang b/sdk/tests/mod/golden/main.dang index 60fbc570..94848e77 100644 --- a/sdk/tests/mod/golden/main.dang +++ b/sdk/tests/mod/golden/main.dang @@ -40,6 +40,7 @@ type Entrypoint implements ModuleEntrypoint { contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), subPath: currentModule.sourceSubpath, moduleName: moduleName, + naming: currentModule.naming, ).installed } } diff --git a/sdk/tests/mod/golden/main_outside.dang b/sdk/tests/mod/golden/main_outside.dang index 4f53dc48..591a4d85 100644 --- a/sdk/tests/mod/golden/main_outside.dang +++ b/sdk/tests/mod/golden/main_outside.dang @@ -42,6 +42,7 @@ type Entrypoint implements ModuleEntrypoint { contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), subPath: currentModule.sourceSubpath, moduleName: moduleName, + naming: currentModule.naming, ).installed } } diff --git a/sdk/tests/mod/test_interfaces.py b/sdk/tests/mod/test_interfaces.py index 443c0258..d49caebf 100644 --- a/sdk/tests/mod/test_interfaces.py +++ b/sdk/tests/mod/test_interfaces.py @@ -69,7 +69,7 @@ class Pond: @pytest.fixture async def duck(mod: Module, engine): engine.names = POND_NAMES - await mod.load_naming() + await mod.load_names() r, t = await mod.get_structured_result( "Pond", {"duck": "123456"}, diff --git a/sdk/tests/mod/test_naming.py b/sdk/tests/mod/test_naming.py index 1a86b8eb..717c26da 100644 --- a/sdk/tests/mod/test_naming.py +++ b/sdk/tests/mod/test_naming.py @@ -1,4 +1,4 @@ -"""How the runtime asks the engine how it names the module.""" +"""How the runtime gets the schema names of the module's declarations.""" import enum import typing @@ -7,8 +7,8 @@ import dagger from dagger.mod import Module -from dagger.mod._exceptions import ModuleError, ModuleLoadError -from dagger.mod._naming import SOURCE_ID_ENV, ModuleNames, ask_naming +from dagger.mod._exceptions import ModuleError +from dagger.mod._naming import ModuleNames, module_names pytestmark = [ pytest.mark.anyio, @@ -71,19 +71,16 @@ async def fetcher(mod: Module): async def test_one_query(mod: Module, engine): engine.names = NAMES - await mod.load_naming() - await mod.load_naming() + await mod.load_names() + await mod.load_names() assert len(engine.naming_queries) == 1 query = engine.naming_queries[0] - assert "currentModule {" in query assert 'typeNames(names: ["HttpFetcher"])' in query assert ( 'fieldNames(names: ["also", "arch", "arches", "e2e_test", "with_arch"])' in query ) assert 'enumMemberNames(names: ["AMD64", "arm64"])' in query - # Given its main object's name, the module doesn't ask for it. - assert "mainObject" not in query async def test_no_interfaces_asks_nothing(engine): @@ -93,93 +90,13 @@ async def test_no_interfaces_asks_nothing(engine): class Plain: pass - await m.load_naming() + await m.load_names() assert engine.queries == [] -async def test_main_object_by_the_engine(engine): - m = Module("") - - @m.object_type - class Helper: - pass - - @m.object_type - class K8STools: - pass - - engine.main_object = "K8STools" - await m.load_naming() - assert len(engine.naming_queries) == 1 - assert 'mainObject(candidates: ["Helper", "K8STools"])' in engine.queries[0] - assert m.main_cls is K8STools - assert m.describe().main_object == "K8STools" - - -async def test_main_object_with_the_names_in_one_query(engine): - m = Module("") - - @m.interface - class Fetcher(typing.Protocol): - @m.function - async def get(self) -> str: ... - - @m.object_type - class Tools: - pass - - engine.names = { - "typeNames": {"Fetcher": "ToolsFetcher"}, - "fieldNames": {"get": "get"}, - } - engine.main_object = "Tools" - await m.load_naming() - assert len(engine.queries) == 1 - assert "mainObject" in engine.queries[0] - assert "typeNames" in engine.queries[0] - assert m.names.type_name("Fetcher") == "ToolsFetcher" - - -@pytest.mark.usefixtures("engine") -async def test_no_main_object_fails(): - m = Module("") - - @m.object_type - class Helper: - pass - - with pytest.raises(ModuleLoadError, match="Helper"): - await m.load_naming() - - -def test_describe_needs_the_main_object(): - m = Module("") - - @m.object_type - class Helper: - pass - - with pytest.raises(ValueError, match="main object isn't known"): - m.describe() - - -async def test_naming_of_a_given_module_source(engine, monkeypatch): - monkeypatch.setenv(SOURCE_ID_ENV, "source-id") - m = Module("") - - @m.object_type - class Tools: - pass - - engine.main_object = "Tools" - await m.load_naming(names=False) - assert 'node(id: "source-id") { ... on ModuleSource {' in engine.queries[0] - assert m.main_cls is Tools - - async def test_calls_by_the_engines_names(mod: Module, engine): engine.names = NAMES - await mod.load_naming() + await mod.load_names() r = await fetcher(mod) arch = mod._enums["Arch"] @@ -195,7 +112,7 @@ async def test_calls_by_the_engines_names(mod: Module, engine): async def test_enum_results(mod: Module, engine): engine.names = NAMES - await mod.load_naming() + await mod.load_names() r = await fetcher(mod) arch = mod._enums["Arch"] @@ -226,4 +143,4 @@ async def execute(_): interfaces = [o for o in mod._objects.values() if o.interface] with pytest.raises(ModuleError, match="typeNames"): - await ask_naming(interfaces=interfaces, execute=execute) + await module_names(interfaces, (), execute) From ee5b797c4f4b64be3387a72c64d7312cb94c0b26 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sat, 31 Oct 2026 00:05:07 +0000 Subject: [PATCH 12/20] sdk: fix what review of the naming port found - The code generator reaches its session without a proxy: urllib honored the HTTP_PROXY an exec inherits, and a non-JSON error reply escaped as a traceback. - The main object scan skips a file this Python can't parse, which the module may never import. - experimentalPrivilegedNesting goes from the execs that reach the session: nesting is the default of the v1 API, which ignores the flag. - The generated entrypoint's header names the beta.22 floor, and the README says which rules name a module's own declarations. - A comment no longer points at the deleted engine refusal. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 2 +- README.md | 4 +++- helpers/pyproject/python.go | 2 +- python-sdk.dang | 6 +++--- runtime/build.dang | 9 +++++++-- scope.dang | 12 ++++++------ sdk/codegen/src/codegen/naming.py | 20 ++++++++++++++------ sdk/src/dagger/mod/_entrypoint.py | 1 + sdk/tests/mod/golden/main.dang | 1 + sdk/tests/mod/golden/main_outside.dang | 1 + 10 files changed, 38 insertions(+), 20 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 390c9cd8..050e7253 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -2143,7 +2143,7 @@ type E2e { .withFile("/core-only.py", ws.file("/helpers/core-schema/core_only.py")) .withFile("/schema.json", core.withEngineVersion(core.engineVersion).clientSchemaIntrospectionJson) .withExec(["python", "/core-only.py", "/schema.json", "/core.json"]) - .withExec(["uv", "run", "--frozen", "python", "-m", "codegen", "generate", "-i", "/core.json", "-o", sdkBindingsPath], experimentalPrivilegedNesting: true) + .withExec(["uv", "run", "--frozen", "python", "-m", "codegen", "generate", "-i", "/core.json", "-o", sdkBindingsPath]) .withExec(["uv", "run", "--frozen", "ruff", "check", "--fix-only", sdkBindingsPath]) .withExec(["uv", "run", "--frozen", "ruff", "format", sdkBindingsPath]) .file(sdkBindingsPath) diff --git a/README.md b/README.md index 392e56d5..1c5eb891 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,9 @@ release. It also needs the first release that names identifiers by its naming rules and answers for them: generation asks it how to spell the Python names of the schema's identifiers, and a module asks it what it named the module's own declarations. An entrypoint runs a module on the engine's own version, so an -entrypoint manifest keeps no `engineVersion`. +entrypoint manifest keeps no `engineVersion`. The engine names the module's own +declarations by the version the entrypoint's `dang.toml` imports, and by the +rules of v1.0.0-beta.20, before the identifier casing cut, without one. The SDK's modules declare `engineVersion` v1.0.0-beta.26. Engines compare only the base version, so an engine from v1.0.0-beta.18 to v1.0.0-beta.25 does diff --git a/helpers/pyproject/python.go b/helpers/pyproject/python.go index 926174fd..325c5f80 100644 --- a/helpers/pyproject/python.go +++ b/helpers/pyproject/python.go @@ -17,7 +17,7 @@ const pythonFloor = "3.11" // lastReleaseBelowPythonFloor is the last release of this SDK, whose floor // was lastReleasePythonFloor. A refusal offers it only to a Python that -// release runs on, as engineRefusal in python-sdk.dang does for engines. +// release runs on. const ( lastReleaseBelowPythonFloor = "v1.2.0" lastReleasePythonFloor = "3.10" diff --git a/python-sdk.dang b/python-sdk.dang index f3931422..9f08cf8b 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -746,8 +746,8 @@ type PythonSdk { """ Render a Python template with the requested module name. The engine spells - the main class's name (formatIdentifiers), which the renderer asks as a - nested client. + the main class's name (formatIdentifiers), which the renderer asks of the + session it runs in. """ let renderedTemplate(name: String!, templateName: String!): Directory! { container @@ -759,7 +759,7 @@ type PythonSdk { .withDirectory("/template", currentModule.source.directory("templates/" + templateName)) .withWorkdir("/helper") .withExec(["go", "build", "-o", "/usr/local/bin/render-template", "."]) - .withExec(["render-template", name, "/template", "/rendered"], experimentalPrivilegedNesting: true) + .withExec(["render-template", name, "/template", "/rendered"]) .directory("/rendered") } diff --git a/runtime/build.dang b/runtime/build.dang index 06675d1b..f9c15246 100644 --- a/runtime/build.dang +++ b/runtime/build.dang @@ -125,7 +125,8 @@ type PythonModuleBuild { """ The classes the module's own code decorates with @object_type, read from its source with Python's ast rather than by importing it, so that it reads - the same whichever SDK version the module installs. + the same whichever SDK version the module installs. A file this Python + can't parse is skipped: the module may never import it. """ let objectTypes: [String!]! { container @@ -148,7 +149,11 @@ type PythonModuleBuild { " return getattr(d, 'attr', getattr(d, 'id', ''))", "found = set()", "for path in pathlib.Path(sys.argv[1]).rglob('*.py'):", - " for node in ast.walk(ast.parse(path.read_bytes(), str(path))):", + " try:", + " tree = ast.parse(path.read_bytes(), str(path))", + " except (SyntaxError, ValueError):", + " continue", + " for node in ast.walk(tree):", " if isinstance(node, ast.ClassDef) and any(name(d) == 'object_type' for d in node.decorator_list):", " found.add(node.name)", "print('\\n'.join(sorted(found)))", diff --git a/scope.dang b/scope.dang index a083fc60..976a0eff 100644 --- a/scope.dang +++ b/scope.dang @@ -495,7 +495,7 @@ type Scope { let names = if (members.length == 0) { [coreDirName] } else { members.map { member => member.dir } } let inputs = names.reduce([] :: [String!]!) { args, name => args + ["-i", schemasPath + "/" + name + ".json"] } mounted - .withExec([codegenPython, "-m", "codegen", "generate-global"] + inputs + ["-o", outputPath], experimentalPrivilegedNesting: true) + .withExec([codegenPython, "-m", "codegen", "generate-global"] + inputs + ["-o", outputPath]) .directory(outputPath + "/" + globalPackage) } @@ -513,7 +513,7 @@ type Scope { let coreSource: Directory! { codegenEnv .withMountedFile(schemaPath, coreSchema) - .withExec([codegenPython, "-m", "codegen", "generate-core", "-i", schemaPath, "-o", outputPath], experimentalPrivilegedNesting: true) + .withExec([codegenPython, "-m", "codegen", "generate-core", "-i", schemaPath, "-o", outputPath]) .directory(outputPath) } @@ -636,7 +636,7 @@ type Scope { codegenPython, "-m", "codegen", "generate-client", "-i", schemaPath, "-o", outputPath, "--name", member.name, "--ref", member.ref, "--core-digest", coreDigest, - ] + pin, experimentalPrivilegedNesting: true) + ] + pin) .directory(outputPath) } @@ -708,9 +708,9 @@ type Scope { """ The code generator's environment, synced once per SDK version and shared by - every scope that generates. The generator runs as a nested client of the - session (experimentalPrivilegedNesting), because the engine spells the - Python names of the schema's identifiers (formatIdentifiers, see + every scope that generates. The generator reaches the session it runs in, + as every exec can, because the engine spells the Python names of the + schema's identifiers (formatIdentifiers, see sdk/codegen/src/codegen/naming.py). """ let codegenEnv: Container! { diff --git a/sdk/codegen/src/codegen/naming.py b/sdk/codegen/src/codegen/naming.py index 6d69217b..4d75e142 100644 --- a/sdk/codegen/src/codegen/naming.py +++ b/sdk/codegen/src/codegen/naming.py @@ -8,10 +8,10 @@ ``experimental_with_all_gpus``) rather than by a converter of the SDK's own. The generator asks once, up front, for every name in the schema, and asks -directly for a name it meets that wasn't among them. It runs as a nested -client of the Dagger session (``experimentalPrivilegedNesting``), which it -reaches through ``DAGGER_SESSION_PORT`` and ``DAGGER_SESSION_TOKEN``. A name -the engine can't format fails the generation. +directly for a name it meets that wasn't among them. It is a nested client of +the Dagger session it runs in, which it reaches through +``DAGGER_SESSION_PORT`` and ``DAGGER_SESSION_TOKEN``. A name the engine can't +format fails the generation. """ from __future__ import annotations @@ -40,6 +40,9 @@ class NamingError(Exception): """The engine couldn't name an identifier.""" +_opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + class Session: """The Dagger session the generator runs in, as a nested client.""" @@ -68,10 +71,15 @@ def query(self, query: str, variables: dict[str, typing.Any]) -> typing.Any: headers={"Content-Type": "application/json", "Authorization": self.auth}, ) try: - with urllib.request.urlopen(request) as response: # noqa: S310 + # The session is local: a proxy the exec inherits must not see it. + with _opener.open(request) as response: result = json.load(response) except urllib.error.HTTPError as e: - result = json.load(e) + try: + result = json.load(e) + except ValueError: + msg = f"the Dagger session answered HTTP {e.code}: {e.reason}" + raise NamingError(msg) from e if errors := result.get("errors"): msg = "; ".join(str(e.get("message", e)) for e in errors) raise NamingError(msg) diff --git a/sdk/src/dagger/mod/_entrypoint.py b/sdk/src/dagger/mod/_entrypoint.py index 1c01ed8b..648885cb 100644 --- a/sdk/src/dagger/mod/_entrypoint.py +++ b/sdk/src/dagger/mod/_entrypoint.py @@ -202,6 +202,7 @@ def _indent(lines: list[str], width: int) -> list[str]: SOURCES_EXCLUDE = '["**/.git", "**/.venv", "**/__pycache__"]' MAIN_TEMPLATE = """{header} +# Needs Dagger v1.0.0-beta.22 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint {{ let moduleName: String! = {name} let clientVersion: String! = {client_version} diff --git a/sdk/tests/mod/golden/main.dang b/sdk/tests/mod/golden/main.dang index 94848e77..af003be3 100644 --- a/sdk/tests/mod/golden/main.dang +++ b/sdk/tests/mod/golden/main.dang @@ -1,5 +1,6 @@ # Code generated by dagger. DO NOT EDIT. +# Needs Dagger v1.0.0-beta.22 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint { let moduleName: String! = "main" let clientVersion: String! = "v1.0.0-beta.27" diff --git a/sdk/tests/mod/golden/main_outside.dang b/sdk/tests/mod/golden/main_outside.dang index 591a4d85..3780b3ad 100644 --- a/sdk/tests/mod/golden/main_outside.dang +++ b/sdk/tests/mod/golden/main_outside.dang @@ -1,5 +1,6 @@ # Code generated by dagger. DO NOT EDIT. +# Needs Dagger v1.0.0-beta.22 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint { let moduleName: String! = "main" let clientVersion: String! = "v1.0.0-beta.27" From 457fbd45028070c2dbff75c166ef70bf404fe02d Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sat, 31 Oct 2026 00:26:28 +0000 Subject: [PATCH 13/20] template: name the main class as the engine will The template named a new module's class with formatIdentifiers, which spells by the newest rules whatever the version. A new module has no dang.toml, so the engine names it by v1.0.0-beta.20's legacy rules, and takes HTTPServer, the class of `http-server`, for no main object: the module did not load. Generation now asks the engine how it will name the module (ModuleNaming.typeNames of the module name), of the manifest it writes, before the template renders, and hands the name to render-template. init-naming-check generates http-server without a version and pinned past the cut, and loads it. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 30 ++++++++++++ helpers/render-template/main.go | 70 ++++------------------------ helpers/render-template/main_test.go | 5 +- mod.dang | 13 ++++++ python-sdk.dang | 38 +++++++++++---- 5 files changed, 84 insertions(+), 72 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 050e7253..285ec8f6 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -304,6 +304,36 @@ type E2e { null } + """ + A new module's main class is named as the engine names the module, whose + rules spell an acronym differently on either side of the identifier casing + cut: http-server is HttpServer by the legacy rules a module without a + dang.toml is named by, and HTTPServer past the cut. Generation fails when + the engine takes the class for no main object, and the module loads. + """ + pub initNamingCheck(ws: Workspace!): Void @check { + [ + {{pinned: false, main: "HttpServer"}}, + {{pinned: true, main: "HTTPServer"}}, + ].each { want => + let label = if (want.pinned) { "http-server at v1.0.0-beta.22" } else { "http-server without a version" } + let scope = outputRoot + "/http-server" + let seeded = if (want.pinned) { + ws.withNewFile("/" + scope + "/dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.22\"\n") + } else { + ws.withNewDirectory("/" + scope, directory) + } + let generated = pythonSdk.generateScope(seeded.withWorkdir(scope), isModule: true, name: "http-server", clients: []) + .withWorkdir(".") + assertContains(generated.file("/" + scope + "/src/http_server/__init__.py").contents, "class " + want.main + ":", label + ": the main class is not " + want.main) + let objects = generated.moduleSource("/" + scope).asModule.objects.{{ asObject.{{ name }} }} + assert(objects.filter { o => o.asObject.name == want.main }.length == 1, label + ": the module does not load with its main object " + want.main) + null + } + + null + } + """ generateScope preserves a current manifest. It migrates a pre-1.0 dagger.json to dagger-module.toml. Both cases get the scope tree, and the diff --git a/helpers/render-template/main.go b/helpers/render-template/main.go index 799287a6..ebf3e18f 100644 --- a/helpers/render-template/main.go +++ b/helpers/render-template/main.go @@ -2,10 +2,7 @@ package main import ( "bytes" - "encoding/json" - "errors" "fmt" - "net/http" "os" "path/filepath" "regexp" @@ -14,7 +11,7 @@ import ( ) func main() { - if err := run(os.Args[1:], engineTypeName); err != nil { + if err := run(os.Args[1:]); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } @@ -29,65 +26,18 @@ func packageName(moduleName string) string { return strings.ReplaceAll(project, "-", "_") } -// engineTypeName is the module's name in PascalCase as the engine spells it -// (formatIdentifiers), which the template names the main class after: the -// engine knows where the name's words are. It asks the Dagger session the -// command runs in as a nested client. -func engineTypeName(moduleName string) (string, error) { - port, token := os.Getenv("DAGGER_SESSION_PORT"), os.Getenv("DAGGER_SESSION_TOKEN") - if port == "" || token == "" { - return "", errors.New("no Dagger session to name the module's class with: run render-template as a nested client") - } - body, err := json.Marshal(map[string]any{ - "query": `query($names: [String!]!) { formatIdentifiers(names: $names, casing: PASCAL) }`, - "variables": map[string]any{"names": []string{moduleName}}, - }) - if err != nil { - return "", err - } - req, err := http.NewRequest(http.MethodPost, "http://127.0.0.1:"+port+"/query", bytes.NewReader(body)) - if err != nil { - return "", err - } - req.Header.Set("Content-Type", "application/json") - req.SetBasicAuth(token, "") - resp, err := http.DefaultClient.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - var result struct { - Data struct { - FormatIdentifiers []string `json:"formatIdentifiers"` - } `json:"data"` - Errors []struct { - Message string `json:"message"` - } `json:"errors"` - } - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return "", fmt.Errorf("format the module's name: HTTP %s: %w", resp.Status, err) - } - if len(result.Errors) > 0 { - return "", fmt.Errorf("format the module's name %q: %s", moduleName, result.Errors[0].Message) - } - if len(result.Data.FormatIdentifiers) != 1 { - return "", fmt.Errorf("format the module's name %q: got %v", moduleName, result.Data.FormatIdentifiers) - } - return result.Data.FormatIdentifiers[0], nil -} - -func run(args []string, typeName func(string) (string, error)) error { - if len(args) != 3 { - return fmt.Errorf("usage: render-template MODULE_NAME TEMPLATE_DIR OUT_DIR") +// run renders the template for a module. MODULE_TYPE names the main class: +// the module's type name as the engine will name the module, which the caller +// asks the engine for. +func run(args []string) error { + if len(args) != 4 { + return fmt.Errorf("usage: render-template MODULE_NAME MODULE_TYPE TEMPLATE_DIR OUT_DIR") } moduleName := args[0] - templateDir := args[1] - outDir := args[2] - moduleType, err := typeName(moduleName) - if err != nil { - return err - } + moduleType := args[1] + templateDir := args[2] + outDir := args[3] data := map[string]string{ "ModuleName": moduleName, "ModuleProject": strings.ToLower(moduleName), diff --git a/helpers/render-template/main_test.go b/helpers/render-template/main_test.go index 609d52ee..03d022fd 100644 --- a/helpers/render-template/main_test.go +++ b/helpers/render-template/main_test.go @@ -7,9 +7,6 @@ import ( "testing" ) -// stubTypeName stands in for the engine, which spells the class name. -func stubTypeName(string) (string, error) { return "Main", nil } - func TestRenderedPackageMatchesTheRuntime(t *testing.T) { for _, tc := range []struct { name, project, pkg string @@ -25,7 +22,7 @@ func TestRenderedPackageMatchesTheRuntime(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { out := t.TempDir() - if err := run([]string{tc.name, filepath.Join("..", "..", "templates", "default"), out}, stubTypeName); err != nil { + if err := run([]string{tc.name, "Main", filepath.Join("..", "..", "templates", "default"), out}); err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(out, "src", tc.pkg, "__init__.py")); err != nil { diff --git a/mod.dang b/mod.dang index 712243e0..94046c6f 100644 --- a/mod.dang +++ b/mod.dang @@ -277,6 +277,19 @@ type Mod { .withNewFile("workspace_reader.py", currentModule.source.file("runtime/workspace_reader.py").contents) } + """ + The engine's naming of this module as generation writes it: the source the + static entrypoint is named by (namedSource), or else the module as its + manifest has it. + """ + pub naming: ModuleNaming! { + if (entrypointMode == "generated") { + namedSource(ws, vendorDirName + "/" + entrypointDirName).naming + } else { + ws.moduleSource("/" + rootPath).naming + } + } + """ The module the engine names once the entrypoint is generated: the manifest this generation writes, with the entrypoint's directory in place, since the diff --git a/python-sdk.dang b/python-sdk.dang index 9f08cf8b..9156cbd8 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -172,7 +172,7 @@ type PythonSdk { let initialized = if (hadConfig) { rooted } else { - let files = moduleTemplate(name, template, pythonVersion, useUv, baseImage) + let files = moduleTemplate(name, mainTypeName(rooted, scope, name), template, pythonVersion, useUv, baseImage) # A module directory's own .gitignore is the user's. let kept = if (scopeHasFile(ws, scope, ".gitignore")) { files.withoutFile(".gitignore") } else { files } # An additive changeset names only template paths. Merging a whole @@ -727,12 +727,35 @@ type PythonSdk { } } + """ + The main class name of a new module: the module's type name as the engine + will name the module, asked of the module as generation writes it, before + it has any code. The engine names a module by its version's rules, which + spell an acronym differently on either side of the identifier casing cut. + """ + let mainTypeName(ws: Workspace!, scope: String!, name: String!): String! { + let staged = Mod( + rootPath: scope, + ws: generateScopeManifest(ws, scope, name), + entrypointMode: entrypointModeOf(ws, scope), + migrating: false, + engineVersion: "", + clients: [] :: [ModuleSource!]!, + ) + let names = staged.naming.typeNames(names: [name]) + if (names.length != 1) { + raise "the engine named " + toString(names.length) + " types for module \"" + name + "\"" + } else { + names[0] ?? "" + } + } + """ The files of a new module: the named template rendered for the module name, with the pyproject.toml settings applied. An empty template name selects the default. """ - let moduleTemplate(name: String!, template: String!, pythonVersion: String!, useUv: Boolean!, baseImage: String!): Directory! { + let moduleTemplate(name: String!, typeName: String!, template: String!, pythonVersion: String!, useUv: Boolean!, baseImage: String!): Directory! { let selectedTemplate = if (template == "") { "default" } else { template } let known = currentModule.source.directory("templates").entries.map { entry => entry.trimSuffix("/") } @@ -740,16 +763,15 @@ type PythonSdk { if (known.filter { entry => entry == selectedTemplate }.length == 0) { raise "unknown init template: " + template } else { - configuredTemplate(renderedTemplate(name, selectedTemplate), pythonVersion, useUv, baseImage) + configuredTemplate(renderedTemplate(name, typeName, selectedTemplate), pythonVersion, useUv, baseImage) } } """ - Render a Python template with the requested module name. The engine spells - the main class's name (formatIdentifiers), which the renderer asks of the - session it runs in. + Render a Python template with the requested module name, its main class + named typeName. """ - let renderedTemplate(name: String!, templateName: String!): Directory! { + let renderedTemplate(name: String!, typeName: String!, templateName: String!): Directory! { container .from("golang:1.25-alpine") .withoutEntrypoint @@ -759,7 +781,7 @@ type PythonSdk { .withDirectory("/template", currentModule.source.directory("templates/" + templateName)) .withWorkdir("/helper") .withExec(["go", "build", "-o", "/usr/local/bin/render-template", "."]) - .withExec(["render-template", name, "/template", "/rendered"]) + .withExec(["render-template", name, typeName, "/template", "/rendered"]) .directory("/rendered") } From a05dbf32b75f02f324a4900f08d408eb147b65bf Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sat, 31 Oct 2026 00:36:29 +0000 Subject: [PATCH 14/20] e2e: init http-server on every kind of entrypoint The shared entrypoint and the runtime name a new module by its manifest alone, a path of generation's main class naming that no other init check took. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 285ec8f6..087b4e90 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -331,6 +331,18 @@ type E2e { null } + # The other kinds of entrypoint name a new module by its manifest alone. + [ + {{label: "on the shared entrypoint", sdk: pythonSdk(remoteEntrypoint: true)}}, + {{label: "on the runtime", sdk: pythonSdk(legacyRuntime: true)}}, + ].each { kind => + let scope = outputRoot + "/http-server" + let generated = kind.sdk.generateScope(ws.withNewDirectory("/" + scope, directory).withWorkdir(scope), isModule: true, name: "http-server", clients: []) + .withWorkdir(".") + assertContains(generated.file("/" + scope + "/src/http_server/__init__.py").contents, "class HttpServer:", "http-server " + kind.label + ": the main class is not HttpServer") + null + } + null } From eac74d73106ad374373862446e49cba6dd214221 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sat, 31 Oct 2026 01:53:26 +0000 Subject: [PATCH 15/20] e2e: init k8s-tools and e2e-test across the cut The engine, from dagger/dagger 9e25570 on, names a module's main object pre-cut by what typeNames answers, so init-naming-check now takes k8s-tools and e2e-test, which strcase spells differently on a second read, on both sides of the cut. Interface members are named once there, so the naming check's note about the legacy double normalization goes. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 087b4e90..b08aec36 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -308,24 +308,30 @@ type E2e { A new module's main class is named as the engine names the module, whose rules spell an acronym differently on either side of the identifier casing cut: http-server is HttpServer by the legacy rules a module without a - dang.toml is named by, and HTTPServer past the cut. Generation fails when - the engine takes the class for no main object, and the module loads. + dang.toml is named by, and HTTPServer past the cut; k8s-tools, which strcase + spells differently when it reads its own spelling again, is K8STools before + the cut. Generation fails when the engine takes the class for no main + object, and the module loads. """ pub initNamingCheck(ws: Workspace!): Void @check { [ - {{pinned: false, main: "HttpServer"}}, - {{pinned: true, main: "HTTPServer"}}, + {{name: "http-server", pkg: "http_server", pinned: false, main: "HttpServer"}}, + {{name: "http-server", pkg: "http_server", pinned: true, main: "HTTPServer"}}, + {{name: "k8s-tools", pkg: "k8s_tools", pinned: false, main: "K8STools"}}, + {{name: "k8s-tools", pkg: "k8s_tools", pinned: true, main: "K8sTools"}}, + {{name: "e2e-test", pkg: "e2e_test", pinned: false, main: "E2ETest"}}, + {{name: "e2e-test", pkg: "e2e_test", pinned: true, main: "E2ETest"}}, ].each { want => - let label = if (want.pinned) { "http-server at v1.0.0-beta.22" } else { "http-server without a version" } - let scope = outputRoot + "/http-server" + let label = want.name + (if (want.pinned) { " at v1.0.0-beta.22" } else { " without a version" }) + let scope = outputRoot + "/" + want.name let seeded = if (want.pinned) { ws.withNewFile("/" + scope + "/dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.22\"\n") } else { ws.withNewDirectory("/" + scope, directory) } - let generated = pythonSdk.generateScope(seeded.withWorkdir(scope), isModule: true, name: "http-server", clients: []) + let generated = pythonSdk.generateScope(seeded.withWorkdir(scope), isModule: true, name: want.name, clients: []) .withWorkdir(".") - assertContains(generated.file("/" + scope + "/src/http_server/__init__.py").contents, "class " + want.main + ":", label + ": the main class is not " + want.main) + assertContains(generated.file("/" + scope + "/src/" + want.pkg + "/__init__.py").contents, "class " + want.main + ":", label + ": the main class is not " + want.main) let objects = generated.moduleSource("/" + scope).asModule.objects.{{ asObject.{{ name }} }} assert(objects.filter { o => o.asObject.name == want.main }.length == 1, label + ": the module does not load with its main object " + want.main) null @@ -3147,12 +3153,8 @@ type E2e { interface by the names the engine gave it (the namespaced type and its function), so the call returns. - The fixture keeps to names the engine names the same on an object and on - an interface: by the legacy rules, it names an interface's fields twice, - which isn't idempotent (e2e_test is e2ETest on an object, e2Etest on an - interface), and CurrentModule.naming answers the object's spelling. Its - interface takes no own enum, which the engine refuses in the module's own - session. + Its interface takes no own enum, which the engine refuses in the module's + own session. """ pub namingCheck(ws: Workspace!): Void @check { [ From 52d4c166569af55a17ff581ebd6449b518739b39 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Mon, 2 Nov 2026 16:04:21 +0000 Subject: [PATCH 16/20] sdk: move the naming cut to beta.26 Beta.22 to beta.25 ship without the naming APIs. Move the entrypoint header, goldens and e2e naming pins to beta.26, and document beta.25 as the unpinned entrypoint fallback. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 12 ++++++------ README.md | 2 +- python-sdk.dang | 2 +- sdk/src/dagger/mod/_entrypoint.py | 2 +- sdk/tests/mod/golden/main.dang | 2 +- sdk/tests/mod/golden/main_outside.dang | 2 +- sdk/tests/mod/test_naming.py | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index b08aec36..c97064b4 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -322,10 +322,10 @@ type E2e { {{name: "e2e-test", pkg: "e2e_test", pinned: false, main: "E2ETest"}}, {{name: "e2e-test", pkg: "e2e_test", pinned: true, main: "E2ETest"}}, ].each { want => - let label = want.name + (if (want.pinned) { " at v1.0.0-beta.22" } else { " without a version" }) + let label = want.name + (if (want.pinned) { " at v1.0.0-beta.26" } else { " without a version" }) let scope = outputRoot + "/" + want.name let seeded = if (want.pinned) { - ws.withNewFile("/" + scope + "/dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.22\"\n") + ws.withNewFile("/" + scope + "/dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.26\"\n") } else { ws.withNewDirectory("/" + scope, directory) } @@ -3116,13 +3116,13 @@ type E2e { """ naming-app generated as a static entrypoint module, and naming-caller generated with a client of it, in a workspace of their own. With pinned, - naming-app's dang.toml declares v1.0.0-beta.22, which the engine names it - by; without one, the engine names it by v1.0.0-beta.20, the legacy rules. + naming-app's dang.toml declares v1.0.0-beta.26, which the engine names it + by; without one, the engine names it by v1.0.0-beta.25, the legacy rules. """ let namingScope(ws: Workspace!, pinned: Boolean!): Workspace! { let app = ws.directory("/" + namingFixturePath + "/app") let appSource = if (pinned) { - app.withNewFile("dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.22\"\n") + app.withNewFile("dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.26\"\n") } else { app } @@ -3161,7 +3161,7 @@ type E2e { {{pinned: false, iface: "NamingAppHttpFetcher", member: "ARM_64"}}, {{pinned: true, iface: "NamingAppHTTPFetcher", member: "ARM64"}}, ].each { want => - let label = if (want.pinned) { "naming-app at v1.0.0-beta.22" } else { "naming-app without a version" } + let label = if (want.pinned) { "naming-app at v1.0.0-beta.26" } else { "naming-app without a version" } let generated = namingScope(ws, want.pinned) let core = pyFiles(generated, "naming-caller/clients/core/src") assertContains(core, "def experimental_with_all_gpus(", label + ": core's Python names are not the engine's") diff --git a/README.md b/README.md index 1c5eb891..cac0e8ad 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ the schema's identifiers, and a module asks it what it named the module's own declarations. An entrypoint runs a module on the engine's own version, so an entrypoint manifest keeps no `engineVersion`. The engine names the module's own declarations by the version the entrypoint's `dang.toml` imports, and by the -rules of v1.0.0-beta.20, before the identifier casing cut, without one. +rules of v1.0.0-beta.25, before the identifier casing cut, without one. The SDK's modules declare `engineVersion` v1.0.0-beta.26. Engines compare only the base version, so an engine from v1.0.0-beta.18 to v1.0.0-beta.25 does diff --git a/python-sdk.dang b/python-sdk.dang index 9156cbd8..774b5c9f 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -290,7 +290,7 @@ type PythonSdk { # generator reads core in; what only a runtime can honour stays as # written. Inline at each site: sdk-helpers' type names change with its # own declared engineVersion (SdkHelpers… vs SDKHelpers… from the - # v1.0.0-beta.22 naming rules), so this module must not spell them. + # v1.0.0-beta.26 naming rules), so this module must not spell them. sdkHelpers.moduleManifest(loadToml: manifest).withoutEntrypoint .withLegacyRuntime(runtime: sdkRuntimeSource, engineVersion: sdkEngineVersion) } else if (ours) { diff --git a/sdk/src/dagger/mod/_entrypoint.py b/sdk/src/dagger/mod/_entrypoint.py index 648885cb..7a632030 100644 --- a/sdk/src/dagger/mod/_entrypoint.py +++ b/sdk/src/dagger/mod/_entrypoint.py @@ -202,7 +202,7 @@ def _indent(lines: list[str], width: int) -> list[str]: SOURCES_EXCLUDE = '["**/.git", "**/.venv", "**/__pycache__"]' MAIN_TEMPLATE = """{header} -# Needs Dagger v1.0.0-beta.22 or later; older engines report a missing "naming" field. +# Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint {{ let moduleName: String! = {name} let clientVersion: String! = {client_version} diff --git a/sdk/tests/mod/golden/main.dang b/sdk/tests/mod/golden/main.dang index af003be3..5d3c33be 100644 --- a/sdk/tests/mod/golden/main.dang +++ b/sdk/tests/mod/golden/main.dang @@ -1,6 +1,6 @@ # Code generated by dagger. DO NOT EDIT. -# Needs Dagger v1.0.0-beta.22 or later; older engines report a missing "naming" field. +# Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint { let moduleName: String! = "main" let clientVersion: String! = "v1.0.0-beta.27" diff --git a/sdk/tests/mod/golden/main_outside.dang b/sdk/tests/mod/golden/main_outside.dang index 3780b3ad..230304a8 100644 --- a/sdk/tests/mod/golden/main_outside.dang +++ b/sdk/tests/mod/golden/main_outside.dang @@ -1,6 +1,6 @@ # Code generated by dagger. DO NOT EDIT. -# Needs Dagger v1.0.0-beta.22 or later; older engines report a missing "naming" field. +# Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint { let moduleName: String! = "main" let clientVersion: String! = "v1.0.0-beta.27" diff --git a/sdk/tests/mod/test_naming.py b/sdk/tests/mod/test_naming.py index 717c26da..8030b3ee 100644 --- a/sdk/tests/mod/test_naming.py +++ b/sdk/tests/mod/test_naming.py @@ -15,7 +15,7 @@ ] # CurrentModule.naming's answers for a module "naming-app" at -# v1.0.0-beta.22, as the engine's identifier naming rules name it. +# v1.0.0-beta.26, as the engine's identifier naming rules name it. NAMES = { "typeNames": {"HttpFetcher": "NamingAppHTTPFetcher"}, "fieldNames": { From 3e980fc58827bd7d78ffb951845bfa9e62a4ce15 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Mon, 2 Nov 2026 21:33:15 +0000 Subject: [PATCH 17/20] codegen: format identifiers through Query.naming dagger#14996 moved formatIdentifiers under Query.naming(version:), so the generator now asks naming(version: $v) { formatIdentifiers(...) }, or naming without a version where it passed none. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- sdk/codegen/src/codegen/naming.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/sdk/codegen/src/codegen/naming.py b/sdk/codegen/src/codegen/naming.py index 4d75e142..d27c4102 100644 --- a/sdk/codegen/src/codegen/naming.py +++ b/sdk/codegen/src/codegen/naming.py @@ -2,10 +2,11 @@ Every Python identifier the generator styles from the schema (methods, arguments, input fields) is the schema name in snake_case, and the engine is -the one that spells it: ``Query.formatIdentifiers(casing: SNAKE)``, at the -schema's version, so the words are cut by the engine's naming dictionary -(``withGPU`` is ``with_gpu``, ``experimentalWithAllGPUs`` is -``experimental_with_all_gpus``) rather than by a converter of the SDK's own. +the one that spells it: ``Query.naming(version:).formatIdentifiers(casing: +SNAKE)``, at the schema's version, so the words are cut by the engine's +naming dictionary (``withGPU`` is ``with_gpu``, ``experimentalWithAllGPUs`` +is ``experimental_with_all_gpus``) rather than by a converter of the SDK's +own. The generator asks once, up front, for every name in the schema, and asks directly for a name it meets that wasn't among them. It is a nested client of @@ -90,13 +91,15 @@ def formatter(self, version: str) -> Format: if version: query = ( "query FormatIdentifiers($names: [String!]!, $version: String!) {\n" - " formatIdentifiers(names: $names, casing: SNAKE, version: $version)\n" + " naming(version: $version) {\n" + " formatIdentifiers(names: $names, casing: SNAKE)\n" + " }\n" "}" ) else: query = ( "query FormatIdentifiers($names: [String!]!) {\n" - " formatIdentifiers(names: $names, casing: SNAKE)\n" + " naming { formatIdentifiers(names: $names, casing: SNAKE) }\n" "}" ) @@ -104,7 +107,7 @@ def fmt(names: list[str]) -> list[str]: variables: dict[str, typing.Any] = {"names": names} if version: variables["version"] = version - formatted = self.query(query, variables)["formatIdentifiers"] + formatted = self.query(query, variables)["naming"]["formatIdentifiers"] if len(formatted) != len(names): msg = f"formatIdentifiers gave {len(formatted)} of {len(names)} names" raise NamingError(msg) From c0542867575ee5329ead1e853239419a7ca2c607 Mon Sep 17 00:00:00 2001 From: Yves Brissaud Date: Tue, 17 Nov 2026 18:17:46 +0100 Subject: [PATCH 18/20] sdk: name the final configured Python module Integrate the naming port with generated dang.toml and targetVersion. Stage the final manifest and config before main-class selection and entrypoint rendering, while retaining a runtime staging source for the build. Exercise new configs, the released target, a pin at the beta.26 floor and owned-config upgrades without resurrecting removed shared settings. Signed-off-by: Alex Suraci Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 103 ++++++++++++++++------------------ README.md | 15 ++--- mod.dang | 31 ++++++---- python-sdk.dang | 1 + 4 files changed, 78 insertions(+), 72 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index c97064b4..74f76490 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -305,49 +305,42 @@ type E2e { } """ - A new module's main class is named as the engine names the module, whose - rules spell an acronym differently on either side of the identifier casing - cut: http-server is HttpServer by the legacy rules a module without a - dang.toml is named by, and HTTPServer past the cut; k8s-tools, which strcase - spells differently when it reads its own spelling again, is K8STools before - the cut. Generation fails when the engine takes the class for no main - object, and the module loads. + A new module's main class follows the final generated config, at the SDK's + released target and at the oldest release a pin may name. Both are past the + identifier casing cut, so http-server is HTTPServer at each. """ pub initNamingCheck(ws: Workspace!): Void @check { [ - {{name: "http-server", pkg: "http_server", pinned: false, main: "HttpServer"}}, - {{name: "http-server", pkg: "http_server", pinned: true, main: "HTTPServer"}}, - {{name: "k8s-tools", pkg: "k8s_tools", pinned: false, main: "K8STools"}}, - {{name: "k8s-tools", pkg: "k8s_tools", pinned: true, main: "K8sTools"}}, - {{name: "e2e-test", pkg: "e2e_test", pinned: false, main: "E2ETest"}}, - {{name: "e2e-test", pkg: "e2e_test", pinned: true, main: "E2ETest"}}, + {{name: "http-server", pkg: "http_server", main: "HTTPServer"}}, + {{name: "k8s-tools", pkg: "k8s_tools", main: "K8sTools"}}, + {{name: "e2e-test", pkg: "e2e_test", main: "E2ETest"}}, ].each { want => - let label = want.name + (if (want.pinned) { " at v1.0.0-beta.26" } else { " without a version" }) - let scope = outputRoot + "/" + want.name - let seeded = if (want.pinned) { - ws.withNewFile("/" + scope + "/dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.26\"\n") - } else { - ws.withNewDirectory("/" + scope, directory) + ["", "v" + floorVersion].each { pin => + let target = pythonSdk.targetVersionOf(pin) + let label = want.name + " at " + target + let scope = outputRoot + "/" + want.name + let seeded = ws.withNewDirectory("/" + scope, directory) + let generated = pythonSdk(targetVersion: pin).generateScope(seeded.withWorkdir(scope), isModule: true, name: want.name, clients: []) + .withWorkdir(".") + assertContains(generated.file("/" + scope + "/src/" + want.pkg + "/__init__.py").contents, "class " + want.main + ":", label + ": the main class is not " + want.main) + assertContains(generated.file("/" + scope + "/sdk/entrypoint/dang.toml").contents, "dagger = \"" + target + "\"", label + ": config target differs") + let source = generated.moduleSource("/" + scope) + let names = source.naming.typeNames(names: [want.name]) + assert((names[0] ?? "") == want.main, label + ": served naming differs from the generated class") + let objects = source.asModule.objects.{{ asObject.{{ name }} }} + assert(objects.filter { o => o.asObject.name == want.main }.length == 1, label + ": the module does not load with its main object " + want.main) + null } - let generated = pythonSdk.generateScope(seeded.withWorkdir(scope), isModule: true, name: want.name, clients: []) - .withWorkdir(".") - assertContains(generated.file("/" + scope + "/src/" + want.pkg + "/__init__.py").contents, "class " + want.main + ":", label + ": the main class is not " + want.main) - let objects = generated.moduleSource("/" + scope).asModule.objects.{{ asObject.{{ name }} }} - assert(objects.filter { o => o.asObject.name == want.main }.length == 1, label + ": the module does not load with its main object " + want.main) - null } - # The other kinds of entrypoint name a new module by its manifest alone. - [ - {{label: "on the shared entrypoint", sdk: pythonSdk(remoteEntrypoint: true)}}, - {{label: "on the runtime", sdk: pythonSdk(legacyRuntime: true)}}, - ].each { kind => - let scope = outputRoot + "/http-server" - let generated = kind.sdk.generateScope(ws.withNewDirectory("/" + scope, directory).withWorkdir(scope), isModule: true, name: "http-server", clients: []) - .withWorkdir(".") - assertContains(generated.file("/" + scope + "/src/http_server/__init__.py").contents, "class HttpServer:", "http-server " + kind.label + ": the main class is not HttpServer") - null - } + # A runtime module is named by its manifest, not a generated config. + let scope = outputRoot + "/http-server-runtime" + let generated = pythonSdk(legacyRuntime: true).generateScope(ws.withNewDirectory("/" + scope, directory).withWorkdir(scope), isModule: true, name: "http-server", clients: []) + .withWorkdir(".") + let names = generated.moduleSource("/" + scope).naming.typeNames(names: ["http-server"]) + let main = names[0] ?? "" + assert(main != "", "runtime module has no main name") + assertContains(generated.file("/" + scope + "/src/http_server/__init__.py").contents, "class " + main + ":", "runtime main class differs from the engine's name") null } @@ -1624,7 +1617,7 @@ type E2e { "--use-uv=false", "--base-image", "python:3.13-slim", ]) - .withExec(["grep", "-q", "class SdkSettings:", ".dagger/modules/sdk-settings/src/sdk_settings/__init__.py"]) + .withExec(["grep", "-q", "class SDKSettings:", ".dagger/modules/sdk-settings/src/sdk_settings/__init__.py"]) .withExec(["grep", "-q", ">=3.13", ".dagger/modules/sdk-settings/pyproject.toml"]) .withExec(["grep", "-q", "use-uv = false", ".dagger/modules/sdk-settings/pyproject.toml"]) .withExec(["grep", "-q", "python:3.13-slim", ".dagger/modules/sdk-settings/pyproject.toml"]) @@ -1781,9 +1774,8 @@ type E2e { let floorPinned = pythonSdk(targetVersion: floor).generateScope(scoped, isModule: true, name: name, clients: []).withWorkdir(".") assertContains(floorPinned.file("/" + scope + "/sdk/entrypoint/main.dang").contents, "let clientVersion: String! = \"" + floor + "\"", "the entrypoint does not declare the pinned release") assertContains(floorPinned.file("/" + scope + "/sdk/entrypoint/dang.toml").contents, "dagger = \"" + floor + "\"", "dang.toml does not follow the targetVersion pin") - if (version.contains(target)) { - assertContains(pinned.file("/" + scope + "/" + coreInitPath).contents, newInBeta22, "core was not read in the view of the targeted release") - } + # The engine running the checks serves the targeted release's view. + assertContains(pinned.file("/" + scope + "/" + coreInitPath).contents, newInBeta22, "core was not read in the view of the targeted release") let remedy = ": set targetVersion in its dagger.toml settings to " + target + ", or remove it to generate for " + target let refusals = [ @@ -3115,22 +3107,21 @@ type E2e { """ naming-app generated as a static entrypoint module, and naming-caller - generated with a client of it, in a workspace of their own. With pinned, - naming-app's dang.toml declares v1.0.0-beta.26, which the engine names it - by; without one, the engine names it by v1.0.0-beta.25, the legacy rules. + generated with a client of it, in a workspace of their own. Both use the + SDK's released target, past the identifier casing cut. With pinned, an old + leaf config is replaced before naming. """ let namingScope(ws: Workspace!, pinned: Boolean!): Workspace! { let app = ws.directory("/" + namingFixturePath + "/app") - let appSource = if (pinned) { - app.withNewFile("dang.toml", "[imports.Dagger]\ndagger = \"v1.0.0-beta.26\"\n") - } else { - app - } let tree = directory - .withDirectory("naming-app", appSource) + .withDirectory("naming-app", app) .withDirectory("naming-caller", ws.directory("/" + namingFixturePath + "/caller")) - let withApp = pythonSdk.generateScope(tree.asWorkspace.withWorkdir("naming-app"), isModule: true, name: "naming-app", clients: []) + let fresh = pythonSdk.generateScope(tree.asWorkspace.withWorkdir("naming-app"), isModule: true, name: "naming-app", clients: []) .withWorkdir(".") + let withApp = if (pinned) { + let older = fresh.withNewFile("/naming-app/sdk/entrypoint/dang.toml", "[imports.Dagger]\ndagger = \"v" + floorVersion + "\"\n") + pythonSdk.generateScope(older.withWorkdir("naming-app"), isModule: true, name: "naming-app", clients: []).withWorkdir(".") + } else { fresh } pythonSdk.generateScope(withApp.withWorkdir("naming-caller"), isModule: true, name: "naming-caller", clients: [withApp.moduleSource("/naming-app")]) .withWorkdir(".") } @@ -3142,13 +3133,12 @@ type E2e { """ The engine names a module's declarations by the version it names the module - by, and the SDK follows it on both sides of the identifier casing cut: + by, and the SDK follows the config generation actually writes: - generation spells the Python names of every schema identifier as the engine does (experimental_with_all_gpus in core, whatever the version); - the client generated for naming-app names its declarations as the - engine does at naming-app's version (NamingAppHttpFetcher and ARM_64 - before the cut, NamingAppHTTPFetcher and ARM64 past it); + engine does at the released target (NamingAppHTTPFetcher and ARM64); - naming-app's runtime, called through that client, calls its own interface by the names the engine gave it (the namespaced type and its function), so the call returns. @@ -3158,11 +3148,14 @@ type E2e { """ pub namingCheck(ws: Workspace!): Void @check { [ - {{pinned: false, iface: "NamingAppHttpFetcher", member: "ARM_64"}}, + {{pinned: false, iface: "NamingAppHTTPFetcher", member: "ARM64"}}, {{pinned: true, iface: "NamingAppHTTPFetcher", member: "ARM64"}}, ].each { want => - let label = if (want.pinned) { "naming-app at v1.0.0-beta.26" } else { "naming-app without a version" } + let label = if (want.pinned) { "naming-app with an upgraded config" } else { "naming-app with a new config" } let generated = namingScope(ws, want.pinned) + let target = pythonSdk.targetVersionOf("") + assertContains(generated.file("/naming-app/sdk/entrypoint/dang.toml").contents, "dagger = \"" + target + "\"", label + ": wrong generated config") + assert(generated.moduleSource("/naming-app").naming.version == target, label + ": naming does not match the final config") let core = pyFiles(generated, "naming-caller/clients/core/src") assertContains(core, "def experimental_with_all_gpus(", label + ": core's Python names are not the engine's") let client = pyFiles(generated, "naming-caller/clients/naming-app/src") diff --git a/README.md b/README.md index cac0e8ad..8b015ecd 100644 --- a/README.md +++ b/README.md @@ -54,10 +54,10 @@ settings through `WorkspaceSDK.scopeSetting`, which release. It also needs the first release that names identifiers by its naming rules and answers for them: generation asks it how to spell the Python names of the schema's identifiers, and a module asks it what it named the module's own -declarations. An entrypoint runs a module on the engine's own version, so an -entrypoint manifest keeps no `engineVersion`. The engine names the module's own -declarations by the version the entrypoint's `dang.toml` imports, and by the -rules of v1.0.0-beta.25, before the identifier casing cut, without one. +declarations. An entrypoint manifest keeps no `engineVersion` (see "The Dagger +version of a generated entrypoint"). The final config and manifest are staged +before naming or main-object selection, so those answers describe the module +generation actually writes. The SDK's modules declare `engineVersion` v1.0.0-beta.26. Engines compare only the base version, so an engine from v1.0.0-beta.18 to v1.0.0-beta.25 does @@ -256,9 +256,10 @@ The two declarations reach an engine in different ways: - `dang.toml`: [dagger/dagger#14902](https://github.com/dagger/dagger/pull/14902), first released in v1.0.0-beta.26, makes an engine take the module's Dagger version from the file. Engines up to v1.0.0-beta.25 do not read it. It also - refuses an entrypoint whose imports declare different Dagger versions, and - serves v1.0.0-beta.25 to an entrypoint whose `dang.toml` declares no Dagger - version. + refuses an entrypoint whose imports declare different Dagger versions, so + generation stops with that error, and serves v1.0.0-beta.25, the last release + before the identifier casing cut, to an entrypoint whose `dang.toml` declares + no Dagger version. - `DAGGER_CLIENT_VERSION`: [dagger/dagger#14881](https://github.com/dagger/dagger/pull/14881), first released in v1.0.0-beta.22, makes an engine serve that version's view to the process. Engines up to v1.0.0-beta.21 do not read it. diff --git a/mod.dang b/mod.dang index 94046c6f..8fdeead2 100644 --- a/mod.dang +++ b/mod.dang @@ -129,13 +129,9 @@ type Mod { if (entrypointMode == "generated") { let outside = PyprojectHelper().outsidePaths(scoped, rootPath) checkResourcesLoad(scoped, outside) - let withEntrypoint = scoped.withDirectory("/" + rootPath + "/" + entrypointPath, entrypointDir(scoped, patterns(outside), entrypointPath)) - let entrypointDirectory = withEntrypoint.withWorkdir(modulePath(entrypointPath)) - let configured = sdkHelpers.loadDangConfig(entrypointDirectory) - .withVersion("2.1") - .withDaggerImport(name: "Dagger", version: targetVersion) - .generate(entrypointDirectory) - entrypointManifest(configured.withWorkdir("."), entrypointPath) + let configured = namedWorkspace(scoped, entrypointPath) + configured.withDirectory("/" + rootPath + "/" + entrypointPath, + entrypointDir(configured, patterns(outside), entrypointPath)) } else if (entrypointMode == "own") { checkNoResources(PyprojectHelper().outsidePaths(scoped, rootPath)) scoped @@ -237,7 +233,9 @@ type Mod { yet. So the runtime manifest points back at the module being built. """ let staging(target: Workspace!, outside: [String!]!): Workspace! { - if (hasEntrypointManifest) { + # The final entrypoint manifest is already staged for naming, even when + # the input module originally used a runtime or had no entrypoint. + if (hasEntrypointManifest or entrypointMode == "generated") { let loaded = sdkHelpers.moduleManifest(loadToml: ws.file("/" + manifestPath)).withoutEntrypoint # A static entrypoint manifest holds no runtime, and the engine refuses a # manifest with neither. Dang, not Python: the engine loads the added @@ -296,8 +294,21 @@ type Mod { dang.toml governing it decides the version the module is named by. """ let namedSource(target: Workspace!, entrypointPath: String!): ModuleSource! { - entrypointManifest(target.withDirectory("/" + rootPath + "/" + entrypointPath, directory), entrypointPath) - .moduleSource("/" + rootPath) + namedWorkspace(target, entrypointPath).moduleSource("/" + rootPath) + } + + """ + The final manifest and config, before main-object selection or building the + entrypoint. Reuse this workspace in the output so naming never observes the + previous import while the generated module declares a different version. + """ + let namedWorkspace(target: Workspace!, entrypointPath: String!): Workspace! { + let dir = target.withDirectory("/" + modulePath(entrypointPath), directory).withWorkdir(modulePath(entrypointPath)) + let configured = sdkHelpers.loadDangConfig(dir) + .withVersion("2.1") + .withDaggerImport(name: "Dagger", version: targetVersion) + .generate(dir) + entrypointManifest(configured.withWorkdir("."), entrypointPath) } """ diff --git a/python-sdk.dang b/python-sdk.dang index 774b5c9f..3bf7ee9e 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -740,6 +740,7 @@ type PythonSdk { entrypointMode: entrypointModeOf(ws, scope), migrating: false, engineVersion: "", + targetVersion: targetVersionOf(targetVersion), clients: [] :: [ModuleSource!]!, ) let names = staged.naming.typeNames(names: [name]) From 503606dc32544744fe87f80f89b43054595cc32c Mon Sep 17 00:00:00 2001 From: Yves Brissaud Date: Thu, 5 Nov 2026 14:38:45 +0100 Subject: [PATCH 19/20] e2e: name and regenerate through the merged dang.toml Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 74f76490..779a5929 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -1650,6 +1650,8 @@ type E2e { assert(dangConfigDirect(generatedDirectly).changes(generatedDirectly).isEmpty, "a second direct generation changed the module") let owned = "dang = \"2.0\"\n\n[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\npath = \"./schema\"\n\n[imports.Lib]\npath = \"./lib\"\n\n[imports.Other]\ndagger = \"v1.0.0-beta.20\"\n" + let olderLeaf = "[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\n\n[imports.Lib]\npath = \"./lib\"\n" + assert(pythonSdk.mod(generated.withNewFile(configPath, olderLeaf), path: root, findUp: false).naming.version == target, "naming did not read the merged dang.toml") dangConfigBoth(generated.withNewFile(configPath, owned), configPath).each { contents => assertContainsAll(contents, ["dang = \"2.1\"", "dagger = \"" + target + "\"", "[imports.Lib]", "path = \"./lib\"", "[imports.Other]", "dagger = \"v1.0.0-beta.20\""]) assertNotContains(contents, "./schema", "generation kept the Dagger import's path: " + contents) @@ -1693,6 +1695,7 @@ type E2e { assert(onRuntime.file(configPath).contents == customizedLeaf, "moving onto the runtime lost the entrypoint's dang.toml") let returned = dangConfigGenerate(onRuntime.withNewFile("/" + root + "/dagger-module.toml", "name = \"toml-generate-app\"\n")) assertContainsAll(returned.file(configPath).contents, ["dagger = \"" + target + "\"", "[imports.Lib]", "path = \"./lib\""]) + assertContains(returned.file("/" + root + "/sdk/entrypoint/main.dang").contents, "let clientVersion: String! = \"" + target + "\"", "a module back from the runtime declares another version") let ownEntrypoint = customized .withNewFile("/" + root + "/dagger-module.toml", dangEntrypointManifest("toml-generate-app", "./custom")) .withNewFile("/" + root + "/custom/main.dang", "# a Dang entrypoint of the user's own\n") From 2b1b950b1c6a5229a2cfe26f71c2ff00b31b257b Mon Sep 17 00:00:00 2001 From: Yves Brissaud Date: Thu, 5 Nov 2026 14:45:43 +0100 Subject: [PATCH 20/20] e2e: expect the engine to refuse disagreeing versions Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 779a5929..3f066c28 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -1649,11 +1649,11 @@ type E2e { assert(generatedDirectly.cwd == ws.withWorkdir(".").cwd, "direct generation moved the workspace's directory: " + generatedDirectly.cwd) assert(dangConfigDirect(generatedDirectly).changes(generatedDirectly).isEmpty, "a second direct generation changed the module") - let owned = "dang = \"2.0\"\n\n[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\npath = \"./schema\"\n\n[imports.Lib]\npath = \"./lib\"\n\n[imports.Other]\ndagger = \"v1.0.0-beta.20\"\n" + let owned = "dang = \"2.0\"\n\n[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\npath = \"./schema\"\n\n[imports.Lib]\npath = \"./lib\"\n\n[imports.Other]\ndagger = true\n" let olderLeaf = "[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\n\n[imports.Lib]\npath = \"./lib\"\n" assert(pythonSdk.mod(generated.withNewFile(configPath, olderLeaf), path: root, findUp: false).naming.version == target, "naming did not read the merged dang.toml") dangConfigBoth(generated.withNewFile(configPath, owned), configPath).each { contents => - assertContainsAll(contents, ["dang = \"2.1\"", "dagger = \"" + target + "\"", "[imports.Lib]", "path = \"./lib\"", "[imports.Other]", "dagger = \"v1.0.0-beta.20\""]) + assertContainsAll(contents, ["dang = \"2.1\"", "dagger = \"" + target + "\"", "[imports.Lib]", "path = \"./lib\"", "[imports.Other]", "dagger = true"]) assertNotContains(contents, "./schema", "generation kept the Dagger import's path: " + contents) assertNotContains(contents, "dang = \"2.0\"", "generation kept another Dang version: " + contents) } @@ -1665,6 +1665,15 @@ type E2e { assertContainsAll(kept.file(configPath).contents, ["[imports.Lib]", "path = \"./lib\""]) assert(kept.file("/" + root + "/cache/keep.txt").contents == "ignored", "generation changed an unrelated ignored file") } + let disagreeing = generated.withNewFile(configPath, "[imports.Dagger]\ndagger = \"v1.0.0-beta.20\"\n\n[imports.Other]\ndagger = \"v1.0.0-beta.20\"\n") + let scopeDisagreed = dangConfigGenerate(disagreeing).cwd rescue { + err: Error => err.message + } + assertContains(scopeDisagreed, "declare different Dagger versions", "scope generation did not surface the engine's refusal: " + scopeDisagreed) + let directDisagreed = dangConfigDirect(disagreeing).cwd rescue { + err: Error => err.message + } + assertContains(directDisagreed, "declare different Dagger versions", "direct generation did not surface the engine's refusal: " + directDisagreed) let endpoint = generated.withNewFile(configPath, "[imports.Dagger]\nendpoint = \"http://example\"\n") let scopeRefused = dangConfigGenerate(endpoint).cwd rescue { err: Error => err.message