Skip to content

Fix serialize_as_any with recursive ref #1359

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/serializers/type_serializers/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use pyo3::types::{PyDict, PyList};

use crate::definitions::DefinitionsBuilder;
use crate::definitions::{DefinitionRef, RecursionSafeCache};
use crate::serializers::DuckTypingSerMode;

use crate::tools::SchemaDict;

Expand Down Expand Up @@ -93,8 +94,12 @@ impl TypeSerializer for DefinitionRefSerializer {
) -> PyResult<PyObject> {
self.definition.read(|comb_serializer| {
let comb_serializer = comb_serializer.unwrap();
let mut guard = extra.recursion_guard(value, self.definition.id())?;
comb_serializer.to_python(value, include, exclude, guard.state())
if extra.duck_typing_ser_mode != DuckTypingSerMode::Inferred {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

so what I found is that the outer serializer call to rescursive serializer but also put the self.definition.id() in the stack already. So when the rescursive serializer start to eval, the root model of it have the same self.definition.id() result in raise duplicated id error.

Checking for DuckTypingSerMode::Inferred is because that what I saw as a flag when the rescursive serializer started. I could be wrong so very open for suggestions !

Copy link
Contributor

Choose a reason for hiding this comment

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

Hmm, seems like a clever find. I think I'd like to have @davidhewitt take a look at this as well before we merge, he should be back soon :).

Copy link
Contributor

@davidhewitt davidhewitt Sep 26, 2024

Choose a reason for hiding this comment

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

This change (to not introduce recursion guards) is the cause of the segfaults in the tests in CI. (The tests now have unbounded recursion and blow the stack.)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

have fixed the issue!

comb_serializer.to_python(value, include, exclude, extra)
} else {
let mut guard = extra.recursion_guard(value, self.definition.id())?;
comb_serializer.to_python(value, include, exclude, guard.state())
}
})
}

Expand All @@ -112,10 +117,14 @@ impl TypeSerializer for DefinitionRefSerializer {
) -> Result<S::Ok, S::Error> {
self.definition.read(|comb_serializer| {
let comb_serializer = comb_serializer.unwrap();
let mut guard = extra
.recursion_guard(value, self.definition.id())
.map_err(py_err_se_err)?;
comb_serializer.serde_serialize(value, serializer, include, exclude, guard.state())
if extra.duck_typing_ser_mode != DuckTypingSerMode::Inferred {
comb_serializer.serde_serialize(value, serializer, include, exclude, extra)
} else {
let mut guard = extra
.recursion_guard(value, self.definition.id())
.map_err(py_err_se_err)?;
comb_serializer.serde_serialize(value, serializer, include, exclude, guard.state())
}
})
}

Expand Down
36 changes: 36 additions & 0 deletions tests/serializers/test_serialize_as_any.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass
from typing import Optional

from typing_extensions import TypedDict

Expand Down Expand Up @@ -155,3 +156,38 @@ class Other:
'x': 1,
'y': 'hopefully not a secret',
}


def test_serialize_with_recursive_models() -> None:

class Node:
next: Optional['Node'] = None
value: int = 42

schema = core_schema.definitions_schema(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@sydney-runkle I tested the python code and all good but how do I make an equivalent schema for the test here ?

from __future__ import annotations

import traceback

import pydantic


class Model1(pydantic.BaseModel):
    recursive: Model1 | None


class Model2(pydantic.BaseModel):
    recursive: pydantic.SerializeAsAny[Model2] | None

print(Model1(recursive=None).model_dump())
print(Model1(recursive=None).model_dump_json())
print(Model2(recursive=None).model_dump())
print(Model2(recursive=None).model_dump_json())

# All fail:
try:
    print(Model1(recursive=None).model_dump(serialize_as_any=True))
except:
    traceback.print_exc()

try:
    print(Model1(recursive=None).model_dump_json(serialize_as_any=True))
except:
    traceback.print_exc()

try:
    print(Model2(recursive=None).model_dump(serialize_as_any=True))
except:
    traceback.print_exc()

try:
    print(Model2(recursive=None).model_dump_json(serialize_as_any=True))
except:
    traceback.print_exc()

Copy link
Contributor

Choose a reason for hiding this comment

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

Good question - I normally just do

from pydantic._internal._core_utils import pretty_print_core_schema
from pydantic import BaseModel

class SomeModel(BaseModel): ...

pretty_print_core_schema(SomeModel.__pydantic_core_schema__)

And then go from that representation in order to build up an equivalent core schema

core_schema.definition_reference_schema('Node'),
[
core_schema.model_schema(
Node,
core_schema.model_fields_schema(
{
'value': core_schema.model_field(core_schema.with_default_schema(core_schema.int_schema(), default=42)),
'next': core_schema.model_field(
core_schema.with_default_schema(
core_schema.nullable_schema(
core_schema.definition_reference_schema('Node')
),
default=None,
)
),
}
),
ref='Node',
)
],
)

s = SchemaSerializer(schema)
v = SchemaValidator(schema)

obj = v.validate_python({'value': 2, 'asdas': 1})
Loading