Skip to content

fix: Handle serialization of empty Maps with keys other than String - #3803

Merged
tp merged 11 commits into
serverpod:mainfrom
tp:map-serialization
Jul 23, 2025
Merged

tp merged 11 commits into
serverpod:mainfrom
tp:map-serialization

Conversation

@tp

@tp tp commented Jul 21, 2025 •

Copy link
Copy Markdown
Contributor

For Maps with keys other than String, we usually rely on the toEncodable parameter of the JsonEncoder, which calls to custom mapping code when it can not handle serializing the object to JSON internally.

While this works e.g. for a <int, String>{1: 'hello'}, it does not for <int, String>{}, because the JSON encode looks at the actual data of the map, and not it's type. And thus it can perfectly fine convert it to JSON as "{}".
The issue is then, that we expect all such non-String-keyed Maps to be encoded as lists ([]) with objects inside contains k/v keys. Thus the later deserialization fails, as the empty map became as "{}" instead of "[]".

Interestingly, this worked for models containing such maps, because there the model's toJson code was always invoked and that converted each non-String-keyed child map to a list.

So the issue was limited to only top-level Map parameters on endpoint methods and the server-side return types.

Relates to #3801, #1806

Closes #1908

Summary by CodeRabbit

Summary by CodeRabbit

  • Tests

    • Added new test cases verifying correct handling of empty map types during serialization, deserialization, database roundtrip, and endpoint calls.
    • Extended tests to ensure records containing maps and sets with nested records are correctly processed and returned.
  • New Features

    • Added new endpoint methods supporting nested maps and records with map and set fields, returning inputs unmodified.
  • Refactor

    • Unified and enhanced serialization and deserialization handling for map types with non-string keys and record-containing containers in code generation tools, improving consistency and coverage.

@coderabbitai

coderabbitai Bot commented Jul 21, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes introduce and update test cases to verify correct handling of empty maps for various key types (including non-string keys) in serialization, deserialization, endpoint parameters, and database round-trips. Generator logic is refactored to consistently serialize empty maps, especially those with non-string keys, by conditionally converting them to empty lists. Parameter and return type handling in code generation is centralized and extended.

Changes

File(s) Change Summary
tests/serverpod_test_server/test/serialization_legacy_test.dart Reordered import statements; no logic changes.
tests/serverpod_test_server/test_e2e/connection_test.dart Added tests verifying endpoints handle empty Map<int, int>, Map<TestEnum, int>, and nested empty maps correctly.
tests/serverpod_test_server/test_e2e/database_roundtrip_type_test.dart Added test confirming database roundtrip with object containing empty map yields empty map on retrieval.
tests/serverpod_test_server/test_integration/test_tools/protocol_test.dart Added test verifying endpoint returns empty map when called with empty Map<int, int>.
tests/serverpod_test_server/test_integration/test_tools/serverpod_test_tools.dart Swapped import aliases; updated multiple endpoint classes to consistently use protocol mapping functions for complex maps and records; added methods handling nested maps and records.
tools/serverpod_cli/lib/src/generator/dart/library_generators/library_generator.dart Refactored parameter and return type transformation logic: added handleParameter helper, extended/renamed extension, added detection for non-string-keyed maps.
tools/serverpod_cli/lib/src/generator/dart/library_generators/server_test_tools_generator.dart Added handleParameter helper to centralize parameter serialization logic; enhanced deserialization for futures returning maps with non-string keys.
tests/serverpod_test_server/lib/src/endpoints/map_parameters.dart Added methods returning nested maps and maps with records and non-string keys unchanged.
tests/serverpod_test_server/lib/src/endpoints/record_parameters.dart Added methods returning records containing maps and sets with nested records unchanged.
tests/serverpod_test_server/test/serialization_test.dart Updated tests to use mapContainerToJson instead of mapRecordContainingContainerToJson for container encoding; added test serializing/deserializing object with empty maps.
tests/serverpod_test_server/test_e2e/record_types_test.dart Added tests verifying records with empty and non-empty maps and sets are correctly sent and returned by the server.
tools/serverpod_cli/lib/src/generator/dart/library_generators/model_library_generator.dart Updated references to JSON conversion functions to use configurable function name variables instead of hardcoded strings.

Sequence Diagram(s)

sequenceDiagram
    participant TestCase
    participant Client
    participant ServerEndpoint
    participant SerializationManager
    participant Database

    TestCase->>Client: Call endpoint with empty map parameter
    Client->>SerializationManager: Serialize empty map (as empty list if non-string key)
    SerializationManager-->>Client: Serialized parameter
    Client->>ServerEndpoint: Send serialized parameter
    ServerEndpoint->>SerializationManager: Deserialize parameter (empty map)
    ServerEndpoint-->>Client: Return empty map
    Client->>SerializationManager: Deserialize response
    SerializationManager-->>Client: Empty map
    Client-->>TestCase: Assert empty map result

    TestCase->>ServerEndpoint: Insert object with empty map to DB
    ServerEndpoint->>Database: Store object
    Database-->>ServerEndpoint: Confirm insert
    ServerEndpoint->>Database: Retrieve object by ID
    Database-->>ServerEndpoint: Object with empty map
    ServerEndpoint-->>TestCase: Assert retrieved map is empty
Loading

Estimated code review effort

3 (30–60 minutes)


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.

@tp
tp force-pushed the map-serialization branch 2 times, most recently from 3c22fe2 to 22d6baa Compare July 21, 2025 07:49
@tp tp changed the title Add E2E test case for empty Map<int, int> fix: Handle serialization of empty Maps with keys other than String Jul 21, 2025
@tp
tp force-pushed the map-serialization branch from 22d6baa to 2c785a0 Compare July 21, 2025 09:12
@tp
tp force-pushed the map-serialization branch 2 times, most recently from 18b2290 to 40c46cf Compare July 21, 2025 12:16
@tp

tp commented Jul 21, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 21, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

tp added 2 commits July 21, 2025 14:27
For Maps with keys other than `String`, we usually rely on the `toEncodable` parameter of the `JsonEncoder`, which calls to custom mapping code when it can not handle serializing the object to JSON internally.
While this works e.g. for a `<int, String>{1: 'hello'}`, it does not for `<int, String>{}`, because the JSON encode looks at the actual data of the map, and not it's type. And thus it can perfectly fine convert it to JSON as `"{}"`.
The issue is then, that we expect all such non-String-keyed Maps to be encoded as lists (`[]`) with objects inside contains `k`/`v` keys.
Thus the later deserialization fails, as the empty map came as `"{}"` instead of `"[]"`.

Interestingly this worked for models containing such maps, because there the model's `toJson` code was always invoked and that converted each non-String-keyed child map to a list.

So the issue was limited to only top-level `Map` parameters on endpoint methods.
@tp
tp force-pushed the map-serialization branch from 40c46cf to 957f32b Compare July 21, 2025 12:28
@tp
tp marked this pull request as ready for review July 21, 2025 12:43
@tp
tp requested a review from Isakdl July 21, 2025 12:52
@tp
tp requested a review from exaby73 July 22, 2025 11:49

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good work! I had some suggestions on a few points!

One thing I would like to be added is additional tests to validate nested Maps making sure we support that too, this is supported inside models already (and there are tests for it!), might be good to validate that the empty map case is covered too!

tp added 2 commits July 22, 2025 18:24
Also fix detection of "records inside containers insides records", which would not get mapped before
@tp

tp commented Jul 22, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 22, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
tests/serverpod_test_server/test_integration/test_tools/serverpod_test_tools.dart (1)

5231-5256: Missing Protocol().deserialize for consistency.

Similar to the previous comment, this method should use _i17.Protocol().deserialize for consistency with other methods.

Apply this diff:

-        var _localReturnValue = await (_localCallContext.method.call(
-          _localUniqueSession,
-          _localCallContext.arguments,
-        ) as _i3.Future<Map<String, _i18.TestEnum>>);
+        var _localReturnValue = await _localCallContext.method
+            .call(
+              _localUniqueSession,
+              _localCallContext.arguments,
+            )
+            .then((map) =>
+                _i17.Protocol().deserialize<Map<String, _i18.TestEnum>>(map));
♻️ Duplicate comments (2)
tests/serverpod_test_server/test/serialization_legacy_test.dart (1)

478-514: Test logic is correct but consider file placement.

The test comprehensively validates that empty maps of various types are preserved through serialization/deserialization, directly addressing the PR objectives. However, as noted in a previous review, this test should ideally be moved to the non-legacy serialization test file for better organization.

tools/serverpod_cli/lib/src/generator/dart/library_generators/server_test_tools_generator.dart (1)

