We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
clean and transparent store registration
These lines

https://github.com/mlflow/mlflow/blob/152063e0b6fbadfbb2baecaf7d0ac7ca1b304b31/mlflow/tracking/_tracking_service/utils.py#L194C1-L206C1

initialize a global variable holding important information about store endpoints. 

But the style is not good:
- should be moved to the top and marked clearly
- perhaps it would be beneficial to wrap them to be recycled per user request (re-register / re-initialize)

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mlflow/tracking/_tracking_service/utils.py`
Content:
```
1 import os
2 from functools import partial
3 import logging
4 from pathlib import Path
5 from typing import Union
6 from contextlib import contextmanager
7 
8 from mlflow.environment_variables import (
9     MLFLOW_TRACKING_AWS_SIGV4,
10     MLFLOW_TRACKING_URI,
11     MLFLOW_TRACKING_TOKEN,
12     MLFLOW_TRACKING_INSECURE_TLS,
13     MLFLOW_TRACKING_CLIENT_CERT_PATH,
14     MLFLOW_TRACKING_SERVER_CERT_PATH,
15 )
16 from mlflow.store.tracking import DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH
17 from mlflow.store.db.db_types import DATABASE_ENGINES
18 from mlflow.store.tracking.file_store import FileStore
19 from mlflow.store.tracking.rest_store import RestStore
20 from mlflow.tracking._tracking_service.registry import TrackingStoreRegistry
21 from mlflow.utils import rest_utils
22 from mlflow.utils.file_utils import path_to_local_file_uri
23 from mlflow.utils.databricks_utils import get_databricks_host_creds
24 from mlflow.utils.uri import _DATABRICKS_UNITY_CATALOG_SCHEME
25 from mlflow.utils.credentials import read_mlflow_creds
26 
27 _logger = logging.getLogger(__name__)
28 _tracking_uri = None
29 
30 
31 def is_tracking_uri_set():
32     """Returns True if the tracking URI has been set, False otherwise."""
33     if _tracking_uri or MLFLOW_TRACKING_URI.get():
34         return True
35     return False
36 
37 
38 def set_tracking_uri(uri: Union[str, Path]) -> None:
39     """
40     Set the tracking server URI. This does not affect the
41     currently active run (if one exists), but takes effect for successive runs.
42 
43     :param uri:
44 
45                 - An empty string, or a local file path, prefixed with ``file:/``. Data is stored
46                   locally at the provided file (or ``./mlruns`` if empty).
47                 - An HTTP URI like ``https://my-tracking-server:5000``.
48                 - A Databricks workspace, provided as the string "databricks" or, to use a
49                   Databricks CLI
50                   `profile <https://github.com/databricks/databricks-cli#installation>`_,
51                   "databricks://<profileName>".
52                 - A :py:class:`pathlib.Path` instance
53 
54     .. test-code-block:: python
55         :caption: Example
56 
57         import mlflow
58 
59         mlflow.set_tracking_uri("file:///tmp/my_tracking")
60         tracking_uri = mlflow.get_tracking_uri()
61         print("Current tracking uri: {}".format(tracking_uri))
62 
63     .. code-block:: text
64         :caption: Output
65 
66         Current tracking uri: file:///tmp/my_tracking
67     """
68     if isinstance(uri, Path):
69         # On Windows with Python3.8 (https://bugs.python.org/issue38671)
70         # .resolve() doesn't return the absolute path if the directory doesn't exist
71         # so we're calling .absolute() first to get the absolute path on Windows,
72         # then .resolve() to clean the path
73         uri = uri.absolute().resolve().as_uri()
74     global _tracking_uri
75     _tracking_uri = uri
76 
77 
78 @contextmanager
79 def _use_tracking_uri(uri: str, local_store_root_path: str = None) -> None:
80     """
81     Similar to `mlflow.tracking.set_tracking_uri` function but return a context manager.
82     :param uri: tracking URI to use.
83     :param local_store_root_path: the local store root path for the tracking URI.
84     """
85     global _tracking_uri
86     cwd = os.getcwd()
87     old_tracking_uri = _tracking_uri
88     try:
89         if local_store_root_path is not None:
90             os.chdir(local_store_root_path)
91         _tracking_uri = uri
92         yield
93     finally:
94         _tracking_uri = old_tracking_uri
95         os.chdir(cwd)
96 
97 
98 def _resolve_tracking_uri(tracking_uri=None):
99     return tracking_uri or get_tracking_uri()
100 
101 
102 def get_tracking_uri() -> str:
103     """
104     Get the current tracking URI. This may not correspond to the tracking URI of
105     the currently active run, since the tracking URI can be updated via ``set_tracking_uri``.
106 
107     :return: The tracking URI.
108 
109     .. code-block:: python
110         :caption: Example
111 
112         import mlflow
113 
114         # Get the current tracking uri
115         tracking_uri = mlflow.get_tracking_uri()
116         print("Current tracking uri: {}".format(tracking_uri))
117 
118     .. code-block:: text
119         :caption: Output
120 
121         Current tracking uri: file:///.../mlruns
122     """
123     global _tracking_uri
124     if _tracking_uri is not None:
125         return _tracking_uri
126     elif uri := MLFLOW_TRACKING_URI.get():
127         return uri
128     else:
129         return path_to_local_file_uri(os.path.abspath(DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH))
130 
131 
132 def _get_file_store(store_uri, **_):
133     return FileStore(store_uri, store_uri)
134 
135 
136 def _get_sqlalchemy_store(store_uri, artifact_uri):
137     from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
138 
139     if artifact_uri is None:
140         artifact_uri = DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH
141     return SqlAlchemyStore(store_uri, artifact_uri)
142 
143 
144 def _get_default_host_creds(store_uri):
145     creds = read_mlflow_creds()
146     return rest_utils.MlflowHostCreds(
147         host=store_uri,
148         username=creds.username,
149         password=creds.password,
150         token=MLFLOW_TRACKING_TOKEN.get(),
151         aws_sigv4=MLFLOW_TRACKING_AWS_SIGV4.get(),
152         ignore_tls_verification=MLFLOW_TRACKING_INSECURE_TLS.get(),
153         client_cert_path=MLFLOW_TRACKING_CLIENT_CERT_PATH.get(),
154         server_cert_path=MLFLOW_TRACKING_SERVER_CERT_PATH.get(),
155     )
156 
157 
158 def _get_rest_store(store_uri, **_):
159     return RestStore(partial(_get_default_host_creds, store_uri))
160 
161 
162 def _get_databricks_rest_store(store_uri, **_):
163     return RestStore(partial(get_databricks_host_creds, store_uri))
164 
165 
166 def _get_databricks_uc_rest_store(store_uri, **_):
167     from mlflow.exceptions import MlflowException
168     from mlflow.version import VERSION
169 
170     global _tracking_store_registry
171     supported_schemes = [
172         scheme
173         for scheme in _tracking_store_registry._registry
174         if scheme != _DATABRICKS_UNITY_CATALOG_SCHEME
175     ]
176     raise MlflowException(
177         f"Detected Unity Catalog tracking URI '{store_uri}'. "
178         "Setting the tracking URI to a Unity Catalog backend is not supported in the current "
179         f"version of the MLflow client ({VERSION}). "
180         "Please specify a different tracking URI via mlflow.set_tracking_uri, with "
181         "one of the supported schemes: "
182         f"{supported_schemes}. If you're trying to access models in the Unity "
183         "Catalog, please upgrade to the latest version of the MLflow Python "
184         "client, then specify a Unity Catalog model registry URI via "
185         f"mlflow.set_registry_uri('{_DATABRICKS_UNITY_CATALOG_SCHEME}') or "
186         f"mlflow.set_registry_uri('{_DATABRICKS_UNITY_CATALOG_SCHEME}://profile_name'), where "
187         "'profile_name' is the name of the Databricks CLI profile to use for "
188         "authentication. Be sure to leave the tracking URI configured to use "
189         "one of the supported schemes listed above."
190     )
191 
192 
193 _tracking_store_registry = TrackingStoreRegistry()
194 _tracking_store_registry.register("", _get_file_store)
195 _tracking_store_registry.register("file", _get_file_store)
196 _tracking_store_registry.register("databricks", _get_databricks_rest_store)
197 _tracking_store_registry.register(_DATABRICKS_UNITY_CATALOG_SCHEME, _get_databricks_uc_rest_store)
198 
199 for scheme in ["http", "https"]:
200     _tracking_store_registry.register(scheme, _get_rest_store)
201 
202 for scheme in DATABASE_ENGINES:
203     _tracking_store_registry.register(scheme, _get_sqlalchemy_store)
204 
205 _tracking_store_registry.register_entrypoints()
206 
207 
208 def _get_store(store_uri=None, artifact_uri=None):
209     return _tracking_store_registry.get_store(store_uri, artifact_uri)
210 
211 
212 # TODO(sueann): move to a projects utils module
213 def _get_git_url_if_present(uri):
214     """
215     Return the path git_uri#sub_directory if the URI passed is a local path that's part of
216     a Git repo, or returns the original URI otherwise.
217     :param uri: The expanded uri
218     :return: The git_uri#sub_directory if the uri is part of a Git repo,
219              otherwise return the original uri
220     """
221     if "#" in uri:
222         # Already a URI in git repo format
223         return uri
224     try:
225         from git import Repo, InvalidGitRepositoryError, GitCommandNotFound, NoSuchPathError
226     except ImportError as e:
227         _logger.warning(
228             "Failed to import Git (the git executable is probably not on your PATH),"
229             " so Git SHA is not available. Error: %s",
230             e,
231         )
232         return uri
233     try:
234         # Check whether this is part of a git repo
235         repo = Repo(uri, search_parent_directories=True)
236 
237         # Repo url
238         repo_url = "file://%s" % repo.working_tree_dir
239 
240         # Sub directory
241         rlpath = uri.replace(repo.working_tree_dir, "")
242         if rlpath == "":
243             git_path = repo_url
244         elif rlpath[0] == "/":
245             git_path = repo_url + "#" + rlpath[1:]
246         else:
247             git_path = repo_url + "#" + rlpath
248         return git_path
249     except (InvalidGitRepositoryError, GitCommandNotFound, ValueError, NoSuchPathError):
250         return uri
251
```
--- 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/mlflow/tracking/_tracking_service/utils.py b/mlflow/tracking/_tracking_service/utils.py
--- a/mlflow/tracking/_tracking_service/utils.py
+++ b/mlflow/tracking/_tracking_service/utils.py
@@ -191,18 +191,27 @@
 
 
 _tracking_store_registry = TrackingStoreRegistry()
-_tracking_store_registry.register("", _get_file_store)
-_tracking_store_registry.register("file", _get_file_store)
-_tracking_store_registry.register("databricks", _get_databricks_rest_store)
-_tracking_store_registry.register(_DATABRICKS_UNITY_CATALOG_SCHEME, _get_databricks_uc_rest_store)
 
-for scheme in ["http", "https"]:
-    _tracking_store_registry.register(scheme, _get_rest_store)
 
-for scheme in DATABASE_ENGINES:
-    _tracking_store_registry.register(scheme, _get_sqlalchemy_store)
+def _register_tracking_stores():
+    global _tracking_store_registry
+    _tracking_store_registry.register("", _get_file_store)
+    _tracking_store_registry.register("file", _get_file_store)
+    _tracking_store_registry.register("databricks", _get_databricks_rest_store)
+    _tracking_store_registry.register(
+        _DATABRICKS_UNITY_CATALOG_SCHEME, _get_databricks_uc_rest_store
+    )
+
+    for scheme in ["http", "https"]:
+        _tracking_store_registry.register(scheme, _get_rest_store)
+
+    for scheme in DATABASE_ENGINES:
+        _tracking_store_registry.register(scheme, _get_sqlalchemy_store)
+
+    _tracking_store_registry.register_entrypoints()
+
 
-_tracking_store_registry.register_entrypoints()
+_register_tracking_stores()
 
 
 def _get_store(store_uri=None, artifact_uri=None):

{"golden_diff": "diff --git a/mlflow/tracking/_tracking_service/utils.py b/mlflow/tracking/_tracking_service/utils.py\n--- a/mlflow/tracking/_tracking_service/utils.py\n+++ b/mlflow/tracking/_tracking_service/utils.py\n@@ -191,18 +191,27 @@\n \n \n _tracking_store_registry = TrackingStoreRegistry()\n-_tracking_store_registry.register(\"\", _get_file_store)\n-_tracking_store_registry.register(\"file\", _get_file_store)\n-_tracking_store_registry.register(\"databricks\", _get_databricks_rest_store)\n-_tracking_store_registry.register(_DATABRICKS_UNITY_CATALOG_SCHEME, _get_databricks_uc_rest_store)\n \n-for scheme in [\"http\", \"https\"]:\n-    _tracking_store_registry.register(scheme, _get_rest_store)\n \n-for scheme in DATABASE_ENGINES:\n-    _tracking_store_registry.register(scheme, _get_sqlalchemy_store)\n+def _register_tracking_stores():\n+    global _tracking_store_registry\n+    _tracking_store_registry.register(\"\", _get_file_store)\n+    _tracking_store_registry.register(\"file\", _get_file_store)\n+    _tracking_store_registry.register(\"databricks\", _get_databricks_rest_store)\n+    _tracking_store_registry.register(\n+        _DATABRICKS_UNITY_CATALOG_SCHEME, _get_databricks_uc_rest_store\n+    )\n+\n+    for scheme in [\"http\", \"https\"]:\n+        _tracking_store_registry.register(scheme, _get_rest_store)\n+\n+    for scheme in DATABASE_ENGINES:\n+        _tracking_store_registry.register(scheme, _get_sqlalchemy_store)\n+\n+    _tracking_store_registry.register_entrypoints()\n+\n \n-_tracking_store_registry.register_entrypoints()\n+_register_tracking_stores()\n \n \n def _get_store(store_uri=None, artifact_uri=None):\n", "issue": "clean and transparent store registration\nThese lines\r\n\r\nhttps://github.com/mlflow/mlflow/blob/152063e0b6fbadfbb2baecaf7d0ac7ca1b304b31/mlflow/tracking/_tracking_service/utils.py#L194C1-L206C1\r\n\r\ninitialize a global variable holding important information about store endpoints. \r\n\r\nBut the style is not good:\r\n- should be moved to the top and marked clearly\r\n- perhaps it would be beneficial to wrap them to be recycled per user request (re-register / re-initialize)\n", "before_files": [{"content": "import os\nfrom functools import partial\nimport logging\nfrom pathlib import Path\nfrom typing import Union\nfrom contextlib import contextmanager\n\nfrom mlflow.environment_variables import (\n    MLFLOW_TRACKING_AWS_SIGV4,\n    MLFLOW_TRACKING_URI,\n    MLFLOW_TRACKING_TOKEN,\n    MLFLOW_TRACKING_INSECURE_TLS,\n    MLFLOW_TRACKING_CLIENT_CERT_PATH,\n    MLFLOW_TRACKING_SERVER_CERT_PATH,\n)\nfrom mlflow.store.tracking import DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH\nfrom mlflow.store.db.db_types import DATABASE_ENGINES\nfrom mlflow.store.tracking.file_store import FileStore\nfrom mlflow.store.tracking.rest_store import RestStore\nfrom mlflow.tracking._tracking_service.registry import TrackingStoreRegistry\nfrom mlflow.utils import rest_utils\nfrom mlflow.utils.file_utils import path_to_local_file_uri\nfrom mlflow.utils.databricks_utils import get_databricks_host_creds\nfrom mlflow.utils.uri import _DATABRICKS_UNITY_CATALOG_SCHEME\nfrom mlflow.utils.credentials import read_mlflow_creds\n\n_logger = logging.getLogger(__name__)\n_tracking_uri = None\n\n\ndef is_tracking_uri_set():\n    \"\"\"Returns True if the tracking URI has been set, False otherwise.\"\"\"\n    if _tracking_uri or MLFLOW_TRACKING_URI.get():\n        return True\n    return False\n\n\ndef set_tracking_uri(uri: Union[str, Path]) -> None:\n    \"\"\"\n    Set the tracking server URI. This does not affect the\n    currently active run (if one exists), but takes effect for successive runs.\n\n    :param uri:\n\n                - An empty string, or a local file path, prefixed with ``file:/``. Data is stored\n                  locally at the provided file (or ``./mlruns`` if empty).\n                - An HTTP URI like ``https://my-tracking-server:5000``.\n                - A Databricks workspace, provided as the string \"databricks\" or, to use a\n                  Databricks CLI\n                  `profile <https://github.com/databricks/databricks-cli#installation>`_,\n                  \"databricks://<profileName>\".\n                - A :py:class:`pathlib.Path` instance\n\n    .. test-code-block:: python\n        :caption: Example\n\n        import mlflow\n\n        mlflow.set_tracking_uri(\"file:///tmp/my_tracking\")\n        tracking_uri = mlflow.get_tracking_uri()\n        print(\"Current tracking uri: {}\".format(tracking_uri))\n\n    .. code-block:: text\n        :caption: Output\n\n        Current tracking uri: file:///tmp/my_tracking\n    \"\"\"\n    if isinstance(uri, Path):\n        # On Windows with Python3.8 (https://bugs.python.org/issue38671)\n        # .resolve() doesn't return the absolute path if the directory doesn't exist\n        # so we're calling .absolute() first to get the absolute path on Windows,\n        # then .resolve() to clean the path\n        uri = uri.absolute().resolve().as_uri()\n    global _tracking_uri\n    _tracking_uri = uri\n\n\n@contextmanager\ndef _use_tracking_uri(uri: str, local_store_root_path: str = None) -> None:\n    \"\"\"\n    Similar to `mlflow.tracking.set_tracking_uri` function but return a context manager.\n    :param uri: tracking URI to use.\n    :param local_store_root_path: the local store root path for the tracking URI.\n    \"\"\"\n    global _tracking_uri\n    cwd = os.getcwd()\n    old_tracking_uri = _tracking_uri\n    try:\n        if local_store_root_path is not None:\n            os.chdir(local_store_root_path)\n        _tracking_uri = uri\n        yield\n    finally:\n        _tracking_uri = old_tracking_uri\n        os.chdir(cwd)\n\n\ndef _resolve_tracking_uri(tracking_uri=None):\n    return tracking_uri or get_tracking_uri()\n\n\ndef get_tracking_uri() -> str:\n    \"\"\"\n    Get the current tracking URI. This may not correspond to the tracking URI of\n    the currently active run, since the tracking URI can be updated via ``set_tracking_uri``.\n\n    :return: The tracking URI.\n\n    .. code-block:: python\n        :caption: Example\n\n        import mlflow\n\n        # Get the current tracking uri\n        tracking_uri = mlflow.get_tracking_uri()\n        print(\"Current tracking uri: {}\".format(tracking_uri))\n\n    .. code-block:: text\n        :caption: Output\n\n        Current tracking uri: file:///.../mlruns\n    \"\"\"\n    global _tracking_uri\n    if _tracking_uri is not None:\n        return _tracking_uri\n    elif uri := MLFLOW_TRACKING_URI.get():\n        return uri\n    else:\n        return path_to_local_file_uri(os.path.abspath(DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH))\n\n\ndef _get_file_store(store_uri, **_):\n    return FileStore(store_uri, store_uri)\n\n\ndef _get_sqlalchemy_store(store_uri, artifact_uri):\n    from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore\n\n    if artifact_uri is None:\n        artifact_uri = DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH\n    return SqlAlchemyStore(store_uri, artifact_uri)\n\n\ndef _get_default_host_creds(store_uri):\n    creds = read_mlflow_creds()\n    return rest_utils.MlflowHostCreds(\n        host=store_uri,\n        username=creds.username,\n        password=creds.password,\n        token=MLFLOW_TRACKING_TOKEN.get(),\n        aws_sigv4=MLFLOW_TRACKING_AWS_SIGV4.get(),\n        ignore_tls_verification=MLFLOW_TRACKING_INSECURE_TLS.get(),\n        client_cert_path=MLFLOW_TRACKING_CLIENT_CERT_PATH.get(),\n        server_cert_path=MLFLOW_TRACKING_SERVER_CERT_PATH.get(),\n    )\n\n\ndef _get_rest_store(store_uri, **_):\n    return RestStore(partial(_get_default_host_creds, store_uri))\n\n\ndef _get_databricks_rest_store(store_uri, **_):\n    return RestStore(partial(get_databricks_host_creds, store_uri))\n\n\ndef _get_databricks_uc_rest_store(store_uri, **_):\n    from mlflow.exceptions import MlflowException\n    from mlflow.version import VERSION\n\n    global _tracking_store_registry\n    supported_schemes = [\n        scheme\n        for scheme in _tracking_store_registry._registry\n        if scheme != _DATABRICKS_UNITY_CATALOG_SCHEME\n    ]\n    raise MlflowException(\n        f\"Detected Unity Catalog tracking URI '{store_uri}'. \"\n        \"Setting the tracking URI to a Unity Catalog backend is not supported in the current \"\n        f\"version of the MLflow client ({VERSION}). \"\n        \"Please specify a different tracking URI via mlflow.set_tracking_uri, with \"\n        \"one of the supported schemes: \"\n        f\"{supported_schemes}. If you're trying to access models in the Unity \"\n        \"Catalog, please upgrade to the latest version of the MLflow Python \"\n        \"client, then specify a Unity Catalog model registry URI via \"\n        f\"mlflow.set_registry_uri('{_DATABRICKS_UNITY_CATALOG_SCHEME}') or \"\n        f\"mlflow.set_registry_uri('{_DATABRICKS_UNITY_CATALOG_SCHEME}://profile_name'), where \"\n        \"'profile_name' is the name of the Databricks CLI profile to use for \"\n        \"authentication. Be sure to leave the tracking URI configured to use \"\n        \"one of the supported schemes listed above.\"\n    )\n\n\n_tracking_store_registry = TrackingStoreRegistry()\n_tracking_store_registry.register(\"\", _get_file_store)\n_tracking_store_registry.register(\"file\", _get_file_store)\n_tracking_store_registry.register(\"databricks\", _get_databricks_rest_store)\n_tracking_store_registry.register(_DATABRICKS_UNITY_CATALOG_SCHEME, _get_databricks_uc_rest_store)\n\nfor scheme in [\"http\", \"https\"]:\n    _tracking_store_registry.register(scheme, _get_rest_store)\n\nfor scheme in DATABASE_ENGINES:\n    _tracking_store_registry.register(scheme, _get_sqlalchemy_store)\n\n_tracking_store_registry.register_entrypoints()\n\n\ndef _get_store(store_uri=None, artifact_uri=None):\n    return _tracking_store_registry.get_store(store_uri, artifact_uri)\n\n\n# TODO(sueann): move to a projects utils module\ndef _get_git_url_if_present(uri):\n    \"\"\"\n    Return the path git_uri#sub_directory if the URI passed is a local path that's part of\n    a Git repo, or returns the original URI otherwise.\n    :param uri: The expanded uri\n    :return: The git_uri#sub_directory if the uri is part of a Git repo,\n             otherwise return the original uri\n    \"\"\"\n    if \"#\" in uri:\n        # Already a URI in git repo format\n        return uri\n    try:\n        from git import Repo, InvalidGitRepositoryError, GitCommandNotFound, NoSuchPathError\n    except ImportError as e:\n        _logger.warning(\n            \"Failed to import Git (the git executable is probably not on your PATH),\"\n            \" so Git SHA is not available. Error: %s\",\n            e,\n        )\n        return uri\n    try:\n        # Check whether this is part of a git repo\n        repo = Repo(uri, search_parent_directories=True)\n\n        # Repo url\n        repo_url = \"file://%s\" % repo.working_tree_dir\n\n        # Sub directory\n        rlpath = uri.replace(repo.working_tree_dir, \"\")\n        if rlpath == \"\":\n            git_path = repo_url\n        elif rlpath[0] == \"/\":\n            git_path = repo_url + \"#\" + rlpath[1:]\n        else:\n            git_path = repo_url + \"#\" + rlpath\n        return git_path\n    except (InvalidGitRepositoryError, GitCommandNotFound, ValueError, NoSuchPathError):\n        return uri\n", "path": "mlflow/tracking/_tracking_service/utils.py"}], "after_files": [{"content": "import os\nfrom functools import partial\nimport logging\nfrom pathlib import Path\nfrom typing import Union\nfrom contextlib import contextmanager\n\nfrom mlflow.environment_variables import (\n    MLFLOW_TRACKING_AWS_SIGV4,\n    MLFLOW_TRACKING_URI,\n    MLFLOW_TRACKING_TOKEN,\n    MLFLOW_TRACKING_INSECURE_TLS,\n    MLFLOW_TRACKING_CLIENT_CERT_PATH,\n    MLFLOW_TRACKING_SERVER_CERT_PATH,\n)\nfrom mlflow.store.tracking import DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH\nfrom mlflow.store.db.db_types import DATABASE_ENGINES\nfrom mlflow.store.tracking.file_store import FileStore\nfrom mlflow.store.tracking.rest_store import RestStore\nfrom mlflow.tracking._tracking_service.registry import TrackingStoreRegistry\nfrom mlflow.utils import rest_utils\nfrom mlflow.utils.file_utils import path_to_local_file_uri\nfrom mlflow.utils.databricks_utils import get_databricks_host_creds\nfrom mlflow.utils.uri import _DATABRICKS_UNITY_CATALOG_SCHEME\nfrom mlflow.utils.credentials import read_mlflow_creds\n\n_logger = logging.getLogger(__name__)\n_tracking_uri = None\n\n\ndef is_tracking_uri_set():\n    \"\"\"Returns True if the tracking URI has been set, False otherwise.\"\"\"\n    if _tracking_uri or MLFLOW_TRACKING_URI.get():\n        return True\n    return False\n\n\ndef set_tracking_uri(uri: Union[str, Path]) -> None:\n    \"\"\"\n    Set the tracking server URI. This does not affect the\n    currently active run (if one exists), but takes effect for successive runs.\n\n    :param uri:\n\n                - An empty string, or a local file path, prefixed with ``file:/``. Data is stored\n                  locally at the provided file (or ``./mlruns`` if empty).\n                - An HTTP URI like ``https://my-tracking-server:5000``.\n                - A Databricks workspace, provided as the string \"databricks\" or, to use a\n                  Databricks CLI\n                  `profile <https://github.com/databricks/databricks-cli#installation>`_,\n                  \"databricks://<profileName>\".\n                - A :py:class:`pathlib.Path` instance\n\n    .. test-code-block:: python\n        :caption: Example\n\n        import mlflow\n\n        mlflow.set_tracking_uri(\"file:///tmp/my_tracking\")\n        tracking_uri = mlflow.get_tracking_uri()\n        print(\"Current tracking uri: {}\".format(tracking_uri))\n\n    .. code-block:: text\n        :caption: Output\n\n        Current tracking uri: file:///tmp/my_tracking\n    \"\"\"\n    if isinstance(uri, Path):\n        # On Windows with Python3.8 (https://bugs.python.org/issue38671)\n        # .resolve() doesn't return the absolute path if the directory doesn't exist\n        # so we're calling .absolute() first to get the absolute path on Windows,\n        # then .resolve() to clean the path\n        uri = uri.absolute().resolve().as_uri()\n    global _tracking_uri\n    _tracking_uri = uri\n\n\n@contextmanager\ndef _use_tracking_uri(uri: str, local_store_root_path: str = None) -> None:\n    \"\"\"\n    Similar to `mlflow.tracking.set_tracking_uri` function but return a context manager.\n    :param uri: tracking URI to use.\n    :param local_store_root_path: the local store root path for the tracking URI.\n    \"\"\"\n    global _tracking_uri\n    cwd = os.getcwd()\n    old_tracking_uri = _tracking_uri\n    try:\n        if local_store_root_path is not None:\n            os.chdir(local_store_root_path)\n        _tracking_uri = uri\n        yield\n    finally:\n        _tracking_uri = old_tracking_uri\n        os.chdir(cwd)\n\n\ndef _resolve_tracking_uri(tracking_uri=None):\n    return tracking_uri or get_tracking_uri()\n\n\ndef get_tracking_uri() -> str:\n    \"\"\"\n    Get the current tracking URI. This may not correspond to the tracking URI of\n    the currently active run, since the tracking URI can be updated via ``set_tracking_uri``.\n\n    :return: The tracking URI.\n\n    .. code-block:: python\n        :caption: Example\n\n        import mlflow\n\n        # Get the current tracking uri\n        tracking_uri = mlflow.get_tracking_uri()\n        print(\"Current tracking uri: {}\".format(tracking_uri))\n\n    .. code-block:: text\n        :caption: Output\n\n        Current tracking uri: file:///.../mlruns\n    \"\"\"\n    global _tracking_uri\n    if _tracking_uri is not None:\n        return _tracking_uri\n    elif uri := MLFLOW_TRACKING_URI.get():\n        return uri\n    else:\n        return path_to_local_file_uri(os.path.abspath(DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH))\n\n\ndef _get_file_store(store_uri, **_):\n    return FileStore(store_uri, store_uri)\n\n\ndef _get_sqlalchemy_store(store_uri, artifact_uri):\n    from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore\n\n    if artifact_uri is None:\n        artifact_uri = DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH\n    return SqlAlchemyStore(store_uri, artifact_uri)\n\n\ndef _get_default_host_creds(store_uri):\n    creds = read_mlflow_creds()\n    return rest_utils.MlflowHostCreds(\n        host=store_uri,\n        username=creds.username,\n        password=creds.password,\n        token=MLFLOW_TRACKING_TOKEN.get(),\n        aws_sigv4=MLFLOW_TRACKING_AWS_SIGV4.get(),\n        ignore_tls_verification=MLFLOW_TRACKING_INSECURE_TLS.get(),\n        client_cert_path=MLFLOW_TRACKING_CLIENT_CERT_PATH.get(),\n        server_cert_path=MLFLOW_TRACKING_SERVER_CERT_PATH.get(),\n    )\n\n\ndef _get_rest_store(store_uri, **_):\n    return RestStore(partial(_get_default_host_creds, store_uri))\n\n\ndef _get_databricks_rest_store(store_uri, **_):\n    return RestStore(partial(get_databricks_host_creds, store_uri))\n\n\ndef _get_databricks_uc_rest_store(store_uri, **_):\n    from mlflow.exceptions import MlflowException\n    from mlflow.version import VERSION\n\n    global _tracking_store_registry\n    supported_schemes = [\n        scheme\n        for scheme in _tracking_store_registry._registry\n        if scheme != _DATABRICKS_UNITY_CATALOG_SCHEME\n    ]\n    raise MlflowException(\n        f\"Detected Unity Catalog tracking URI '{store_uri}'. \"\n        \"Setting the tracking URI to a Unity Catalog backend is not supported in the current \"\n        f\"version of the MLflow client ({VERSION}). \"\n        \"Please specify a different tracking URI via mlflow.set_tracking_uri, with \"\n        \"one of the supported schemes: \"\n        f\"{supported_schemes}. If you're trying to access models in the Unity \"\n        \"Catalog, please upgrade to the latest version of the MLflow Python \"\n        \"client, then specify a Unity Catalog model registry URI via \"\n        f\"mlflow.set_registry_uri('{_DATABRICKS_UNITY_CATALOG_SCHEME}') or \"\n        f\"mlflow.set_registry_uri('{_DATABRICKS_UNITY_CATALOG_SCHEME}://profile_name'), where \"\n        \"'profile_name' is the name of the Databricks CLI profile to use for \"\n        \"authentication. Be sure to leave the tracking URI configured to use \"\n        \"one of the supported schemes listed above.\"\n    )\n\n\n_tracking_store_registry = TrackingStoreRegistry()\n\n\ndef _register_tracking_stores():\n    global _tracking_store_registry\n    _tracking_store_registry.register(\"\", _get_file_store)\n    _tracking_store_registry.register(\"file\", _get_file_store)\n    _tracking_store_registry.register(\"databricks\", _get_databricks_rest_store)\n    _tracking_store_registry.register(\n        _DATABRICKS_UNITY_CATALOG_SCHEME, _get_databricks_uc_rest_store\n    )\n\n    for scheme in [\"http\", \"https\"]:\n        _tracking_store_registry.register(scheme, _get_rest_store)\n\n    for scheme in DATABASE_ENGINES:\n        _tracking_store_registry.register(scheme, _get_sqlalchemy_store)\n\n    _tracking_store_registry.register_entrypoints()\n\n\n_register_tracking_stores()\n\n\ndef _get_store(store_uri=None, artifact_uri=None):\n    return _tracking_store_registry.get_store(store_uri, artifact_uri)\n\n\n# TODO(sueann): move to a projects utils module\ndef _get_git_url_if_present(uri):\n    \"\"\"\n    Return the path git_uri#sub_directory if the URI passed is a local path that's part of\n    a Git repo, or returns the original URI otherwise.\n    :param uri: The expanded uri\n    :return: The git_uri#sub_directory if the uri is part of a Git repo,\n             otherwise return the original uri\n    \"\"\"\n    if \"#\" in uri:\n        # Already a URI in git repo format\n        return uri\n    try:\n        from git import Repo, InvalidGitRepositoryError, GitCommandNotFound, NoSuchPathError\n    except ImportError as e:\n        _logger.warning(\n            \"Failed to import Git (the git executable is probably not on your PATH),\"\n            \" so Git SHA is not available. Error: %s\",\n            e,\n        )\n        return uri\n    try:\n        # Check whether this is part of a git repo\n        repo = Repo(uri, search_parent_directories=True)\n\n        # Repo url\n        repo_url = \"file://%s\" % repo.working_tree_dir\n\n        # Sub directory\n        rlpath = uri.replace(repo.working_tree_dir, \"\")\n        if rlpath == \"\":\n            git_path = repo_url\n        elif rlpath[0] == \"/\":\n            git_path = repo_url + \"#\" + rlpath[1:]\n        else:\n            git_path = repo_url + \"#\" + rlpath\n        return git_path\n    except (InvalidGitRepositoryError, GitCommandNotFound, ValueError, NoSuchPathError):\n        return uri\n", "path": "mlflow/tracking/_tracking_service/utils.py"}]}