9
We handle those by pre-filtering them before passing to the library.
10
"""
11
12
+import decimal
13
import re
14
import types
15
import typing as t
23
from json_schema_to_pydantic import (
24
create_model as create_model_from_schema,
25
)
26
+from jsonschema import exceptions as jsonschema_exceptions
27
from jsonschema import validators as jsonschema_validators
28
from jsonschema.protocols import Validator
29
from pydantic import (
30
+ AfterValidator,
31
BaseModel,
32
+ BeforeValidator,
33
ConfigDict,
34
Field,
35
TypeAdapter,
36
+ ValidationError,
37
model_validator,
38
)
39
from pydantic import (
40
create_model as create_pydantic_model,
41
)
42
from pydantic_core import core_schema
43
+from referencing import Registry
44
45
from composio.utils.logging import get as get_logger
46
51
52
53
class _UnsatisfiableSchema:
48
- """Pydantic type for JSON schemas that reject every value."""
54
+ """Pydantic type for JSON schemas that reject every value.
55
+
56
+ JSON Schema (draft-06+) allows the literal ``false`` anywhere a schema is
57
+ expected, meaning "no value is valid". This marker stands in for it during
58
+ conversion so combiners can tell an always-rejecting member apart from an
59
+ absent one, and so the exact validator can turn it back into ``false``.
60
+ The literal ``true`` ("any value is valid") simply becomes ``t.Any``.
61
+ """
62
63
@staticmethod
64
def _reject(_value: t.Any) -> t.NoReturn:
93
"boolean": bool,
94
"array": t.List,
95
"object": t.Dict,
83
- "null": t.Optional[t.Any],
96
+ "null": type(None),
97
}
98
99
CONTAINER_TYPE = ("array", "object")
100
101
+# Keywords that constrain which instances a schema accepts. A schema whose keys
102
+# are all outside this set (title, description, default, examples, ...) is pure
103
+# annotation and accepts every value, exactly like the empty schema.
104
+_ASSERTION_KEYWORDS = frozenset(
105
+ {
106
+ "type",
107
+ "enum",
108
+ "const",
109
+ "anyOf",
110
+ "allOf",
111
+ "oneOf",
112
+ "not",
113
+ "if",
114
+ "then",
115
+ "else",
116
+ "$ref",
117
+ "properties",
118
+ "patternProperties",
119
+ "additionalProperties",
120
+ "propertyNames",
121
+ "required",
122
+ "dependencies",
123
+ "minProperties",
124
+ "maxProperties",
125
+ "items",
126
+ "additionalItems",
127
+ "contains",
128
+ "minItems",
129
+ "maxItems",
130
+ "uniqueItems",
131
+ "minLength",
132
+ "maxLength",
133
+ "pattern",
134
+ "minimum",
135
+ "maximum",
136
+ "exclusiveMinimum",
137
+ "exclusiveMaximum",
138
+ "multipleOf",
139
+ }
140
+)
141
+
142
+_SCALAR_CONSTRAINT_KEYWORDS = frozenset(
143
+ {
144
+ "minLength",
145
+ "maxLength",
146
+ "pattern",
147
+ "minimum",
148
+ "maximum",
149
+ "exclusiveMinimum",
150
+ "exclusiveMaximum",
151
+ "multipleOf",
152
+ }
153
+)
154
+
155
+_STRUCTURAL_KEYWORDS = frozenset(
156
+ {"anyOf", "allOf", "oneOf", "not", "if", "$ref", "properties", "items"}
157
+)
158
+
159
+_TYPELESS_TYPE_SCOPED_KEYWORDS = frozenset(
160
+ {
161
+ "properties",
162
+ "patternProperties",
163
+ "additionalProperties",
164
+ "propertyNames",
165
+ "required",
166
+ "dependencies",
167
+ "minProperties",
168
+ "maxProperties",
169
+ "items",
170
+ "additionalItems",
171
+ "contains",
172
+ "minItems",
173
+ "maxItems",
174
+ "uniqueItems",
175
+ }
176
+)
177
+
178
+# Keywords each type-array member keeps when the array is rewritten to anyOf.
179
+_TYPE_SCOPED_KEYWORDS: t.Dict[str, frozenset] = {
180
+ "string": frozenset({"minLength", "maxLength", "pattern"}),
181
+ "integer": frozenset(
182
+ {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
183
+ ),
184
+ "number": frozenset(
185
+ {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
186
+ ),
187
+ "array": frozenset(
188
+ {
189
+ "items",
190
+ "additionalItems",
191
+ "contains",
192
+ "minItems",
193
+ "maxItems",
194
+ "uniqueItems",
195
+ }
196
+ ),
197
+ "object": frozenset(
198
+ {
199
+ "properties",
200
+ "patternProperties",
201
+ "additionalProperties",
202
+ "propertyNames",
203
+ "required",
204
+ "dependencies",
205
+ "minProperties",
206
+ "maxProperties",
207
+ }
208
+ ),
209
+ "boolean": frozenset(),
210
+ "null": frozenset(),
211
+}
212
+
213
+_TYPE_ARRAY_SHARED_KEYWORDS = frozenset({"enum", "const", "format"})
214
+_TYPE_ARRAY_WRAPPER_KEYWORDS = frozenset(
215
+ {"title", "description", "default", "examples"}
216
+)
217
+
218
# Should be deprecated,
219
# required values will always be provided by users
220
# Non-required values are nullable(None) if default value not provided.
268
if not isinstance(schema, dict):
269
return schema
270
271
+ # A schema that enumerates no acceptable values rejects everything, exactly
272
+ # like `false`. Normalizing here routes both spellings through the same
273
+ # unsatisfiable-property handling (which tolerates the property's absence).
274
+ if schema.get("enum") == [] or schema.get("type") == []:
275
+ return _UnsatisfiableSchema
276
+
277
# Make a copy to avoid mutating the original
278
result = {}
279
for key, value in schema.items():
578
"""Attach recursive default-presence metadata to generated model classes."""
579
origin = t.get_origin(annotation)
580
arguments = t.get_args(annotation)
581
+ if origin is t.Annotated:
582
+ # Exact-validation wrappers must not hide the materialized type below.
583
+ _mark_explicit_default_fields(arguments[0], schema, root_schema, visiting)
584
+ return
585
if origin in (t.Union, types.UnionType):
586
options: t.List[t.Dict[str, t.Any]] = []
587
resolved_schema = _resolve_default_metadata_schema(schema, root_schema)
1139
:param root_schema: Full schema document used to resolve nested local references.
1140
:return: A Pydantic type.
1141
"""
1002
- # Handle boolean schemas (JSON Schema draft-06+)
1142
+ # A schema may be the literal `true` or `false` instead of an object
1143
+ # (JSON Schema draft-06+), e.g. `additionalProperties: false` or a member
1144
+ # of `anyOf`. `true` accepts every value; `false` rejects every value.
1145
if isinstance(json_schema, bool):
1146
if json_schema:
1005
- return t.Any # true schema accepts any value
1006
- else:
1007
- return None # false schema - will be filtered out in union processing
1147
+ return t.Any
1148
+ return _UnsatisfiableSchema
1149
1150
# Pre-filter boolean schemas from combiners
1151
filtered_schema = _filter_boolean_schemas(json_schema)
1152
filtered_schema = _resolve_unsatisfiable_references(filtered_schema)
1153
document_root = root_schema if root_schema is not None else json_schema
1154
_validate_dynamic_object_policies(json_schema, document_root)
1014
- return _filtered_schema_to_pydantic_type(
1155
+ annotation = _filtered_schema_to_pydantic_type(
1156
filtered_schema,
1157
root_schema=document_root,
1158
)
1159
+ # Two layers: Pydantic materializes the value (defaults, aliases, models),
1160
+ # while the source schema decides acceptance. Keywords Pydantic cannot
1161
+ # express get a Draft 7 "exact" check that runs before Pydantic coercion.
1162
+ # Generated models already carry that check (see `_with_exact_validation`),
1163
+ # so only non-model annotations are wrapped here. When Pydantic would
1164
+ # narrow a valid value (e.g. `$ref`, `allOf`), the value is kept as-is.
1165
+ if (
1166
+ _requires_whole_schema_validation(json_schema)
1167
+ and not _is_unsatisfiable_schema(annotation)
1168
+ and not (isinstance(annotation, type) and issubclass(annotation, BaseModel))
1169
+ ):
1170
+ return _with_exact_validation_annotation(
1171
+ t.Any if _needs_permissive_materialization(json_schema) else annotation,
1172
+ json_schema,
1173
+ document_root,
1174
+ )
1175
+ return annotation
1176
1177
1178
def _filtered_schema_to_pydantic_type(
1184
if schema is None or _is_unsatisfiable_schema(schema):
1185
return _UnsatisfiableSchema
1186
1187
+ if not _ASSERTION_KEYWORDS.intersection(schema):
1188
+ # Pure-annotation schemas (only title/description/default/...) accept
1189
+ # every value, exactly like the empty schema.
1190
+ return t.Any
1191
+
1192
+ schema_type = schema.get("type")
1193
+ if isinstance(schema_type, list):
1194
+ if not schema_type:
1195
+ return _UnsatisfiableSchema
1196
+ return _build_union_from_options(
1197
+ [
1198
+ {**schema, "type": member, "x-composio-strict-type": True}
1199
+ for member in schema_type
1200
+ ],
1201
+ root_schema=root_schema,
1202
+ )
1203
+
1204
+ if schema_type is None and (
1205
+ "enum" in schema
1206
+ or "const" in schema
1207
+ or (
1208
+ _SCALAR_CONSTRAINT_KEYWORDS.intersection(schema)
1209
+ and not _STRUCTURAL_KEYWORDS.intersection(schema)
1210
+ )
1211
+ ):
1212
+ return _apply_scalar_constraints(t.Any, schema)
1213
+
1214
# Handle simple primitive types without complex combiners
1215
if _is_simple_primitive(schema):
1216
return _convert_simple_type(schema)
1233
)
1234
1235
1236
+def _matches_json_type(type_: str, value: t.Any) -> bool:
1237
+ """JSON type membership per Draft 7 (booleans are not numbers, 2.0 is an integer)."""
1238
+ if type_ == "string":
1239
+ return isinstance(value, str)
1240
+ if type_ == "boolean":
1241
+ return isinstance(value, bool)
1242
+ if type_ == "null":
1243
+ return value is None
1244
+ if type_ == "integer":
1245
+ if isinstance(value, bool):
1246
+ return False
1247
+ return isinstance(value, int) or (
1248
+ isinstance(value, float) and value.is_integer()
1249
+ )
1250
+ if type_ == "number":
1251
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
1252
+ if type_ == "array":
1253
+ return isinstance(value, list)
1254
+ if type_ == "object":
1255
+ return isinstance(value, dict)
1256
+ return True
1257
+
1258
+
1259
+def _json_type_guard(type_: str) -> t.Callable[[t.Any], t.Any]:
1260
+ def validate(value: t.Any) -> t.Any:
1261
+ if not _matches_json_type(type_, value):
1262
+ raise ValueError(f"value is not of JSON type {type_!r}")
1263
+ return value
1264
+
1265
+ return validate
1266
+
1267
+
1268
+def _strict_json_type_annotation(type_: str) -> t.Any:
1269
+ """A type-checked annotation that still coerces integral floats for `integer`."""
1270
+ if type_ == "null":
1271
+ return type(None)
1272
+ base = PYDANTIC_TYPE_TO_PYTHON_TYPE.get(type_, str)
1273
+ return t.Annotated[base, BeforeValidator(_json_type_guard(type_))]
1274
+
1275
+
1276
def _convert_simple_type(schema: t.Dict[str, t.Any]) -> t.Type[t.Any]:
1277
"""Convert simple primitive types directly."""
1278
type_ = schema.get("type", "string")
1054
- return t.cast(t.Type[t.Any], PYDANTIC_TYPE_TO_PYTHON_TYPE.get(type_, str))
1279
+ use_strict_type = (
1280
+ schema.get("x-composio-strict-type") is True
1281
+ or "enum" in schema
1282
+ or "const" in schema
1283
+ )
1284
+ base_type = (
1285
+ _strict_json_type_annotation(type_)
1286
+ if use_strict_type
1287
+ else t.cast(t.Type[t.Any], PYDANTIC_TYPE_TO_PYTHON_TYPE.get(type_, str))
1288
+ )
1289
+ return _apply_scalar_constraints(base_type, schema)
1290
+
1291
+
1292
+def _json_values_equal(left: t.Any, right: t.Any) -> bool:
1293
+ """Compare JSON values without treating booleans as numbers."""
1294
+ if isinstance(left, bool) or isinstance(right, bool):
1295
+ return type(left) is type(right) and left == right
1296
+
1297
+ if isinstance(left, list) and isinstance(right, list):
1298
+ return len(left) == len(right) and all(
1299
+ _json_values_equal(left_item, right_item)
1300
+ for left_item, right_item in zip(left, right)
1301
+ )
1302
+
1303
+ if isinstance(left, dict) and isinstance(right, dict):
1304
+ return left.keys() == right.keys() and all(
1305
+ _json_values_equal(left[key], right[key]) for key in left
1306
+ )
1307
+
1308
+ return bool(left == right)
1309
+
1310
+
1311
+def _allowed_values_validator(
1312
+ allowed: t.Tuple[t.Any, ...],
1313
+) -> t.Callable[[t.Any], t.Any]:
1314
+ """Create a Pydantic validator for JSON Schema enum/const values."""
1315
+
1316
+ def validate(value: t.Any) -> t.Any:
1317
+ if not any(_json_values_equal(value, candidate) for candidate in allowed):
1318
+ raise ValueError(f"value must be one of {allowed!r}")
1319
+ return value
1320
+
1321
+ return validate
1322
+
1323
+
1324
+def _is_numeric(value: t.Any) -> bool:
1325
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
1326
+
1327
+
1328
+def _is_json_multiple_of(value: t.Any, multiple: t.Any) -> bool:
1329
+ """Decimal-scaled multipleOf, matching the Zod and Effect converters.
1330
+
1331
+ Raw float modulo misreports common decimal steps (0.3 % 0.1 != 0 in
1332
+ binary floating point); comparing through `Decimal(str(...))` recovers the
1333
+ author's decimal intent.
1334
+ """
1335
+ try:
1336
+ return (decimal.Decimal(str(value)) % decimal.Decimal(str(multiple))) == 0
1337
+ except (decimal.InvalidOperation, decimal.DivisionByZero):
1338
+ return False
1339
+
1340
+
1341
+def _multiple_of_validator(multiple: t.Any) -> t.Callable[[t.Any], t.Any]:
1342
+ def validate(value: t.Any) -> t.Any:
1343
+ if _is_numeric(value) and not _is_json_multiple_of(value, multiple):
1344
+ raise ValueError(f"value is not a multiple of {multiple!r}")
1345
+ return value
1346
+
1347
+ return validate
1348
+
1349
+
1350
+def _compile_pattern(pattern: str) -> t.Optional[t.Pattern[str]]:
1351
+ try:
1352
+ return re.compile(pattern)
1353
+ except re.error:
1354
+ logger.warning(
1355
+ "Ignoring JSON Schema pattern %r: not a valid Python regular expression",
1356
+ pattern,
1357
+ )
1358
+ return None
1359
+
1360
+
1361
+def _with_string_constraints(annotation: t.Any, schema: t.Dict[str, t.Any]) -> t.Any:
1362
+ field_constraints: t.Dict[str, t.Any] = {}
1363
+ if "minLength" in schema:
1364
+ field_constraints["min_length"] = schema["minLength"]
1365
+ if "maxLength" in schema:
1366
+ field_constraints["max_length"] = schema["maxLength"]
1367
+ if field_constraints:
1368
+ annotation = t.Annotated[annotation, Field(**field_constraints)]
1369
+ if "pattern" in schema:
1370
+ annotation = _with_pattern_constraint(annotation, schema["pattern"])
1371
+ return annotation
1372
+
1373
+
1374
+def _with_pattern_constraint(annotation: t.Any, pattern: str) -> t.Any:
1375
+ """Prefer pydantic's native pattern; fall back to Python `re` when the Rust
1376
+ regex crate rejects an ECMA construct such as look-around (legal in
1377
+ Draft 7, whose regex dialect is ECMA-262)."""
1378
+ candidate = t.Annotated[annotation, Field(pattern=pattern)]
1379
+ try:
1380
+ TypeAdapter(candidate)
1381
+ return candidate
1382
+ except Exception: # noqa: BLE001 - pydantic raises SchemaError subclasses
1383
+ pass
1384
+
1385
+ compiled = _compile_pattern(pattern)
1386
+ if compiled is None:
1387
+ return annotation
1388
+
1389
+ def validate(value: t.Any) -> t.Any:
1390
+ if isinstance(value, str) and compiled.search(value) is None:
1391
+ raise ValueError(f"string does not match pattern {pattern!r}")
1392
+ return value
1393
+
1394
+ return t.Annotated[annotation, AfterValidator(validate)]
1395
+
1396
+
1397
+def _with_numeric_constraints(annotation: t.Any, schema: t.Dict[str, t.Any]) -> t.Any:
1398
+ field_constraints: t.Dict[str, t.Any] = {}
1399
+ if "minimum" in schema:
1400
+ field_constraints["gt" if schema.get("exclusiveMinimum") is True else "ge"] = (
1401
+ schema["minimum"]
1402
+ )
1403
+ if _is_numeric(schema.get("exclusiveMinimum")):
1404
+ field_constraints["gt"] = schema["exclusiveMinimum"]
1405
+
1406
+ if "maximum" in schema:
1407
+ field_constraints["lt" if schema.get("exclusiveMaximum") is True else "le"] = (
1408
+ schema["maximum"]
1409
+ )
1410
+ if _is_numeric(schema.get("exclusiveMaximum")):
1411
+ field_constraints["lt"] = schema["exclusiveMaximum"]
1412
+
1413
+ if field_constraints:
1414
+ annotation = t.Annotated[annotation, Field(**field_constraints)]
1415
+ if "multipleOf" in schema:
1416
+ annotation = t.Annotated[
1417
+ annotation, AfterValidator(_multiple_of_validator(schema["multipleOf"]))
1418
+ ]
1419
+ return annotation
1420
+
1421
+
1422
+def _check_numeric_keywords(schema: t.Dict[str, t.Any], value: t.Any) -> None:
1423
+ minimum = schema.get("minimum")
1424
+ if _is_numeric(minimum):
1425
+ if schema.get("exclusiveMinimum") is True:
1426
+ if value <= minimum:
1427
+ raise ValueError(f"value must be greater than {minimum!r}")
1428
+ elif value < minimum:
1429
+ raise ValueError(f"value must be at least {minimum!r}")
1430
+ exclusive_minimum = schema.get("exclusiveMinimum")
1431
+ if _is_numeric(exclusive_minimum) and value <= exclusive_minimum:
1432
+ raise ValueError(f"value must be greater than {exclusive_minimum!r}")
1433
+
1434
+ maximum = schema.get("maximum")
1435
+ if _is_numeric(maximum):
1436
+ if schema.get("exclusiveMaximum") is True:
1437
+ if value >= maximum:
1438
+ raise ValueError(f"value must be less than {maximum!r}")
1439
+ elif value > maximum:
1440
+ raise ValueError(f"value must be at most {maximum!r}")
1441
+ exclusive_maximum = schema.get("exclusiveMaximum")
1442
+ if _is_numeric(exclusive_maximum) and value >= exclusive_maximum:
1443
+ raise ValueError(f"value must be less than {exclusive_maximum!r}")
1444
+
1445
+ if "multipleOf" in schema and not _is_json_multiple_of(value, schema["multipleOf"]):
1446
+ raise ValueError(f"value is not a multiple of {schema['multipleOf']!r}")
1447
+
1448
+
1449
+def _typeless_constraint_validator(
1450
+ schema: t.Dict[str, t.Any],
1451
+) -> t.Optional[t.Callable[[t.Any], t.Any]]:
1452
+ """Draft 7 applies scalar constraints per instance type even without `type`."""
1453
+ if not _SCALAR_CONSTRAINT_KEYWORDS.intersection(schema):
1454
+ return None
1455
+
1456
+ compiled_pattern = (
1457
+ _compile_pattern(schema["pattern"]) if "pattern" in schema else None
1458
+ )
1459
+
1460
+ def validate(value: t.Any) -> t.Any:
1461
+ if isinstance(value, str):
1462
+ if "minLength" in schema and len(value) < schema["minLength"]:
1463
+ raise ValueError(
1464
+ f"string must contain at least {schema['minLength']} characters"
1465
+ )
1466
+ if "maxLength" in schema and len(value) > schema["maxLength"]:
1467
+ raise ValueError(
1468
+ f"string must contain at most {schema['maxLength']} characters"
1469
+ )
1470
+ if compiled_pattern is not None and compiled_pattern.search(value) is None:
1471
+ raise ValueError(f"string does not match pattern {schema['pattern']!r}")
1472
+ if _is_numeric(value):
1473
+ _check_numeric_keywords(schema, value)
1474
+ return value
1475
+
1476
+ return validate
1477
+
1478
+
1479
+def _apply_scalar_constraints(
1480
+ base_type: t.Type[t.Any],
1481
+ schema: t.Dict[str, t.Any],
1482
+) -> t.Type[t.Any]:
1483
+ """Apply scalar JSON Schema validation keywords to a Python annotation."""
1484
+ type_ = schema.get("type")
1485
+ annotation: t.Any = base_type
1486
+
1487
+ if type_ == "string":
1488
+ annotation = _with_string_constraints(annotation, schema)
1489
+ elif type_ in ("integer", "number"):
1490
+ annotation = _with_numeric_constraints(annotation, schema)
1491
+ elif type_ is None:
1492
+ validator = _typeless_constraint_validator(schema)
1493
+ if validator is not None:
1494
+ annotation = t.Annotated[annotation, AfterValidator(validator)]
1495
+
1496
+ allowed: t.Optional[t.Tuple[t.Any, ...]] = None
1497
+ if "const" in schema and "enum" in schema:
1498
+ # Both keywords assert independently, so only their intersection is
1499
+ # acceptable; a const outside the enum makes the schema unsatisfiable.
1500
+ allowed = tuple(
1501
+ candidate
1502
+ for candidate in (schema["const"],)
1503
+ if any(_json_values_equal(candidate, member) for member in schema["enum"])
1504
+ )
1505
+ elif "const" in schema:
1506
+ allowed = (schema["const"],)
1507
+ elif "enum" in schema:
1508
+ allowed = tuple(schema["enum"])
1509
+
1510
+ if allowed is not None:
1511
+ if not allowed:
1512
+ return _UnsatisfiableSchema
1513
+ annotation = t.Annotated[
1514
+ annotation,
1515
+ AfterValidator(_allowed_values_validator(allowed)),
1516
+ ]
1517
+
1518
+ return t.cast(t.Type[t.Any], annotation)
1519
+
1520
+
1521
+def _schema_for_exact_validation(value: t.Any) -> t.Any:
1522
+ """Turn internal boolean-schema markers back into JSON Schema values.
1523
+
1524
+ Conversion replaces the literal ``false`` with `_UnsatisfiableSchema`; the
1525
+ `jsonschema` validator needs the original ``false`` back.
1526
+ """
1527
+ if _is_unsatisfiable_schema(value):
1528
+ return False
1529
+ if isinstance(value, dict):
1530
+ return {key: _schema_for_exact_validation(item) for key, item in value.items()}
1531
+ if isinstance(value, list):
1532
+ return [_schema_for_exact_validation(item) for item in value]
1533
+ return value
1534
+
1535
+
1536
+_EXACT_SCHEMA_MAP_KEYWORDS = frozenset(
1537
+ {
1538
+ "$defs",
1539
+ "definitions",
1540
+ "dependencies",
1541
+ "patternProperties",
1542
+ "properties",
1543
+ }
1544
+)
1545
+_EXACT_SCHEMA_ARRAY_KEYWORDS = frozenset({"allOf", "anyOf", "oneOf"})
1546
+_EXACT_SCHEMA_VALUE_KEYWORDS = frozenset(
1547
+ {
1548
+ "additionalItems",
1549
+ "additionalProperties",
1550
+ "contains",
1551
+ "else",
1552
+ "if",
1553
+ "items",
1554
+ "not",
1555
+ "propertyNames",
1556
+ "then",
1557
+ }
1558
+)
1559
+
1560
+_REQUIRES_WHOLE_SCHEMA_VALIDATION = frozenset(
1561
+ {
1562
+ "$ref",
1563
+ "additionalItems",
1564
+ "contains",
1565
+ "dependencies",
1566
+ "else",
1567
+ "if",
1568
+ "maxItems",
1569
+ "maxProperties",
1570
+ "minItems",
1571
+ "minProperties",
1572
+ "not",
1573
+ "propertyNames",
1574
+ "required",
1575
+ "then",
1576
+ "uniqueItems",
1577
+ }
1578
+)
1579
+
1580
+
1581
+def _contains_compound_literal(schema: t.Dict[str, t.Any]) -> bool:
1582
+ values: t.List[t.Any] = []
1583
+ if "const" in schema:
1584
+ values.append(schema["const"])
1585
+ enum = schema.get("enum")
1586
+ if isinstance(enum, list):
1587
+ values.extend(enum)
1588
+ return any(isinstance(value, (dict, list)) for value in values)
1589
+
1590
+
1591
+def _one_of_needs_exact_validation(options: t.Any) -> bool:
1592
+ """Return whether two oneOf branches can accept the same JSON type."""
1593
+ if not isinstance(options, list) or len(options) < 2:
1594
+ return False
1595
+
1596
+ branch_types: t.List[t.Set[str]] = []
1597
+ all_types = {"array", "boolean", "integer", "null", "number", "object", "string"}
1598
+ for option in options:
1599
+ if option is True or not isinstance(option, dict) or "type" not in option:
1600
+ branch_types.append(set(all_types))
1601
+ continue
1602
+ if option is False:
1603
+ branch_types.append(set())
1604
+ continue
1605
+ declared = option["type"]
1606
+ types = {declared} if isinstance(declared, str) else set(declared)
1607
+ if "number" in types:
1608
+ types.add("integer")
1609
+ branch_types.append(types)
1610
+
1611
+ return any(
1612
+ left.intersection(right)
1613
+ for index, left in enumerate(branch_types)
1614
+ for right in branch_types[index + 1 :]
1615
+ )
1616
+
1617
+
1618
+def _combiner_has_assertion_siblings(schema: t.Dict[str, t.Any], keyword: str) -> bool:
1619
+ return bool(_ASSERTION_KEYWORDS.intersection(schema) - {keyword})
1620
+
1621
+
1622
+def _requires_whole_schema_validation(schema: t.Any) -> bool:
1623
+ """Whether the materializing converter needs an authoritative final guard.
1624
+
1625
+ True when the schema (or any nested schema) uses a keyword that Pydantic
1626
+ field constraints cannot express faithfully: `required`, `contains`,
1627
+ `if`/`then`/`else`, `not`, `$ref`, unions (which Pydantic coerces across),
1628
+ and so on. Those schemas get a Draft 7 check on the raw value first.
1629
+ """
1630
+ if isinstance(schema, bool) or not isinstance(schema, dict):
1631
+ return False
1632
+ if (
1633
+ _REQUIRES_WHOLE_SCHEMA_VALIDATION.intersection(schema)
1634
+ or "allOf" in schema
1635
+ or (
1636
+ schema.get("type") is None
1637
+ and _TYPELESS_TYPE_SCOPED_KEYWORDS.intersection(schema)
1638
+ )
1639
+ # Pydantic unions coerce across members (`True` satisfies `integer |
1640
+ # null`), so every combiner needs the exact check, not only those with
1641
+ # sibling assertions or overlapping branches.
1642
+ or "anyOf" in schema
1643
+ or "oneOf" in schema
1644
+ or _contains_compound_literal(schema)
1645
+ ):
1646
+ return True
1647
+
1648
+ for key, child in schema.items():
1649
+ if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(child, dict):
1650
+ if any(
1651
+ _requires_whole_schema_validation(value) for value in child.values()
1652
+ ):
1653
+ return True
1654
+ elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS and isinstance(child, list):
1655
+ if any(_requires_whole_schema_validation(value) for value in child):
1656
+ return True
1657
+ elif key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1658
+ values = child if isinstance(child, list) else [child]
1659
+ if any(_requires_whole_schema_validation(value) for value in values):
1660
+ return True
1661
+
1662
+ return False
1663
+
1664
+
1665
+def _needs_permissive_materialization(
1666
+ schema: t.Any,
1667
+ visited: t.Optional[t.Set[int]] = None,
1668
+) -> bool:
1669
+ """Detect schemas whose exact validator must not pipe into a narrower type.
1670
+
1671
+ For `$ref`, `allOf`, and typeless assertions the Pydantic type the library
1672
+ builds can be narrower than what the schema accepts. Once the Draft 7 check
1673
+ has accepted the raw value, it is passed through as `t.Any` rather than
1674
+ risk a second, stricter rejection or a lossy coercion.
1675
+ """
1676
+ if isinstance(schema, bool) or not isinstance(schema, dict):
1677
+ return False
1678
+ if visited is None:
1679
+ visited = set()
1680
+ if id(schema) in visited:
1681
+ return False
1682
+ visited.add(id(schema))
1683
+
1684
+ if "$ref" in schema or "allOf" in schema:
1685
+ return True
1686
+ if schema.get("type") is None and (
1687
+ _TYPELESS_TYPE_SCOPED_KEYWORDS.intersection(schema)
1688
+ or {"if", "then", "else", "not"}.intersection(schema)
1689
+ ):
1690
+ return True
1691
+ for key, child in schema.items():
1692
+ if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(child, dict):
1693
+ if any(
1694
+ _needs_permissive_materialization(value, visited)
1695
+ for value in child.values()
1696
+ ):
1697
+ return True
1698
+ elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS and isinstance(child, list):
1699
+ if any(
1700
+ _needs_permissive_materialization(value, visited) for value in child
1701
+ ):
1702
+ return True
1703
+ elif key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1704
+ values = child if isinstance(child, list) else [child]
1705
+ if any(
1706
+ _needs_permissive_materialization(value, visited) for value in values
1707
+ ):
1708
+ return True
1709
+ return False
1710
+
1711
+
1712
+def _relax_exact_model_fields(
1713
+ schema: t.Dict[str, t.Any],
1714
+ base_model: t.Type[BaseModel],
1715
+) -> t.Type[BaseModel]:
1716
+ """Let exact source validation own fields the library would over-narrow."""
1717
+ properties = schema.get("properties")
1718
+ if not isinstance(properties, dict):
1719
+ return base_model
1720
+
1721
+ field_definitions = {}
1722
+ for internal_name, model_field in base_model.model_fields.items():
1723
+ external_name = (
1724
+ model_field.alias if isinstance(model_field.alias, str) else internal_name
1725
+ )
1726
+ property_schema = properties.get(external_name)
1727
+ if not _needs_permissive_materialization(property_schema):
1728
+ continue
1729
+
1730
+ default = ... if model_field.is_required() else model_field.default
1731
+ field_definitions[internal_name] = (
1732
+ t.Any,
1733
+ Field(
1734
+ default,
1735
+ alias=model_field.alias,
1736
+ description=model_field.description,
1737
+ examples=model_field.examples,
1738
+ title=model_field.title,
1739
+ ),
1740
+ )
1741
+
1742
+ if not field_definitions:
1743
+ return base_model
1744
+ return create_pydantic_model( # type: ignore[call-overload]
1745
+ base_model.__name__,
1746
+ __base__=base_model,
1747
+ **field_definitions,
1748
+ )
1749
+
1750
+
1751
+def _normalize_draft4_exclusive_bounds(value: t.Any) -> t.Any:
1752
+ """Translate OpenAPI 3.0 boolean bounds without changing nearby keywords."""
1753
+ if isinstance(value, bool) or not isinstance(value, dict):
1754
+ return value
1755
+
1756
+ normalized: t.Dict[str, t.Any] = {}
1757
+ for key, child in value.items():
1758
+ if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(child, dict):
1759
+ normalized[key] = {
1760
+ name: _normalize_draft4_exclusive_bounds(schema)
1761
+ for name, schema in child.items()
1762
+ }
1763
+ elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS and isinstance(child, list):
1764
+ normalized[key] = [
1765
+ _normalize_draft4_exclusive_bounds(schema) for schema in child
1766
+ ]
1767
+ elif key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1768
+ if isinstance(child, list):
1769
+ normalized[key] = [
1770
+ _normalize_draft4_exclusive_bounds(schema) for schema in child
1771
+ ]
1772
+ else:
1773
+ normalized[key] = _normalize_draft4_exclusive_bounds(child)
1774
+ else:
1775
+ # Values under enum/const/default/examples are instance data, not
1776
+ # schemas, and must remain byte-for-byte equivalent.
1777
+ normalized[key] = child
1778
+
1779
+ if normalized.get("exclusiveMinimum") is True and _is_numeric(
1780
+ normalized.get("minimum")
1781
+ ):
1782
+ normalized["exclusiveMinimum"] = normalized.pop("minimum")
1783
+ elif isinstance(normalized.get("exclusiveMinimum"), bool):
1784
+ normalized.pop("exclusiveMinimum")
1785
+
1786
+ if normalized.get("exclusiveMaximum") is True and _is_numeric(
1787
+ normalized.get("maximum")
1788
+ ):
1789
+ normalized["exclusiveMaximum"] = normalized.pop("maximum")
1790
+ elif isinstance(normalized.get("exclusiveMaximum"), bool):
1791
+ normalized.pop("exclusiveMaximum")
1792
+
1793
+ return normalized
1794
+
1795
+
1796
+def _exact_validation_multiple_of(
1797
+ _validator: t.Any,
1798
+ multiple: t.Any,
1799
+ instance: t.Any,
1800
+ _schema: t.Any,
1801
+) -> t.Iterator[t.Any]:
1802
+ if _is_numeric(instance) and not _is_json_multiple_of(instance, multiple):
1803
+ yield jsonschema_exceptions.ValidationError(
1804
+ f"{instance!r} is not a multiple of {multiple!r}"
1805
+ )
1806
+
1807
+
1808
+_PATTERN_MATCHER_CACHE: t.Dict[str, t.Optional[t.Callable[[str], bool]]] = {}
1809
+
1810
+
1811
+def _pattern_matcher(pattern: str) -> t.Optional[t.Callable[[str], bool]]:
1812
+ """Match `pattern` with pydantic's linear-time Rust regex when it can
1813
+ compile it, falling back to Python `re` only for ECMA-only constructs."""
1814
+ if pattern in _PATTERN_MATCHER_CACHE:
1815
+ return _PATTERN_MATCHER_CACHE[pattern]
1816
+ matcher: t.Optional[t.Callable[[str], bool]] = None
1817
+ if _pattern_supported_by_pydantic(pattern):
1818
+ adapter = TypeAdapter(t.Annotated[str, Field(pattern=pattern)])
1819
+
1820
+ def match_with_pydantic(value: str) -> bool:
1821
+ try:
1822
+ adapter.validate_python(value, strict=True)
1823
+ except ValidationError:
1824
+ return False
1825
+ return True
1826
+
1827
+ matcher = match_with_pydantic
1828
+ else:
1829
+ compiled = _compile_pattern(pattern)
1830
+ if compiled is not None:
1831
+
1832
+ def match_with_re(value: str) -> bool:
1833
+ return compiled.search(value) is not None
1834
+
1835
+ matcher = match_with_re
1836
+ _PATTERN_MATCHER_CACHE[pattern] = matcher
1837
+ return matcher
1838
+
1839
+
1840
+def _exact_validation_pattern(
1841
+ _validator: Validator,
1842
+ pattern: t.Any,
1843
+ instance: t.Any,
1844
+ _schema: t.Any,
1845
+) -> t.Iterator[t.Any]:
1846
+ if not isinstance(instance, str) or not isinstance(pattern, str):
1847
+ return
1848
+ matcher = _pattern_matcher(pattern)
1849
+ if matcher is not None and not matcher(instance):
1850
+ yield jsonschema_exceptions.ValidationError(
1851
+ f"{instance!r} does not match {pattern!r}"
1852
+ )
1853
+
1854
+
1855
+# A bare registry resolves only references inside the schema document and
1856
+# raises on anything else; jsonschema's default registry falls back to
1857
+# fetching unknown URIs over the network.
1858
+_LOCAL_ONLY_REGISTRY: Registry[t.Any] = Registry()
1859
+
1860
+
1861
+def _reject_external_references(schema: t.Any) -> None:
1862
+ """Fail at conversion time on any `$ref` that is not a local JSON Pointer.
1863
+
1864
+ Only schema positions are walked; `const`, `default`, `enum`, and
1865
+ `examples` hold instance data.
1866
+ """
1867
+ if isinstance(schema, list):
1868
+ for item in schema:
1869
+ _reject_external_references(item)
1870
+ return
1871
+ if not isinstance(schema, dict):
1872
+ return
1873
+ reference = schema.get("$ref")
1874
+ if isinstance(reference, str) and not reference.startswith("#"):
1875
+ raise ValueError(
1876
+ f"External schema reference {reference!r} is not supported; "
1877
+ "only local references (#/...) are resolved"
1878
+ )
1879
+ for keyword, value in schema.items():
1880
+ if keyword in _SCHEMA_VALUED_KEYWORDS or keyword in _SCHEMA_LIST_KEYWORDS:
1881
+ _reject_external_references(value)
1882
+ elif keyword in _SCHEMA_MAP_KEYWORDS:
1883
+ if isinstance(value, dict):
1884
+ for entry in value.values():
1885
+ _reject_external_references(entry)
1886
+ elif keyword == "items":
1887
+ _reject_external_references(value)
1888
+ elif keyword == "dependencies" and isinstance(value, dict):
1889
+ for entry in value.values():
1890
+ if isinstance(entry, (dict, bool)):
1891
+ _reject_external_references(entry)
1892
+
1893
+
1894
+def _is_closed_object_branch(branch: t.Any) -> bool:
1895
+ return (
1896
+ isinstance(branch, dict)
1897
+ and isinstance(branch.get("properties"), dict)
1898
+ and len(branch["properties"]) > 0
1899
+ and "additionalProperties" not in branch
1900
+ and "patternProperties" not in branch
1901
+ and "$ref" not in branch
1902
+ )
1903
+
1904
+
1905
+def _close_all_of_branches(schema: t.Any) -> t.Any:
1906
+ """Apply the omitted-`additionalProperties` strictness rule once per `allOf`.
1907
+
1908
+ Draft 7 already lets sibling object branches accept each other's keys, so
1909
+ the exact validator only needs the strictness a lone named-property object
1910
+ would have had: the union of every branch's declared keys, applied at the
1911
+ `allOf` node. Mirrors `parseAllOf` in @composio/json-schema-to-zod and
1912
+ `openAllOfBranches` in @composio/json-schema-to-effect-schema.
1913
+ """
1914
+ if isinstance(schema, list):
1915
+ return [_close_all_of_branches(item) for item in schema]
1916
+ if not isinstance(schema, dict):
1917
+ return schema
1918
+
1919
+ result: t.Dict[str, t.Any] = {}
1920
+ for key, value in schema.items():
1921
+ if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(value, dict):
1922
+ result[key] = {
1923
+ name: _close_all_of_branches(child) for name, child in value.items()
1924
+ }
1925
+ elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS or key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1926
+ result[key] = _close_all_of_branches(value)
1927
+ else:
1928
+ result[key] = value
1929
+
1930
+ branches = schema.get("allOf")
1931
+ if (
1932
+ isinstance(branches, list)
1933
+ and len(branches) >= 2
1934
+ and all(_is_closed_object_branch(branch) for branch in branches)
1935
+ and not {"properties", "patternProperties", "additionalProperties"}
1936
+ & set(schema)
1937
+ ):
1938
+ result["properties"] = {
1939
+ name: True for branch in branches for name in branch["properties"]
1940
+ }
1941
+ result["additionalProperties"] = False
1942
+ return result
1943
+
1944
+
1945
+def _validate_json_schema(
1946
+ schema: t.Dict[str, t.Any],
1947
+ root_schema: t.Dict[str, t.Any],
1948
+) -> t.Callable[[t.Any], t.Any]:
1949
+ """Compile an exact JSON Schema acceptance check for a Pydantic model."""
1950
+ validation_schema = _close_all_of_branches(
1951
+ _normalize_draft4_exclusive_bounds(_schema_for_exact_validation(schema))
1952
+ )
1953
+ validation_root = _close_all_of_branches(
1954
+ _normalize_draft4_exclusive_bounds(_schema_for_exact_validation(root_schema))
1955
+ )
1956
+ _reject_external_references(validation_root)
1957
+ _reject_external_references(validation_schema)
1958
+ # The SDK contract is Draft 7 plus the OpenAPI 3.0 boolean spelling for
1959
+ # exclusive bounds. Falling the entire document back to Draft 4 would make
1960
+ # `contains`, `const`, `if`/`then`/`else`, and `propertyNames` disappear.
1961
+ validator_class = jsonschema_validators.Draft7Validator
1962
+ # Align multipleOf with the decimal-scaled checks in the Zod and Effect
1963
+ # converters instead of raw float modulo.
1964
+ # `pattern` goes through pydantic's Rust regex where possible so a
1965
+ # backtracking pattern cannot stall validation (Python `re` is exponential
1966
+ # on inputs such as `(a+)+$`).
1967
+ validator_class = jsonschema_validators.extend(
1968
+ validator_class,
1969
+ {
1970
+ "multipleOf": _exact_validation_multiple_of,
1971
+ "pattern": _exact_validation_pattern,
1972
+ },
1973
+ )
1974
+ validator = validator_class(
1975
+ validation_root,
1976
+ registry=_LOCAL_ONLY_REGISTRY,
1977
+ ).evolve(schema=validation_schema)
1978
+
1979
+ def validate(value: t.Any) -> t.Any:
1980
+ error = next(validator.iter_errors(value), None)
1981
+ if error is not None:
1982
+ location = ".".join(str(part) for part in error.path)
1983
+ message = f"{location}: {error.message}" if location else error.message
1984
+ raise ValueError(message)
1985
+ return value
1986
+
1987
+ return validate
1988
+
1989
+
1990
+def _with_exact_validation_annotation(
1991
+ annotation: t.Any,
1992
+ schema: t.Dict[str, t.Any],
1993
+ root_schema: t.Dict[str, t.Any],
1994
+) -> t.Type[t.Any]:
1995
+ """Validate the raw value before Pydantic coercion or default handling."""
1996
+ validate_schema = _validate_json_schema(schema, root_schema)
1997
+ return t.cast(
1998
+ t.Type[t.Any],
1999
+ t.Annotated[annotation, BeforeValidator(validate_schema)],
2000
+ )
2001
+
2002
+
2003
+def _with_exact_validation(
2004
+ model: t.Type[BaseModel],
2005
+ schema: t.Dict[str, t.Any],
2006
+ root_schema: t.Dict[str, t.Any],
2007
+) -> t.Type[t.Any]:
2008
+ """Keep model materialization while enforcing the source schema first."""
2009
+ validate_schema = _validate_json_schema(schema, root_schema)
2010
+
2011
+ def validate_source_schema(cls, value: t.Any) -> t.Any:
2012
+ return validate_schema(value)
2013
+
2014
+ validator = model_validator(mode="before")(
2015
+ t.cast(t.Any, classmethod(validate_source_schema))
2016
+ )
2017
+
2018
+ name = model.__name__
2019
+ return t.cast(
2020
+ t.Type[BaseModel],
2021
+ type(
2022
+ name,
2023
+ (model,),
2024
+ {
2025
+ "__module__": __name__,
2026
+ "__qualname__": name,
2027
+ "_validate_source_schema": validator,
2028
+ },
2029
+ ),
2030
+ )
2031
2032
2033
def _convert_object_with_unsatisfiable_properties(
2059
],
2060
}
2061
base_model = create_model_from_schema(
1086
- base_schema,
2062
+ _normalize_schema_for_library(base_schema),
2063
allow_undefined_array_items=True,
2064
allow_undefined_type=True,
2065
)
2094
)
2095
2096
2097
+_TYPE_ARRAY_CHILD_KEYWORDS_MAPS = (
2098
+ "properties",
2099
+ "patternProperties",
2100
+ "$defs",
2101
+ "definitions",
2102
+)
2103
+_TYPE_ARRAY_CHILD_KEYWORDS_LISTS = ("anyOf", "allOf", "oneOf")
2104
+_TYPE_ARRAY_CHILD_KEYWORDS_SCHEMAS = (
2105
+ "items",
2106
+ "additionalItems",
2107
+ "additionalProperties",
2108
+ "contains",
2109
+ "propertyNames",
2110
+ "not",
2111
+ "if",
2112
+ "then",
2113
+ "else",
2114
+)
2115
+
2116
+
2117
+_PYDANTIC_PATTERN_SUPPORT_CACHE: t.Dict[str, bool] = {}
2118
+
2119
+
2120
+def _pattern_supported_by_pydantic(pattern: str) -> bool:
2121
+ cached = _PYDANTIC_PATTERN_SUPPORT_CACHE.get(pattern)
2122
+ if cached is not None:
2123
+ return cached
2124
+ try:
2125
+ TypeAdapter(t.Annotated[str, Field(pattern=pattern)])
2126
+ supported = True
2127
+ except Exception: # noqa: BLE001 - pydantic raises SchemaError subclasses
2128
+ supported = False
2129
+ _PYDANTIC_PATTERN_SUPPORT_CACHE[pattern] = supported
2130
+ return supported
2131
+
2132
+
2133
+def _normalize_schema_for_library(schema: t.Any) -> t.Any:
2134
+ """Rewrite constructs the json-schema-to-pydantic library mishandles.
2135
+
2136
+ - `type: [...]` becomes an equivalent `anyOf` of single-type schemas: the
2137
+ library applies every sibling constraint to every union member, so
2138
+ `{"type": ["string", "number"], "minLength": 2, "minimum": 10}` raises
2139
+ `TypeError` at validation time when a valid string hits the numeric
2140
+ constraint. Scoping constraints per member is semantically identical
2141
+ under Draft 7 (mismatched-type keywords are ignored).
2142
+ - `pattern` values the Rust regex crate rejects (ECMA look-around) are
2143
+ dropped from the library input; the exact-validation layer still
2144
+ enforces them through Python `re`.
2145
+ """
2146
+ if not isinstance(schema, dict):
2147
+ return schema
2148
+
2149
+ result: t.Dict[str, t.Any] = {}
2150
+ for key, value in schema.items():
2151
+ if key in _TYPE_ARRAY_CHILD_KEYWORDS_MAPS and isinstance(value, dict):
2152
+ result[key] = {
2153
+ name: _normalize_schema_for_library(child)
2154
+ for name, child in value.items()
2155
+ }
2156
+ elif key in _TYPE_ARRAY_CHILD_KEYWORDS_LISTS and isinstance(value, list):
2157
+ result[key] = [_normalize_schema_for_library(child) for child in value]
2158
+ elif key in _TYPE_ARRAY_CHILD_KEYWORDS_SCHEMAS:
2159
+ result[key] = _normalize_schema_for_library(value)
2160
+ else:
2161
+ result[key] = value
2162
+
2163
+ pattern = result.get("pattern")
2164
+ if isinstance(pattern, str) and not _pattern_supported_by_pydantic(pattern):
2165
+ del result["pattern"]
2166
+
2167
+ # Draft-4 boolean exclusive flags: the library reads the boolean itself as
2168
+ # the numeric bound (lt=True becomes "less than 1"). Translate them to the
2169
+ # Draft 7 numeric spelling before the library sees them.
2170
+ if result.get("exclusiveMinimum") is True and _is_numeric(result.get("minimum")):
2171
+ result["exclusiveMinimum"] = result.pop("minimum")
2172
+ elif isinstance(result.get("exclusiveMinimum"), bool):
2173
+ del result["exclusiveMinimum"]
2174
+ if result.get("exclusiveMaximum") is True and _is_numeric(result.get("maximum")):
2175
+ result["exclusiveMaximum"] = result.pop("maximum")
2176
+ elif isinstance(result.get("exclusiveMaximum"), bool):
2177
+ del result["exclusiveMaximum"]
2178
+
2179
+ # A one-member type array is the same as the bare type, and collapsing it
2180
+ # lets the constraint scoping below apply.
2181
+ if isinstance(result.get("type"), list) and len(result["type"]) == 1:
2182
+ result["type"] = result["type"][0]
2183
+
2184
+ # The library applies scalar keywords unconditionally, so a keyword that
2185
+ # does not scope to the declared type (or any keyword on a typeless
2186
+ # schema) raises TypeError at validation time on mismatched instances.
2187
+ # Drop them from the library input; the exact-validation layer that wraps
2188
+ # every object conversion still enforces them per Draft 7.
2189
+ declared_type = result.get("type")
2190
+ if isinstance(declared_type, str):
2191
+ scoped_keywords = _TYPE_SCOPED_KEYWORDS.get(declared_type)
2192
+ if scoped_keywords is not None:
2193
+ for keyword in _SCALAR_CONSTRAINT_KEYWORDS - scoped_keywords:
2194
+ result.pop(keyword, None)
2195
+ elif declared_type is None:
2196
+ for keyword in _SCALAR_CONSTRAINT_KEYWORDS:
2197
+ result.pop(keyword, None)
2198
+
2199
+ type_ = result.get("type")
2200
+ if not isinstance(type_, list) or len(type_) < 2:
2201
+ return result
2202
+
2203
+ members = []
2204
+ for member in type_:
2205
+ member_schema: t.Dict[str, t.Any] = {"type": member}
2206
+ scoped = _TYPE_SCOPED_KEYWORDS.get(member, frozenset())
2207
+ for keyword in scoped | _TYPE_ARRAY_SHARED_KEYWORDS:
2208
+ if keyword in result:
2209
+ member_schema[keyword] = result[keyword]
2210
+ members.append(member_schema)
2211
+
2212
+ wrapper: t.Dict[str, t.Any] = {
2213
+ key: value
2214
+ for key, value in result.items()
2215
+ if key in _TYPE_ARRAY_WRAPPER_KEYWORDS
2216
+ }
2217
+ wrapper["anyOf"] = members
2218
+ return wrapper
2219
+
2220
+
2221
def _convert_with_library(
2222
schema: t.Dict[str, t.Any],
2223
*,
2237
)
2238
except (SchemaError, CombinerError) as e:
2239
logger.debug(
1140
- f"Library schema conversion failed: {e}, falling back to string"
2240
+ f"Library schema conversion failed: {e}, preserving exact validation"
2241
+ )
2242
+ return _with_exact_validation_annotation(
2243
+ t.Any,
2244
+ schema,
2245
+ document_root,
2246
)
1142
- return str
2247
except Exception as e:
2248
logger.debug(
1145
- f"Unexpected error in schema conversion: {e}, falling back to string"
2249
+ f"Unexpected error in schema conversion: {e}, preserving exact validation"
2250
)
1147
- return str
1148
- return apply_object_policy(
2251
+ return _with_exact_validation_annotation(
2252
+ t.Any,
2253
+ schema,
2254
+ document_root,
2255
+ )
2256
+ return _with_exact_validation(
2257
+ apply_object_policy(
2258
+ schema,
2259
+ _apply_nested_object_policies(schema, base_model, document_root),
2260
+ root_schema=document_root,
2261
+ ),
2262
schema,
1150
- _apply_nested_object_policies(schema, base_model, document_root),
1151
- root_schema=document_root,
2263
+ document_root,
2264
)
2265
# A property-less object with no dynamic-key constraints accepts and
2266
# preserves arbitrary content. Modelling it as an empty Pydantic
2272
2273
try:
2274
base_model = create_model_from_schema(
1163
- schema,
2275
+ _normalize_schema_for_library(schema),
2276
allow_undefined_array_items=True,
2277
allow_undefined_type=True,
2278
)
2279
except (SchemaError, CombinerError) as e:
2280
logger.debug(
1169
- f"Library schema conversion failed: {e}, falling back to string"
2281
+ f"Library schema conversion failed: {e}, preserving exact validation"
2282
+ )
2283
+ return _with_exact_validation_annotation(
2284
+ t.Any,
2285
+ schema,
2286
+ document_root,
2287
)
1171
- return str
2288
except Exception as e:
2289
logger.debug(
1174
- f"Unexpected error in schema conversion: {e}, falling back to string"
2290
+ f"Unexpected error in schema conversion: {e}, preserving exact validation"
2291
+ )
2292
+ return _with_exact_validation_annotation(
2293
+ t.Any,
2294
+ schema,
2295
+ document_root,
2296
)
1176
- return str
2297
1178
- return apply_object_policy(
2298
+ base_model = _relax_exact_model_fields(schema, base_model)
2299
+ return _with_exact_validation(
2300
+ apply_object_policy(
2301
+ schema,
2302
+ _apply_nested_object_policies(schema, base_model, document_root),
2303
+ root_schema=document_root,
2304
+ ),
2305
schema,
1180
- _apply_nested_object_policies(schema, base_model, document_root),
1181
- root_schema=document_root,
2306
+ document_root,
2307
)
2308
2309
try:
2331
return _convert_simple_type(schema)
2332
2333
except (SchemaError, CombinerError) as e:
1209
- logger.debug(f"Library schema conversion failed: {e}, falling back to string")
1210
- return str
2334
+ logger.debug(
2335
+ f"Library schema conversion failed: {e}, preserving exact validation"
2336
+ )
2337
+ document_root = root_schema if root_schema is not None else schema
2338
+ return _with_exact_validation_annotation(t.Any, schema, document_root)
2339
except Exception as e:
2340
logger.debug(
1213
- f"Unexpected error in schema conversion: {e}, falling back to string"
2341
+ f"Unexpected error in schema conversion: {e}, preserving exact validation"
2342
)
1215
- return str
2343
+ document_root = root_schema if root_schema is not None else schema
2344
+ return _with_exact_validation_annotation(t.Any, schema, document_root)
2345
2346
2347
def _handle_toplevel_combiner(
2357
try:
2358
# Try direct conversion - library handles anyOf/oneOf/allOf at top level
2359
result = create_model_from_schema(
1231
- schema,
2360
+ _normalize_schema_for_library(schema),
2361
allow_undefined_array_items=True,
2362
allow_undefined_type=True,
2363
)
2364
if result is type(None):
1236
- return t.Optional[t.Any]
1237
- # If result is a type (like a Union or Optional), return it directly
1238
- # If result is a model class, return it
2365
+ return type(None)
2366
+ if "allOf" in schema:
2367
+ options = schema.get("allOf")
2368
+ requires_object = isinstance(options, list) and any(
2369
+ isinstance(option, dict) and option.get("type") == "object"
2370
+ for option in options
2371
+ )
2372
+ if (
2373
+ requires_object
2374
+ and isinstance(result, type)
2375
+ and issubclass(result, BaseModel)
2376
+ ):
2377
+ document_root = root_schema if root_schema is not None else schema
2378
+ return _with_exact_validation(result, schema, document_root)
2379
+
2380
+ # The library models scalar intersections as object models.
2381
+ # Preserve the JSON value and let exact validation own acceptance.
2382
+ return t.Any
2383
+ # A library model for anyOf/oneOf drops sibling assertions such as
2384
+ # `required` and exclusive oneOf matching; let the source schema own it.
2385
+ if isinstance(result, type) and issubclass(result, BaseModel):
2386
+ document_root = root_schema if root_schema is not None else schema
2387
+ return _with_exact_validation(result, schema, document_root)
2388
return result
2389
except (SchemaError, CombinerError):
2390
pass
2426
pydantic_types.append(ptype)
2427
2428
if len(pydantic_types) == 0:
1280
- return t.Optional[t.Any] if has_null else _UnsatisfiableSchema # type: ignore
2429
+ return type(None) if has_null else _UnsatisfiableSchema
2430
2431
if len(pydantic_types) == 1:
2432
base_type = pydantic_types[0]