597-650: Extension correctly handles maps with non-string keys, but architectural concerns remain.

The new logic properly extends deserialization support to future-returned maps with non-string keys, following the same pattern as record handling. The implementation is consistent and correct.

However, this addition reinforces the architectural concern mentioned in previous reviews about server test tools not using the full serialization/deserialization flow that normal E2E calls use. This continues the pattern of adding mapping workarounds rather than addressing the root cause.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4a72e4 and 5deaa92.

⛔ Files ignored due to path filters (15)
  • tests/serverpod_test_client/lib/src/protocol/client.dart is excluded by !**/lib/src/protocol/**
  • tests/serverpod_test_client/lib/src/protocol/protocol.dart is excluded by !**/lib/src/protocol/**
  • tests/serverpod_test_client/lib/src/protocol/subfolder/model_in_subfolder.dart is excluded by !**/lib/src/protocol/**
  • tests/serverpod_test_client/lib/src/protocol/types_list.dart is excluded by !**/lib/src/protocol/**
  • tests/serverpod_test_client/lib/src/protocol/types_map.dart is excluded by !**/lib/src/protocol/**
  • tests/serverpod_test_client/lib/src/protocol/types_set.dart is excluded by !**/lib/src/protocol/**
  • tests/serverpod_test_module/serverpod_test_module_client/lib/src/protocol/protocol.dart is excluded by !**/lib/src/protocol/**
  • tests/serverpod_test_module/serverpod_test_module_server/lib/src/generated/protocol.dart is excluded by !**/generated/**
  • tests/serverpod_test_server/lib/src/generated/endpoints.dart is excluded by !**/generated/**
  • tests/serverpod_test_server/lib/src/generated/protocol.dart is excluded by !**/generated/**
  • tests/serverpod_test_server/lib/src/generated/protocol.yaml is excluded by !**/generated/**
  • tests/serverpod_test_server/lib/src/generated/subfolder/model_in_subfolder.dart is excluded by !**/generated/**
  • tests/serverpod_test_server/lib/src/generated/types_list.dart is excluded by !**/generated/**
  • tests/serverpod_test_server/lib/src/generated/types_map.dart is excluded by !**/generated/**
  • tests/serverpod_test_server/lib/src/generated/types_set.dart is excluded by !**/generated/**
📒 Files selected for processing (12)
  • tests/serverpod_test_server/lib/src/endpoints/map_parameters.dart (1 hunks)
  • tests/serverpod_test_server/lib/src/endpoints/record_parameters.dart (2 hunks)
  • tests/serverpod_test_server/test/serialization_legacy_test.dart (2 hunks)
  • tests/serverpod_test_server/test/serialization_test.dart (4 hunks)
  • tests/serverpod_test_server/test_e2e/connection_test.dart (2 hunks)
  • tests/serverpod_test_server/test_e2e/database_roundtrip_type_test.dart (1 hunks)
  • tests/serverpod_test_server/test_e2e/record_types_test.dart (4 hunks)
  • tests/serverpod_test_server/test_integration/test_tools/protocol_test.dart (1 hunks)
  • tests/serverpod_test_server/test_integration/test_tools/serverpod_test_tools.dart (55 hunks)
  • tools/serverpod_cli/lib/src/generator/dart/library_generators/library_generator.dart (12 hunks)
  • tools/serverpod_cli/lib/src/generator/dart/library_generators/model_library_generator.dart (1 hunks)
  • tools/serverpod_cli/lib/src/generator/dart/library_generators/server_test_tools_generator.dart (5 hunks)
🧠 Learnings (8)
tests/serverpod_test_server/test/serialization_legacy_test.dart (4)

Learnt from: tp
PR: #3625
File: packages/serverpod/lib/src/cloud_storage/public_endpoint.dart:0-0
Timestamp: 2025-07-04T07:30:27.709Z
Learning: In Dart, ByteData.sublistView() is safer than ByteData.view() when working with TypedData views like Uint8List. ByteData.view() creates a view from a raw ByteBuffer without considering the original view's offset/length, potentially exposing the entire underlying buffer. ByteData.sublistView() properly accounts for data.offsetInBytes, data.elementSizeInBytes, and data.lengthInBytes, ensuring the view respects the original bounds. When converting TypedData to ByteData, use ByteData.sublistView(data) instead of ByteData.view(data.buffer).

Learnt from: nielsenko
PR: #3625
File: packages/serverpod/lib/src/cloud_storage/public_endpoint.dart:82-93
Timestamp: 2025-07-03T09:16:08.642Z
Learning: In Serverpod's CloudStoragePublicEndpoint, the _readBinaryBody method must buffer the entire request body in memory because the storage.storeFile interface requires a ByteData object. Implementing true streaming uploads would require reworking Serverpod's serialization handling of binary arguments. The current implementation uses BytesBuilder for efficient byte accumulation instead of list concatenation.

Learnt from: nielsenko
PR: #3625
File: packages/serverpod/lib/src/web_server/routes/static_directory.dart:155-157
Timestamp: 2025-07-03T09:33:09.654Z
Learning: In Dart, Stream.cast() returns Stream where R (the element type) is inferred from context through Dart's downward inference system. For example, when Body.fromDataStream expects Stream, calling file.openRead().cast() will automatically infer R as Uint8List, effectively becoming cast(). The cast method transforms each element of the stream using 'as R'.

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

tests/serverpod_test_server/test_integration/test_tools/protocol_test.dart (2)

Learnt from: tp
PR: #3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., late AuthenticationInfo? authenticationInfo;) rather than non-nullable ones to avoid using ! operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when session.authenticated returns null.

Learnt from: tp
PR: #3651
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:1-1
Timestamp: 2025-06-19T10:25:15.101Z
Learning: Explicit tests for complex endpoint methods provide cleaner error reporting and better debugging experience compared to testing the same functionality only within setUp blocks or helper methods.

tests/serverpod_test_server/test_e2e/connection_test.dart (1)

Learnt from: tp
PR: #3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., late AuthenticationInfo? authenticationInfo;) rather than non-nullable ones to avoid using ! operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when session.authenticated returns null.

tests/serverpod_test_server/test_e2e/database_roundtrip_type_test.dart (1)

Learnt from: tp
PR: #3651
File: modules/new_serverpod_auth/serverpod_auth_email_account/serverpod_auth_email_account_server/lib/src/business/email_accounts.dart:35-39
Timestamp: 2025-06-16T12:07:26.018Z
Learning: The withServerpod test helper runs tests within a transaction, which may require adapting database queries to accept transaction parameters for proper snapshot consistency during testing.

tests/serverpod_test_server/test_e2e/record_types_test.dart (1)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

tests/serverpod_test_server/test_integration/test_tools/serverpod_test_tools.dart (7)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

Learnt from: tp
PR: #3747
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/pubspec.yaml:37-38
Timestamp: 2025-07-02T16:09:27.702Z
Learning: In Serverpod migration testing, it's appropriate for test servers like serverpod_new_auth_test_server to include dependencies on both legacy packages (e.g., serverpod_auth_server) and new modular packages to enable comprehensive testing of migration paths from old to new authentication systems.

Learnt from: tp
PR: #3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., late AuthenticationInfo? authenticationInfo;) rather than non-nullable ones to avoid using ! operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when session.authenticated returns null.

Learnt from: tp
PR: #3651
File: modules/new_serverpod_auth/serverpod_auth_email_account/serverpod_auth_email_account_server/lib/src/business/email_accounts.dart:35-39
Timestamp: 2025-06-16T12:07:26.018Z
Learning: The withServerpod test helper runs tests within a transaction, which may require adapting database queries to accept transaction parameters for proper snapshot consistency during testing.

Learnt from: exaby73
PR: #3741
File: modules/serverpod_auth/serverpod_auth_server/analysis_options.yaml:14-16
Timestamp: 2025-07-01T13:01:27.054Z
Learning: In Serverpod, first-party packages like serverpod_auth_server can appropriately use blanket invalid_use_of_internal_member: ignore directives in their analysis_options.yaml since they use internal Database methods internally without exposing them in their public APIs to end users.

Learnt from: tp
PR: #3721
File: modules/new_serverpod_auth/serverpod_auth_session/serverpod_auth_session_flutter/test/serverpod_auth_session_flutter_test.dart:1-7
Timestamp: 2025-06-27T07:44:09.048Z
Learning: In Serverpod packages, the uuid package is re-exported through a chain: serverpod_auth_session_client re-exports serverpod_client, which re-exports serverpod_serialization, which re-exports uuid. This means Uuid class is available in files that import serverpod_auth_session_client without needing a direct uuid package import.

Learnt from: tp
PR: #3721
File: util/pub_get_all:0-0
Timestamp: 2025-06-27T08:39:36.440Z
Learning: In the Serverpod project, dart pub get commands work fine on Flutter packages both locally and in CI environments, even when the package has flutter: sdk: flutter dependencies in pubspec.yaml. The technical constraint of Flutter SDK dependencies causing dart pub failures may not apply in all environments or recent Dart versions.

tools/serverpod_cli/lib/src/generator/dart/library_generators/server_test_tools_generator.dart (3)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

Learnt from: tp
PR: #3651
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:1-1
Timestamp: 2025-06-19T10:25:15.101Z
Learning: When reviewing test coverage, consider that endpoint methods that simply forward to underlying service classes don't necessarily need their own tests if the underlying functionality is well-tested, especially when they get indirect testing through helper methods.

Learnt from: tp
PR: #3651
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:1-1
Timestamp: 2025-06-19T10:25:15.101Z
Learning: Explicit tests for complex endpoint methods provide cleaner error reporting and better debugging experience compared to testing the same functionality only within setUp blocks or helper methods.

tools/serverpod_cli/lib/src/generator/dart/library_generators/library_generator.dart (1)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

🧰 Additional context used
🧠 Learnings (8)
tests/serverpod_test_server/test/serialization_legacy_test.dart (4)

Learnt from: tp
PR: #3625
File: packages/serverpod/lib/src/cloud_storage/public_endpoint.dart:0-0
Timestamp: 2025-07-04T07:30:27.709Z
Learning: In Dart, ByteData.sublistView() is safer than ByteData.view() when working with TypedData views like Uint8List. ByteData.view() creates a view from a raw ByteBuffer without considering the original view's offset/length, potentially exposing the entire underlying buffer. ByteData.sublistView() properly accounts for data.offsetInBytes, data.elementSizeInBytes, and data.lengthInBytes, ensuring the view respects the original bounds. When converting TypedData to ByteData, use ByteData.sublistView(data) instead of ByteData.view(data.buffer).

Learnt from: nielsenko
PR: #3625
File: packages/serverpod/lib/src/cloud_storage/public_endpoint.dart:82-93
Timestamp: 2025-07-03T09:16:08.642Z
Learning: In Serverpod's CloudStoragePublicEndpoint, the _readBinaryBody method must buffer the entire request body in memory because the storage.storeFile interface requires a ByteData object. Implementing true streaming uploads would require reworking Serverpod's serialization handling of binary arguments. The current implementation uses BytesBuilder for efficient byte accumulation instead of list concatenation.

Learnt from: nielsenko
PR: #3625
File: packages/serverpod/lib/src/web_server/routes/static_directory.dart:155-157
Timestamp: 2025-07-03T09:33:09.654Z
Learning: In Dart, Stream.cast() returns Stream where R (the element type) is inferred from context through Dart's downward inference system. For example, when Body.fromDataStream expects Stream, calling file.openRead().cast() will automatically infer R as Uint8List, effectively becoming cast(). The cast method transforms each element of the stream using 'as R'.

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

tests/serverpod_test_server/test_integration/test_tools/protocol_test.dart (2)

Learnt from: tp
PR: #3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., late AuthenticationInfo? authenticationInfo;) rather than non-nullable ones to avoid using ! operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when session.authenticated returns null.

Learnt from: tp
PR: #3651
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:1-1
Timestamp: 2025-06-19T10:25:15.101Z
Learning: Explicit tests for complex endpoint methods provide cleaner error reporting and better debugging experience compared to testing the same functionality only within setUp blocks or helper methods.

tests/serverpod_test_server/test_e2e/connection_test.dart (1)

Learnt from: tp
PR: #3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., late AuthenticationInfo? authenticationInfo;) rather than non-nullable ones to avoid using ! operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when session.authenticated returns null.

tests/serverpod_test_server/test_e2e/database_roundtrip_type_test.dart (1)

Learnt from: tp
PR: #3651
File: modules/new_serverpod_auth/serverpod_auth_email_account/serverpod_auth_email_account_server/lib/src/business/email_accounts.dart:35-39
Timestamp: 2025-06-16T12:07:26.018Z
Learning: The withServerpod test helper runs tests within a transaction, which may require adapting database queries to accept transaction parameters for proper snapshot consistency during testing.

tests/serverpod_test_server/test_e2e/record_types_test.dart (1)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

tests/serverpod_test_server/test_integration/test_tools/serverpod_test_tools.dart (7)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

Learnt from: tp
PR: #3747
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/pubspec.yaml:37-38
Timestamp: 2025-07-02T16:09:27.702Z
Learning: In Serverpod migration testing, it's appropriate for test servers like serverpod_new_auth_test_server to include dependencies on both legacy packages (e.g., serverpod_auth_server) and new modular packages to enable comprehensive testing of migration paths from old to new authentication systems.

Learnt from: tp
PR: #3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., late AuthenticationInfo? authenticationInfo;) rather than non-nullable ones to avoid using ! operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when session.authenticated returns null.

Learnt from: tp
PR: #3651
File: modules/new_serverpod_auth/serverpod_auth_email_account/serverpod_auth_email_account_server/lib/src/business/email_accounts.dart:35-39
Timestamp: 2025-06-16T12:07:26.018Z
Learning: The withServerpod test helper runs tests within a transaction, which may require adapting database queries to accept transaction parameters for proper snapshot consistency during testing.

Learnt from: exaby73
PR: #3741
File: modules/serverpod_auth/serverpod_auth_server/analysis_options.yaml:14-16
Timestamp: 2025-07-01T13:01:27.054Z
Learning: In Serverpod, first-party packages like serverpod_auth_server can appropriately use blanket invalid_use_of_internal_member: ignore directives in their analysis_options.yaml since they use internal Database methods internally without exposing them in their public APIs to end users.

Learnt from: tp
PR: #3721
File: modules/new_serverpod_auth/serverpod_auth_session/serverpod_auth_session_flutter/test/serverpod_auth_session_flutter_test.dart:1-7
Timestamp: 2025-06-27T07:44:09.048Z
Learning: In Serverpod packages, the uuid package is re-exported through a chain: serverpod_auth_session_client re-exports serverpod_client, which re-exports serverpod_serialization, which re-exports uuid. This means Uuid class is available in files that import serverpod_auth_session_client without needing a direct uuid package import.

Learnt from: tp
PR: #3721
File: util/pub_get_all:0-0
Timestamp: 2025-06-27T08:39:36.440Z
Learning: In the Serverpod project, dart pub get commands work fine on Flutter packages both locally and in CI environments, even when the package has flutter: sdk: flutter dependencies in pubspec.yaml. The technical constraint of Flutter SDK dependencies causing dart pub failures may not apply in all environments or recent Dart versions.

tools/serverpod_cli/lib/src/generator/dart/library_generators/server_test_tools_generator.dart (3)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

Learnt from: tp
PR: #3651
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:1-1
Timestamp: 2025-06-19T10:25:15.101Z
Learning: When reviewing test coverage, consider that endpoint methods that simply forward to underlying service classes don't necessarily need their own tests if the underlying functionality is well-tested, especially when they get indirect testing through helper methods.

Learnt from: tp
PR: #3651
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:1-1
Timestamp: 2025-06-19T10:25:15.101Z
Learning: Explicit tests for complex endpoint methods provide cleaner error reporting and better debugging experience compared to testing the same functionality only within setUp blocks or helper methods.

tools/serverpod_cli/lib/src/generator/dart/library_generators/library_generator.dart (1)

Learnt from: tp
PR: #3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Migration e2e tests (3.24.0)
  • GitHub Check: Migration e2e tests (3.32.1)
🔇 Additional comments (35)
tests/serverpod_test_server/test_integration/test_tools/protocol_test.dart (1)

163-172: LGTM: Test correctly validates empty non-string-keyed map handling.

This test case directly addresses the core issue described in the PR objectives - ensuring empty maps with non-string keys (like Map<int, int>) are properly serialized and deserialized through endpoint calls.

tests/serverpod_test_server/test/serialization_test.dart (1)

313-313: LGTM: Function rename improves clarity and generality.

The renaming from mapRecordContainingContainerToJson to mapContainerToJson better reflects the function's expanded purpose of handling both record-containing containers and non-string-keyed maps.

Also applies to: 347-347, 380-380, 413-413

tests/serverpod_test_server/lib/src/endpoints/map_parameters.dart (1)

45-50: LGTM: Method supports testing of nested non-string-keyed maps.

The implementation follows the established pattern in this endpoint class and provides necessary infrastructure for testing nested map serialization, which is relevant to the PR's objectives.

tests/serverpod_test_server/test_e2e/database_roundtrip_type_test.dart (1)

264-280: LGTM: Database roundtrip test ensures persistence of empty non-string-keyed maps.

This test correctly verifies that empty maps with non-string keys survive database storage and retrieval, which is crucial for the fix described in the PR objectives. The test structure is consistent with the existing pattern in the file.

tests/serverpod_test_server/test_e2e/connection_test.dart (3)

421-429: LGTM! Excellent test coverage for the nested empty map edge case.

This test directly addresses the core issue described in the PR - ensuring empty maps with non-string keys are properly serialized and deserialized when nested within other maps.


431-434: LGTM! Essential test case for the primary bug fix.

This test verifies that empty maps with integer keys are properly handled, which was the core serialization issue described in the PR objectives.


448-452: LGTM! Comprehensive coverage for enum-keyed empty maps.

This test ensures that the fix works for all non-string key types, including enums, providing thorough coverage of the serialization issue.

tools/serverpod_cli/lib/src/generator/dart/library_generators/model_library_generator.dart (1)

1193-1210: Constants verified
mapRecordToJsonFuncName and mapContainerToJsonFunctionName are declared as top-level constants in library_generator.dart and correctly imported into model_library_generator.dart. No further action required.

tests/serverpod_test_server/test_e2e/record_types_test.dart (5)

143-151: LGTM! Test covers empty string-keyed map scenario.

This test verifies that empty maps with string keys are correctly serialized and deserialized when contained within records.


163-171: Excellent coverage for the core PR objective.

This test specifically addresses the main issue described in the PR: handling empty maps with non-string keys (int in this case). The test verifies that an empty Map<int, int> within a record is correctly serialized and returned as an empty map rather than causing deserialization failures.


173-181: Good complementary test for non-empty non-string-keyed maps.

This test ensures that the fix doesn't break the existing functionality for non-empty maps with non-string keys.


274-296: Comprehensive test coverage for complex nested scenarios.

These tests cover:

  1. Named records with empty non-string-keyed maps (lines 274-283)
  2. Named records with nested sets containing records (lines 285-296)

This ensures the serialization fix works correctly in more complex nested structures.


249-250: Minor formatting improvements.

Good cleanup of extra spaces in test descriptions for consistency.

Also applies to: 261-262

tests/serverpod_test_server/lib/src/endpoints/record_parameters.dart (3)

73-85: Well-structured endpoint methods for map serialization testing.

These methods provide the necessary server-side endpoints to test:

  1. String-keyed maps in records (lines 73-78)
  2. Non-string-keyed maps in records (lines 80-85)

The simple pass-through implementation is appropriate for testing serialization/deserialization behavior. The non-string-keyed map method directly supports testing the core PR objective.


87-92: Good addition for testing nested record structures.

This method handles records containing sets with nested records, which tests more complex serialization scenarios beyond just maps.


133-145: Comprehensive coverage for named record scenarios.

These methods extend the testing to named records containing:

  1. Non-string-keyed maps (lines 133-138)
  2. Sets with nested records (lines 140-145)

This ensures the serialization fix works correctly across different record structure types.

tests/serverpod_test_server/test_integration/test_tools/serverpod_test_tools.dart (9)

35-36: Import alias refactoring looks good.

The swap of import aliases (_i17 for protocol.dart and _i18 for test_enum.dart) aligns with the new serialization approach where protocol methods are used for container and record serialization.


5148-5166: Correct implementation for non-string keyed map serialization.

The use of _i17.mapContainerToJson(map) and _i17.Protocol().deserialize<Map<int, int>>(map) properly handles serialization of maps with non-string keys, ensuring empty maps are serialized as [] instead of {}.


5198-5229: Proper handling of enum-keyed maps.

The serialization and deserialization of Map<_i18.TestEnum, int> is correctly implemented using the new pattern.


7738-8175: Consistent record serialization across module endpoints.

All module endpoint methods (ModuleEndpointSubclass, ModuleEndpointAdaptation, ModuleEndpointReduction, ModuleEndpointExtension) correctly use _i17.mapRecordToJson for serialization and _i17.Protocol().deserialize for deserialization of record types.


8477-8750: Excellent consistency in record type handling.

All record parameter methods correctly handle various record types including:

  • Simple records: (int,), (int, String)
  • Nullable variations: (int,)?, (int?,), (int?,)?
  • Complex records with objects: (int, _i11.SimpleData)

The serialization and deserialization patterns are uniformly applied.


8756-8850: New methods properly handle complex nested structures.

The addition of these methods extends support for:

  • Records containing string-keyed maps: (Map<String, int>,)
  • Records containing non-string-keyed maps: (Map<int, int>,) - directly addresses PR objectives
  • Records containing sets with nested records: (Set<(int,)>,)

All follow the established serialization pattern correctly.


8868-9087: Named record methods maintain consistency.

All named record methods correctly handle serialization/deserialization, including the new methods:

  • returnNamedNonStringKeyedMapRecord: Handles ({Map<int, int> intIntMap})
  • returnNamedSetWithNestedRecordRecord: Handles ({Set<(bool,)> boolSet})

These additions complete the support for non-string keyed containers in various record contexts.


9089-9600: Comprehensive support for complex data structures.

The implementation correctly handles:

  • Record typedefs with proper serialization
  • Collections of records (List, Set, Map) using mapContainerToJson
  • Nullable collections with appropriate null checks
  • Deeply nested structures like Map<String, List<Set<(int,)>>>

All maintain the consistent serialization/deserialization pattern.


9633-12164: Stream methods correctly integrate new serialization.

All stream-related methods properly use the new serialization functions within the JSON encoding context:

  • Record streams use _i17.mapRecordToJson
  • Container streams use _i17.mapContainerToJson
  • Nullable initial values are properly handled with conditional checks

The implementation maintains consistency throughout.

tools/serverpod_cli/lib/src/generator/dart/library_generators/server_test_tools_generator.dart (3)

176-176: LGTM! Function names are now configurable.

The function name references are now using configurable constants instead of hardcoded strings, improving consistency and maintainability across the codebase.

Also applies to: 180-180


184-200: Excellent refactoring to centralize parameter handling logic.

The new handleParameter helper function effectively consolidates the parameter serialization logic that was previously scattered. The implementation correctly handles:

  • Record types with mapRecordToJsonRef
  • Container types with records or non-string keyed maps with proper null safety
  • Regular parameters passed through unchanged

This improves code maintainability and reduces duplication.


231-231: Consistent application of the refactoring.

The usage of the new handleParameter function and updated function name references maintain consistency with the centralized approach.

Also applies to: 556-556, 560-560

tools/serverpod_cli/lib/src/generator/dart/library_generators/library_generator.dart (7)

12-13: Well-structured constant definitions for function names.

Defining these constants improves maintainability by centralizing function name references and preventing typos across the codebase.


353-353: Consistent use of the new constant.

The usage of mapContainerToJsonFunctionName constant maintains consistency with the refactoring approach.


781-809: Consistent refactoring maintains uniformity across generators.

The handleParameter helper function in the client code generation follows the same beneficial pattern as the server test tools, ensuring consistent parameter handling across the codebase.

Also applies to: 818-818


968-972: Consistent application of function name constants.

The transformReturnType method correctly uses the configurable function name constants, maintaining consistency across the codebase.


1128-1128: Documentation and implementation properly updated.

The function name constant usage is consistent, and the documentation correctly reflects the expanded functionality to handle both records and non-string-keyed maps.

Also applies to: 1142-1153, 1169-1170


1213-1221: Well-implemented type checking for non-string-keyed maps.

The containsNonStringKeyedMap getter correctly implements recursive checking for non-string-keyed maps within container types, following the same pattern as returnsRecordInContainer. The recursive logic should properly handle nested scenarios as mentioned in past review comments.


1432-1448: Comprehensive extension to handle non-string-keyed maps.

The extensions to transformReturnType and recordToJsonMapCode properly integrate support for non-string-keyed maps, maintaining consistency with the existing record handling patterns. The null safety handling is correctly implemented.

Also applies to: 1473-1501

@tp
tp requested a review from Isakdl July 23, 2025 08:15

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have one more concern on the nested checks, see comment.

@tp
tp force-pushed the map-serialization branch from c2e412f to 2dfd779 Compare July 23, 2025 11:24
@tp

tp commented Jul 23, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 23, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@tp
tp requested a review from Isakdl July 23, 2025 12:04

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! LGTM 🚀

@tp
tp merged commit 5604d63 into serverpod:main Jul 23, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Jul 23, 2025
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

2 participants