Skip to content

fix(dto): codegen backend for a nested structure#4670

Open
abdulhaq-e wants to merge 1 commit intolitestar-org:mainfrom
abdulhaq-e:fix_codegen_nested
Open

fix(dto): codegen backend for a nested structure#4670
abdulhaq-e wants to merge 1 commit intolitestar-org:mainfrom
abdulhaq-e:fix_codegen_nested

Conversation

@abdulhaq-e
Copy link
Copy Markdown
Contributor

Codegen was generating incorrect syntax for specific data container nesting. The example shown in the test raises the error:

    def _make_function(
        self,
        source_value_name: str,
        return_value_name: str,
        fn_name: str = "func",
    ) -> Callable[[Any], Any]:
        """Wrap the current body contents in a function definition and turn it into a callable object"""
        source = f"def {fn_name}({source_value_name}):\n{self._body} return {return_value_name}"
        ctx: dict[str, Any] = {**self._fn_locals}

        # add the function to linecache, to get better stacktraces when an error occurs
        # otherwise, the traceback within the generated code will just point
        # to '<string>'
        file_name = f"dto_transfer_function_{secrets.token_hex(6)}"
        linecache.cache[file_name] = (
            len(source),
            None,  # mtime: not applicable
            [line + "\n" for line in source.splitlines()],
            file_name,
        )
>       code = compile(source, file_name, "exec")
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E         File "dto_transfer_function_2714053d47d7", line 38
E           source_instance_0['wrapper']_inner_0 = source_instance_0['wrapper'].inner
E                                       ^^^^^^^^
E       SyntaxError: invalid syntax

litestar/dto/_codegen_backend.py:233: SyntaxError

A similar production use case that raised this error:

class CursorPaginationMetadata(Struct):
    limit: int = 50
    next_cursor: str | None = None
    previous_cursor: str | None = None

class PaginatedResponseMetadata(ResponseMetadata):
    pagination: CursorPaginationMetadata

class UsersWithPagination(Struct):
    data: list[User]
    pagination: CursorPaginationMetadata

The code and tests have been entirely generated by AI. I don't understand the codegen backend enough to evaluate this properly. There might be a simpler fix. I'm also not sure if DTO classes other than that for msgspec are affected.

Codegen was generating incorrect syntax for specific data container
nesting. The example shown in the test raises the error:

```
    def _make_function(
        self,
        source_value_name: str,
        return_value_name: str,
        fn_name: str = "func",
    ) -> Callable[[Any], Any]:
        """Wrap the current body contents in a function definition and turn it into a callable object"""
        source = f"def {fn_name}({source_value_name}):\n{self._body} return {return_value_name}"
        ctx: dict[str, Any] = {**self._fn_locals}

        # add the function to linecache, to get better stacktraces when an error occurs
        # otherwise, the traceback within the generated code will just point
        # to '<string>'
        file_name = f"dto_transfer_function_{secrets.token_hex(6)}"
        linecache.cache[file_name] = (
            len(source),
            None,  # mtime: not applicable
            [line + "\n" for line in source.splitlines()],
            file_name,
        )
>       code = compile(source, file_name, "exec")
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E         File "dto_transfer_function_2714053d47d7", line 38
E           source_instance_0['wrapper']_inner_0 = source_instance_0['wrapper'].inner
E                                       ^^^^^^^^
E       SyntaxError: invalid syntax

litestar/dto/_codegen_backend.py:233: SyntaxError
```

A similar production use case that raised this error:

```
class CursorPaginationMetadata(Struct):
    limit: int = 50
    next_cursor: str | None = None
    previous_cursor: str | None = None

class PaginatedResponseMetadata(ResponseMetadata):
    pagination: CursorPaginationMetadata

class UsersWithPagination(Struct):
    data: list[User]
    pagination: CursorPaginationMetadata
```
@abdulhaq-e abdulhaq-e requested review from a team as code owners April 4, 2026 22:04
@github-actions github-actions bot added area/dto This PR involves changes to the DTOs area/private-api This PR involves changes to the privatized API size: small type/bug pr/external Triage Required 🏥 This requires triage labels Apr 4, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 4, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 67.34%. Comparing base (69a1ad9) to head (8b41b7f).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4670   +/-   ##
=======================================
  Coverage   67.33%   67.34%           
=======================================
  Files         292      292           
  Lines       14941    14942    +1     
  Branches     1676     1676           
=======================================
+ Hits        10061    10062    +1     
  Misses       4743     4743           
  Partials      137      137           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/dto This PR involves changes to the DTOs area/private-api This PR involves changes to the privatized API pr/external size: small Triage Required 🏥 This requires triage type/bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant