"""Public schema conversion and argument serialization boundary contracts.""" import inspect import typing as t import uuid import pytest from composio.exceptions import InvalidSchemaError from composio.utils.schema_converter import ( json_schema_from_pydantic_type, json_schema_to_pydantic_type, ) from composio.utils.shared import ( alias_tool_input_schema, generate_request_id, get_pydantic_signature_format_from_schema_params, get_signature_format_from_schema_params, pydantic_model_from_param_schema, reinstate_reserved_python_keywords, substitute_reserved_python_keywords, validate_and_serialize_tool_arguments, ) from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError def test_aliases_cover_identifiers_dependencies_conditionals_and_tuple_items(): source = { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "": {"type": "string"}, "3d": {"type": "number"}, "x" * 100: {"type": "boolean"}, "$tuple": { "type": "array", "prefixItems": [ {"type": "object", "properties": {"$value": {"type": "integer"}}}, True, { "type": "array", "items": {"properties": {"from": {"type": "string"}}}, }, ], }, }, "dependentRequired": {"safe": ["other"]}, "dependentSchemas": {"safe": {"properties": {"other": True}}, "other": True}, "if": {"properties": {"safe": True}}, "then": {"properties": {"other": True}}, "else": {"properties": {"third": True}}, "not": {"required": ["impossible"]}, } projection = alias_tool_input_schema(source) names = projection.schema["properties"] long_name = next(name for name in names if name.startswith("x")) assert len(long_name) == 64 restored = projection.restore_arguments( { "param": "empty", "param_3d": 2, long_name: True, "param_tuple": [{"param_value": 3}, "scalar", [{"from_rs": "a"}]], } ) assert restored == { "": "empty", "3d": 2, "x" * 100: True, "$tuple": [{"$value": 3}, "scalar", [{"from": "a"}]], } def test_legacy_alias_wrappers_preserve_absent_and_heterogeneous_array_values(): projected, aliases = substitute_reserved_python_keywords( { "properties": { "from": {"type": "array", "items": {"properties": {"$key": {}}}}, "to": {"type": "string"}, } } ) assert "from_rs" in projected["properties"] assert reinstate_reserved_python_keywords({"to": "a"}, aliases) == {"to": "a"} assert reinstate_reserved_python_keywords( {"from_rs": [7, {"param_key": 2}]}, aliases ) == {"from": [7, {"$key": 2}]} @pytest.mark.parametrize( "source", [ {"type": "array", "title": "Values", "items": {"type": "integer"}}, {"title": "Composed", "allOf": [{"type": "integer"}, {"minimum": 2}]}, ], ) def test_legacy_param_model_keeps_non_object_assertions(source): adapter = TypeAdapter(pydantic_model_from_param_schema(source)) value = [3] if source.get("type") == "array" else 3 assert adapter.validate_python(value) == value with pytest.raises(ValidationError): adapter.validate_python(["bad"] if isinstance(value, list) else 1) def test_legacy_param_model_requires_title_and_preserves_reserved_field_names(): with pytest.raises(ValueError, match="Missing 'title'"): pydantic_model_from_param_schema({"type": "object"}) model = pydantic_model_from_param_schema( { "title": "Named model", "type": "object", "properties": { "validate": {"type": "string"}, "required": {"type": "integer"}, }, "required": ["validate"], } ) assert issubclass(model, BaseModel) assert ( model.model_validate({"validate": "a"}).model_dump(by_alias=True)["validate"] == "a" ) def test_foreign_model_serialization_respects_aliases_and_omissions(): class Child(BaseModel): model_config = ConfigDict(extra="allow", populate_by_name=True) internal: int = Field(alias="external", serialization_alias="wire") optional: str | None = None class Arguments(BaseModel): child: Child items: tuple[Child, ...] supplied = { "child": {"external": 2, "dynamic": {"a": 3}}, "items": [{"external": 4}], } assert validate_and_serialize_tool_arguments(Arguments, supplied) == { "child": {"wire": 2, "dynamic": {"a": 3}}, "items": ({"wire": 4},), } def test_signature_contracts_keep_required_order_types_and_skip_optional_defaults(): source = { "properties": { "union": {"anyOf": [{"type": "integer"}, {"type": "string"}]}, "singleton": {"type": ["integer"]}, "many": {"type": ["string", "integer"]}, "opaque": {"description": "Anything"}, "required": {"type": "boolean"}, }, "required": ["required"], } plain = get_signature_format_from_schema_params(source, skip_default=True) assert plain[0].name == "required" assert plain[0].default is inspect.Parameter.empty assert all(parameter.default is None for parameter in plain[1:]) materialized = get_pydantic_signature_format_from_schema_params( source, skip_default=True ) assert {parameter.name for parameter in materialized} == set(source["properties"]) assert ( TypeAdapter( next(p.annotation for p in materialized if p.name == "singleton") ).validate_python(3) == 3 ) def test_unsatisfiable_native_json_export_is_valid_false_schema(): annotation = json_schema_to_pydantic_type(False) assert TypeAdapter(annotation).json_schema() == {"not": {}} with pytest.raises(ValidationError): TypeAdapter(annotation).validate_python(None) def test_annotated_foreign_metadata_does_not_hide_schema_constraints(): annotation = t.Annotated[int, "annotation", Field(gt=1)] assert json_schema_from_pydantic_type(annotation) == { "type": "integer", "exclusiveMinimum": 1, } def test_request_identifiers_are_distinct_uuid_strings(): first, second = generate_request_id(), generate_request_id() assert str(uuid.UUID(first)) == first assert first != second @pytest.mark.parametrize("failure", ["schema", "combiner", "unexpected"]) @pytest.mark.parametrize( "source,accepted,rejected", [ ( {"type": "object", "properties": {"n": {"type": "integer"}}}, {"n": 2}, {"n": "bad"}, ), ({"type": "object", "properties": {"forbidden": False}}, {}, {"forbidden": 2}), ({"allOf": [{"type": "integer"}, {"minimum": 2}]}, 3, 1), ({"anyOf": [{"type": "integer"}, {"type": "boolean"}]}, 3, "bad"), ], ) def test_native_dependency_failure_keeps_source_acceptance( monkeypatch, failure, source, accepted, rejected ): import composio.utils.schema_converter as converter def unavailable(*args, **kwargs): if failure == "schema": raise converter.SchemaError("native schema unavailable") if failure == "combiner": raise converter.CombinerError("native combiner unavailable") raise RuntimeError("native converter unavailable") monkeypatch.setattr(converter, "create_model_from_schema", unavailable) adapter = TypeAdapter(json_schema_to_pydantic_type(source)) assert adapter.validate_python(accepted) == accepted with pytest.raises(ValidationError): adapter.validate_python(rejected) @pytest.mark.parametrize( "source,value", [ ({"type": "array", "items": {"type": "string"}}, ["a"]), ({"type": "object", "properties": {"n": {"type": "integer"}}}, {"n": 2}), ], ) def test_native_dependency_unexpected_return_keeps_source_values( monkeypatch, source, value ): import composio.utils.schema_converter as converter monkeypatch.setattr( converter, "create_model_from_schema", lambda *args, **kwargs: str ) adapter = TypeAdapter(json_schema_to_pydantic_type(source)) assert adapter.validate_python(value) == value @pytest.mark.parametrize( "source,accepted,rejected", [ ( { "type": "object", "properties": { "bad": { "allOf": [ False, { "description": "forbidden", "examples": [1], "title": "Never", }, ] } }, }, {}, {"bad": 1}, ), ( { "definitions": {"Never": False}, "type": "object", "properties": { "bad": {"$ref": "#/definitions/Never"}, "ok": {"type": "string"}, }, }, {"ok": "a"}, {"bad": "a"}, ), ( { "type": "object", "patternProperties": {"^x": {"type": "integer"}}, "additionalProperties": False, }, {"x1": 2}, {"a": 1, "b": 2}, ), ( {"patternProperties": {"^x": {"type": "integer"}}}, "valid non-object", {"x1": "bad"}, ), ( { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "patternProperties": {"^x": {"type": "integer"}}, "unevaluatedProperties": False, }, {"x1": 2}, {"other": 2}, ), ], ) def test_false_schemas_and_dynamic_property_assertions_keep_exact_acceptance( source, accepted, rejected ): adapter = TypeAdapter(json_schema_to_pydantic_type(source)) adapter.validate_python(accepted) with pytest.raises(ValidationError): adapter.validate_python(rejected) def test_shared_subschema_identity_does_not_change_acceptance(): shared = {"type": "string", "minLength": 2} schema = {"type": "object", "properties": {"first": shared, "second": shared}} adapter = TypeAdapter(json_schema_to_pydantic_type(schema)) adapter.validate_python({"first": "aa", "second": "bb"}) with pytest.raises(ValidationError): adapter.validate_python({"first": "aa", "second": "b"}) def test_explicit_reference_promotes_only_its_extension_target(): from composio.utils.schema_policy import prepare_json_schema_object_policy source = { "type": "object", "properties": {"payload": {"$ref": "#/x/target"}}, "x": { "target": { "type": "object", "properties": { "nested": { "type": "object", "properties": {"name": {"type": "string", "min": 2}}, } }, }, "untouched": {"type": "string", "nullable": True, "min": 9}, }, } effective = prepare_json_schema_object_policy(source) target = effective["x"]["target"] assert target["additionalProperties"] is False assert target["properties"]["nested"]["additionalProperties"] is False assert target["properties"]["nested"]["properties"]["name"]["minLength"] == 2 assert effective["x"]["untouched"] == source["x"]["untouched"] adapter = TypeAdapter(json_schema_to_pydantic_type(source)) adapter.validate_python({"payload": {"nested": {"name": "ab"}}}) with pytest.raises(ValidationError): adapter.validate_python({"payload": {"nested": {"name": "a"}}}) with pytest.raises(ValidationError): adapter.validate_python({"payload": {"nested": {"name": "ab", "extra": 2}}}) @pytest.mark.parametrize( "literal", [ {"type": "integer", "min": 2}, {"type": "string", "nullable": True}, {"type": "object", "properties": {"name": {"type": "string"}}}, {"$ref": "#"}, {"$id": "https://example.test/literal", "type": "integer"}, ], ) def test_complex_reference_into_annotation_data_rejects_precisely(literal): source = { "type": "object", "properties": { "value": {"$ref": "#/properties/template/default"}, "template": {"default": literal}, }, } with pytest.raises( InvalidSchemaError, match="reference into annotation data: target requires normalization", ): json_schema_to_pydantic_type(source) @pytest.mark.parametrize( "literal,accepted,rejected", [ ({"type": "integer", "minimum": 2}, 3, 1), (False, None, 1), (True, "anything", None), ], ) def test_flat_and_boolean_annotation_targets_preserve_source_data( literal, accepted, rejected ): from composio.utils.schema_policy import prepare_json_schema_object_policy source = { "type": "object", "properties": { "value": {"$ref": "#/properties/template/default"}, "template": {"default": literal}, }, } assert ( prepare_json_schema_object_policy(source)["properties"]["template"]["default"] == literal ) adapter = TypeAdapter(json_schema_to_pydantic_type(source)) if literal is not False: adapter.validate_python({"value": accepted}) if literal is not True: with pytest.raises(ValidationError): adapter.validate_python({"value": rejected}) def test_alias_projection_rejects_dependency_trigger_that_matches_wire_alias(): source = { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": {"$top": {"type": "integer"}}, "dependentSchemas": {"param_top": {"required": ["q"]}}, "additionalProperties": False, } TypeAdapter(json_schema_to_pydantic_type(source)).validate_python({"$top": 1}) with pytest.raises(InvalidSchemaError, match="active dependency constraints"): alias_tool_input_schema(source) @pytest.mark.parametrize("keyword", ["unevaluatedProperties", "unevaluatedItems"]) def test_active_unevaluated_schema_with_nested_alias_rejects_precisely(keyword): source = { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": {"safe": {"type": "integer"}}, keyword: {"type": "object", "properties": {"$nested": {"type": "integer"}}}, } json_schema_to_pydantic_type(source) with pytest.raises(InvalidSchemaError, match=f"inside {keyword} is not supported"): alias_tool_input_schema(source) def test_inactive_unevaluated_schema_is_opaque_during_alias_projection(): source = { "type": "object", "properties": {"$top": {"type": "integer"}}, "unevaluatedProperties": {"properties": {"$nested": {"type": "integer"}}}, } aliases = alias_tool_input_schema(source) assert aliases.schema["unevaluatedProperties"] == source["unevaluatedProperties"] assert aliases.restore_arguments({"param_top": 2}) == {"$top": 2} def test_alias_restore_rejects_simultaneous_wire_and_source_names(): from composio.exceptions import InvalidParams aliases = alias_tool_input_schema({"properties": {"$top": {"type": "integer"}}}) with pytest.raises(InvalidParams, match="both alias"): aliases.restore_arguments({"param_top": 1, "$top": 2}) @pytest.mark.parametrize( "schema,accepted,rejected", [ ({"type": "string", "enum": ["a", "b"]}, "a", "c"), ({"type": "integer", "const": 3}, 3, 4), ({"const": "allowed"}, "allowed", "wrong"), ], ) def test_scalar_literal_constraints_reject_validly_typed_nonmembers( schema, accepted, rejected ): adapter = TypeAdapter(json_schema_to_pydantic_type(schema)) assert adapter.validate_python(accepted) == accepted with pytest.raises(ValidationError): adapter.validate_python(rejected) def test_aliases_reject_conflicting_nested_maps_from_composition(): schema = { "allOf": [ {"properties": {"cfg": {"properties": {"$key": {"type": "integer"}}}}}, {"properties": {"cfg": {"properties": {"_key": {"type": "integer"}}}}}, ] } with pytest.raises(InvalidSchemaError, match="conflicting Python parameter alias"): alias_tool_input_schema(schema) def test_alias_projection_has_its_own_expansion_budget(monkeypatch): import composio.utils.shared as shared definitions = { f"D{index}": {"properties": {"child": {"$ref": f"#/$defs/D{index + 1}"}}} for index in range(8) } definitions["D8"] = {"properties": {"$key": {"type": "integer"}}} source = { "type": "object", "$defs": definitions, "properties": {"root": {"$ref": "#/$defs/D0"}}, } monkeypatch.setattr(shared, "MAX_NODE_DEPTH", 12) with pytest.raises( InvalidSchemaError, match="alias projection exceeds schema depth limit" ): alias_tool_input_schema(source) def test_serialization_uses_internal_input_names_and_omits_computed_fields(): from pydantic import computed_field class Arguments(BaseModel): model_config = ConfigDict(populate_by_name=True) internal: int = Field(alias="external", serialization_alias="wire") @computed_field @property def derived(self) -> int: return self.internal * 2 assert validate_and_serialize_tool_arguments(Arguments, {"internal": 3}) == { "wire": 3 } def test_alias_inlining_preserves_referenced_false_schema_and_old_ref_siblings(): source = { "$schema": "http://json-schema.org/draft-07/schema#", "$defs": {"Never": False, "Number": {"type": "integer"}}, "type": "object", "properties": { "$top": {"type": "integer"}, "blocked": {"$ref": "#/$defs/Never"}, "count": {"$ref": "#/$defs/Number", "type": "string"}, }, } aliases = alias_tool_input_schema(source) assert aliases.schema["properties"]["blocked"] is False assert aliases.schema["properties"]["count"]["type"] == "integer" assert aliases.restore_arguments({"param_top": 3, "count": 2}) == { "$top": 3, "count": 2, } def test_array_of_false_schema_preserves_annotations_and_accepts_empty_array(): source = { "type": "object", "properties": { "empty": { "type": "array", "items": False, "description": "Empty", "title": "Nothing", "examples": [[]], } }, } annotation = json_schema_to_pydantic_type(source) TypeAdapter(annotation).validate_python({"empty": []}) exported = json_schema_from_pydantic_type(annotation) assert exported["properties"]["empty"]["description"] == "Empty" with pytest.raises(ValidationError): TypeAdapter(annotation).validate_python({"empty": [1]}) @pytest.mark.parametrize( "dialect", [None, "https://json-schema.org/draft/2020-12/schema"] ) def test_recursive_reference_keywords_are_inactive_data(dialect): from composio.utils.schema_policy import prepare_json_schema_object_policy # Draft 2019-09 is unsupported; `$recursiveRef` and `$recursiveAnchor` are # inactive in both supported dialects, so they neither resolve nor reject. source = { "$recursiveAnchor": True, "type": "object", "properties": {"child": {"$recursiveRef": "#/$defs/Missing"}}, } if dialect is not None: source["$schema"] = dialect prepared = prepare_json_schema_object_policy(source) assert prepared["properties"]["child"]["$recursiveRef"] == "#/$defs/Missing" adapter = TypeAdapter(json_schema_to_pydantic_type(source)) assert adapter.dump_python(adapter.validate_python({"child": 3})) == {"child": 3} @pytest.mark.parametrize("binding", ["$id", "$anchor", "id"]) def test_referenced_ambiguous_resource_binding_rejects_without_last_wins(binding): from composio.utils.schema_policy import prepare_json_schema_object_policy name = ( "https://example.test/duplicate" if binding == "$id" else "duplicate" if binding == "$anchor" else "#duplicate" ) reference = name if binding == "$id" else "#duplicate" source = { "type": "object", "$defs": { "A": {binding: name, "type": "integer"}, "B": {binding: name, "type": "string"}, }, "properties": {"value": {"$ref": reference}}, } with pytest.raises(InvalidSchemaError, match="Ambiguous JSON Schema resource"): prepare_json_schema_object_policy(source) source["properties"].pop("value") prepare_json_schema_object_policy(source) @pytest.mark.parametrize( "dialect", [ "http://json-schema.org/draft-07/schema#", "https://json-schema.org/draft-07/schema", ], ) def test_old_draft_reference_nullable_sibling_does_not_widen_target(dialect): source = { "$schema": dialect, "$defs": {"Value": {"type": "integer"}}, "$ref": "#/$defs/Value", "nullable": True, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) assert adapter.validate_python(3) == 3 with pytest.raises(ValidationError): adapter.validate_python(None) exported = json_schema_from_pydantic_type(json_schema_to_pydantic_type(source)) assert "anyOf" not in exported def test_explicit_draft7_reference_sibling_does_not_open_object_scope(): source = { "$schema": "http://json-schema.org/draft-07/schema#", "properties": {"name": {"type": "string"}}, "allOf": [{"$ref": "#/$defs/Value", "additionalProperties": True}], "$defs": {"Value": {}}, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) assert adapter.validate_python({"name": "example"}) == {"name": "example"} with pytest.raises(ValidationError): adapter.validate_python({"name": "example", "extra": 1}) def test_old_reference_root_retains_resource_context_when_target_nullable_is_lowered(): source = { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://example.test/root", "$defs": { "Value": { "type": "object", "nullable": True, "properties": {"name": {"type": "string"}}, } }, "$ref": "https://example.test/root#/$defs/Value/properties/name", "nullable": True, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) assert adapter.validate_python("accepted") == "accepted" with pytest.raises(ValidationError): adapter.validate_python(None) @pytest.mark.parametrize( "reference", [ "https://example.test/thing#/properties/name", "thing#/properties/name", ], ) def test_reference_into_nullable_embedded_resource_matches_relative_and_absolute_ids( reference, ): source = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.test/root", "type": "object", "properties": {"copy": {"$ref": reference}}, "$defs": { "thing": { "$id": "thing", "type": "object", "nullable": True, "properties": {"name": {"type": "string"}}, } }, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) assert adapter.validate_python({"copy": "accepted"}) == {"copy": "accepted"} with pytest.raises(ValidationError): adapter.validate_python({"copy": 7}) @pytest.mark.parametrize( "reference,inner_reference", [ ("https://example.test/root#/properties/x/properties/y", None), ("root#/properties/x/properties/y", None), ("#/properties/x/properties/y", "#/properties/x/properties/y"), ], ) def test_fragment_identifier_does_not_take_its_parent_resource_in_nullable_rewrite( reference, inner_reference ): tagged: dict[str, t.Any] = {"$id": "#tagged", "type": "object"} if inner_reference is not None: tagged["properties"] = {"w": {"$ref": inner_reference}} source = { "$id": "https://example.test/root", "type": "object", "properties": { "x": { "type": "object", "nullable": True, "properties": {"y": {"type": "integer"}}, }, "tagged": tagged, "r": {"$ref": reference}, }, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) adapter.validate_python({"r": 1}) with pytest.raises(ValidationError): adapter.validate_python({"r": "text"}) if inner_reference is not None: adapter.validate_python({"tagged": {"w": 2}}) with pytest.raises(ValidationError): adapter.validate_python({"tagged": {"w": "text"}}) def test_empty_nested_identifier_is_an_ambiguous_resource_in_nullable_rewrite(): source = { "$id": "https://example.test/root", "type": "object", "properties": { "x": {"type": "string", "nullable": True}, "tagged": {"$id": "", "type": "object"}, "r": {"$ref": "https://example.test/root#/properties/x"}, }, } with pytest.raises(InvalidSchemaError, match="Ambiguous JSON Schema resource"): json_schema_to_pydantic_type(source) @pytest.mark.parametrize("root_id", [None, "https://example.test/root"]) def test_resource_inlined_into_a_composition_keeps_other_references_unambiguous( root_id, ): from composio.utils.shared import json_schema_to_model resource = { "$id": "item.json", "$defs": {"text": {"$anchor": "text", "type": "string"}}, "type": "object", "properties": { "name": {"$ref": "#/$defs/text"}, "label": {"$ref": "#text"}, }, } source: dict[str, t.Any] = { "type": "object", "$defs": {"item": resource}, "allOf": [{"$ref": "#/$defs/item"}], "properties": {"nested": {"$ref": "item.json"}}, } if root_id is not None: source["$id"] = root_id model = json_schema_to_model(source) valid = {"name": "a", "label": "b", "nested": {"name": "c"}} assert validate_and_serialize_tool_arguments(model, valid) == valid for invalid in ({"name": 1}, {"label": 2}, {"nested": {"name": 3}}): with pytest.raises(ValidationError): model(**invalid) def test_resource_inlined_across_relative_directories_keeps_its_references(): from composio.utils.shared import json_schema_to_model source = { "type": "object", "$defs": { "outer": {"$id": "sub/outer.json", "allOf": [{"$ref": "inner.json"}]}, "inner": { "$id": "sub/inner.json", "$defs": {"count": {"type": "integer"}}, "type": "object", "properties": {"count": {"$ref": "#/$defs/count"}}, }, }, "properties": { "outer": {"$ref": "sub/outer.json"}, "inner": {"$ref": "sub/inner.json"}, }, } model = json_schema_to_model(source) valid = {"outer": {"count": 1}, "inner": {"count": 2}} assert validate_and_serialize_tool_arguments(model, valid) == valid for invalid in ({"outer": {"count": "x"}}, {"inner": {"count": "y"}}): with pytest.raises(ValidationError): model(**invalid) def test_subschema_policy_inherits_explicit_root_draft_reference_semantics(): from composio.utils.schema_policy import prepare_json_schema_object_policy child = {"$ref": "#/$defs/Value", "nullable": True, "default": 4} root = { "$schema": "http://json-schema.org/draft-07/schema#", "$defs": {"Value": {"type": "integer", "default": 3}}, "allOf": [child], } effective = prepare_json_schema_object_policy(child, root_schema=root) assert effective["$ref"] == "#/$defs/Value" assert "allOf" not in effective and "anyOf" not in effective root["$schema"] = "https://json-schema.org/draft/2020-12/schema" active = {"unevaluatedProperties": {"properties": {"named": {"type": "string"}}}} assert ( prepare_json_schema_object_policy(active, root_schema=root)[ "unevaluatedProperties" ]["additionalProperties"] is False ) @pytest.mark.parametrize("additional", [True, {"type": "integer"}]) @pytest.mark.parametrize("entry", ["model", "annotation"]) def test_composed_explicit_open_scope_is_not_reclosed_by_native_projection( additional, entry ): from composio.utils.shared import json_schema_to_model source = { "type": "object", "properties": {"parent": {"type": "integer"}}, "allOf": [ { "properties": {"child": {"type": "string"}}, "additionalProperties": additional, } ], } value = {"parent": 1, "child": "ok", "extra": 2} if entry == "model": assert ( validate_and_serialize_tool_arguments(json_schema_to_model(source), value) == value ) else: validated = TypeAdapter(json_schema_to_pydantic_type(source)).validate_python( value ) assert validated.model_dump() == value @pytest.mark.parametrize( "root_dialect,resource_dialect", [ ( "http://json-schema.org/draft-07/schema#", "https://json-schema.org/draft/2020-12/schema", ), ( "https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft-07/schema#", ), (None, "http://json-schema.org/draft-07/schema#"), ], ) @pytest.mark.parametrize("skip_defaults", [False, True]) @pytest.mark.parametrize("has_resource_id", [False, True]) def test_active_mixed_resource_profiles_reject_in_both_default_modes( root_dialect, resource_dialect, skip_defaults, has_resource_id ): from composio.utils.shared import json_schema_to_model source = { "type": "object", "$defs": { "Value": { "$id": "https://example.test/value", "$schema": resource_dialect, "type": "integer", "default": 3, } }, "properties": {"payload": {"$ref": "https://example.test/value"}}, } if not has_resource_id: source["$defs"]["Value"].pop("$id") source["properties"]["payload"]["$ref"] = "#/$defs/Value" if root_dialect is not None: source["$schema"] = root_dialect with pytest.raises( InvalidSchemaError, match="mixed resource dialects are not supported" ): json_schema_to_model(source, skip_default=skip_defaults) with pytest.raises( InvalidSchemaError, match="mixed resource dialects are not supported" ): json_schema_to_pydantic_type(source) def test_unreferenced_mixed_resource_and_opaque_dialect_data_are_preserved(): from composio.utils.schema_policy import prepare_json_schema_object_policy source = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": {"value": {"type": "integer"}}, "$defs": { "Unused": { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.test/unused", "type": "string", } }, "const": {"$id": "literal", "$schema": "literal"}, } assert ( prepare_json_schema_object_policy(source)["$defs"]["Unused"]["$schema"] == source["$defs"]["Unused"]["$schema"] ) assert prepare_json_schema_object_policy(source)["const"] == source["const"] def test_same_profile_resource_uri_alias_is_supported(): source = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "$defs": { "Value": { "$id": "https://example.test/value", "$schema": "https://json-schema.org/draft-07/schema", "type": "integer", } }, "properties": {"payload": {"$ref": "https://example.test/value"}}, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) adapter.validate_python({"payload": 2}) with pytest.raises(ValidationError): adapter.validate_python({"payload": "bad"}) def test_standalone_dereference_keeps_inactive_draft7_keywords_opaque(): from composio.utils.json_schema import dereference_json_schema source = { "type": "object", "properties": {"value": {"type": "integer"}}, "prefixItems": [{"$ref": "#/missing"}], "dependentSchemas": {"value": {"$ref": "#/missing"}}, } assert dereference_json_schema(source) == source source["$schema"] = "https://json-schema.org/draft/2020-12/schema" from composio.exceptions import JSONSchemaRefResolutionError with pytest.raises(JSONSchemaRefResolutionError, match="Cannot resolve"): dereference_json_schema(source) def test_direct_field_skip_defaults_retains_reference_scope_without_mutating_source(): from composio.utils.shared import json_schema_to_pydantic_field source = { "$defs": {"Value": {"type": "integer", "default": 3}}, "properties": {"value": {"$ref": "#/$defs/Value"}}, } name, annotation, field = json_schema_to_pydantic_field( "value", source["properties"]["value"], [], skip_default=True, root_schema=source, ) assert name == "value" and field.default is None assert TypeAdapter(annotation).validate_python(2) == 2 assert source["$defs"]["Value"]["default"] == 3 def test_owned_models_avoid_collisions_for_reserved_internal_field_names(): from composio.utils.shared import json_schema_to_model source = { "type": "object", "properties": { "__proto__": {"type": "integer"}, "field_proto__": {"type": "string"}, "field_proto___": {"type": "string"}, }, } supplied = {"__proto__": 2, "field_proto__": "first", "field_proto___": "second"} model = json_schema_to_model(source) assert validate_and_serialize_tool_arguments(model, supplied) == supplied def test_pydantic_signature_exposes_valid_authored_optional_default(): parameters = get_pydantic_signature_format_from_schema_params( {"properties": {"count": {"type": "integer", "default": 3}}} ) assert parameters[0].default == 3 assert TypeAdapter(parameters[0].annotation).validate_python(4) == 4 @pytest.mark.parametrize("properties", [None, [], False, "invalid"]) def test_owned_model_rejects_malformed_properties_with_typed_error(properties): from composio.utils.shared import json_schema_to_model with pytest.raises(InvalidSchemaError, match="properties: expected an object"): json_schema_to_model({"type": "object", "properties": properties}) @pytest.mark.parametrize( "schema", [ # A sibling default used to reach DefaultPlan and raise AttributeError. { "type": "object", "properties": {"cfg": {"type": "object", "properties": [], "default": {}}}, }, # Without a default the malformed map converted, then failed at validation. {"type": "object", "properties": {"cfg": {"type": "object", "properties": []}}}, {"type": "object", "patternProperties": ["^a"]}, {"type": "object", "properties": [{"a": 1}]}, ], ) def test_malformed_schema_maps_fail_at_construction_on_every_entry_point(schema): from composio.utils.schema_policy import prepare_json_schema_object_policy from composio.utils.shared import alias_tool_input_schema, json_schema_to_model for construct in ( prepare_json_schema_object_policy, json_schema_to_pydantic_type, json_schema_to_model, alias_tool_input_schema, ): with pytest.raises(InvalidSchemaError, match="expected an object"): construct(schema) def test_pattern_length_limit_applies_to_patterns_and_property_keys(): from composio.utils.schema_contract_constants import MAX_PATTERN_LENGTH from composio.utils.schema_policy import prepare_json_schema_object_policy longest = "a" * MAX_PATTERN_LENGTH prepare_json_schema_object_policy({"type": "string", "pattern": longest}) prepare_json_schema_object_policy( {"type": "object", "patternProperties": {longest: {}}} ) with pytest.raises(InvalidSchemaError, match="pattern exceeds 1024 characters"): prepare_json_schema_object_policy({"type": "string", "pattern": longest + "a"}) with pytest.raises(ValueError, match="pattern exceeds 1024 characters"): prepare_json_schema_object_policy( {"type": "object", "patternProperties": {longest + "a": {}}} ) @pytest.mark.parametrize( "dialect", [ "http://json-schema.org/draft-04/schema#", "https://json-schema.org/draft/2019-09/schema", "urn:example:draft-07", "http://json-schema.org/draft-07/schema#/", None, ], ) def test_unsupported_dialect_in_unused_definition_fails_at_construction(dialect): from composio.utils.schema_policy import prepare_json_schema_object_policy from composio.utils.schema_positions import UnsupportedDialectError source = { "type": "object", "properties": {"value": {"type": "integer"}}, "$defs": {"Unused": {"$schema": dialect, "type": "string"}}, } with pytest.raises(UnsupportedDialectError) as raised: prepare_json_schema_object_policy(source) assert raised.value.code == "unsupported-dialect" assert raised.value.dialect == dialect def test_different_supported_dialect_fails_only_when_its_definition_is_used(): from composio.utils.schema_policy import prepare_json_schema_object_policy source = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": {"value": {"type": "string"}}, "$defs": { "Modern": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string", } }, } prepare_json_schema_object_policy(source) source["properties"]["value"] = {"$ref": "#/$defs/Modern"} with pytest.raises(InvalidSchemaError, match="mixed resource dialects"): prepare_json_schema_object_policy(source) def test_aliases_reject_undeclared_dependency_trigger_that_would_corrupt_valid_field(): source = { "type": "object", "properties": {"$top": {"type": "integer"}, "param_other": {"type": "integer"}}, "dependencies": {"$other": ["param_other"]}, "additionalProperties": False, } TypeAdapter(json_schema_to_pydantic_type(source)).validate_python( {"$top": 1, "param_other": 2} ) with pytest.raises(InvalidSchemaError, match="active dependency constraints"): alias_tool_input_schema(source) def test_aliases_leave_unmapped_dependency_names_unchanged_at_unrenamed_location(): source = { "type": "object", "properties": { "$top": {"type": "integer"}, "nested": { "type": "object", "properties": {"param_other": {"type": "integer"}}, "dependencies": {"$other": ["param_other"]}, "additionalProperties": False, }, }, } aliases = alias_tool_input_schema(source) assert ( aliases.schema["properties"]["nested"]["dependencies"] == source["properties"]["nested"]["dependencies"] ) assert aliases.restore_arguments( {"param_top": 1, "nested": {"param_other": 2}} ) == {"$top": 1, "nested": {"param_other": 2}} def test_valid_identifier_alias_projection_preserves_productive_reference_graph(): source = { "type": "object", "$defs": { "Node": { "type": "object", "properties": { "value": {"type": "integer"}, "next": {"$ref": "#/$defs/Node"}, }, } }, "properties": {"root": {"$ref": "#/$defs/Node"}}, } aliases = alias_tool_input_schema(source) assert aliases.aliases == {} assert ( aliases.schema["$defs"]["Node"]["properties"]["next"]["$ref"] == "#/$defs/Node" ) assert aliases.restore_arguments({"root": {"value": 1}}) == {"root": {"value": 1}} source["properties"]["$top"] = {"type": "integer"} with pytest.raises(InvalidSchemaError, match="recursive renamed properties"): alias_tool_input_schema(source) def test_alias_reference_projection_preserves_annotation_siblings(): source = { "type": "object", "$defs": {"Value": {"type": "integer"}}, "properties": {"$top": {"$ref": "#/$defs/Value", "description": "Authored"}}, } aliases = alias_tool_input_schema(source) assert ( aliases.schema["properties"]["param_top"]["allOf"][1]["description"] == "Authored" ) assert aliases.restore_arguments({"param_top": 2}) == {"$top": 2} @pytest.mark.parametrize( "pattern_schema", [True, {}, {"description": "Annotation"}, {"type": "integer"}] ) def test_alias_projection_keeps_patterns_that_do_not_match_either_name(pattern_schema): source = { "type": "object", "properties": {"$top": {"type": "integer"}}, "patternProperties": {"^x": pattern_schema}, } aliases = alias_tool_input_schema(source) assert aliases.restore_arguments({"param_top": 2, "x": 3}) == {"$top": 2, "x": 3} def test_dynamic_defaults_preserve_open_nested_model_extras(): from composio.utils.shared import json_schema_to_model source = { "type": "object", "properties": { "mapping": { "type": "object", "additionalProperties": { "type": "object", "properties": {"count": {"type": "integer", "default": 3}}, "additionalProperties": True, }, } }, } assert validate_and_serialize_tool_arguments( json_schema_to_model(source), {"mapping": {"entry": {"label": "ok"}}} ) == {"mapping": {"entry": {"count": 3, "label": "ok"}}} def test_legacy_schema_dependencies_validate_the_original_argument_location(): source = { "type": "object", "properties": {"flag": {"type": "boolean"}, "value": {"type": "integer"}}, "dependencies": {"flag": {"required": ["value"]}}, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) adapter.validate_python({"flag": True, "value": 2}) with pytest.raises(ValidationError): adapter.validate_python({"flag": True}) def test_false_definition_references_remain_unsatisfiable_inside_composition_lists(): source = { "type": "object", "definitions": {"Never": False}, "properties": { "forbidden": {"$ref": "#/definitions/Never"}, "safe": {"type": "string"}, }, "allOf": [{}], } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) adapter.validate_python({"safe": "kept"}) with pytest.raises(ValidationError): adapter.validate_python({"forbidden": 2}) def test_dynamic_policy_survives_two_named_object_layers(): from composio.utils.shared import json_schema_to_model source = { "type": "object", "properties": { "outer": { "type": "object", "properties": { "mapping": { "type": "object", "additionalProperties": {"type": "integer"}, } }, } }, } value = {"outer": {"mapping": {"one": 1}}} assert ( validate_and_serialize_tool_arguments(json_schema_to_model(source), value) == value ) with pytest.raises(ValidationError): json_schema_to_model(source).model_validate( {"outer": {"mapping": {"one": "bad"}}} ) def test_unreferenced_draft7_definition_payload_does_not_narrow_the_root(): source = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "$defs": {"Unreferenced": {"type": "opaque-provider-type", "minLength": 2}}, "properties": {"value": {"type": "integer"}}, } adapter = TypeAdapter(json_schema_to_pydantic_type(source)) adapter.validate_python({"value": 2}) with pytest.raises(ValidationError): adapter.validate_python({"value": "bad"}) def test_legacy_empty_type_choices_remain_fail_closed_in_owned_conversion(): adapter = TypeAdapter(json_schema_to_pydantic_type({"type": []})) assert adapter.json_schema() == {"not": {}} for value in (None, True, 1, "text", [], {}): with pytest.raises(ValidationError): adapter.validate_python(value) def test_alias_namespace_rejects_patterns_admitting_the_generated_wire_name(): source = { "type": "object", "properties": {"$top": {"type": "integer"}}, "patternProperties": {"^param_": True}, } TypeAdapter(json_schema_to_pydantic_type(source)).validate_python( {"$top": 1, "param_top": "extra"} ) with pytest.raises( InvalidSchemaError, match="conflicts with a pattern argument namespace" ): alias_tool_input_schema(source) def test_aliasing_rejects_malformed_composed_properties_as_a_schema_error(): source = { "type": "object", "properties": {"$top": {"type": "integer"}}, "allOf": [{"properties": False}], "additionalProperties": True, } with pytest.raises(InvalidSchemaError): alias_tool_input_schema(source) def test_aliases_preserve_boolean_composition_members_and_unmapped_tuple_slots(): source = { "type": "object", "properties": { "$top": {"type": "integer"}, "rows": { "anyOf": [ False, { "type": "array", "items": [ { "type": "object", "properties": {"$nested": {"type": "integer"}}, }, {"type": "string"}, ], "additionalItems": False, }, ] }, }, "allOf": [True, {"required": ["$top"]}], } aliases = alias_tool_input_schema(source) wire = {"param_top": 1, "rows": [{"param_nested": 2}, "plain"]} from composio.utils.shared import json_schema_to_model json_schema_to_model(aliases.schema).model_validate(wire) assert aliases.restore_arguments(wire) == { "$top": 1, "rows": [{"$nested": 2}, "plain"], } def test_type_conversion_applies_dynamic_policy_inside_named_object_layers(): source = { "type": "object", "properties": { "outer": { "type": "object", "properties": { "mapping": { "type": "object", "additionalProperties": {"type": "integer"}, } }, } }, } value = {"outer": {"mapping": {"one": 1}}} assert ( TypeAdapter(json_schema_to_pydantic_type(source)) .validate_python(value) .model_dump() == value ) def test_false_array_items_preserve_partial_property_annotations(): source = { "type": "object", "properties": { "empty": {"type": "array", "items": False, "description": "Empty"} }, } annotation = json_schema_to_pydantic_type(source) TypeAdapter(annotation).validate_python({"empty": []}) assert ( json_schema_from_pydantic_type(annotation)["properties"]["empty"]["description"] == "Empty" ) @pytest.mark.parametrize("key", ["$top", "param_top"]) @pytest.mark.parametrize("constraint", ["const", "enum"]) def test_ancestor_literals_reject_nested_aliases_for_original_and_wire_names( key, constraint ): literal = {"nested": {key: 1}} source = { "type": "object", "properties": { "nested": {"type": "object", "properties": {"$top": {"type": "integer"}}} }, constraint: [literal] if constraint == "enum" else literal, } with pytest.raises(InvalidSchemaError, match="changes const/enum object data"): alias_tool_input_schema(source) @pytest.mark.parametrize("nesting", ["array", "nested_array", "tuple", "prefix"]) def test_ancestor_literals_reject_actual_array_item_alias_changes(nesting): item = {"type": "object", "properties": {"$top": {"type": "integer"}}} if nesting == "nested_array": rows = {"type": "array", "items": {"type": "array", "items": item}} literal = [[{"param_top": 1}]] elif nesting in ("tuple", "prefix"): rows = { "type": "array", "prefixItems" if nesting == "prefix" else "items": [item], } literal = [{"param_top": 1}] else: rows = {"type": "array", "items": item} literal = [{"param_top": 1}] source = { "type": "object", "properties": {"rows": rows}, "const": {"rows": literal}, } if nesting == "prefix": source["$schema"] = "https://json-schema.org/draft/2020-12/schema" with pytest.raises(InvalidSchemaError, match="changes const/enum object data"): alias_tool_input_schema(source) @pytest.mark.parametrize( "literal", [{}, {"nested": {"safe": 2}}, {"metadata": {"param_top": 1}}] ) def test_ancestor_literal_guard_preserves_unaffected_data_and_omitted_aliases(literal): source = { "type": "object", "properties": { "nested": { "type": "object", "properties": { "$top": {"type": "integer"}, "safe": {"type": "integer"}, }, }, "metadata": {"type": "object"}, }, "enum": [literal], } aliases = alias_tool_input_schema(source) assert aliases.schema["enum"] == [literal] def test_ancestor_literal_guard_keeps_unmapped_tuple_slots_and_scalar_literals(): source = { "type": "object", "properties": { "rows": { "type": "array", "items": [ { "type": "object", "properties": { "$top": {"type": "integer"}, "safe": {"type": "integer"}, }, }, {"type": "object", "properties": {"safe": {"type": "integer"}}}, ], } }, "enum": [ {"rows": [{"safe": 1}, {"safe": 2}]}, "unsatisfiable scalar", {"rows": []}, ], } aliases = alias_tool_input_schema(source) assert aliases.schema["enum"] == source["enum"]