We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Optimize use of jsonschema.validate()
It could be interesting to investigate if the fastjsonschema lib would give us better perfs :)

I marked this as easy-pick since everything happens in `schema_validation.py`

https://github.com/horejsek/python-fastjsonschema/

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kinto/schema_validation.py`
Content:
```
1 import colander
2 from jsonschema import ValidationError, SchemaError, RefResolutionError, validate
3 
4 try:  # pragma: no cover
5     from jsonschema import Draft7Validator as DraftValidator
6 except ImportError:
7     from jsonschema import Draft4Validator as DraftValidator
8 
9 from pyramid.settings import asbool
10 
11 from kinto.core import utils
12 from kinto.core.errors import raise_invalid
13 from kinto.views import object_exists_or_404
14 
15 
16 class JSONSchemaMapping(colander.SchemaNode):
17     def schema_type(self, **kw):
18         return colander.Mapping(unknown="preserve")
19 
20     def deserialize(self, cstruct=colander.null):
21         # Start by deserializing a simple mapping.
22         validated = super().deserialize(cstruct)
23 
24         # In case it is optional in parent schema.
25         if not validated or validated in (colander.null, colander.drop):
26             return validated
27         try:
28             check_schema(validated)
29         except ValidationError as e:
30             self.raise_invalid(e.message)
31         return validated
32 
33 
34 def check_schema(data):
35     try:
36         DraftValidator.check_schema(data)
37     except SchemaError as e:
38         message = e.path.pop() + e.message
39         raise ValidationError(message)
40 
41 
42 def validate_schema(data, schema, ignore_fields=[]):
43     required_fields = [f for f in schema.get("required", []) if f not in ignore_fields]
44     # jsonschema doesn't accept 'required': [] yet.
45     # See https://github.com/Julian/jsonschema/issues/337.
46     # In the meantime, strip out 'required' if no other fields are required.
47     if required_fields:
48         schema = {**schema, "required": required_fields}
49     else:
50         schema = {f: v for f, v in schema.items() if f != "required"}
51 
52     data = {f: v for f, v in data.items() if f not in ignore_fields}
53 
54     try:
55         validate(data, schema)
56     except ValidationError as e:
57         if e.path:
58             field = e.path[-1]
59         elif e.validator_value:
60             field = e.validator_value[-1]
61         else:
62             field = e.schema_path[-1]
63         e.field = field
64         raise e
65     # Raise an error here if a reference in the schema doesn't resolve.
66     # jsonschema doesn't provide schema validation checking upon creation yet,
67     # it must be validated against data.
68     # See https://github.com/Julian/jsonschema/issues/399
69     # For future support https://github.com/Julian/jsonschema/issues/346.
70     except RefResolutionError as e:
71         raise e
72 
73 
74 def validate_from_bucket_schema_or_400(data, resource_name, request, ignore_fields=[]):
75     """Lookup in the parent objects if a schema was defined for this resource.
76 
77     If the schema validation feature is enabled, if a schema is/are defined, and if the
78     data does not validate it/them, then it raises a 400 exception.
79     """
80     settings = request.registry.settings
81     schema_validation = "experimental_collection_schema_validation"
82     # If disabled from settings, do nothing.
83     if not asbool(settings.get(schema_validation)):
84         return
85 
86     bucket_id = request.matchdict["bucket_id"]
87     bucket_uri = utils.instance_uri(request, "bucket", id=bucket_id)
88     buckets = request.bound_data.setdefault("buckets", {})
89     if bucket_uri not in buckets:
90         # Unknown yet, fetch from storage.
91         bucket = object_exists_or_404(
92             request, resource_name="bucket", parent_id="", object_id=bucket_id
93         )
94         buckets[bucket_uri] = bucket
95 
96     # Let's see if the bucket defines a schema for this resource.
97     metadata_field = f"{resource_name}:schema"
98     bucket = buckets[bucket_uri]
99     if metadata_field not in bucket:
100         return
101 
102     # Validate or fail with 400.
103     schema = bucket[metadata_field]
104     try:
105         validate_schema(data, schema, ignore_fields=ignore_fields)
106     except ValidationError as e:
107         raise_invalid(request, name=e.field, description=e.message)
108     except RefResolutionError as e:
109         raise_invalid(request, name="schema", description=str(e))
110
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/kinto/schema_validation.py b/kinto/schema_validation.py
--- a/kinto/schema_validation.py
+++ b/kinto/schema_validation.py
@@ -1,5 +1,6 @@
 import colander
