Files
OpenBB/openbb_platform/dev_install.py
dlee-bq 53d4dcc46d [Feature] Drop Python 3.10 and Resolve Open Dependabot Alerts (#7804)
* Drop Python 3.10 support

Python 3.10 reached end of life on 2026-10-01, and the patched releases of
Pillow (13.0.0) and filelock (>=4.2.1) require Python >=3.11, so the 3.10
resolution fork kept vulnerable versions in every lockfile.

- requires-python = ">=3.11,<4" in all pyproject.toml files, the
  cookiecutter template, and the CLI codegen project template
- CI: drop the ubuntu 3.10 matrix rows, move the macOS/Windows minimum
  rows and the lint jobs to 3.11, drop 3.10 from the nox sessions
- READMEs: state 3.11 as the minimum supported version

* Relock with patched certifi, filelock, virtualenv, Pillow, and fastmcp

Regenerate all 38 uv.lock files against requires-python >=3.11 and upgrade
only the packages with open Dependabot advisories:

- certifi 2026.7.22 -> 2026.10.23 (GHSA-6q48-6c7w-9gw2, compromised emSign CAs)
- virtualenv 21.14.7 -> 21.14.13
- filelock 4.1.0/4.2.0 -> 4.2.4
- Pillow 12.3.0 -> 13.0.0
- fastmcp / fastmcp-slim 4.1.0 -> 4.1.3

All other changes are removed Python 3.10-only resolution forks; no other
package changes version for Python 3.11+.

* desktop: bump zod, @hookform/resolvers, and vitest

- zod ^3.25.76 -> ^4.6.7 (GHSA-mrhx-c7xc-m3w5; no patched 3.x exists)
- @hookform/resolvers ^3.10.0 -> ^5.9.2 for zod 4 support
- vitest ^4.1.11 -> ^4.1.12 (@vitest/mocker GHSA-qxg6-89mg-rqv8,
  GHSA-xp26-3454-mjgp)
- override zod to the root version so @openbb/ui-pro, which declares
  zod ^3 but never imports it, does not pull in a second, vulnerable copy

* desktop: remove Python 3.10 from environment pickers

- version pickers in InstallComponents and AddExtensionSelector start at 3.11
- create_environment_from_requirements accepts 3.11 through 3.14 and falls
  back to 3.12 otherwise (previously 3.10 through 3.13)
- component tests select 3.11 instead of 3.10

* Remove Python 3.10 tomli fallbacks

With requires-python >=3.11, tomllib is always available, so the
version-conditional tomli imports are dead code.

- import tomllib directly in the cli and core config loaders, the
  mcp_server and platform_api config validators, dev_install.py, and
  the cli and cookiecutter tests; dev_install.py no longer pip-installs
  tomli on the fly
- drop the tomli>=2.0; python_version<'3.11' dependency from cli, core,
  mcp_server, and platform_api, plus platform_api's backport comment
- raise the fake-extension fixtures in cli/conftest.py,
  core/integration/conftest.py, and the charting test metadata to
  >=3.11
- relock cli, core, mcp_server, and platform_api; only the tomli
  requires-dist entry is removed and resolution markers are reordered,
  no package versions change

* Target Python 3.11 in ruff and ty for cli, core, mcp_server, platform_api, cookiecutter

With ruff target-version py310 and ty python-version 3.10, both tools
reject an unconditional `import tomllib`: ty reports it as unresolved
(exit 1) and ruff's isort classifies it as third-party. Raise the targets
in the projects that now import tomllib directly, and in the root
ruff.toml that governs dev_install.py.

- ruff target-version = "py311" and ty python-version = "3.11" in cli,
  core, mcp_server, platform_api, and cookiecutter; root ruff.toml
  target-version = "py311"
- UP042: OutputMode, ChartLifecycle, MCPType, and HTTPMethod become
  StrEnum; every consumer uses .value or == comparisons, so only str()
  and format() output change
- UP017: datetime.timezone.utc -> datetime.UTC (ruff autofix) in the cli
  dispatchers, the cli test generator, and a core test

* Fix ruff and ty failures in packages this PR touches

CI installs unpinned dependencies, so the lint jobs ran against
pandas 3.1.0, ruff 0.17.2, and ty 0.0.91.

- cli/conftest.py: guard the find_spec("openbb") lookup so ty no longer
  reports an Optional ModuleSpec/origin (failing Lint openbb-cli)
- quantitative: pandas 3.1 types Index.max() as object; cast max_date to
  Timestamp before period_start in attribution, factors, and
  risk_decomposition (failing ty)
- federal_reserve: use Series(...).dt.date instead of
  DatetimeIndex.date so neither pandas 3.0 nor 3.1 needs a ty: ignore
  (pandas 3.1 made the existing ignores unused, failing ty)
- core tests: type the filter_by_dates doubles as Data subclasses and
  cast the deliberate bad arguments in test_helpers.py; apply ruff format
  to test_docstring_generator_helpers.py
- platform_api README: apply ruff format to the Python code blocks

* Fix pandas 3.1 deprecations failing fred, sec, and eia tests

These suites turn warnings into errors, and pandas 3.1.0 adds
Pandas4Warning deprecations for several patterns they use. Every change
also passes with the locked pandas 3.0.6.

- fred, sec: replace inplace=True sort_values/reset_index/rename/
  set_index/drop with reassignment
- fred balance_of_payments, sec as_filed_widget: replace fillna with a
  string on float columns by astype(object).where(notna, ...)
- sec: build quarter start dates from ISO strings instead of parsing
  "2024Q2"-style strings; use the DataFrame constructor instead of
  DataFrame.from_records for column dicts; pad CIK lookup rows to two
  fields instead of constructing a ragged DataFrame
- eia: read EIA workbooks with the calamine engine (xlrd is deprecated);
  replace the xlrd dependency with python-calamine and relock; calamine
  workbooks are not safe for concurrent reads, so the petroleum status
  report serializes its sheet reads with a lock

* imf: fall back to the published catalog when the IMF API is unreachable

imf_cache.json.xz is generated at build time and is not committed, so
every CI build of openbb-imf needed a live api.imf.org. The only fallback
was actions/cache, and caches saved by pull_request runs are scoped to
that PR, so a new PR never had one. With api.imf.org returning
"503 no healthy upstream" during IMF's data portal maintenance window,
the build failed.

When live generation fails on a non-forced build, the hook now copies
imf_cache.json.xz from the latest openbb-imf wheel on PyPI, after
checking the wheel's sha256 against the digest PyPI publishes. Builds
with OPENBB_IMF_FORCE_CACHE_REBUILD=1, which the publish workflow sets,
still fail hard, so a release never ships a stale catalog.

---------

Co-authored-by: dlee-bq <325002271+dlee-bq@users.noreply.github.com>
2026-11-01 18:16:45 +00:00

298 lines
8.8 KiB
Python

"""Install the tracked, published OpenBB packages in editable mode."""
# flake8: noqa: S603, S607
import argparse
import os
import re
import shutil
import subprocess
import sys
import time
import tomllib
from importlib.util import find_spec
from pathlib import Path
PLATFORM_PATH = Path(__file__).parent.resolve()
REPO_PATH = PLATFORM_PATH.parent
PACKAGE_GLOBS = (
"openbb_platform/core/pyproject.toml",
"openbb_platform/extensions/*/pyproject.toml",
"openbb_platform/obbject_extensions/*/pyproject.toml",
"openbb_platform/providers/*/pyproject.toml",
"cli/pyproject.toml",
)
ROUTERS_PATH = Path("openbb_platform/extensions")
ALWAYS_INSTALLED_ROUTERS = frozenset({"openbb-news"})
UV_BUILD_LOG = "uv_build_frontend=debug"
REQUIREMENT_NAME_RE = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)")
def log(message: str) -> None:
"""Write a progress line to stdout immediately.
Parameters
----------
message : str
The line to write.
"""
sys.stdout.write(f"[dev_install] {message}\n")
sys.stdout.flush()
def run_step(title: str, command: list[str], env: dict[str, str]) -> None:
"""Run one install step, streaming its output and reporting its duration.
Parameters
----------
title : str
The step name shown in the progress lines.
command : list[str]
The command to run from the repository root.
env : dict[str, str]
The environment for the command.
"""
log(f"{title}...")
start = time.monotonic()
subprocess.run(command, cwd=REPO_PATH, env=env, check=True)
log(f"{title} finished in {time.monotonic() - start:.1f}s")
def get_uv() -> list[str]:
"""Return the command that invokes uv.
Returns
-------
list[str]
The uv module of the running interpreter, else the uv executable on PATH.
Raises
------
SystemExit
If uv is not installed.
"""
if find_spec("uv"):
return [sys.executable, "-m", "uv"]
uv = shutil.which("uv")
if uv:
return [uv]
sys.exit(
"dev_install.py requires uv: "
"https://docs.astral.sh/uv/getting-started/installation/"
)
def load_toml(path: Path) -> dict:
"""Parse a TOML file.
Parameters
----------
path : Path
The TOML file to read.
Returns
-------
dict
The parsed document.
"""
return tomllib.loads(path.read_text(encoding="utf-8"))
def get_tracked_packages() -> list[Path]:
"""Return the repository-relative directory of every tracked, published package.
Returns
-------
list[Path]
Package directories, sorted.
"""
result = subprocess.run(
["git", "ls-files", "-z", "--", *(f":(glob){g}" for g in PACKAGE_GLOBS)],
cwd=REPO_PATH,
capture_output=True,
text=True,
check=True,
)
return sorted(Path(f).parent for f in result.stdout.split("\0") if f)
def is_optional_router(package: Path, pyproject: dict) -> bool:
"""Return whether a package is a router extension installed only with --routers.
Parameters
----------
package : Path
The repository-relative package directory.
pyproject : dict
The package's parsed pyproject.toml.
Returns
-------
bool
True for an extension that registers an `openbb_core_extension` router,
other than those in ALWAYS_INSTALLED_ROUTERS.
"""
project = pyproject.get("project", {})
return (
package.parent == ROUTERS_PATH
and "openbb_core_extension" in project.get("entry-points", {})
and project.get("name") not in ALWAYS_INSTALLED_ROUTERS
)
def normalize_name(name: str) -> str:
"""Return the PEP 503 normalized form of a distribution name.
Parameters
----------
name : str
The distribution name.
Returns
-------
str
The lowercase name with runs of ``-``, ``_``, and ``.`` collapsed to ``-``.
"""
return re.sub(r"[-_.]+", "-", name).lower()
def get_editable_target(package: Path, pyproject: dict) -> str:
"""Return the editable install target for a package, with all of its extras.
Parameters
----------
package : Path
The repository-relative package directory.
pyproject : dict
The package's parsed pyproject.toml.
Returns
-------
str
The package path, followed by ``[extra,...]`` when it declares extras.
"""
extras = sorted(pyproject.get("project", {}).get("optional-dependencies", {}))
return package.as_posix() + (f"[{','.join(extras)}]" if extras else "")
def resolve_dev_requirements(
pyprojects: dict[Path, dict], selected: list[Path]
) -> tuple[list[Path], list[str], list[str]]:
"""Resolve the ``dev`` dependency groups of the selected packages.
Parameters
----------
pyprojects : dict[Path, dict]
The parsed pyproject.toml of every tracked package, by directory.
selected : list[Path]
The packages being installed.
Returns
-------
tuple[list[Path], list[str], list[str]]
Tracked packages that are only dev dependencies and install editable,
requirements to install from the index, and local path-sourced
requirements outside the tracked packages, such as test fixtures,
that are left out.
"""
tracked = {
normalize_name(pyproject["project"]["name"]): package
for package, pyproject in pyprojects.items()
}
editables: list[Path] = []
requirements: list[str] = []
skipped: list[str] = []
for package in selected:
pyproject = pyprojects[package]
sources = {
normalize_name(name): source
for name, source in pyproject.get("tool", {})
.get("uv", {})
.get("sources", {})
.items()
}
for requirement in pyproject.get("dependency-groups", {}).get("dev", []):
match = REQUIREMENT_NAME_RE.match(requirement)
name = normalize_name(match.group(1)) if match else ""
if name in tracked:
target = tracked[name]
if target not in selected and target not in editables:
editables.append(target)
elif isinstance(sources.get(name), dict) and "path" in sources[name]:
if requirement not in skipped:
skipped.append(requirement)
elif requirement not in requirements:
requirements.append(requirement)
return editables, requirements, skipped
def main(argv: list[str] | None = None) -> None:
"""Install the packages into the running interpreter and build the static assets.
Parameters
----------
argv : list[str] | None
Command-line arguments, defaulting to sys.argv.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--routers",
action="store_true",
help="Also install the router extensions (equity, economy, fixedincome, ...).",
)
args = parser.parse_args(argv)
log(f"Installing into {sys.executable}")
pyprojects = {
package: load_toml(REPO_PATH / package / "pyproject.toml")
for package in get_tracked_packages()
}
selected = [
package
for package, pyproject in pyprojects.items()
if args.routers or not is_optional_router(package, pyproject)
]
install_args: list[str] = []
for package in selected:
install_args += [
"--editable",
get_editable_target(package, pyprojects[package]),
]
log(f" + {package.as_posix()}")
skipped_routers = [
package.name for package in pyprojects if package not in selected
]
editables, requirements, skipped_local = resolve_dev_requirements(
pyprojects, selected
)
for package in editables:
install_args += [
"--editable",
get_editable_target(package, pyprojects[package]),
]
log(f" + {package.as_posix()} (dev dependency)")
install_args += requirements
log(f"Dev requirements: {', '.join(requirements)}")
if skipped_routers:
log(
"Skipping routers (pass --routers to include): "
f"{', '.join(skipped_routers)}"
)
if skipped_local:
log(f"Skipping local test packages: {', '.join(skipped_local)}")
run_step(
"Resolving, building, and installing with uv "
"(package builds and their hook output stream below)",
[*get_uv(), "pip", "install", "--python", sys.executable, *install_args],
{**os.environ, "RUST_LOG": os.environ.get("RUST_LOG", UV_BUILD_LOG)},
)
run_step(
"Building the openbb package",
[sys.executable, "-c", "import openbb; openbb.build(verbose=True)"],
{**os.environ, "OPENBB_AUTO_BUILD": "false"},
)
log("Done")
if __name__ == "__main__":
main()