We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
RC versions of dependencies don't satisfy the run-time dependency checker; `Need Twisted>=18.9.0, but got Twisted==21.7.0rc3` (1.54.0rc1 suspected regression)
When deploying `1.54.0rc1` to matrix.org and some personal homeservers that had an RC of Twisted installed, the dependency checker complained:

`Need Twisted>=18.9.0, but got Twisted==21.7.0rc3`

For some reason it appears that being an RC makes the version insufficient, even though the version is higher. Using the non-RC version works fine.

Possibly fall-out from https://github.com/matrix-org/synapse/pull/12088?

I wonder if the same logic as e.g. `pip` is being used, in that it would never select an RC version as being satisfactory unless it was a hard match?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `synapse/util/check_dependencies.py`
Content:
```
1 #  Copyright 2022 The Matrix.org Foundation C.I.C.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14 #
15 
16 """
17 This module exposes a single function which checks synapse's dependencies are present
18 and correctly versioned. It makes use of `importlib.metadata` to do so. The details
19 are a bit murky: there's no easy way to get a map from "extras" to the packages they
20 require. But this is probably just symptomatic of Python's package management.
21 """
22 
23 import logging
24 from typing import Iterable, NamedTuple, Optional
25 
26 from packaging.requirements import Requirement
27 
28 DISTRIBUTION_NAME = "matrix-synapse"
29 
30 try:
31     from importlib import metadata
32 except ImportError:
33     import importlib_metadata as metadata  # type: ignore[no-redef]
34 
35 __all__ = ["check_requirements"]
36 
37 
38 class DependencyException(Exception):
39     @property
40     def message(self) -> str:
41         return "\n".join(
42             [
43                 "Missing Requirements: %s" % (", ".join(self.dependencies),),
44                 "To install run:",
45                 "    pip install --upgrade --force %s" % (" ".join(self.dependencies),),
46                 "",
47             ]
48         )
49 
50     @property
51     def dependencies(self) -> Iterable[str]:
52         for i in self.args[0]:
53             yield '"' + i + '"'
54 
55 
56 DEV_EXTRAS = {"lint", "mypy", "test", "dev"}
57 RUNTIME_EXTRAS = (
58     set(metadata.metadata(DISTRIBUTION_NAME).get_all("Provides-Extra")) - DEV_EXTRAS
59 )
60 VERSION = metadata.version(DISTRIBUTION_NAME)
61 
62 
63 def _is_dev_dependency(req: Requirement) -> bool:
64     return req.marker is not None and any(
65         req.marker.evaluate({"extra": e}) for e in DEV_EXTRAS
66     )
67 
68 
69 class Dependency(NamedTuple):
70     requirement: Requirement
71     must_be_installed: bool
72 
73 
74 def _generic_dependencies() -> Iterable[Dependency]:
75     """Yield pairs (requirement, must_be_installed)."""
76     requirements = metadata.requires(DISTRIBUTION_NAME)
77     assert requirements is not None
78     for raw_requirement in requirements:
79         req = Requirement(raw_requirement)
80         if _is_dev_dependency(req):
81             continue
82 
83         # https://packaging.pypa.io/en/latest/markers.html#usage notes that
84         #   > Evaluating an extra marker with no environment is an error
85         # so we pass in a dummy empty extra value here.
86         must_be_installed = req.marker is None or req.marker.evaluate({"extra": ""})
87         yield Dependency(req, must_be_installed)
88 
89 
90 def _dependencies_for_extra(extra: str) -> Iterable[Dependency]:
91     """Yield additional dependencies needed for a given `extra`."""
92     requirements = metadata.requires(DISTRIBUTION_NAME)
93     assert requirements is not None
94     for raw_requirement in requirements:
95         req = Requirement(raw_requirement)
96         if _is_dev_dependency(req):
97             continue
98         # Exclude mandatory deps by only selecting deps needed with this extra.
99         if (
100             req.marker is not None
101             and req.marker.evaluate({"extra": extra})
102             and not req.marker.evaluate({"extra": ""})
103         ):
104             yield Dependency(req, True)
105 
106 
107 def _not_installed(requirement: Requirement, extra: Optional[str] = None) -> str:
108     if extra:
109         return (
110             f"Synapse {VERSION} needs {requirement.name} for {extra}, "
111             f"but it is not installed"
112         )
113     else:
114         return f"Synapse {VERSION} needs {requirement.name}, but it is not installed"
115 
116 
117 def _incorrect_version(
118     requirement: Requirement, got: str, extra: Optional[str] = None
119 ) -> str:
120     if extra:
121         return (
122             f"Synapse {VERSION} needs {requirement} for {extra}, "
123             f"but got {requirement.name}=={got}"
124         )
125     else:
126         return (
127             f"Synapse {VERSION} needs {requirement}, but got {requirement.name}=={got}"
128         )
129 
130 
131 def check_requirements(extra: Optional[str] = None) -> None:
132     """Check Synapse's dependencies are present and correctly versioned.
133 
134     If provided, `extra` must be the name of an pacakging extra (e.g. "saml2" in
135     `pip install matrix-synapse[saml2]`).
136 
137     If `extra` is None, this function checks that
138     - all mandatory dependencies are installed and correctly versioned, and
139     - each optional dependency that's installed is correctly versioned.
140 
141     If `extra` is not None, this function checks that
142     - the dependencies needed for that extra are installed and correctly versioned.
143 
144     :raises DependencyException: if a dependency is missing or incorrectly versioned.
145     :raises ValueError: if this extra does not exist.
146     """
147     # First work out which dependencies are required, and which are optional.
148     if extra is None:
149         dependencies = _generic_dependencies()
150     elif extra in RUNTIME_EXTRAS:
151         dependencies = _dependencies_for_extra(extra)
152     else:
153         raise ValueError(f"Synapse {VERSION} does not provide the feature '{extra}'")
154 
155     deps_unfulfilled = []
156     errors = []
157 
158     for (requirement, must_be_installed) in dependencies:
159         try:
160             dist: metadata.Distribution = metadata.distribution(requirement.name)
161         except metadata.PackageNotFoundError:
162             if must_be_installed:
163                 deps_unfulfilled.append(requirement.name)
164                 errors.append(_not_installed(requirement, extra))
165         else:
166             if not requirement.specifier.contains(dist.version):
167                 deps_unfulfilled.append(requirement.name)
168                 errors.append(_incorrect_version(requirement, dist.version, extra))
169 
170     if deps_unfulfilled:
171         for err in errors:
172             logging.error(err)
173 
174         raise DependencyException(deps_unfulfilled)
175
```
--- 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/synapse/util/check_dependencies.py b/synapse/util/check_dependencies.py
--- a/synapse/util/check_dependencies.py
+++ b/synapse/util/check_dependencies.py
@@ -163,7 +163,8 @@
                 deps_unfulfilled.append(requirement.name)
                 errors.append(_not_installed(requirement, extra))
         else:
-            if not requirement.specifier.contains(dist.version):
+            # We specify prereleases=True to allow prereleases such as RCs.
+            if not requirement.specifier.contains(dist.version, prereleases=True):
                 deps_unfulfilled.append(requirement.name)
                 errors.append(_incorrect_version(requirement, dist.version, extra))

{"golden_diff": "diff --git a/synapse/util/check_dependencies.py b/synapse/util/check_dependencies.py\n--- a/synapse/util/check_dependencies.py\n+++ b/synapse/util/check_dependencies.py\n@@ -163,7 +163,8 @@\n                 deps_unfulfilled.append(requirement.name)\n                 errors.append(_not_installed(requirement, extra))\n         else:\n-            if not requirement.specifier.contains(dist.version):\n+            # We specify prereleases=True to allow prereleases such as RCs.\n+            if not requirement.specifier.contains(dist.version, prereleases=True):\n                 deps_unfulfilled.append(requirement.name)\n                 errors.append(_incorrect_version(requirement, dist.version, extra))\n", "issue": "RC versions of dependencies don't satisfy the run-time dependency checker; `Need Twisted>=18.9.0, but got Twisted==21.7.0rc3` (1.54.0rc1 suspected regression)\nWhen deploying `1.54.0rc1` to matrix.org and some personal homeservers that had an RC of Twisted installed, the dependency checker complained:\r\n\r\n`Need Twisted>=18.9.0, but got Twisted==21.7.0rc3`\r\n\r\nFor some reason it appears that being an RC makes the version insufficient, even though the version is higher. Using the non-RC version works fine.\r\n\r\nPossibly fall-out from https://github.com/matrix-org/synapse/pull/12088?\r\n\r\nI wonder if the same logic as e.g. `pip` is being used, in that it would never select an RC version as being satisfactory unless it was a hard match?\n", "before_files": [{"content": "#  Copyright 2022 The Matrix.org Foundation C.I.C.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\");\n#  you may not use this file except in compliance with the License.\n#  You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  Unless required by applicable law or agreed to in writing, software\n#  distributed under the License is distributed on an \"AS IS\" BASIS,\n#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#  See the License for the specific language governing permissions and\n#  limitations under the License.\n#\n\n\"\"\"\nThis module exposes a single function which checks synapse's dependencies are present\nand correctly versioned. It makes use of `importlib.metadata` to do so. The details\nare a bit murky: there's no easy way to get a map from \"extras\" to the packages they\nrequire. But this is probably just symptomatic of Python's package management.\n\"\"\"\n\nimport logging\nfrom typing import Iterable, NamedTuple, Optional\n\nfrom packaging.requirements import Requirement\n\nDISTRIBUTION_NAME = \"matrix-synapse\"\n\ntry:\n    from importlib import metadata\nexcept ImportError:\n    import importlib_metadata as metadata  # type: ignore[no-redef]\n\n__all__ = [\"check_requirements\"]\n\n\nclass DependencyException(Exception):\n    @property\n    def message(self) -> str:\n        return \"\\n\".join(\n            [\n                \"Missing Requirements: %s\" % (\", \".join(self.dependencies),),\n                \"To install run:\",\n                \"    pip install --upgrade --force %s\" % (\" \".join(self.dependencies),),\n                \"\",\n            ]\n        )\n\n    @property\n    def dependencies(self) -> Iterable[str]:\n        for i in self.args[0]:\n            yield '\"' + i + '\"'\n\n\nDEV_EXTRAS = {\"lint\", \"mypy\", \"test\", \"dev\"}\nRUNTIME_EXTRAS = (\n    set(metadata.metadata(DISTRIBUTION_NAME).get_all(\"Provides-Extra\")) - DEV_EXTRAS\n)\nVERSION = metadata.version(DISTRIBUTION_NAME)\n\n\ndef _is_dev_dependency(req: Requirement) -> bool:\n    return req.marker is not None and any(\n        req.marker.evaluate({\"extra\": e}) for e in DEV_EXTRAS\n    )\n\n\nclass Dependency(NamedTuple):\n    requirement: Requirement\n    must_be_installed: bool\n\n\ndef _generic_dependencies() -> Iterable[Dependency]:\n    \"\"\"Yield pairs (requirement, must_be_installed).\"\"\"\n    requirements = metadata.requires(DISTRIBUTION_NAME)\n    assert requirements is not None\n    for raw_requirement in requirements:\n        req = Requirement(raw_requirement)\n        if _is_dev_dependency(req):\n            continue\n\n        # https://packaging.pypa.io/en/latest/markers.html#usage notes that\n        #   > Evaluating an extra marker with no environment is an error\n        # so we pass in a dummy empty extra value here.\n        must_be_installed = req.marker is None or req.marker.evaluate({\"extra\": \"\"})\n        yield Dependency(req, must_be_installed)\n\n\ndef _dependencies_for_extra(extra: str) -> Iterable[Dependency]:\n    \"\"\"Yield additional dependencies needed for a given `extra`.\"\"\"\n    requirements = metadata.requires(DISTRIBUTION_NAME)\n    assert requirements is not None\n    for raw_requirement in requirements:\n        req = Requirement(raw_requirement)\n        if _is_dev_dependency(req):\n            continue\n        # Exclude mandatory deps by only selecting deps needed with this extra.\n        if (\n            req.marker is not None\n            and req.marker.evaluate({\"extra\": extra})\n            and not req.marker.evaluate({\"extra\": \"\"})\n        ):\n            yield Dependency(req, True)\n\n\ndef _not_installed(requirement: Requirement, extra: Optional[str] = None) -> str:\n    if extra:\n        return (\n            f\"Synapse {VERSION} needs {requirement.name} for {extra}, \"\n            f\"but it is not installed\"\n        )\n    else:\n        return f\"Synapse {VERSION} needs {requirement.name}, but it is not installed\"\n\n\ndef _incorrect_version(\n    requirement: Requirement, got: str, extra: Optional[str] = None\n) -> str:\n    if extra:\n        return (\n            f\"Synapse {VERSION} needs {requirement} for {extra}, \"\n            f\"but got {requirement.name}=={got}\"\n        )\n    else:\n        return (\n            f\"Synapse {VERSION} needs {requirement}, but got {requirement.name}=={got}\"\n        )\n\n\ndef check_requirements(extra: Optional[str] = None) -> None:\n    \"\"\"Check Synapse's dependencies are present and correctly versioned.\n\n    If provided, `extra` must be the name of an pacakging extra (e.g. \"saml2\" in\n    `pip install matrix-synapse[saml2]`).\n\n    If `extra` is None, this function checks that\n    - all mandatory dependencies are installed and correctly versioned, and\n    - each optional dependency that's installed is correctly versioned.\n\n    If `extra` is not None, this function checks that\n    - the dependencies needed for that extra are installed and correctly versioned.\n\n    :raises DependencyException: if a dependency is missing or incorrectly versioned.\n    :raises ValueError: if this extra does not exist.\n    \"\"\"\n    # First work out which dependencies are required, and which are optional.\n    if extra is None:\n        dependencies = _generic_dependencies()\n    elif extra in RUNTIME_EXTRAS:\n        dependencies = _dependencies_for_extra(extra)\n    else:\n        raise ValueError(f\"Synapse {VERSION} does not provide the feature '{extra}'\")\n\n    deps_unfulfilled = []\n    errors = []\n\n    for (requirement, must_be_installed) in dependencies:\n        try:\n            dist: metadata.Distribution = metadata.distribution(requirement.name)\n        except metadata.PackageNotFoundError:\n            if must_be_installed:\n                deps_unfulfilled.append(requirement.name)\n                errors.append(_not_installed(requirement, extra))\n        else:\n            if not requirement.specifier.contains(dist.version):\n                deps_unfulfilled.append(requirement.name)\n                errors.append(_incorrect_version(requirement, dist.version, extra))\n\n    if deps_unfulfilled:\n        for err in errors:\n            logging.error(err)\n\n        raise DependencyException(deps_unfulfilled)\n", "path": "synapse/util/check_dependencies.py"}], "after_files": [{"content": "#  Copyright 2022 The Matrix.org Foundation C.I.C.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\");\n#  you may not use this file except in compliance with the License.\n#  You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  Unless required by applicable law or agreed to in writing, software\n#  distributed under the License is distributed on an \"AS IS\" BASIS,\n#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#  See the License for the specific language governing permissions and\n#  limitations under the License.\n#\n\n\"\"\"\nThis module exposes a single function which checks synapse's dependencies are present\nand correctly versioned. It makes use of `importlib.metadata` to do so. The details\nare a bit murky: there's no easy way to get a map from \"extras\" to the packages they\nrequire. But this is probably just symptomatic of Python's package management.\n\"\"\"\n\nimport logging\nfrom typing import Iterable, NamedTuple, Optional\n\nfrom packaging.requirements import Requirement\n\nDISTRIBUTION_NAME = \"matrix-synapse\"\n\ntry:\n    from importlib import metadata\nexcept ImportError:\n    import importlib_metadata as metadata  # type: ignore[no-redef]\n\n__all__ = [\"check_requirements\"]\n\n\nclass DependencyException(Exception):\n    @property\n    def message(self) -> str:\n        return \"\\n\".join(\n            [\n                \"Missing Requirements: %s\" % (\", \".join(self.dependencies),),\n                \"To install run:\",\n                \"    pip install --upgrade --force %s\" % (\" \".join(self.dependencies),),\n                \"\",\n            ]\n        )\n\n    @property\n    def dependencies(self) -> Iterable[str]:\n        for i in self.args[0]:\n            yield '\"' + i + '\"'\n\n\nDEV_EXTRAS = {\"lint\", \"mypy\", \"test\", \"dev\"}\nRUNTIME_EXTRAS = (\n    set(metadata.metadata(DISTRIBUTION_NAME).get_all(\"Provides-Extra\")) - DEV_EXTRAS\n)\nVERSION = metadata.version(DISTRIBUTION_NAME)\n\n\ndef _is_dev_dependency(req: Requirement) -> bool:\n    return req.marker is not None and any(\n        req.marker.evaluate({\"extra\": e}) for e in DEV_EXTRAS\n    )\n\n\nclass Dependency(NamedTuple):\n    requirement: Requirement\n    must_be_installed: bool\n\n\ndef _generic_dependencies() -> Iterable[Dependency]:\n    \"\"\"Yield pairs (requirement, must_be_installed).\"\"\"\n    requirements = metadata.requires(DISTRIBUTION_NAME)\n    assert requirements is not None\n    for raw_requirement in requirements:\n        req = Requirement(raw_requirement)\n        if _is_dev_dependency(req):\n            continue\n\n        # https://packaging.pypa.io/en/latest/markers.html#usage notes that\n        #   > Evaluating an extra marker with no environment is an error\n        # so we pass in a dummy empty extra value here.\n        must_be_installed = req.marker is None or req.marker.evaluate({\"extra\": \"\"})\n        yield Dependency(req, must_be_installed)\n\n\ndef _dependencies_for_extra(extra: str) -> Iterable[Dependency]:\n    \"\"\"Yield additional dependencies needed for a given `extra`.\"\"\"\n    requirements = metadata.requires(DISTRIBUTION_NAME)\n    assert requirements is not None\n    for raw_requirement in requirements:\n        req = Requirement(raw_requirement)\n        if _is_dev_dependency(req):\n            continue\n        # Exclude mandatory deps by only selecting deps needed with this extra.\n        if (\n            req.marker is not None\n            and req.marker.evaluate({\"extra\": extra})\n            and not req.marker.evaluate({\"extra\": \"\"})\n        ):\n            yield Dependency(req, True)\n\n\ndef _not_installed(requirement: Requirement, extra: Optional[str] = None) -> str:\n    if extra:\n        return (\n            f\"Synapse {VERSION} needs {requirement.name} for {extra}, \"\n            f\"but it is not installed\"\n        )\n    else:\n        return f\"Synapse {VERSION} needs {requirement.name}, but it is not installed\"\n\n\ndef _incorrect_version(\n    requirement: Requirement, got: str, extra: Optional[str] = None\n) -> str:\n    if extra:\n        return (\n            f\"Synapse {VERSION} needs {requirement} for {extra}, \"\n            f\"but got {requirement.name}=={got}\"\n        )\n    else:\n        return (\n            f\"Synapse {VERSION} needs {requirement}, but got {requirement.name}=={got}\"\n        )\n\n\ndef check_requirements(extra: Optional[str] = None) -> None:\n    \"\"\"Check Synapse's dependencies are present and correctly versioned.\n\n    If provided, `extra` must be the name of an pacakging extra (e.g. \"saml2\" in\n    `pip install matrix-synapse[saml2]`).\n\n    If `extra` is None, this function checks that\n    - all mandatory dependencies are installed and correctly versioned, and\n    - each optional dependency that's installed is correctly versioned.\n\n    If `extra` is not None, this function checks that\n    - the dependencies needed for that extra are installed and correctly versioned.\n\n    :raises DependencyException: if a dependency is missing or incorrectly versioned.\n    :raises ValueError: if this extra does not exist.\n    \"\"\"\n    # First work out which dependencies are required, and which are optional.\n    if extra is None:\n        dependencies = _generic_dependencies()\n    elif extra in RUNTIME_EXTRAS:\n        dependencies = _dependencies_for_extra(extra)\n    else:\n        raise ValueError(f\"Synapse {VERSION} does not provide the feature '{extra}'\")\n\n    deps_unfulfilled = []\n    errors = []\n\n    for (requirement, must_be_installed) in dependencies:\n        try:\n            dist: metadata.Distribution = metadata.distribution(requirement.name)\n        except metadata.PackageNotFoundError:\n            if must_be_installed:\n                deps_unfulfilled.append(requirement.name)\n                errors.append(_not_installed(requirement, extra))\n        else:\n            # We specify prereleases=True to allow prereleases such as RCs.\n            if not requirement.specifier.contains(dist.version, prereleases=True):\n                deps_unfulfilled.append(requirement.name)\n                errors.append(_incorrect_version(requirement, dist.version, extra))\n\n    if deps_unfulfilled:\n        for err in errors:\n            logging.error(err)\n\n        raise DependencyException(deps_unfulfilled)\n", "path": "synapse/util/check_dependencies.py"}]}