-from jsonschema import ValidationError, SchemaError, RefResolutionError, validate
+from jsonschema import ValidationError, SchemaError, RefResolutionError
+from jsonschema.validators import validator_for
 
 try:  # pragma: no cover
     from jsonschema import Draft7Validator as DraftValidator
@@ -39,6 +40,34 @@
         raise ValidationError(message)
 
 
+# Module level global that stores a version of every possible schema (as a <class 'dict'>)
+# turned into a jsonschema instance (as <class 'jsonschema.validators.Validator'>).
+_schema_cache = {}
+
+
+def validate(data, schema):
+    """Raise a ValidationError or a RefResolutionError if the data doesn't validate
+    with the given schema.
+
+    Note that this function is just a "wrapper" on `jsonschema.validate()` but with
+    some memoization based on the schema for better repeat performance.
+    """
+    # Because the schema is a dict, it can't be used as a hash key so it needs to be
+    # "transformed" to something that is hashable. The quickest solution is to convert
+    # it to a string.
+    # Note that the order of the dict will determine the string it becomes. The solution
+    # to that would a canonical serializer like `json.dumps(..., sort_keys=True)` but it's
+    # overkill since the assumption is that the schema is very unlikely to be exactly
+    # the same but different order.
+    cache_key = str(schema)
+    if cache_key not in _schema_cache:
+        # This is essentially what the `jsonschema.validate()` shortcut function does.
+        cls = validator_for(schema)
+        cls.check_schema(schema)
+        _schema_cache[cache_key] = cls(schema)
+    return _schema_cache[cache_key].validate(data)
+
+
 def validate_schema(data, schema, ignore_fields=[]):
     required_fields = [f for f in schema.get("required", []) if f not in ignore_fields]
     # jsonschema doesn't accept 'required': [] yet.

