repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
mlflow | dev/clint/tests/rules/conftest.py | .py | import pytest
from clint.index import SymbolIndex
@pytest.fixture(scope="session")
def index() -> SymbolIndex:
return SymbolIndex.build()
| 8 | 144 |
mlflow | dev/clint/src/clint/utils.py | .py | from __future__ import annotations
import ast
import re
import subprocess
from functools import lru_cache
from pathlib import Path
@lru_cache(maxsize=1)
def get_repo_root() -> Path:
"""Find the git repository root directory with caching."""
try:
result = subprocess.check_output(["git", "rev-parse", "... | 91 | 2,796 |
mlflow | dev/clint/src/clint/index.py | .py | """Symbol indexing for MLflow codebase.
This module provides efficient indexing and lookup of Python symbols (functions, classes)
across the MLflow codebase using AST parsing and parallel processing.
Key components:
- FunctionInfo: Lightweight function signature information
- ModuleSymbolExtractor: AST visitor for ex... | 222 | 7,936 |
mlflow | dev/clint/src/clint/__main__.py | .py | from clint import main
main()
| 4 | 31 |
mlflow | dev/clint/src/clint/__init__.py | .py | import argparse
import itertools
import json
import re
import sys
import tempfile
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
from typing_extensions import Self
from clint.config import Config
from clint.index i... | 111 | 3,823 |
mlflow | dev/clint/src/clint/comments.py | .py | import io
import re
import tokenize
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterator
from typing_extensions import Self
if TYPE_CHECKING:
from clint.linter import Position
NOQA_REGEX = re.compile(r"#\s*noqa\s*:\s*([A-Z]\d+(?:\s*,\s*[A-Z]\d+)*)", re.IGNORECASE)
@dataclass
class Noqa:... | 42 | 1,174 |
mlflow | dev/clint/src/clint/builtin.py | .py | # https://github.com/PyCQA/isort/blob/b818cec889657cb786beafe94a6641f8fc0f0e64/isort/stdlibs/py311.py
BUILTIN_MODULES = {
"_ast",
"_thread",
"abc",
"aifc",
"argparse",
"array",
"ast",
"asynchat",
"asyncio",
"asyncore",
"atexit",
"audioop",
"base64",
"bdb",
"bi... | 217 | 3,223 |
mlflow | dev/clint/src/clint/config.py | .py | import re
import typing
from dataclasses import dataclass, field
import tomli
from typing_extensions import Self
from clint.rules import ALL_RULES
from clint.utils import get_repo_root
def _validate_exclude_paths(exclude_paths: list[str]) -> None:
"""Validate that all paths in the exclude list exist.
Args:... | 111 | 3,827 |
mlflow | dev/clint/src/clint/resolver.py | .py | import ast
from collections.abc import Iterator
from contextlib import contextmanager
class Resolver:
def __init__(self) -> None:
self.name_map: dict[str, list[str]] = {}
self._scope_stack: list[dict[str, list[str]]] = []
def clear(self) -> None:
"""Clear all name mappings. Useful whe... | 90 | 2,931 |
mlflow | dev/clint/src/clint/linter.py | .py | import ast
import fnmatch
import json
import re
import textwrap
import tokenize
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Iterator, TypeAlias
from typing_extensions import Self
from clint import rules
from clint.comments import Noqa, iter_comments
from clint.config i... | 1,085 | 41,242 |
mlflow | dev/clint/src/clint/rules/os_chdir_in_test.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class OsChdirInTest(Rule):
def _message(self) -> str:
return "Do not use `os.chdir` in test directly. Use `monkeypatch.chdir` (https://docs.pytest.org/en/stable/reference/reference.html#pytest.MonkeyPatch.chdir)."
@stat... | 17 | 520 |
mlflow | dev/clint/src/clint/rules/no_rst.py | .py | from clint.rules.base import Rule
class NoRst(Rule):
def _message(self) -> str:
return "Do not use RST style. Use Google style instead."
| 7 | 151 |
mlflow | dev/clint/src/clint/rules/pytest_mark_repeat.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class PytestMarkRepeat(Rule):
def _message(self) -> str:
return (
"@pytest.mark.repeat decorator should not be committed. "
"This decorator is meant for local testing only to check for flaky tests."
... | 23 | 709 |
mlflow | dev/clint/src/clint/rules/os_environ_delete_in_test.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class OsEnvironDeleteInTest(Rule):
def _message(self) -> str:
return (
"Do not delete `os.environ` in test directly (del os.environ[...] or "
"os.environ.pop(...)). Use `monkeypatch.delenv` "
... | 31 | 1,148 |
mlflow | dev/clint/src/clint/rules/lazy_import.py | .py | from clint.builtin import BUILTIN_MODULES
from clint.rules.base import Rule
# Third-party packages that are always available as core dependencies of mlflow-tracing
# (the smallest installable unit of MLflow). Lazy imports of these packages are flagged
# the same way as stdlib lazy imports.
_ALWAYS_AVAILABLE_MODULES = ... | 27 | 851 |
mlflow | dev/clint/src/clint/rules/assign_before_append.py | .py | import ast
from clint.rules.base import Rule
class AssignBeforeAppend(Rule):
def _message(self) -> str:
return (
"Avoid unnecessary assignment before appending to a list. "
"Use a list comprehension instead."
)
@staticmethod
def check(node: ast.For, prev_stmt: ast... | 65 | 2,027 |
mlflow | dev/clint/src/clint/rules/os_environ_set_in_test.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class OsEnvironSetInTest(Rule):
def _message(self) -> str:
return "Do not set `os.environ` in test directly. Use `monkeypatch.setenv` (https://docs.pytest.org/en/stable/reference/reference.html#pytest.MonkeyPatch.setenv)."
... | 20 | 700 |
mlflow | dev/clint/src/clint/rules/markdown_link.py | .py | from clint.rules.base import Rule
class MarkdownLink(Rule):
def _message(self) -> str:
return (
"Markdown link is not supported in docstring. "
"Use reST link instead (e.g., `Link text <link URL>`_)."
)
| 10 | 249 |
mlflow | dev/clint/src/clint/rules/lazy_module.py | .py | from clint.rules.base import Rule
class LazyModule(Rule):
def _message(self) -> str:
return "Module loaded by `LazyLoader` must be imported in `TYPE_CHECKING` block."
| 7 | 181 |
mlflow | dev/clint/src/clint/rules/do_not_disable.py | .py | from typing_extensions import Self
from clint.rules.base import Rule
class DoNotDisable(Rule):
RULES = {
"B006": "Use None as default and set value in function body instead of mutable defaults",
"F821": "Use typing.TYPE_CHECKING for forward references to optional dependencies",
}
def __i... | 30 | 937 |
mlflow | dev/clint/src/clint/rules/mock_patch_as_decorator.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class MockPatchAsDecorator(Rule):
def _message(self) -> str:
return (
"Do not use `unittest.mock.patch` as a decorator. "
"Use it as a context manager to avoid patches being active longer than needed ... | 28 | 981 |
mlflow | dev/clint/src/clint/rules/no_class_based_tests.py | .py | import ast
from typing_extensions import Self
from clint.rules.base import Rule
class NoClassBasedTests(Rule):
def __init__(self, class_name: str) -> None:
self.class_name = class_name
@classmethod
def check(cls, node: ast.ClassDef, path_name: str) -> Self | None:
# Only check in test f... | 36 | 932 |
mlflow | dev/clint/src/clint/rules/isinstance_union_syntax.py | .py | import ast
from clint.rules.base import Rule
class IsinstanceUnionSyntax(Rule):
def _message(self) -> str:
return (
"Use `isinstance(obj, (X, Y))` instead of `isinstance(obj, X | Y)`. "
"The union syntax with `|` is slower than using a tuple of types."
)
@staticmethod... | 53 | 1,749 |
mlflow | dev/clint/src/clint/rules/unsafe_version_parse.py | .py | import ast
from typing import TYPE_CHECKING
from clint.rules.base import Rule
if TYPE_CHECKING:
from clint.resolver import Resolver
class UnsafeVersionParse(Rule):
# Names/attributes that hold a raw Databricks runtime (DBR) version string. These are NOT
# PEP 440 (e.g. "18.x-aarch64-photon-scala2") and ... | 68 | 2,501 |
mlflow | dev/clint/src/clint/rules/unnamed_thread_pool.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class UnnamedThreadPool(Rule):
def _message(self) -> str:
return (
"`ThreadPoolExecutor()` must be called with a `thread_name_prefix` argument to improve "
"debugging and traceability of thread-relate... | 24 | 779 |
mlflow | dev/clint/src/clint/rules/incorrect_type_annotation.py | .py | import ast
from clint.rules.base import Rule
class IncorrectTypeAnnotation(Rule):
MAPPING = {
"callable": "Callable",
"any": "Any",
}
def __init__(self, type_hint: str) -> None:
self.type_hint = type_hint
@staticmethod
def check(node: ast.Name) -> bool:
return no... | 26 | 664 |
mlflow | dev/clint/src/clint/rules/forbidden_set_active_model_usage.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class ForbiddenSetActiveModelUsage(Rule):
def _message(self) -> str:
return (
"Usage of `set_active_model` is not allowed in mlflow, use `_set_active_model` instead."
)
@staticmethod
def check(no... | 23 | 667 |
mlflow | dev/clint/src/clint/rules/__init__.py | .py | from clint.rules.assign_before_append import AssignBeforeAppend
from clint.rules.base import Rule
from clint.rules.do_not_disable import DoNotDisable
from clint.rules.docstring_param_order import DocstringParamOrder
from clint.rules.empty_notebook_cell import EmptyNotebookCell
from clint.rules.example_syntax_error impo... | 125 | 5,227 |
mlflow | dev/clint/src/clint/rules/unknown_mlflow_function.py | .py | from clint.rules.base import Rule
class UnknownMlflowFunction(Rule):
def __init__(self, function_name: str) -> None:
self.function_name = function_name
def _message(self) -> str:
return (
f"Unknown MLflow function: `{self.function_name}`. "
"This function may not exist... | 13 | 356 |
mlflow | dev/clint/src/clint/rules/forbidden_deprecation_warning.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
def _is_deprecation_warning(expr: ast.expr) -> bool:
return isinstance(expr, ast.Name) and expr.id == "DeprecationWarning"
class ForbiddenDeprecationWarning(Rule):
def _message(self) -> str:
return (
"Do no... | 35 | 1,331 |
mlflow | dev/clint/src/clint/rules/use_walrus_operator.py | .py | import ast
from clint.rules.base import Rule
class UseWalrusOperator(Rule):
def _message(self) -> str:
return (
"Use the walrus operator `:=` when a variable is assigned and only used "
"within an `if` block that tests its truthiness. "
"For example, replace `a = ...; ... | 190 | 6,365 |
mlflow | dev/clint/src/clint/rules/prefer_dict_union.py | .py | import ast
from clint.rules.base import Rule
def _is_simple_name_or_attribute(node: ast.expr) -> bool:
"""
Check if a node is a simple name (e.g., `a`) or a chain of attribute
accesses on a simple name (e.g., `obj.attr` or `a.b.c`).
"""
if isinstance(node, ast.Name):
return True
if is... | 57 | 1,797 |
mlflow | dev/clint/src/clint/rules/mock_patch_dict_environ.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class MockPatchDictEnviron(Rule):
def _message(self) -> str:
return (
"Do not use `mock.patch.dict` to modify `os.environ` in tests; "
"use pytest's monkeypatch fixture (monkeypatch.setenv / monkeypat... | 47 | 1,482 |
mlflow | dev/clint/src/clint/rules/no_shebang.py | .py | from clint.rules.base import Rule
class NoShebang(Rule):
def _message(self) -> str:
return "Python scripts should not contain shebang lines"
@staticmethod
def check(file_content: str) -> bool:
"""
Returns True if the file contains a shebang line at the beginning.
A sheban... | 16 | 451 |
mlflow | dev/clint/src/clint/rules/forbidden_make_judge_in_builtin_scorers.py | .py | import ast
from pathlib import Path
from clint.resolver import Resolver
from clint.rules.base import Rule
class ForbiddenMakeJudgeInBuiltinScorers(Rule):
"""Ensure make_judge is not used in builtin_scorers.py.
After switching to InstructionsJudge in builtin_scorers.py, this rule
prevents future regressi... | 47 | 1,503 |
mlflow | dev/clint/src/clint/rules/forbidden_trace_ui_in_notebook.py | .py | from clint.rules.base import Rule
class ForbiddenTraceUIInNotebook(Rule):
def _message(self) -> str:
return (
"Found the MLflow Trace UI iframe in the notebook. "
"The trace UI in cell outputs will not render correctly in previews or the website. "
"Please run `mlflow.t... | 12 | 422 |
mlflow | dev/clint/src/clint/rules/subprocess_check_call.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class SubprocessCheckCall(Rule):
def _message(self) -> str:
return (
"Use `subprocess.check_call(...)` instead of `subprocess.run(..., check=True)` "
"for better readability. Only applies when check=T... | 44 | 1,269 |
mlflow | dev/clint/src/clint/rules/log_model_artifact_path.py | .py | import ast
from typing import TYPE_CHECKING
from clint.rules.base import Rule
from clint.utils import resolve_expr
if TYPE_CHECKING:
from clint.index import SymbolIndex
class LogModelArtifactPath(Rule):
def _message(self) -> str:
return "`artifact_path` parameter of `log_model` is deprecated. Use `n... | 55 | 1,800 |
mlflow | dev/clint/src/clint/rules/prefer_os_environ.py | .py | import ast
from typing import Literal
from typing_extensions import Self
from clint.resolver import Resolver
from clint.rules.base import Rule
# See https://github.com/astral-sh/ruff/issues/3608
class PreferOsEnviron(Rule):
def __init__(self, func: Literal["getenv", "putenv"]) -> None:
self.func = func
... | 26 | 770 |
mlflow | dev/clint/src/clint/rules/prefer_next.py | .py | import ast
from clint.rules.base import Rule
class PreferNext(Rule):
def _message(self) -> str:
return (
"Use `next(x for x in items if condition)` instead of "
"`[x for x in items if condition][0]` for finding the first matching element."
)
@staticmethod
def chec... | 37 | 1,159 |
mlflow | dev/clint/src/clint/rules/unparameterized_generic_type.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class UnparameterizedGenericType(Rule):
def __init__(self, type_hint: str) -> None:
self.type_hint = type_hint
@staticmethod
def is_generic_type(node: ast.Name | ast.Attribute, resolver: Resolver) -> bool:
i... | 33 | 902 |
mlflow | dev/clint/src/clint/rules/invalid_experimental_decorator.py | .py | import ast
from packaging.version import InvalidVersion, Version
from clint.resolver import Resolver
from clint.rules.base import Rule
def _is_valid_version(version: str) -> bool:
try:
v = Version(version)
return not (v.is_devrelease or v.is_prerelease or v.is_postrelease)
except InvalidVers... | 54 | 1,614 |
mlflow | dev/clint/src/clint/rules/extraneous_docstring_param.py | .py | from clint.rules.base import Rule
class ExtraneousDocstringParam(Rule):
def __init__(self, params: set[str]) -> None:
self.params = params
def _message(self) -> str:
return f"Extraneous parameters in docstring: {self.params}"
| 10 | 253 |
mlflow | dev/clint/src/clint/rules/unnamed_thread.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class UnnamedThread(Rule):
def _message(self) -> str:
return (
"`threading.Thread()` must be called with a `name` argument to improve debugging "
"and traceability of thread-related issues."
)... | 24 | 715 |
mlflow | dev/clint/src/clint/rules/missing_docstring_param.py | .py | from clint.rules.base import Rule
class MissingDocstringParam(Rule):
def __init__(self, params: set[str]) -> None:
self.params = params
def _message(self) -> str:
return f"Missing parameters in docstring: {self.params}"
| 10 | 247 |
mlflow | dev/clint/src/clint/rules/forbidden_top_level_import.py | .py | from clint.rules.base import Rule
class ForbiddenTopLevelImport(Rule):
def __init__(self, module: str) -> None:
self.module = module
def _message(self) -> str:
return (
f"Importing module `{self.module}` at the top level is not allowed "
"in this file. Use lazy import ... | 13 | 340 |
mlflow | dev/clint/src/clint/rules/tempfile_in_test.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class TempfileInTest(Rule):
def _message(self) -> str:
return (
"Do not use `tempfile` in tests. Use the `tmp_path` fixture instead "
"(https://docs.pytest.org/en/stable/reference/reference.html#tmp-p... | 24 | 683 |
mlflow | dev/clint/src/clint/rules/get_artifact_uri.py | .py | from clint.rules.base import Rule
class GetArtifactUri(Rule):
def _message(self) -> str:
return (
"`mlflow.get_artifact_uri` should not be used in examples. "
"Use the return value of `log_model` instead."
)
| 10 | 254 |
mlflow | dev/clint/src/clint/rules/docstring_param_order.py | .py | from clint.rules.base import Rule
class DocstringParamOrder(Rule):
def __init__(self, params: list[str]) -> None:
self.params = params
def _message(self) -> str:
return f"Unordered parameters in docstring: {self.params}"
| 10 | 248 |
mlflow | dev/clint/src/clint/rules/unknown_mlflow_arguments.py | .py | from clint.rules.base import Rule
class UnknownMlflowArguments(Rule):
def __init__(self, function_name: str, unknown_args: set[str]) -> None:
self.function_name = function_name
self.unknown_args = unknown_args
def _message(self) -> str:
args_str = ", ".join(f"`{arg}`" for arg in sorte... | 15 | 518 |
mlflow | dev/clint/src/clint/rules/example_syntax_error.py | .py | from clint.rules.base import Rule
class ExampleSyntaxError(Rule):
def _message(self) -> str:
return "This example has a syntax error."
| 7 | 149 |
mlflow | dev/clint/src/clint/rules/nested_mock_patch.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class NestedMockPatch(Rule):
def _message(self) -> str:
return (
"Do not nest `unittest.mock.patch` context managers. "
"Use multiple context managers in a single `with` statement instead: "
... | 55 | 1,963 |
mlflow | dev/clint/src/clint/rules/implicit_optional.py | .py | import ast
from clint.rules.base import Rule
class ImplicitOptional(Rule):
def _message(self) -> str:
return "Use `Optional` if default value is `None`"
@staticmethod
def check(node: ast.AnnAssign) -> bool:
"""
Returns True if the value to assign is `None` but the type annotation... | 61 | 1,988 |
mlflow | dev/clint/src/clint/rules/typing_extensions.py | .py | from clint.rules.base import Rule
class TypingExtensions(Rule):
def __init__(self, *, full_name: str, allowlist: list[str]) -> None:
self.full_name = full_name
self.allowlist = allowlist
def _message(self) -> str:
return (
f"`{self.full_name}` is not allowed to use. Only {... | 16 | 594 |
mlflow | dev/clint/src/clint/rules/use_sys_executable.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class UseSysExecutable(Rule):
def _message(self) -> str:
return (
"Use `[sys.executable, '-m', 'mlflow', ...]` when running mlflow CLI in a subprocess."
)
@staticmethod
def check(node: ast.Call, ... | 35 | 1,105 |
mlflow | dev/clint/src/clint/rules/empty_notebook_cell.py | .py | from clint.rules.base import Rule
class EmptyNotebookCell(Rule):
def _message(self) -> str:
return "Empty notebook cell. Remove it or add some content."
| 7 | 167 |
mlflow | dev/clint/src/clint/rules/redundant_test_docstring.py | .py | """Rule to detect redundant docstrings in test files.
This rule flags:
- ALL single-line docstrings in test functions and classes (multi-line
function/class docstrings are allowed since they generally provide
meaningful context).
- ALL module-level docstrings in test files (single- or multi-line).
"""
import ast
... | 65 | 2,096 |
mlflow | dev/clint/src/clint/rules/except_bool_op.py | .py | import ast
from clint.rules.base import Rule
class ExceptBoolOp(Rule):
def _message(self) -> str:
return (
"Did you mean `except (X, Y):`? Using or/and in an except handler is likely a mistake."
)
@staticmethod
def check(node: ast.ExceptHandler) -> bool:
return isinst... | 15 | 348 |
mlflow | dev/clint/src/clint/rules/redundant_mock_return_value.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class RedundantMockReturnValue(Rule):
def _message(self) -> str:
return (
"Do not pass `return_value=MagicMock()` or `return_value=Mock()` to `patch()`. "
"The default return value of a mock is alread... | 37 | 1,181 |
mlflow | dev/clint/src/clint/rules/invalid_abstract_method.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class InvalidAbstractMethod(Rule):
def _message(self) -> str:
return (
"Abstract method should only contain a single statement/expression, "
"and it must be `pass`, `...`, or a docstring."
)
... | 51 | 1,684 |
mlflow | dev/clint/src/clint/rules/mlflow_class_name.py | .py | from clint.rules.base import Rule
class MlflowClassName(Rule):
def _message(self) -> str:
return "Should use `Mlflow` in class name, not `MLflow` or `MLFlow`."
| 7 | 174 |
mlflow | dev/clint/src/clint/rules/use_gh_token.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class UseGhToken(Rule):
def _message(self) -> str:
return "Use GH_TOKEN instead of GITHUB_TOKEN for the environment variable name."
@staticmethod
def check(node: ast.Call, resolver: Resolver) -> bool:
"""
... | 25 | 774 |
mlflow | dev/clint/src/clint/rules/base.py | .py | import inspect
import itertools
import re
from abc import ABC, abstractmethod
from typing import Any
_id_counter = itertools.count(start=1)
_CLASS_NAME_TO_RULE_NAME_REGEX = re.compile(r"(?<!^)(?=[A-Z])")
class Rule(ABC):
id: str
name: str
def __init_subclass__(cls, **kwargs: Any) -> None:
super(... | 32 | 798 |
mlflow | dev/clint/src/clint/rules/multi_assign.py | .py | import ast
from clint.rules.base import Rule
class MultiAssign(Rule):
def _message(self) -> str:
return (
"Avoid multiple assignment (e.g., `x, y = func()`). Use separate assignments "
"instead for better readability and easier debugging."
)
@staticmethod
def chec... | 52 | 1,779 |
mlflow | dev/clint/src/clint/rules/unused_disable_comment.py | .py | from clint.rules.base import Rule
class UnusedDisableComment(Rule):
def __init__(self, rule_name: str) -> None:
self.rule_name = rule_name
def _message(self) -> str:
return f"Unused disable comment for rule `{self.rule_name}`"
| 10 | 254 |
mlflow | dev/clint/src/clint/rules/test_name_typo.py | .py | from clint.rules.base import Rule
class TestNameTypo(Rule):
def _message(self) -> str:
return "This function looks like a test, but its name does not start with 'test_'."
| 7 | 185 |
mlflow | dev/clint/src/clint/rules/version_major_check.py | .py | import ast
import re
from typing import TYPE_CHECKING
from clint.rules.base import Rule
if TYPE_CHECKING:
from clint.resolver import Resolver
class MajorVersionCheck(Rule):
def _message(self) -> str:
return (
"Use `.major` field for major version comparisons instead of full version strin... | 58 | 1,899 |
mlflow | dev/clint/src/clint/rules/missing_notebook_h1_header.py | .py | from clint.rules.base import Rule
class MissingNotebookH1Header(Rule):
def _message(self) -> str:
return "Notebook should have at least one H1 header for the title."
| 7 | 180 |
mlflow | dev/dev_stubs/__init__.py | .py | """Credential-free dev/CI stubs for reviewing provider-gated MLflow UI.
``run_dev_server.py --stub-providers <names>`` installs these before launching
the dev server so features gated on external providers/credentials render
without real keys, cost, or nondeterminism.
- ``claude`` -- a fake ``claude`` CLI on PATH, sa... | 87 | 3,021 |
mlflow | dev/dev_stubs/claude_cli.py | .py | """Credential-free stub `claude` CLI for reviewing provider-gated Assistant UI.
The MLflow Assistant's "Claude Code" provider only reveals its chat panel after
an auth probe succeeds: it shells out to
``claude -p hi --max-turns 1 --output-format json`` and unlocks the UI when that
exits 0 (see ``mlflow/assistant/provi... | 110 | 4,093 |
mlflow | docs/api_reference/broken_links.py | .py | import contextlib
import socket
import subprocess
import sys
import time
import requests
from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
def get_safe_port():
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_ST... | 73 | 1,987 |
mlflow | docs/api_reference/gateway_api_docs.py | .py | import json
import tempfile
from pathlib import Path
from mlflow.gateway.app import create_app_from_path
# This HTML was obtained by sending a request to the `/docs` route and saving the response.
# To hide the "try it out" button, we set `supportedSubmitMethods` to an empty list.
# The url was changed to "./openapi.... | 94 | 2,529 |
mlflow | docs/api_reference/mcp_server_registry_api_docs.py | .py | import json
from pathlib import Path
from fastapi import FastAPI
from mlflow.server.mcp_server_api import mcp_server_router
API_HTML = """
<!DOCTYPE html>
<html>
<head>
<link
type="text/css"
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css"
/>
<link... | 63 | 1,656 |
mlflow | docs/api_reference/conftest.py | .py | import os
import pytest
import mlflow
@pytest.fixture(autouse=True)
def tracking_uri_mock(tmp_path, monkeypatch):
tracking_uri = "sqlite:///{}".format(tmp_path / "mlruns.sqlite")
mlflow.set_tracking_uri(tracking_uri)
monkeypatch.setenv("MLFLOW_TRACKING_URI", tracking_uri)
yield
mlflow.set_tracki... | 29 | 676 |
mlflow | docs/api_reference/theme/mlflow/__init__.py | .py | """Sphinx ReadTheDocs theme.
From https://github.com/ryan-roemer/sphinx-bootstrap-theme.
"""
import os
VERSION = (0, 1, 9)
__version__ = ".".join(str(v) for v in VERSION)
__version_full__ = __version__
def get_html_theme_path():
"""Return list of HTML theme paths."""
return os.path.abspath(os.path.dirnam... | 18 | 350 |
mlflow | docs/api_reference/source/testcode_block.py | .py | """
Standalone script to extract code blocks marked with :test: from Python docstrings.
Uses AST to parse Python files and extract docstrings with test code blocks.
"""
import ast
import re
import subprocess
import textwrap
from pathlib import Path
_CODE_BLOCK_HEADER_REGEX = re.compile(r"^\.\.\s+code-block::\s*py(tho... | 212 | 7,011 |
mlflow | docs/api_reference/source/languagesections/__init__.py | .py | import os
from docutils import nodes
from docutils.parsers.rst import Directive
from sphinx.util import logging
from sphinx.util.osutil import copyfile
logger = logging.getLogger(__name__)
JS_FILE = "languagesections.js"
class CodeSectionDirective(Directive):
has_content = True
def run(self):
self... | 58 | 1,607 |
mlflow | docs/scripts/build-all.py | .py | import os
import shutil
import subprocess
from pathlib import Path
import click
import mlflow
mlflow_version = mlflow.version.VERSION
def build_docs(package_manager, version):
env = os.environ.copy()
# ensure it ends with a "/"
base_url = env.get("DOCS_BASE_URL", "/docs/").rstrip("/") + "/"
api_re... | 93 | 2,366 |
mlflow | docs/scripts/convert-notebooks.py | .py | """
Converts all .ipynb files from the docs/ folder into .mdx files.
This script uses nbconvert to do the processing.
"""
import multiprocessing
import re
from pathlib import Path
import nbformat
import yaml
from nbconvert.exporters import MarkdownExporter
from nbconvert.preprocessors import Preprocessor
SOURCE_DIR... | 118 | 3,591 |
mlflow | docs/scripts/build-api-docs.py | .py | import os
import shutil
import subprocess
import click
@click.command()
@click.option("--with-r", "with_r", is_flag=True, default=False, help="Build R documentation")
@click.option(
"--with-ts", "with_ts", is_flag=True, default=True, help="Build TypeScript documentation"
)
def main(with_r, with_ts):
try:
... | 44 | 1,550 |
mlflow | tests/generate_ui_test_data.py | .py | """
Small script used to generate mock data to test the UI.
"""
import argparse
import itertools
import random
import string
from random import random as rand
import mlflow
from mlflow import MlflowClient
def log_metrics(metrics):
for k, values in metrics.items():
for v in values:
mlflow.log... | 195 | 6,890 |
mlflow | tests/test_exceptions.py | .py | import json
import pickle
import pytest
from mlflow.exceptions import MlflowException, RestException
from mlflow.protos.databricks_pb2 import (
ENDPOINT_NOT_FOUND,
INTERNAL_ERROR,
INVALID_PARAMETER_VALUE,
INVALID_STATE,
IO_ERROR,
RESOURCE_ALREADY_EXISTS,
)
def test_error_code_constructor():
... | 213 | 7,849 |
mlflow | tests/test_environment_variables.py | .py | import os
import pytest
from mlflow.environment_variables import _BooleanEnvironmentVariable, _EnvironmentVariable
@pytest.mark.parametrize("value", [0, 1, "0", "1", "TRUE", "FALSE"])
def test_boolean_environment_variable_invalid_default_value(value):
with pytest.raises(ValueError, match=r"must be one of \[True... | 91 | 3,104 |
mlflow | tests/test_flavors.py | .py | import ast
import os
import mlflow
def read_file(path):
with open(path) as f:
return f.read()
def is_model_flavor(src):
for node in ast.iter_child_nodes(ast.parse(src)):
if (
isinstance(node, ast.Assign)
and isinstance(node.targets[0], ast.Name)
and node.... | 41 | 988 |
mlflow | tests/simple_repository_server.py | .py | """PEP 700-compliant Simple Repository API server for serving wheels in tests.
This replaces the plain ``http.server`` approach so that uv's ``exclude-newer``
can filter packages by upload time when resolving the local dev wheel.
"""
from __future__ import annotations
import hashlib
import json
import threading
from... | 125 | 4,427 |
mlflow | tests/test_skinny_client_omits_data_science_libs.py | .py | import os
import pytest
@pytest.fixture(autouse=True)
def is_skinny():
if "MLFLOW_SKINNY" not in os.environ:
pytest.skip("This test is only valid for the skinny client")
def test_fails_import_flask():
import mlflow # noqa: F401
with pytest.raises(ImportError, match="flask"):
import fl... | 31 | 647 |
mlflow | tests/test_version.py | .py | from mlflow import version
def test_is_release_version(monkeypatch):
monkeypatch.setattr(version, "VERSION", "1.19.0")
assert version.is_release_version()
monkeypatch.setattr(version, "VERSION", "1.19.0.dev0")
assert not version.is_release_version()
| 10 | 269 |
mlflow | tests/__init__.py | .py | from mlflow.utils.logging_utils import _configure_mlflow_loggers
_configure_mlflow_loggers(root_module_name=__name__)
| 4 | 119 |
mlflow | tests/test_mismatch.py | .py | import warnings
from importlib.metadata import PackageNotFoundError
from unittest import mock
import pytest
from mlflow.mismatch import _check_version_mismatch
@pytest.mark.parametrize(
("mlflow_version", "skinny_version"),
[
("1.0.0", "1.0.0"),
("1.0.0.dev0", "1.0.0"),
("1.0.0", "1.... | 85 | 2,706 |
mlflow | tests/test_skinny_client_omits_sql_libs.py | .py | import os
import sys
import pytest
@pytest.mark.skipif(
"MLFLOW_SKINNY" not in os.environ, reason="This test is only valid for the skinny client"
)
def test_fails_import_sqlalchemy():
import mlflow # noqa: F401
with pytest.raises(ImportError, match="sqlalchemy"):
import sqlalchemy # noqa: F401... | 30 | 776 |
mlflow | tests/check_mlflow_lazily_imports_ml_packages.py | .py | """
Tests that `import mlflow` and `mlflow.autolog()` do not import ML packages.
"""
import importlib
import logging
import sys
import mlflow
logger = logging.getLogger()
def main():
ml_packages = {
"catboost",
"h2o",
"lightgbm",
"onnx",
"pytorch_lightning",
"pys... | 57 | 1,380 |
mlflow | tests/test_skinny_client_autolog_without_scipy.py | .py | import os
import pytest
@pytest.mark.skipif(
"MLFLOW_SKINNY" not in os.environ, reason="This test is only valid for the skinny client"
)
def test_autolog_without_scipy():
import mlflow
with pytest.raises(ImportError, match="scipy"):
import scipy # noqa: F401
assert not mlflow.models.utils.... | 19 | 389 |
mlflow | tests/helper_functions.py | .py | import functools
import json
import logging
import numbers
import os
import random
import signal
import socket
import subprocess
import sys
import tempfile
import time
import uuid
from contextlib import contextmanager
from functools import wraps
from pathlib import Path
from typing import Iterator
from unittest import ... | 854 | 27,931 |
mlflow | tests/test_mlflow_version_comp.py | .py | import os
import subprocess
import sys
import uuid
from pathlib import Path
import numpy as np
import sklearn
from pyspark.sql import SparkSession
from sklearn.linear_model import LinearRegression
import mlflow
from mlflow.models import Model
def check_load(model_uri: str) -> None:
Model.load(model_uri)
mod... | 230 | 9,038 |
mlflow | tests/test_xdist_serial_partition.py | .py | # Tests for the xdist serial/parallel partition used by the two-pass `python` CI job.
#
# The `python` job runs the suite twice: `--serial=exclude` (parallel bulk) and
# `--serial=only` (serial tail). The safety-critical property is that these two passes
# form an *exhaustive, disjoint* partition of the collected tests... | 198 | 9,104 |
mlflow | tests/test_import.py | .py | import subprocess
import sys
from pathlib import Path
import pytest
from mlflow.utils.os import is_windows
@pytest.mark.skipif(is_windows(), reason="This test fails on Windows")
def test_import_mlflow(tmp_path: Path):
tmp_script = tmp_path.joinpath("test.py")
tmp_script.write_text(
"""
from pathlib ... | 36 | 822 |
mlflow | tests/test_cli.py | .py | import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from unittest import mock
from urllib.parse import unquote, urlparse
from urllib.request import url2pathname
import click
import numpy as np
import pytest
import requests
from botocore.stub import Stubber
from cli... | 1,893 | 67,287 |
mlflow | tests/test_runs.py | .py | import json
import logging
import os
import textwrap
from unittest import mock
from unittest.mock import patch
import pytest
from click.testing import CliRunner
import mlflow
from mlflow import experiments
from mlflow.exceptions import MlflowException
from mlflow.runs import create_run, link_traces, list_run
from mlf... | 597 | 19,179 |
mlflow | tests/test_skinny_client_anthropic_import.py | .py | # Regression test for https://github.com/mlflow/mlflow/issues/21779:
# mlflow-skinny users couldn't use mlflow.anthropic.autolog() because importing
# mlflow.types.chat transitively pulled in numpy via
# mlflow.types.__init__ -> mlflow.types.llm -> mlflow.types.schema.
import importlib.util
import os
import pytest
... | 25 | 876 |
mlflow | tests/conftest.py | .py | import cProfile
import inspect
import io
import json
import logging
import os
import posixpath
import pstats
import re
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import threading
import time
import uuid
from collections import defaultdict
from contextlib import nullcontext
from dataclasse... | 1,405 | 50,338 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.