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
jkomyno committed
Aug 7, 2026 at 21:56 UTC
191d919eefca88caa3d35ca99d43ec714968d5a4
5 files changed
+560
-45
docs/content/changelog/08-06-26-free-form-tool-arguments.mdx
+4
-4
@@ -57,7 +57,7 @@ Where a schema declares `patternProperties` or a schema-valued `additionalProper
57
58
Root-level `patternProperties` and boolean- or schema-valued `additionalProperties` also survive tool schema parsing; they were previously dropped before any converter could see them.
59
60
-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.
60
+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.
61
62
### Behavior Change for Python Agentic Providers
63
@@ -91,7 +91,7 @@ This brings Python in line with the TypeScript SDK, where the Zod converter has
91
92
- **`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.
93
- **`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.
94
-- **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.
94
+- **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.
95
96
### Behavior Change for the Claude Agent SDK Provider
97
@@ -114,6 +114,6 @@ This is also what makes free-form object arguments reach execution intact throug
114
115
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.
116
117
-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.
117
+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.
118
119
-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.
119
+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.
python/composio/utils/schema_converter.py
+152
-38
@@ -412,16 +412,25 @@ def _check_dynamic_references(
412
)
413
414
415
-def _dynamic_key_validator(
415
+def _validate_dynamic_key_schema(
416
schema: t.Any,
417
root_schema: t.Dict[str, t.Any],
418
root_validator: Validator,
419
-) -> _DynamicKeyValidator:
420
- """Compile a complete inline JSON subschema without coercive acceptance."""
419
+) -> None:
420
+ """Validate one dynamic-key subschema without constructing a materializer."""
421
validator_type = type(root_validator)
422
validator_type.check_schema(schema)
423
_check_dynamic_references(schema, root_schema)
424
425
+
426
+def _dynamic_key_validator(
427
+ schema: t.Any,
428
+ root_schema: t.Dict[str, t.Any],
429
+ root_validator: Validator,
430
+) -> _DynamicKeyValidator:
431
+ """Compile a complete inline JSON subschema without coercive acceptance."""
432
+ _validate_dynamic_key_schema(schema, root_schema, root_validator)
433
+
434
materializer = None
435
if _contains_default(schema):
436
annotation = json_schema_to_pydantic_type(schema, root_schema=root_schema)
@@ -433,6 +442,39 @@ def _dynamic_key_validator(
442
)
443
444
445
+def _compile_pattern_property(pattern: str) -> t.Pattern[str]:
446
+ try:
447
+ return re.compile(pattern)
448
+ except re.error as exc:
449
+ raise ValueError(
450
+ f"Invalid patternProperties regular expression: {pattern!r}"
451
+ ) from exc
452
+
453
+
454
+def _validate_object_policy_schema(
455
+ schema: t.Dict[str, t.Any],
456
+ root_schema: t.Dict[str, t.Any],
457
+) -> None:
458
+ """Validate a dynamic object policy without materializing defaults."""
459
+ validator_type = jsonschema_validators.validator_for(
460
+ root_schema,
461
+ default=jsonschema_validators.Draft7Validator,
462
+ )
463
+ root_validator = validator_type(root_schema)
464
+
465
+ for pattern, pattern_schema in (schema.get("patternProperties") or {}).items():
466
+ _compile_pattern_property(pattern)
467
+ _validate_dynamic_key_schema(
468
+ pattern_schema,
469
+ root_schema,
470
+ root_validator,
471
+ )
472
+
473
+ additional = schema.get("additionalProperties")
474
+ if isinstance(additional, dict):
475
+ _validate_dynamic_key_schema(additional, root_schema, root_validator)
476
+
477
+
478
def _compile_object_policy(
479
schema: t.Dict[str, t.Any],
480
root_schema: t.Optional[t.Dict[str, t.Any]] = None,
@@ -448,21 +490,16 @@ def _compile_object_policy(
490
491
patterns = []
492
for pattern, pattern_schema in (schema.get("patternProperties") or {}).items():
451
- try:
452
- patterns.append(
453
- (
454
- re.compile(pattern),
455
- _dynamic_key_validator(
456
- pattern_schema,
457
- document_root,
458
- root_validator,
459
- ),
460
- )
493
+ patterns.append(
494
+ (
495
+ _compile_pattern_property(pattern),
496
+ _dynamic_key_validator(
497
+ pattern_schema,
498
+ document_root,
499
+ root_validator,
500
+ ),
501
)
462
- except re.error as exc:
463
- raise ValueError(
464
- f"Invalid patternProperties regular expression: {pattern!r}"
465
- ) from exc
502
+ )
503
504
return _ObjectPolicy(
505
declared=declared,
@@ -477,26 +514,22 @@ def _compile_object_policy(
514
)
515
516
480
-def _validate_dynamic_object_policies(
517
+def _iter_reachable_schemas(
518
schema: t.Any,
519
root_schema: t.Dict[str, t.Any],
520
visited: t.Optional[t.Set[int]] = None,
484
-) -> None:
485
- """Compile every reachable dynamic object policy before conversion fallback."""
521
+) -> t.Iterator[t.Dict[str, t.Any]]:
522
+ """Yield schema nodes reached through Draft 7 schema-valued keywords."""
523
if visited is None:
524
visited = set()
525
if isinstance(schema, list):
526
for item in schema:
490
- _validate_dynamic_object_policies(item, root_schema, visited)
527
+ yield from _iter_reachable_schemas(item, root_schema, visited)
528
return
529
if not isinstance(schema, dict) or id(schema) in visited:
530
return
531
visited.add(id(schema))
495
-
496
- if schema.get("patternProperties") or isinstance(
497
- schema.get("additionalProperties"), dict
498
- ):
499
- _compile_object_policy(schema, root_schema)
532
+ yield schema
533
534
reference = schema.get("$ref")
535
if isinstance(reference, str) and (reference == "#" or reference.startswith("#/")):
@@ -504,37 +537,112 @@ def _validate_dynamic_object_policies(
537
resolved = _resolve_local_json_pointer(reference, root_schema)
538
except ValueError:
539
# Ordinary references retain the converter's legacy fallback.
507
- # References used by dynamic-key constraints are rejected by
508
- # `_compile_object_policy` above.
540
+ # Dynamic-key references are checked when their owning policy is
541
+ # validated.
542
resolved = None
543
if isinstance(resolved, (dict, list)):
511
- _validate_dynamic_object_policies(resolved, root_schema, visited)
544
+ yield from _iter_reachable_schemas(resolved, root_schema, visited)
545
546
for keyword in ("properties", "patternProperties"):
547
values = schema.get(keyword)
548
if isinstance(values, dict):
549
for child in values.values():
517
- _validate_dynamic_object_policies(child, root_schema, visited)
550
+ yield from _iter_reachable_schemas(child, root_schema, visited)
551
552
for keyword in _SCHEMA_VALUED_KEYWORDS:
553
child = schema.get(keyword)
554
if isinstance(child, (dict, list)):
522
- _validate_dynamic_object_policies(child, root_schema, visited)
555
+ yield from _iter_reachable_schemas(child, root_schema, visited)
556
557
for keyword in _SCHEMA_LIST_KEYWORDS:
558
children = schema.get(keyword)
559
if isinstance(children, list):
527
- _validate_dynamic_object_policies(children, root_schema, visited)
560
+ yield from _iter_reachable_schemas(children, root_schema, visited)
561
562
items = schema.get("items")
563
if isinstance(items, (dict, list)):
531
- _validate_dynamic_object_policies(items, root_schema, visited)
564
+ yield from _iter_reachable_schemas(items, root_schema, visited)
565
566
dependencies = schema.get("dependencies")
567
if isinstance(dependencies, dict):
568
for child in dependencies.values():
569
if isinstance(child, (dict, bool)):
537
- _validate_dynamic_object_policies(child, root_schema, visited)
570
+ yield from _iter_reachable_schemas(child, root_schema, visited)
571
+
572
+
573
+def _has_dynamic_object_policy(schema: t.Dict[str, t.Any]) -> bool:
574
+ return bool(schema.get("patternProperties")) or isinstance(
575
+ schema.get("additionalProperties"), dict
576
+ )
577
+
578
+
579
+def _validate_dynamic_object_policies(
580
+ schema: t.Any,
581
+ root_schema: t.Dict[str, t.Any],
582
+) -> None:
583
+ """Validate every reachable dynamic object policy before conversion fallback."""
584
+ for candidate in _iter_reachable_schemas(schema, root_schema):
585
+ if _has_dynamic_object_policy(candidate):
586
+ _validate_object_policy_schema(candidate, root_schema)
587
+
588
+
589
+def _contains_inline_object_policy(
590
+ schema: t.Any,
591
+ visited: t.Optional[t.Set[int]] = None,
592
+) -> bool:
593
+ """Whether direct object or array nesting contains a dynamic policy."""
594
+ if visited is None:
595
+ visited = set()
596
+ if isinstance(schema, list):
597
+ return any(_contains_inline_object_policy(item, visited) for item in schema)
598
+ if not isinstance(schema, dict) or id(schema) in visited:
599
+ return False
600
+ visited.add(id(schema))
601
+ if _has_dynamic_object_policy(schema):
602
+ return True
603
+
604
+ properties = schema.get("properties")
605
+ if isinstance(properties, dict) and any(
606
+ _contains_inline_object_policy(child, visited) for child in properties.values()
607
+ ):
608
+ return True
609
+
610
+ items = schema.get("items")
611
+ return isinstance(items, (dict, list)) and _contains_inline_object_policy(
612
+ items,
613
+ visited,
614
+ )
615
+
616
+
617
+def _apply_nested_object_policies(
618
+ schema: t.Dict[str, t.Any],
619
+ base_model: t.Type[BaseModel],
620
+ root_schema: t.Dict[str, t.Any],
621
+) -> t.Type[BaseModel]:
622
+ """Replace fields whose schemas contain dynamic object policies."""
623
+ field_overrides = {}
624
+ for name, property_schema in (schema.get("properties") or {}).items():
625
+ if not _contains_inline_object_policy(property_schema):
626
+ continue
627
+ field = base_model.model_fields.get(name)
628
+ if field is None:
629
+ continue
630
+ field_overrides[name] = (
631
+ _filtered_schema_to_pydantic_type(
632
+ property_schema,
633
+ root_schema=root_schema,
634
+ ),
635
+ field,
636
+ )
637
+
638
+ if not field_overrides:
639
+ return base_model
640
+
641
+ return create_pydantic_model( # type: ignore[call-overload]
642
+ schema.get("title", "GeneratedModel"),
643
+ __base__=base_model,
644
+ **field_overrides,
645
+ )
646
647
648
class _DynamicObjectModel(BaseModel):
@@ -789,11 +897,12 @@ def _convert_with_library(
897
# outside the legacy library-conversion fallback below. Invalid patterns or
898
# references must fail closed instead of silently changing the field to str.
899
if schema.get("type") == "object":
900
+ document_root = root_schema if root_schema is not None else schema
901
if _contains_unsatisfiable_schema(schema.get("properties", {})):
902
try:
794
- return _convert_object_with_unsatisfiable_properties(
903
+ base_model = _convert_object_with_unsatisfiable_properties(
904
schema,
796
- root_schema=root_schema,
905
+ root_schema=document_root,
906
)
907
except (SchemaError, CombinerError) as e:
908
logger.debug(
@@ -805,6 +914,11 @@ def _convert_with_library(
914
f"Unexpected error in schema conversion: {e}, falling back to string"
915
)
916
return str
917
+ return apply_object_policy(
918
+ schema,
919
+ _apply_nested_object_policies(schema, base_model, document_root),
920
+ root_schema=document_root,
921
+ )
922
# A property-less object with no dynamic-key constraints accepts and
923
# preserves arbitrary content. Modelling it as an empty Pydantic
924
# model instead silently discarded every key (issue #4064).
@@ -832,8 +946,8 @@ def _convert_with_library(
946
947
return apply_object_policy(
948
schema,
835
- base_model,
836
- root_schema=root_schema,
949
+ _apply_nested_object_policies(schema, base_model, document_root),
950
+ root_schema=document_root,
951
)
952
953
try:
python/tests/fixtures/json-schema-conversion/object-cases.json
+92
@@ -94,6 +94,98 @@
94
}
95
]
96
},
97
+ {
98
+ "id": "nested-pattern-properties-object",
99
+ "description": "A dynamic-key policy nested under a declared property validates and preserves matching keys.",
100
+ "schema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "payload": {
104
+ "type": "object",
105
+ "patternProperties": { "^count_": { "type": "integer" } },
106
+ "additionalProperties": false
107
+ }
108
+ },
109
+ "required": ["payload"]
110
+ },
111
+ "ingress": {
112
+ "accepted": true,
113
+ "preserved": {
114
+ "type": "object",
115
+ "properties": {
116
+ "payload": {
117
+ "type": "object",
118
+ "patternProperties": { "^count_": { "type": "integer" } },
119
+ "additionalProperties": false
120
+ }
121
+ },
122
+ "required": ["payload"]
123
+ }
124
+ },
125
+ "instances": [
126
+ {
127
+ "input": { "payload": { "count_a": 1 } },
128
+ "accepted": true,
129
+ "zod": { "output": { "payload": { "count_a": 1 } } },
130
+ "effect": { "output": { "payload": { "count_a": 1 } } },
131
+ "python": { "output": { "payload": { "count_a": 1 } } }
132
+ },
133
+ {
134
+ "input": { "payload": { "count_a": "1" } },
135
+ "accepted": false
136
+ },
137
+ {
138
+ "input": { "payload": { "other": 1 } },
139
+ "accepted": false
140
+ }
141
+ ]
142
+ },
143
+ {
144
+ "id": "schema-valued-additional-properties-in-array-items",
145
+ "description": "A schema-valued dynamic-key policy inside array items validates every preserved value.",
146
+ "schema": {
147
+ "type": "object",
148
+ "properties": {
149
+ "records": {
150
+ "type": "array",
151
+ "items": {
152
+ "type": "object",
153
+ "additionalProperties": { "type": "number" }
154
+ }
155
+ }
156
+ },
157
+ "required": ["records"]
158
+ },
159
+ "ingress": {
160
+ "accepted": true,
161
+ "preserved": {
162
+ "type": "object",
163
+ "properties": {
164
+ "records": {
165
+ "type": "array",
166
+ "items": {
167
+ "type": "object",
168
+ "additionalProperties": { "type": "number" }
169
+ }
170
+ }
171
+ },
172
+ "required": ["records"]
173
+ }
174
+ },
175
+ "instances": [
176
+ {
177
+ "input": { "records": [{ "a": 1 }, { "b": 2.5 }] },
178
+ "accepted": true,
179
+ "zod": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
180
+ "effect": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
181
+ "python": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } }
182
+ },
183
+ {
184
+ "input": { "records": [{ "a": "1" }] },
185
+ "accepted": false
186
+ }
187
+ ]
188
+ },
189
{
190
"id": "explicit-additional-properties-false",
191
"description": "An explicit `additionalProperties: false` closes an otherwise property-less object.",
python/tests/test_schema_converter.py
+220
-3
@@ -1,6 +1,8 @@
1
"""Tests for the schema_converter boolean-schema pre-filter."""
2
3
import pytest
4
+from jsonschema import Draft7Validator
5
+from jsonschema.exceptions import SchemaError
6
from pydantic import TypeAdapter, ValidationError
7
8
from composio.utils.schema_converter import (
@@ -198,7 +200,33 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
200
201
202
@pytest.mark.parametrize(
201
- "invalid_object_schema,error_match",
203
+ "converter",
204
+ [json_schema_to_model, json_schema_to_pydantic_type],
205
+ ids=["model", "pydantic-type"],
206
+)
207
+def test_unsatisfiable_declared_property_keeps_root_dynamic_policy(converter):
208
+ schema = {
209
+ "type": "object",
210
+ "properties": {"impossible": {"allOf": [False, {"type": "string"}]}},
211
+ "patternProperties": {"^count_": {"type": "integer"}},
212
+ }
213
+ adapter = TypeAdapter(converter(schema))
214
+
215
+ result = adapter.validate_python({"count_a": 1})
216
+ assert adapter.dump_python(
217
+ result,
218
+ mode="json",
219
+ by_alias=True,
220
+ exclude_none=True,
221
+ ) == {"count_a": 1}
222
+ with pytest.raises(ValidationError):
223
+ adapter.validate_python({"count_a": "1"})
224
+ with pytest.raises(ValidationError):
225
+ adapter.validate_python({"impossible": None})
226
+
227
+
228
+@pytest.mark.parametrize(
229
+ "invalid_object_schema,error_type,error_match",
230
[
231
(
232
{
@@ -207,6 +235,7 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
235
"^value_": {"$ref": "https://example.com/schema.json"}
236
},
237
},
238
+ ValueError,
239
"must be a local JSON Pointer",
240
),
241
(
@@ -214,17 +243,77 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
243
"type": "object",
244
"patternProperties": {"^value_": {"$ref": "#/$defs/missing"}},
245
},
246
+ ValueError,
247
"Unresolvable dynamic-key schema reference",
248
),
249
+ (
250
+ {
251
+ "type": "object",
252
+ "patternProperties": {"^value_": {"$ref": "#anchor"}},
253
+ },
254
+ ValueError,
255
+ "must be a local JSON Pointer",
256
+ ),
257
(
258
{
259
"type": "object",
260
"patternProperties": {"[": {"type": "string"}},
261
},
262
+ ValueError,
263
"Invalid patternProperties regular expression",
264
),
265
+ (
266
+ {
267
+ "type": "object",
268
+ "patternProperties": {"^value_": {"type": "not-a-json-schema-type"}},
269
+ },
270
+ SchemaError,
271
+ "not valid under any of the given schemas",
272
+ ),
273
+ (
274
+ {
275
+ "type": "object",
276
+ "additionalProperties": {"$ref": "https://example.com/schema.json"},
277
+ },
278
+ ValueError,
279
+ "must be a local JSON Pointer",
280
+ ),
281
+ (
282
+ {
283
+ "type": "object",
284
+ "additionalProperties": {"$ref": "#/$defs/missing"},
285
+ },
286
+ ValueError,
287
+ "Unresolvable dynamic-key schema reference",
288
+ ),
289
+ (
290
+ {
291
+ "type": "object",
292
+ "additionalProperties": {"$ref": "#anchor"},
293
+ },
294
+ ValueError,
295
+ "must be a local JSON Pointer",
296
+ ),
297
+ (
298
+ {
299
+ "type": "object",
300
+ "additionalProperties": {"type": "not-a-json-schema-type"},
301
+ },
302
+ SchemaError,
303
+ "not valid under any of the given schemas",
304
+ ),
305
+ ],
306
+ ids=[
307
+ "pattern-external-ref",
308
+ "pattern-missing-local-ref",
309
+ "pattern-anchored-ref",
310
+ "invalid-pattern",
311
+ "pattern-invalid-draft7",
312
+ "additional-external-ref",
313
+ "additional-missing-local-ref",
314
+ "additional-anchored-ref",
315
+ "additional-invalid-draft7",
316
],
227
- ids=["external-ref", "missing-local-ref", "invalid-pattern"],
317
)
318
@pytest.mark.parametrize(
319
"converter",
@@ -234,6 +323,7 @@ def test_schema_converter_required_unsatisfiable_property_has_no_valid_value():
323
@pytest.mark.parametrize("nested", [False, True], ids=["root", "nested"])
324
def test_invalid_dynamic_object_schema_fails_closed_across_public_entry_points(
325
invalid_object_schema,
326
+ error_type,
327
error_match,
328
converter,
329
nested,
@@ -246,10 +336,137 @@ def test_invalid_dynamic_object_schema_fails_closed_across_public_entry_points(
336
"required": ["payload"],
337
}
338
249
- with pytest.raises(ValueError, match=error_match):
339
+ with pytest.raises(error_type, match=error_match):
340
converter(schema)
341
342
343
+_INVALID_DYNAMIC_POLICY = {
344
+ "type": "object",
345
+ "patternProperties": {"[": {"type": "string"}},
346
+}
347
+
348
+
349
+@pytest.mark.parametrize(
350
+ "schema",
351
+ [
352
+ {"type": "object", "properties": {"payload": _INVALID_DYNAMIC_POLICY}},
353
+ {"type": "array", "items": _INVALID_DYNAMIC_POLICY},
354
+ {"type": "array", "items": [{}, _INVALID_DYNAMIC_POLICY]},
355
+ {"allOf": [_INVALID_DYNAMIC_POLICY]},
356
+ {"anyOf": [_INVALID_DYNAMIC_POLICY]},
357
+ {"oneOf": [_INVALID_DYNAMIC_POLICY]},
358
+ {"not": _INVALID_DYNAMIC_POLICY},
359
+ {"if": _INVALID_DYNAMIC_POLICY},
360
+ {"then": _INVALID_DYNAMIC_POLICY},
361
+ {"else": _INVALID_DYNAMIC_POLICY},
362
+ {"type": "array", "contains": _INVALID_DYNAMIC_POLICY},
363
+ {"type": "object", "propertyNames": _INVALID_DYNAMIC_POLICY},
364
+ {
365
+ "type": "array",
366
+ "items": [{}],
367
+ "additionalItems": _INVALID_DYNAMIC_POLICY,
368
+ },
369
+ {
370
+ "type": "object",
371
+ "dependencies": {"flag": _INVALID_DYNAMIC_POLICY},
372
+ },
373
+ {
374
+ "$defs": {"Invalid": _INVALID_DYNAMIC_POLICY},
375
+ "$ref": "#/$defs/Invalid",
376
+ },
377
+ {
378
+ "definitions": {"Invalid": _INVALID_DYNAMIC_POLICY},
379
+ "$ref": "#/definitions/Invalid",
380
+ },
381
+ ],
382
+ ids=[
383
+ "property",
384
+ "array-items",
385
+ "tuple-items",
386
+ "all-of",
387
+ "any-of",
388
+ "one-of",
389
+ "not",
390
+ "if",
391
+ "then",
392
+ "else",
393
+ "contains",
394
+ "property-names",
395
+ "additional-items",
396
+ "dependency-schema",
397
+ "defs-reference",
398
+ "legacy-definitions-reference",
399
+ ],
400
+)
401
+def test_invalid_dynamic_policy_is_found_in_reachable_draft7_schema_positions(schema):
402
+ with pytest.raises(ValueError, match="Invalid patternProperties"):
403
+ json_schema_to_pydantic_type(schema)
404
+
405
+
406
+def _recursive_dynamic_schema(dynamic_keyword, nested):
407
+ recursive_ref = "#/$defs/Recursive" if nested else "#"
408
+
409
+ def make_recursive_object():
410
+ dynamic_schema = {
411
+ "allOf": [{"$ref": recursive_ref}],
412
+ "default": {},
413
+ }
414
+ recursive_object = {"type": "object"}
415
+ if dynamic_keyword == "patternProperties":
416
+ recursive_object[dynamic_keyword] = {"^child_": dynamic_schema}
417
+ else:
418
+ recursive_object[dynamic_keyword] = dynamic_schema
419
+ return recursive_object
420
+
421
+ recursive_object = make_recursive_object()
422
+ recursive_input = {"child_one": {}}
423
+
424
+ if not nested:
425
+ return recursive_object, recursive_input
426
+
427
+ return (
428
+ {
429
+ "$defs": {"Recursive": recursive_object},
430
+ "type": "object",
431
+ "properties": {"payload": make_recursive_object()},
432
+ "required": ["payload"],
433
+ },
434
+ {"payload": recursive_input},
435
+ )
436
+
437
+
438
+@pytest.mark.parametrize(
439
+ "dynamic_keyword",
440
+ ["patternProperties", "additionalProperties"],
441
+ ids=["pattern-properties", "additional-properties"],
442
+)
443
+@pytest.mark.parametrize(
444
+ "converter",
445
+ [json_schema_to_model, json_schema_to_pydantic_type],
446
+ ids=["model", "pydantic-type"],
447
+)
448
+@pytest.mark.parametrize("nested", [False, True], ids=["root", "nested"])
449
+def test_recursive_dynamic_schema_with_default_does_not_reenter_policy_validation(
450
+ dynamic_keyword,
451
+ converter,
452
+ nested,
453
+):
454
+ schema, input_value = _recursive_dynamic_schema(dynamic_keyword, nested)
455
+ Draft7Validator.check_schema(schema)
456
+
457
+ annotation = converter(schema)
458
+ adapter = TypeAdapter(annotation)
459
+ result = adapter.validate_python(input_value)
460
+
461
+ assert adapter.dump_python(result, mode="json", by_alias=True) == input_value
462
+
463
+ invalid_value = {"child_one": "not-an-object"}
464
+ if nested:
465
+ invalid_value = {"payload": invalid_value}
466
+ with pytest.raises(ValidationError):
467
+ adapter.validate_python(invalid_value)
468
+
469
+
470
@pytest.mark.parametrize(
471
"case,index",
472
[
ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
+92
@@ -94,6 +94,98 @@
94
}
95
]
96
},
97
+ {
98
+ "id": "nested-pattern-properties-object",
99
+ "description": "A dynamic-key policy nested under a declared property validates and preserves matching keys.",
100
+ "schema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "payload": {
104
+ "type": "object",
105
+ "patternProperties": { "^count_": { "type": "integer" } },
106
+ "additionalProperties": false
107
+ }
108
+ },
109
+ "required": ["payload"]
110
+ },
111
+ "ingress": {
112
+ "accepted": true,
113
+ "preserved": {
114
+ "type": "object",
115
+ "properties": {
116
+ "payload": {
117
+ "type": "object",
118
+ "patternProperties": { "^count_": { "type": "integer" } },
119
+ "additionalProperties": false
120
+ }
121
+ },
122
+ "required": ["payload"]
123
+ }
124
+ },
125
+ "instances": [
126
+ {
127
+ "input": { "payload": { "count_a": 1 } },
128
+ "accepted": true,
129
+ "zod": { "output": { "payload": { "count_a": 1 } } },
130
+ "effect": { "output": { "payload": { "count_a": 1 } } },
131
+ "python": { "output": { "payload": { "count_a": 1 } } }
132
+ },
133
+ {
134
+ "input": { "payload": { "count_a": "1" } },
135
+ "accepted": false
136
+ },
137
+ {
138
+ "input": { "payload": { "other": 1 } },
139
+ "accepted": false
140
+ }
141
+ ]
142
+ },
143
+ {
144
+ "id": "schema-valued-additional-properties-in-array-items",
145
+ "description": "A schema-valued dynamic-key policy inside array items validates every preserved value.",
146
+ "schema": {
147
+ "type": "object",
148
+ "properties": {
149
+ "records": {
150
+ "type": "array",
151
+ "items": {
152
+ "type": "object",
153
+ "additionalProperties": { "type": "number" }
154
+ }
155
+ }
156
+ },
157
+ "required": ["records"]
158
+ },
159
+ "ingress": {
160
+ "accepted": true,
161
+ "preserved": {
162
+ "type": "object",
163
+ "properties": {
164
+ "records": {
165
+ "type": "array",
166
+ "items": {
167
+ "type": "object",
168
+ "additionalProperties": { "type": "number" }
169
+ }
170
+ }
171
+ },
172
+ "required": ["records"]
173
+ }
174
+ },
175
+ "instances": [
176
+ {
177
+ "input": { "records": [{ "a": 1 }, { "b": 2.5 }] },
178
+ "accepted": true,
179
+ "zod": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
180
+ "effect": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } },
181
+ "python": { "output": { "records": [{ "a": 1 }, { "b": 2.5 }] } }
182
+ },
183
+ {
184
+ "input": { "records": [{ "a": "1" }] },
185
+ "accepted": false
186
+ }
187
+ ]
188
+ },
189
{
190
"id": "explicit-additional-properties-false",
191
"description": "An explicit `additionalProperties: false` closes an otherwise property-less object.",