Skip to content

fix: Empty map deserialization bug - #3801

Closed
jason-downs wants to merge 8 commits into
serverpod:mainfrom
jason-downs:fix-empty-map-bugs
Closed

jason-downs wants to merge 8 commits into
serverpod:mainfrom
jason-downs:fix-empty-map-bugs

Conversation

@jason-downs

@jason-downs jason-downs commented Jul 19, 2025 •

Copy link
Copy Markdown

fix #1908
(also fixes #1806 which was closed but not fully fixed)

The actual edits are in tools/serverpod_cli/lib/src/generator/types.dart and tools/serverpod_cli/lib/src/generator/dart/library_generators/util/class_generators_util.dart. The rest of the changes are from changed generated code resulting from the changes in the two files mentioned. Finally, there are new comprehensive unit tests in tests/serverpod_test_server/test/empty_map_serialization_test.dart.

Further details:

The Bug

Error Message:

type '_Map<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

Root Cause:
When Maps with non-String keys (like Map<int, String>) contain empty data, they are supposed to be serialized as empty Lists [] to follow the same pattern where the non-empty map is represented as a list of objects with "k" and "v" names. However, during deserialization, if the data is somehow an empty Map {} instead of a List, the code tries to cast it with (data as List) which throws the type cast error.

The Fix

The generated deserialization code should check if data is a Map before casting as List:

if (t == Map<int, int>) {
  if (data is Map) {
    return Map<int, int>() as T; // Return empty map
  }
  return Map.fromEntries((data as List).map((e) =>
      MapEntry(deserialize<int>(e['k']), deserialize<int>(e['v'])))) as T;
}

Pre-launch Checklist

  • [x ] I read the Contribute page and followed the process outlined there for submitting PRs.
  • [x ] This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • [x ] I read and followed the Dart Style Guide and formatted the code with dart format.
  • [x ] I listed at least one issue that this PR fixes in the description above.
  • [x ] I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • [ x] I added new tests to check the change I am making.
  • [x ] All existing and new tests are passing.
  • [x ] Any breaking changes are documented below.

If you need help, consider asking for advice on the discussion board.

Breaking changes

This shouldn't have any breaking API changes, just internal/bugfixes.

@coderabbitai

coderabbitai Bot commented Jul 19, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions

github-actions Bot commented Jul 19, 2025 •

Copy link
Copy Markdown

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@jason-downs

Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

@jason-downs jason-downs changed the title Fix empty map bugs fix: empty map deserialization bug Jul 19, 2025
@jason-downs jason-downs changed the title fix: empty map deserialization bug Fix: empty map deserialization bug Jul 19, 2025
@jason-downs jason-downs changed the title Fix: empty map deserialization bug fix: Empty map deserialization bug Jul 19, 2025
@tp

tp commented Jul 21, 2025

Copy link
Copy Markdown
Contributor

However, during deserialization, if the data is somehow an empty Map {} instead of a List, the code tries to cast it with (data as List) which throws the type cast error.

But why would this happen? That seems more of a serialization bug (if the framework would ever do it), than a deserialization one, no?


The current implementation seems a bit different than the suggest fix in the description, but the end-result is the same, so it doesn't matter for the following point:

(data is List ? data : [])

Basically this silently discard any "invalid" data. Personally I would not feel comfortable doing this, but rather prefer an explicit error, because the incoming data to deserializre should not be in the wrong shape in the first place. And if it is, we should be notified about it. Today this might fix some class of "empty map" bugs (however they come about, the root cause for the issue is not yet clear to me), but tomorrow this might hide something else.

So I think we need to figure out how the initial (and still current) invalid serialized data comes about, and then make the serialization strict/correct instead of the deserialization more lenient.

What do you think, @jason-downs ?

@jason-downs

Copy link
Copy Markdown
Author

However, during deserialization, if the data is somehow an empty Map {} instead of a List, the code tries to cast it with (data as List) which throws the type cast error.

But why would this happen? That seems more of a serialization bug (if the framework would ever do it), than a deserialization one, no?

The current implementation seems a bit different than the suggest fix in the description, but the end-result is the same, so it doesn't matter for the following point:

(data is List ? data : [])

Basically this silently discard any "invalid" data. Personally I would not feel comfortable doing this, but rather prefer an explicit error, because the incoming data to deserializre should not be in the wrong shape in the first place. And if it is, we should be notified about it. Today this might fix some class of "empty map" bugs (however they come about, the root cause for the issue is not yet clear to me), but tomorrow this might hide something else.

So I think we need to figure out how the initial (and still current) invalid serialized data comes about, and then make the serialization strict/correct instead of the deserialization more lenient.

What do you think, @jason-downs ?

Yes you're right. I admit to being rushed and having a lot of help here from AI in trying to navigate this codebase for the first time, which was rather daunting, and this is what it came up with for a fix. I agree that the real problem may indeed be the serialization of the empty map.

It does happen consistently, for example when an empty Map<int, int> is used in calling an endpoint method - see the minimal implentation that triggers the bug down in the comments on #1908

I can try to dive into the serialization code which might be easier for me now that I've gotten my feet wet in the codebase.

@tp

tp commented Jul 21, 2025

Copy link
Copy Markdown
Contributor

@jason-downs Thanks for the explanation and tracking this down.

The bug indeed is real, but I was only able to trigger it in an E2E test, even though the unit test exhibits the same behavior that an empty Map<int, int> is serialized as [] whereas a String-keyed empty map is {}.

I'll dig into this right away to see how we could fix it and at least give an update on the ticket. I'll ping you once I have anything to share :)

@tp

tp commented Jul 21, 2025

Copy link
Copy Markdown
Contributor

#3803 now fixes this issue on the sending side, instead of making the parsing more lenient.

@jason-downs I totally get your point. This was much trickier than I thought at first, as it touched quite a bit of the code generation logic (client, server, and test tools). It looks like there is some low-hanging fruit to make that whole (de)serialization a little more concise and get it to exercise the same code paths (so this would've worked on both parameters and field, or be broken on both). But for now, I wanted to get a solid fix in for your immediate issue.

As a workaround (until that fix is released), you might be best served by putting the Map inside a model object.

@tp tp closed this Jul 21, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Jul 21, 2025
@jason-downs
jason-downs deleted the fix-empty-map-bugs branch July 22, 2025 03:31
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Empty Maps still causing problems in serialization/deserialization crashes with empty Map, causes type cast error

2 participants