Skip to content

Commit 689f847

Browse files
fix (serialization) : encode unknown dataclasses as plain dicts;add unit test
Signed-off-by: Gautam Datla <[email protected]>
1 parent 89225dc commit 689f847

File tree

3 files changed

+380
-51
lines changed

3 files changed

+380
-51
lines changed

nemoguardrails/colang/v2_x/runtime/serialization.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,21 @@ def encode_to_dict(obj: Any, refs: Dict[int, Any]):
8686
"value": {k: encode_to_dict(v, refs) for k, v in obj.items()},
8787
}
8888
elif is_dataclass(obj):
89-
value = {
90-
"__type": type(obj).__name__,
91-
"value": {
92-
k: encode_to_dict(getattr(obj, k), refs)
93-
for k in obj.__dataclass_fields__.keys()
94-
},
89+
# Encode dataclasses. If it's a known class (present in name_to_class),
90+
# keep its type tag so we can fully round-trip via json_to_state.
91+
# Otherwise, fall back to a plain dict to avoid "Unknown d_type" on decode.
92+
cls = type(obj)
93+
encoded_fields = {
94+
k: encode_to_dict(getattr(obj, k), refs)
95+
for k in obj.__dataclass_fields__.keys()
9596
}
97+
98+
if cls.__name__ in name_to_class and name_to_class[cls.__name__] is cls:
99+
value = {"__type": cls.__name__, "value": encoded_fields}
100+
else:
101+
# Unknown dataclass → JSON-friendly dict
102+
value = {"__type": "dict", "value": encoded_fields}
103+
96104
elif isinstance(obj, RailsConfig):
97105
value = {
98106
"__type": "RailsConfig",

0 commit comments

Comments
 (0)