Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(python): harden dynamic schema validation

jkomyno191d919eefca
diff --git a/docs/content/changelog/08-06-26-free-form-tool-arguments.mdx b/docs/content/changelog/08-06-26-free-form-tool-arguments.mdx
index b3036e0cf..dc3ec53c7 100644
--- a/docs/content/changelog/08-06-26-free-form-tool-arguments.mdx
+++ b/docs/content/changelog/08-06-26-free-form-tool-arguments.mdx
@@ -57,7 +57,7 @@ Where a schema declares `patternProperties` or a schema-valued `additionalProper
Root-level `patternProperties` and boolean- or schema-valued `additionalProperties` also survive tool schema parsing; they were previously dropped before any converter could see them.
-In Python, a `$ref` inside a `patternProperties` or schema-valued `additionalProperties` schema must be a local JSON Pointer such as `#/properties/foo`. External, anchored, and unresolvable references now raise a `ValueError` while the tool is wrapped, rather than being ignored along with the constraint that carried them. The rule is transitive: a local pointer whose target carries a non-local reference raises too. A `$ref`-shaped value under `const`, `default`, `enum`, or `examples` is instance data rather than a reference, and is left alone.
+In Python, an invalid `patternProperties` or schema-valued `additionalProperties` schema now raises while the tool is wrapped instead of being ignored. This includes an external, anchored, or unresolvable `$ref`, a `patternProperties` key that is not a valid regular expression, or a dynamic-key subschema that is not valid Draft 7. A `$ref` in these schemas must be a local JSON Pointer such as `#/properties/foo`. The rule is transitive: a local pointer whose target carries a non-local reference raises too. A `$ref`-shaped value under `const`, `default`, `enum`, or `examples` is instance data rather than a reference, and is left alone.
### Behavior Change for Python Agentic Providers
@@ -91,7 +91,7 @@ This brings Python in line with the TypeScript SDK, where the Zod converter has
- **`composio_openai`, `composio_anthropic`, and the other non-agentic providers.** These hand the raw JSON schema to the model API and pass the returned arguments straight through, so they never build a Pydantic model from a tool schema.
- **`composio_gemini`.** Gemini builds a typed signature through `json_schema_to_pydantic_type`, so free-form object arguments now use `Dict[str, Any]` instead of an empty model. It does not use `json_schema_to_model`, so the unknown-key rejection above does not apply.
-- **Declared field behavior, aliases for reserved Python keywords, `skip_default`, combiners, and references in declared fields.** All unchanged. References inside a dynamic-key schema are the exception, as described above.
+- **Declared field behavior, aliases for reserved Python keywords, `skip_default`, combiners, and references in declared fields.** All unchanged. Dynamic-key schema validation is the exception, as described above.
### Behavior Change for the Claude Agent SDK Provider
@@ -114,6 +114,6 @@ This is also what makes free-form object arguments reach execution intact throug
Accepting and preserving free-form object content is backward compatible: payloads that previously failed now succeed, and payloads that previously arrived empty now arrive complete.
-The two unknown-key rejections described above — Python agentic providers, and the Claude Agent SDK provider — are the behavior changes at call time. Tools whose schemas set `additionalProperties: true`, or whose objects declare no properties, are unaffected.
+The two unknown-key rejections described above (Python agentic providers and the Claude Agent SDK provider) are the behavior changes at call time. Tools whose schemas set `additionalProperties: true`, or whose objects declare no properties, are unaffected.
-The one remaining change happens earlier, while a Python tool is wrapped: a non-local `$ref` inside a dynamic-key schema now raises instead of being ignored. Only tools whose `patternProperties` or schema-valued `additionalProperties` carry an external, anchored, or unresolvable reference are affected.
+The one remaining change happens earlier, while a Python tool is wrapped: an invalid dynamic-key schema now raises instead of being ignored. Only tools whose `patternProperties` or schema-valued `additionalProperties` contain an invalid reference, regular expression, or Draft 7 subschema are affected.
diff --git a/python/composio/utils/schema_converter.py b/python/composio/utils/schema_converter.py
index 3e954054f..21c669aa2 100644
--- a/python/composio/utils/schema_converter.py
+++ b/python/composio/utils/schema_converter.py
@@ -412,16 +412,25 @@ def _check_dynamic_references(
)
-def _dynamic_key_validator(
+def _validate_dynamic_key_schema(
schema: t.Any,
root_schema: t.Dict[str, t.Any],
root_validator: Validator,
-) -> _DynamicKeyValidator:
- """Compile a complete inline JSON subschema without coercive acceptance."""
+) -> None:
+ """Validate one dynamic-key subschema without constructing a materializer."""
validator_type = type(root_validator)
validator_type.check_schema(schema)
_check_dynamic_references(schema, root_schema)
+
+def _dynamic_key_validator(
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+ root_validator: Validator,
+) -> _DynamicKeyValidator:
+ """Compile a complete inline JSON subschema without coercive acceptance."""
+ _validate_dynamic_key_schema(schema, root_schema, root_validator)
+
materializer = None
if _contains_default(schema):
annotation = json_schema_to_pydantic_type(schema, root_schema=root_schema)
@@ -433,6 +442,39 @@ def _dynamic_key_validator(
)
+def _compile_pattern_property(pattern: str) -> t.Pattern[str]:
+ try:
+ return re.compile(pattern)
+ except re.error as exc:
+ raise ValueError(
+ f"Invalid patternProperties regular expression: {pattern!r}"
+ ) from exc
+
+
+def _validate_object_policy_schema(
+ schema: t.Dict[str, t.Any],
+ root_schema: t.Dict[str, t.Any],
+) -> None:
+ """Validate a dynamic object policy without materializing defaults."""
+ validator_type = jsonschema_validators.validator_for(
+ root_schema,
+ default=jsonschema_validators.Draft7Validator,
+ )
+ root_validator = validator_type(root_schema)
+
+ for pattern, pattern_schema in (schema.get("patternProperties") or {}).items():
+ _compile_pattern_property(pattern)
+ _validate_dynamic_key_schema(
+ pattern_schema,
+ root_schema,
+ root_validator,
+ )
+
+ additional = schema.get("additionalProperties")
+ if isinstance(additional, dict):
+ _validate_dynamic_key_schema(additional, root_schema, root_validator)
+
+
def _compile_object_policy(
schema: t.Dict[str, t.Any],
root_schema: t.Optional[t.Dict[str, t.Any]] = None,
@@ -448,21 +490,16 @@ def _compile_object_policy(
patterns = []
for pattern, pattern_schema in (schema.get("patternProperties") or {}).items():
- try:
- patterns.append(
- (
- re.compile(pattern),
- _dynamic_key_validator(
- pattern_schema,
- document_root,
- root_validator,
- ),
- )
+ patterns.append(
+ (
+ _compile_pattern_property(pattern),
+ _dynamic_key_validator(
+ pattern_schema,
+ document_root,
+ root_validator,
+ ),
)
- except re.error as exc:
- raise ValueError(
- f"Invalid patternProperties regular expression: {pattern!r}"
- ) from exc
+ )
return _ObjectPolicy(
declared=declared,
@@ -477,26 +514,22 @@ def _compile_object_policy(
)
-def _validate_dynamic_object_policies(
+def _iter_reachable_schemas(
schema: t.Any,
root_schema: t.Dict[str, t.Any],
visited: t.Optional[t.Set[int]] = None,
-) -> None:
- """Compile every reachable dynamic object policy before conversion fallback."""
+) -> t.Iterator[t.Dict[str, t.Any]]:
+ """Yield schema nodes reached through Draft 7 schema-valued keywords."""
if visited is None:
visited = set()
if isinstance(schema, list):
for item in schema:
- _validate_dynamic_object_policies(item, root_schema, visited)
+ yield from _iter_reachable_schemas(item, root_schema, visited)
return
if not isinstance(schema, dict) or id(schema) in visited:
return
visited.add(id(schema))
-
- if schema.get("patternProperties") or isinstance(
- schema.get("additionalProperties"), dict
- ):
- _compile_object_policy(schema, root_schema)
+ yield schema
reference = schema.get("$ref")
if isinstance(reference, str) and (reference == "#" or reference.startswith("#/")):
@@ -504,37 +537,112 @@ def _validate_dynamic_object_policies(
resolved = _resolve_local_json_pointer(reference, root_schema)
except ValueError:
# Ordinary references retain the converter's legacy fallback.
- # References used by dynamic-key constraints are rejected by
- # `_compile_object_policy` above.
+ # Dynamic-key references are checked when their owning policy is
+ # validated.
resolved = None
if isinstance(resolved, (dict, list)):
- _validate_dynamic_object_policies(resolved, root_schema, visited)
+ yield from _iter_reachable_schemas(resolved, root_schema, visited)
for keyword in ("properties", "patternProperties"):
values = schema.get(keyword)
if isinstance(values, dict):
for child in values.values():
- _validate_dynamic_object_policies(child, root_schema, visited)
+ yield from _iter_reachable_schemas(child, root_schema, visited)
for keyword in _SCHEMA_VALUED_KEYWORDS:
child = schema.get(keyword)
if isinstance(child, (dict, list)):
- _validate_dynamic_object_policies(child, root_schema, visited)
+ yield from _iter_reachable_schemas(child, root_schema, visited)
for keyword in _SCHEMA_LIST_KEYWORDS:
children = schema.get(keyword)
if isinstance(children, list):
- _validate_dynamic_object_policies(children, root_schema, visited)
+ yield from _iter_reachable_schemas(children, root_schema, visited)
items = schema.get("items")
if isinstance(items, (dict, list)):
- _validate_dynamic_object_policies(items, root_schema, visited)
+ yield from _iter_reachable_schemas(items, root_schema, visited)
dependencies = schema.get("dependencies")
if isinstance(dependencies, dict):
for child in dependencies.values():
if isinstance(child, (dict, bool)):
- _validate_dynamic_object_policies(child, root_schema, visited)
+ yield from _iter_reachable_schemas(child, root_schema, visited)
+
+
+def _has_dynamic_object_policy(schema: t.Dict[str, t.Any]) -> bool:
+ return bool(schema.get("patternProperties")) or isinstance(
+ schema.get("additionalProperties"), dict
+ )
+
+
+def _validate_dynamic_object_policies(
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+) -> None:
+ """Validate every reachable dynamic object policy before conversion fallback."""
+ for candidate in _iter_reachable_schemas(schema, root_schema):
+ if _has_dynamic_object_policy(candidate):
+ _validate_object_policy_schema(candidate, root_schema)
+
+
+def _contains_inline_object_policy(
+ schema: t.Any,
+ visited: t.Optional[t.Set[int]] = None,
+) -> bool:
+ """Whether direct object or array nesting contains a dynamic policy."""
+ if visited is None:
+ visited = set()
+ if isinstance(schema, list):
+ return any(_contains_inline_object_policy(item, visited) for item in schema)
+ if not isinstance(schema, dict) or id(schema) in visited:
+ return False
+ visited.add(id(schema))
+ if _has_dynamic_object_policy(schema):
+ return True
+
+ properties = schema.get("properties")
+ if isinstance(properties, dict) and any(
+ _contains_inline_object_policy(child, visited) for child in properties.values()
+ ):
+ return True
+
+ items = schema.get("items")
+ return isinstance(items, (dict, list)) and _contains_inline_object_policy(
+ items,
+ visited,
+ )
+
+
+def _apply_nested_object_policies(
+ schema: t.Dict[str, t.Any],
+ base_model: t.Type[BaseModel],
+ root_schema: t.Dict[str, t.Any],
+) -> t.Type[BaseModel]:
+ """Replace fields whose schemas contain dynamic object policies."""
+ field_overrides = {}
+ for name, property_schema in (schema.get("properties") or {}).items():
+ if not _contains_inline_object_policy(property_schema):
+ continue
+ field = base_model.model_fields.get(name)
+ if field is None:
+ continue
+ field_overrides[name] = (
+ _filtered_schema_to_pydantic_type(
+ property_schema,
+ root_schema=root_schema,
+ ),
+ field,
+ )
+
+ if not field_overrides:
+ return base_model
+
+ return create_pydantic_model( # type: ignore[call-overload]
+ schema.get("title", "GeneratedModel"),
+ __base__=base_model,
+ **field_overrides,
+ )
class _DynamicObjectModel(BaseModel):
@@ -789,11 +897,12 @@ def _convert_with_library(
# outside the legacy library-conversion fallback below. Invalid patterns or
# references must fail closed instead of silently changing the field to str.
if schema.get("type") == "object":
+ document_root = root_schema if root_schema is not None else schema
if _contains_unsatisfiable_schema(schema.get("properties", {})):
try:
- return _convert_object_with_unsatisfiable_properties(
+ base_model = _convert_object_with_unsatisfiable_properties(
schema,
- root_schema=root_schema,
+ root_schema=document_root,
)
except (SchemaError, CombinerError) as e:
logger.debug(
@@ -805,6 +914,11 @@ def _convert_with_library(
f"Unexpected error in schema conversion: {e}, falling back to string"
)
return str
+ return apply_object_policy(
+ schema,
+ _apply_nested_object_policies(schema, base_model, document_root),
+ root_schema=document_root,
+ )
# A property-less object with no dynamic-key constraints accepts and
# preserves arbitrary content. Modelling it as an empty Pydantic
# model instead silently discarded every key (issue #4064).
@@ -832,8 +946,8 @@ def _convert_with_library(
return apply_object_policy(
schema,
- base_model,
- root_schema=root_schema,
+ _apply_nested_object_policies(schema, base_model, document_root),
+ root_schema=document_root,
)
try:
diff --git a/python/tests/fixtures/json-schema-conversion/object-cases.json b/python/tests/fixtures/json-schema-conversion/object-cases.json
index aba143e21..8f85ec595 100644
--- a/python/tests/fixtures/json-schema-conversion/object-cases.json
+++ b/python/tests/fixtures/json-schema-conversion/object-cases.json
@@ -94,6 +94,98 @@
}
]
},
+ {
+ "id": "nested-pattern-properties-object",
+ "description": "A dynamic-key policy nested under a declared property validates and preserves matching keys.",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "payload": {
+ "type": "object",
+ "patternProperties": { "^count_": { "type": "integer" } },
+ "additionalProperties": false
+ }
+ },
+ "required": ["payload"]
+ },
+ "ingress": {
+ "accepted": true,
+ "preserved": {
+ "type": "object",
+ "properties": {
+ "payload": {
+ "type": "object",
+ "patternProperties": { "^count_": { "type": "integer" } },
+ "additionalProperties": false
+ }
+ },
+ "required": ["payload"]
+ }
+ },
+ "instances": [
+ {
+ "input": { "payload": { "count_a": 1 } },
+ "accepted": true,
+ "zod": { "output": { "payload": { "count_a": 1 } } },
+ "effect": { "output": { "payload": { "count_a": 1 } } },
+ "python": { "output": { "payload": { "count_a": 1 } } }
+ },
+ {
+ "input": { "payload": { "count_a": "1" } },
+ "accepted": false
+ },
+ {
+ "input": { "payload": { "other": 1 } },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "schema-valued-additional-properties-in-array-items",
+ "description": "A schema-valued dynamic-key policy inside array items validates every preserved value.",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "records": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": { "type": "number" }
+ }
+ }
+ },
+ "required": ["records"]
+ },
+ "ingress": {
+ "accepted": true,
+ "preserved": {
+ "type": "object",
+ "properties": {
+ "records": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": { "type": "number" }
+ }
+ }
+ },
+ "required": ["records"]
+ }
+ },
+ "instances": [
+ {
+ "input": { "records": [{ "a": 1 }, { "b": 2.5 }] },
+ "accepted": true,
+ "zod": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
+ "effect": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
+ "python": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } }
+ },
+ {
+ "input": { "records": [{ "a": "1" }] },
+ "accepted": false
+ }
+ ]
+ },
{
"id": "explicit-additional-properties-false",
"description": "An explicit `additionalProperties: false` closes an otherwise property-less object.",
diff --git a/python/tests/test_schema_converter.py b/python/tests/test_schema_converter.py
index 817a4434f..167636c51 100644
--- a/python/tests/test_schema_converter.py
+++ b/python/tests/test_schema_converter.py
@@ -1,6 +1,8 @@
"""Tests for the schema_converter boolean-schema pre-filter."""
import pytest
+from jsonschema import Draft7Validator
+from jsonschema.exceptions import SchemaError
from pydantic import TypeAdapter, ValidationError
from composio.utils.schema_converter import (
@@ -198,7 +200,33 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
@pytest.mark.parametrize(
- "invalid_object_schema,error_match",
+ "converter",
+ [json_schema_to_model, json_schema_to_pydantic_type],
+ ids=["model", "pydantic-type"],
+)
+def test_unsatisfiable_declared_property_keeps_root_dynamic_policy(converter):
+ schema = {
+ "type": "object",
+ "properties": {"impossible": {"allOf": [False, {"type": "string"}]}},
+ "patternProperties": {"^count_": {"type": "integer"}},
+ }
+ adapter = TypeAdapter(converter(schema))
+
+ result = adapter.validate_python({"count_a": 1})
+ assert adapter.dump_python(
+ result,
+ mode="json",
+ by_alias=True,
+ exclude_none=True,
+ ) == {"count_a": 1}
+ with pytest.raises(ValidationError):
+ adapter.validate_python({"count_a": "1"})
+ with pytest.raises(ValidationError):
+ adapter.validate_python({"impossible": None})
+
+
+ "invalid_object_schema,error_type,error_match",
[
(
{
@@ -207,6 +235,7 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
"^value_": {"$ref": "https://example.com/schema.json"}
},
},
+ ValueError,
"must be a local JSON Pointer",
),
(
@@ -214,17 +243,77 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
"type": "object",
"patternProperties": {"^value_": {"$ref": "#/$defs/missing"}},
},
+ ValueError,
"Unresolvable dynamic-key schema reference",
),
+ (
+ {
+ "type": "object",
+ "patternProperties": {"^value_": {"$ref": "#anchor"}},
+ },
+ ValueError,
+ "must be a local JSON Pointer",
+ ),
(
{
"type": "object",
"patternProperties": {"[": {"type": "string"}},
},
+ ValueError,
"Invalid patternProperties regular expression",
),
+ (
+ {
+ "type": "object",
+ "patternProperties": {"^value_": {"type": "not-a-json-schema-type"}},
+ },
+ SchemaError,
+ "not valid under any of the given schemas",
+ ),
+ (
+ {
+ "type": "object",
+ "additionalProperties": {"$ref": "https://example.com/schema.json"},
+ },
+ ValueError,
+ "must be a local JSON Pointer",
+ ),
+ (
+ {
+ "type": "object",
+ "additionalProperties": {"$ref": "#/$defs/missing"},
+ },
+ ValueError,
+ "Unresolvable dynamic-key schema reference",
+ ),
+ (
+ {
+ "type": "object",
+ "additionalProperties": {"$ref": "#anchor"},
+ },
+ ValueError,
+ "must be a local JSON Pointer",
+ ),
+ (
+ {
+ "type": "object",
+ "additionalProperties": {"type": "not-a-json-schema-type"},
+ },
+ SchemaError,
+ "not valid under any of the given schemas",
+ ),
+ ],
+ ids=[
+ "pattern-external-ref",
+ "pattern-missing-local-ref",
+ "pattern-anchored-ref",
+ "invalid-pattern",
+ "pattern-invalid-draft7",
+ "additional-external-ref",
+ "additional-missing-local-ref",
+ "additional-anchored-ref",
+ "additional-invalid-draft7",
],
- ids=["external-ref", "missing-local-ref", "invalid-pattern"],
)
@pytest.mark.parametrize(
"converter",
@@ -234,6 +323,7 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
@pytest.mark.parametrize("nested", [False, True], ids=["root", "nested"])
def test_invalid_dynamic_object_schema_fails_closed_across_public_entry_points(
invalid_object_schema,
+ error_type,
error_match,
converter,
nested,
@@ -246,10 +336,137 @@ def test_invalid_dynamic_object_schema_fails_closed_across_public_entry_points(
"required": ["payload"],
}
- with pytest.raises(ValueError, match=error_match):
+ with pytest.raises(error_type, match=error_match):
converter(schema)
+_INVALID_DYNAMIC_POLICY = {
+ "type": "object",
+ "patternProperties": {"[": {"type": "string"}},
+}
+
+
+ "schema",
+ [
+ {"type": "object", "properties": {"payload": _INVALID_DYNAMIC_POLICY}},
+ {"type": "array", "items": _INVALID_DYNAMIC_POLICY},
+ {"type": "array", "items": [{}, _INVALID_DYNAMIC_POLICY]},
+ {"allOf": [_INVALID_DYNAMIC_POLICY]},
+ {"anyOf": [_INVALID_DYNAMIC_POLICY]},
+ {"oneOf": [_INVALID_DYNAMIC_POLICY]},
+ {"not": _INVALID_DYNAMIC_POLICY},
+ {"if": _INVALID_DYNAMIC_POLICY},
+ {"then": _INVALID_DYNAMIC_POLICY},
+ {"else": _INVALID_DYNAMIC_POLICY},
+ {"type": "array", "contains": _INVALID_DYNAMIC_POLICY},
+ {"type": "object", "propertyNames": _INVALID_DYNAMIC_POLICY},
+ {
+ "type": "array",
+ "items": [{}],
+ "additionalItems": _INVALID_DYNAMIC_POLICY,
+ },
+ {
+ "type": "object",
+ "dependencies": {"flag": _INVALID_DYNAMIC_POLICY},
+ },
+ {
+ "$defs": {"Invalid": _INVALID_DYNAMIC_POLICY},
+ "$ref": "#/$defs/Invalid",
+ },
+ {
+ "definitions": {"Invalid": _INVALID_DYNAMIC_POLICY},
+ "$ref": "#/definitions/Invalid",
+ },
+ ],
+ ids=[
+ "property",
+ "array-items",
+ "tuple-items",
+ "all-of",
+ "any-of",
+ "one-of",
+ "not",
+ "if",
+ "then",
+ "else",
+ "contains",
+ "property-names",
+ "additional-items",
+ "dependency-schema",
+ "defs-reference",
+ "legacy-definitions-reference",
+ ],
+)
+def test_invalid_dynamic_policy_is_found_in_reachable_draft7_schema_positions(schema):
+ with pytest.raises(ValueError, match="Invalid patternProperties"):
+ json_schema_to_pydantic_type(schema)
+
+
+def _recursive_dynamic_schema(dynamic_keyword, nested):
+ recursive_ref = "#/$defs/Recursive" if nested else "#"
+
+ def make_recursive_object():
+ dynamic_schema = {
+ "allOf": [{"$ref": recursive_ref}],
+ "default": {},
+ }
+ recursive_object = {"type": "object"}
+ if dynamic_keyword == "patternProperties":
+ recursive_object[dynamic_keyword] = {"^child_": dynamic_schema}
+ else:
+ recursive_object[dynamic_keyword] = dynamic_schema
+ return recursive_object
+
+ recursive_object = make_recursive_object()
+ recursive_input = {"child_one": {}}
+
+ if not nested:
+ return recursive_object, recursive_input
+
+ return (
+ {
+ "$defs": {"Recursive": recursive_object},
+ "type": "object",
+ "properties": {"payload": make_recursive_object()},
+ "required": ["payload"],
+ },
+ {"payload": recursive_input},
+ )
+
+
+ "dynamic_keyword",
+ ["patternProperties", "additionalProperties"],
+ ids=["pattern-properties", "additional-properties"],
+)
+ "converter",
+ [json_schema_to_model, json_schema_to_pydantic_type],
+ ids=["model", "pydantic-type"],
+)
[email protected]("nested", [False, True], ids=["root", "nested"])
+def test_recursive_dynamic_schema_with_default_does_not_reenter_policy_validation(
+ dynamic_keyword,
+ converter,
+ nested,
+):
+ schema, input_value = _recursive_dynamic_schema(dynamic_keyword, nested)
+ Draft7Validator.check_schema(schema)
+
+ annotation = converter(schema)
+ adapter = TypeAdapter(annotation)
+ result = adapter.validate_python(input_value)
+
+ assert adapter.dump_python(result, mode="json", by_alias=True) == input_value
+
+ invalid_value = {"child_one": "not-an-object"}
+ if nested:
+ invalid_value = {"payload": invalid_value}
+ with pytest.raises(ValidationError):
+ adapter.validate_python(invalid_value)
+
+
@pytest.mark.parametrize(
"case,index",
[
diff --git a/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json b/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
index aba143e21..8f85ec595 100644
--- a/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
+++ b/ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
@@ -94,6 +94,98 @@
}
]
},
+ {
+ "id": "nested-pattern-properties-object",
+ "description": "A dynamic-key policy nested under a declared property validates and preserves matching keys.",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "payload": {
+ "type": "object",
+ "patternProperties": { "^count_": { "type": "integer" } },
+ "additionalProperties": false
+ }
+ },
+ "required": ["payload"]
+ },
+ "ingress": {
+ "accepted": true,
+ "preserved": {
+ "type": "object",
+ "properties": {
+ "payload": {
+ "type": "object",
+ "patternProperties": { "^count_": { "type": "integer" } },
+ "additionalProperties": false
+ }
+ },
+ "required": ["payload"]
+ }
+ },
+ "instances": [
+ {
+ "input": { "payload": { "count_a": 1 } },
+ "accepted": true,
+ "zod": { "output": { "payload": { "count_a": 1 } } },
+ "effect": { "output": { "payload": { "count_a": 1 } } },
+ "python": { "output": { "payload": { "count_a": 1 } } }
+ },
+ {
+ "input": { "payload": { "count_a": "1" } },
+ "accepted": false
+ },
+ {
+ "input": { "payload": { "other": 1 } },
+ "accepted": false
+ }
+ ]
+ },
+ {
+ "id": "schema-valued-additional-properties-in-array-items",
+ "description": "A schema-valued dynamic-key policy inside array items validates every preserved value.",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "records": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": { "type": "number" }
+ }
+ }
+ },
+ "required": ["records"]
+ },
+ "ingress": {
+ "accepted": true,
+ "preserved": {
+ "type": "object",
+ "properties": {
+ "records": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": { "type": "number" }
+ }
+ }
+ },
+ "required": ["records"]
+ }
+ },
+ "instances": [
+ {
+ "input": { "records": [{ "a": 1 }, { "b": 2.5 }] },
+ "accepted": true,
+ "zod": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
+ "effect": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
+ "python": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } }
+ },
+ {
+ "input": { "records": [{ "a": "1" }] },
+ "accepted": false
+ }
+ ]
+ },
{
"id": "explicit-additional-properties-false",
"description": "An explicit `additionalProperties: false` closes an otherwise property-less object.",