{"golden_diff": "diff --git a/kinto/schema_validation.py b/kinto/schema_validation.py\n--- a/kinto/schema_validation.py\n+++ b/kinto/schema_validation.py\n@@ -1,5 +1,6 @@\n import colander\n-from jsonschema import ValidationError, SchemaError, RefResolutionError, validate\n+from jsonschema import ValidationError, SchemaError, RefResolutionError\n+from jsonschema.validators import validator_for\n \n try:  # pragma: no cover\n     from jsonschema import Draft7Validator as DraftValidator\n@@ -39,6 +40,34 @@\n         raise ValidationError(message)\n \n \n+# Module level global that stores a version of every possible schema (as a <class 'dict'>)\n+# turned into a jsonschema instance (as <class 'jsonschema.validators.Validator'>).\n+_schema_cache = {}\n+\n+\n+def validate(data, schema):\n+    \"\"\"Raise a ValidationError or a RefResolutionError if the data doesn't validate\n+    with the given schema.\n+\n+    Note that this function is just a \"wrapper\" on `jsonschema.validate()` but with\n+    some memoization based on the schema for better repeat performance.\n+    \"\"\"\n+    # Because the schema is a dict, it can't be used as a hash key so it needs to be\n+    # \"transformed\" to something that is hashable. The quickest solution is to convert\n+    # it to a string.\n+    # Note that the order of the dict will determine the string it becomes. The solution\n+    # to that would a canonical serializer like `json.dumps(..., sort_keys=True)` but it's\n+    # overkill since the assumption is that the schema is very unlikely to be exactly\n+    # the same but different order.\n+    cache_key = str(schema)\n+    if cache_key not in _schema_cache:\n+        # This is essentially what the `jsonschema.validate()` shortcut function does.\n+        cls = validator_for(schema)\n+        cls.check_schema(schema)\n+        _schema_cache[cache_key] = cls(schema)\n+    return _schema_cache[cache_key].validate(data)\n+\n+\n def validate_schema(data, schema, ignore_fields=[]):\n     required_fields = [f for f in schema.get(\"required\", []) if f not in ignore_fields]\n     # jsonschema doesn't accept 'required': [] yet.\n", "issue": "Optimize use of jsonschema.validate()\nIt could be interesting to investigate if the fastjsonschema lib would give us better perfs :)\r\n\r\nI marked this as easy-pick since everything happens in `schema_validation.py`\r\n\r\nhttps://github.com/horejsek/python-fastjsonschema/\n", "before_files": [{"content": "import colander\nfrom jsonschema import ValidationError, SchemaError, RefResolutionError, validate\n\ntry:  # pragma: no cover\n    from jsonschema import Draft7Validator as DraftValidator\nexcept ImportError:\n    from jsonschema import Draft4Validator as DraftValidator\n\nfrom pyramid.settings import asbool\n\nfrom kinto.core import utils\nfrom kinto.core.errors import raise_invalid\nfrom kinto.views import object_exists_or_404\n\n\nclass JSONSchemaMapping(colander.SchemaNode):\n    def schema_type(self, **kw):\n        return colander.Mapping(unknown=\"preserve\")\n\n    def deserialize(self, cstruct=colander.null):\n        # Start by deserializing a simple mapping.\n        validated = super().deserialize(cstruct)\n\n        # In case it is optional in parent schema.\n        if not validated or validated in (colander.null, colander.drop):\n            return validated\n        try:\n            check_schema(validated)\n        except ValidationError as e:\n            self.raise_invalid(e.message)\n        return validated\n\n\ndef check_schema(data):\n    try:\n        DraftValidator.check_schema(data)\n    except SchemaError as e:\n        message = e.path.pop() + e.message\n        raise ValidationError(message)\n\n\ndef validate_schema(data, schema, ignore_fields=[]):\n    required_fields = [f for f in schema.get(\"required\", []) if f not in ignore_fields]\n    # jsonschema doesn't accept 'required': [] yet.\n    # See https://github.com/Julian/jsonschema/issues/337.\n    # In the meantime, strip out 'required' if no other fields are required.\n    if required_fields:\n        schema = {**schema, \"required\": required_fields}\n    else:\n        schema = {f: v for f, v in schema.items() if f != \"required\"}\n\n    data = {f: v for f, v in data.items() if f not in ignore_fields}\n\n    try:\n        validate(data, schema)\n    except ValidationError as e:\n        if e.path:\n            field = e.path[-1]\n        elif e.validator_value:\n            field = e.validator_value[-1]\n        else:\n            field = e.schema_path[-1]\n        e.field = field\n        raise e\n    # Raise an error here if a reference in the schema doesn't resolve.\n    # jsonschema doesn't provide schema validation checking upon creation yet,\n    # it must be validated against data.\n    # See https://github.com/Julian/jsonschema/issues/399\n    # For future support https://github.com/Julian/jsonschema/issues/346.\n    except RefResolutionError as e:\n        raise e\n\n\ndef validate_from_bucket_schema_or_400(data, resource_name, request, ignore_fields=[]):\n    \"\"\"Lookup in the parent objects if a schema was defined for this resource.\n\n    If the schema validation feature is enabled, if a schema is/are defined, and if the\n    data does not validate it/them, then it raises a 400 exception.\n    \"\"\"\n    settings = request.registry.settings\n    schema_validation = \"experimental_collection_schema_validation\"\n    # If disabled from settings, do nothing.\n    if not asbool(settings.get(schema_validation)):\n        return\n\n    bucket_id = request.matchdict[\"bucket_id\"]\n    bucket_uri = utils.instance_uri(request, \"bucket\", id=bucket_id)\n    buckets = request.bound_data.setdefault(\"buckets\", {})\n    if bucket_uri not in buckets:\n        # Unknown yet, fetch from storage.\n        bucket = object_exists_or_404(\n            request, resource_name=\"bucket\", parent_id=\"\", object_id=bucket_id\n        )\n        buckets[bucket_uri] = bucket\n\n    # Let's see if the bucket defines a schema for this resource.\n    metadata_field = f\"{resource_name}:schema\"\n    bucket = buckets[bucket_uri]\n    if metadata_field not in bucket:\n        return\n\n    # Validate or fail with 400.\n    schema = bucket[metadata_field]\n    try:\n        validate_schema(data, schema, ignore_fields=ignore_fields)\n    except ValidationError as e:\n        raise_invalid(request, name=e.field, description=e.message)\n    except RefResolutionError as e:\n        raise_invalid(request, name=\"schema\", description=str(e))\n", "path": "kinto/schema_validation.py"}], "after_files": [{"content": "import colander\nfrom jsonschema import ValidationError, SchemaError, RefResolutionError\nfrom jsonschema.validators import validator_for\n\ntry:  # pragma: no cover\n    from jsonschema import Draft7Validator as DraftValidator\nexcept ImportError:\n    from jsonschema import Draft4Validator as DraftValidator\n\nfrom pyramid.settings import asbool\n\nfrom kinto.core import utils\nfrom kinto.core.errors import raise_invalid\nfrom kinto.views import object_exists_or_404\n\n\nclass JSONSchemaMapping(colander.SchemaNode):\n    def schema_type(self, **kw):\n        return colander.Mapping(unknown=\"preserve\")\n\n    def deserialize(self, cstruct=colander.null):\n        # Start by deserializing a simple mapping.\n        validated = super().deserialize(cstruct)\n\n        # In case it is optional in parent schema.\n        if not validated or validated in (colander.null, colander.drop):\n            return validated\n        try:\n            check_schema(validated)\n        except ValidationError as e:\n            self.raise_invalid(e.message)\n        return validated\n\n\ndef check_schema(data):\n    try:\n        DraftValidator.check_schema(data)\n    except SchemaError as e:\n        message = e.path.pop() + e.message\n        raise ValidationError(message)\n\n\n# Module level global that stores a version of every possible schema (as a <class 'dict'>)\n# turned into a jsonschema instance (as <class 'jsonschema.validators.Validator'>).\n_schema_cache = {}\n\n\ndef validate(data, schema):\n    \"\"\"Raise a ValidationError or a RefResolutionError if the data doesn't validate\n    with the given schema.\n\n    Note that this function is just a \"wrapper\" on `jsonschema.validate()` but with\n    some memoization based on the schema for better repeat performance.\n    \"\"\"\n    # Because the schema is a dict, it can't be used as a hash key so it needs to be\n    # \"transformed\" to something that is hashable. The quickest solution is to convert\n    # it to a string.\n    # Note that the order of the dict will determine the string it becomes. The solution\n    # to that would a canonical serializer like `json.dumps(..., sort_keys=True)` but it's\n    # overkill since the assumption is that the schema is very unlikely to be exactly\n    # the same but different order.\n    cache_key = str(schema)\n    if cache_key not in _schema_cache:\n        # This is essentially what the `jsonschema.validate()` shortcut function does.\n        cls = validator_for(schema)\n        cls.check_schema(schema)\n        _schema_cache[cache_key] = cls(schema)\n    return _schema_cache[cache_key].validate(data)\n\n\ndef validate_schema(data, schema, ignore_fields=[]):\n    required_fields = [f for f in schema.get(\"required\", []) if f not in ignore_fields]\n    # jsonschema doesn't accept 'required': [] yet.\n    # See https://github.com/Julian/jsonschema/issues/337.\n    # In the meantime, strip out 'required' if no other fields are required.\n    if required_fields:\n        schema = {**schema, \"required\": required_fields}\n    else:\n        schema = {f: v for f, v in schema.items() if f != \"required\"}\n\n    data = {f: v for f, v in data.items() if f not in ignore_fields}\n\n    try:\n        validate(data, schema)\n    except ValidationError as e:\n        if e.path:\n            field = e.path[-1]\n        elif e.validator_value:\n            field = e.validator_value[-1]\n        else:\n            field = e.schema_path[-1]\n        e.field = field\n        raise e\n    # Raise an error here if a reference in the schema doesn't resolve.\n    # jsonschema doesn't provide schema validation checking upon creation yet,\n    # it must be validated against data.\n    # See https://github.com/Julian/jsonschema/issues/399\n    # For future support https://github.com/Julian/jsonschema/issues/346.\n    except RefResolutionError as e:\n        raise e\n\n\ndef validate_from_bucket_schema_or_400(data, resource_name, request, ignore_fields=[]):\n    \"\"\"Lookup in the parent objects if a schema was defined for this resource.\n\n    If the schema validation feature is enabled, if a schema is/are defined, and if the\n    data does not validate it/them, then it raises a 400 exception.\n    \"\"\"\n    settings = request.registry.settings\n    schema_validation = \"experimental_collection_schema_validation\"\n    # If disabled from settings, do nothing.\n    if not asbool(settings.get(schema_validation)):\n        return\n\n    bucket_id = request.matchdict[\"bucket_id\"]\n    bucket_uri = utils.instance_uri(request, \"bucket\", id=bucket_id)\n    buckets = request.bound_data.setdefault(\"buckets\", {})\n    if bucket_uri not in buckets:\n        # Unknown yet, fetch from storage.\n        bucket = object_exists_or_404(\n            request, resource_name=\"bucket\", parent_id=\"\", object_id=bucket_id\n        )\n        buckets[bucket_uri] = bucket\n\n    # Let's see if the bucket defines a schema for this resource.\n    metadata_field = f\"{resource_name}:schema\"\n    bucket = buckets[bucket_uri]\n    if metadata_field not in bucket:\n        return\n\n    # Validate or fail with 400.\n    schema = bucket[metadata_field]\n    try:\n        validate_schema(data, schema, ignore_fields=ignore_fields)\n    except ValidationError as e:\n        raise_invalid(request, name=e.field, description=e.message)\n    except RefResolutionError as e:\n        raise_invalid(request, name=\"schema\", description=str(e))\n", "path": "kinto/schema_validation.py"}]}