utils/dep_freshness/resolve.py
Krzysztof kuhy Rudnicki 2a2f18ca56 Add the shared dependency-freshness gate
"Are we on the newest version?" was not mechanically answerable across these
repos: constraint styles had drifted per-ecosystem and a caret range is
"newest-compatible" by definition, which gives a checker nothing to compare.
This gate makes it answerable and then enforces the answer.

Checks two things at once -- that every dependency carries an exact pin, and
that the pin equals its registry's latest STABLE release -- across pub.dev,
PyPI, npm, crates.io, the Go proxy, kuhyx/utils git tags, and the Flutter /
Node / Python toolchains.

Three deliberate design points:

* Pre-releases are rejected per-ecosystem, because every ecosystem leaks them
  differently and each leak fails GREEN. npm lets a maintainer point
  `dist-tags.latest` at an rc; crates.io's `max_version` includes them; PyPI's
  legacy `info.version` includes yanked releases. Unit-tested with fixtures,
  since an end-to-end run cannot surface a wrong "up to date".

* Offline, the gate serves an expired cache entry and PASSES with a DEGRADED
  banner (exit 3 only under --strict, which is CI). `--no-verify` is banned
  here, so a hook that hard-failed offline would leave no way to commit at all.

* The allowlist has two entry classes. `blocked_by: transitive:<pkg>@<ver>` is
  a predicate that clears itself when upstream moves and must NOT carry a
  date; everything else is discretionary and requires `expires`, capped at 90
  days. Exact pins plus latest-everywhere is provably unsatisfiable when a
  dependency internally constrains a shared transitive, and expiring the
  predicate class on a calendar would turn the gate red for a reason no commit
  could fix. An entry with nothing left to excuse is itself an error.

One hook id, one shim, one shared implementation -- always delegating, so it
cannot fork the way the 250-line cap forked into four ids, two of which were
independent reimplementations.

256 tests, 100% branch coverage on every module of the gate. Also adds the
workflow that runs them, which incidentally gives md_naming's 71 tests their
first CI run.

Not yet installed in any repo: a repo that gets the gate before its deps are
bumped is instantly and permanently red, so the gate and the upgrade land
together, per repo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 13:00:35 +02:00

109 lines
3.7 KiB
Python

"""Turn a `Dep` into "what is the newest stable of this?", via cache then net.
The cache is consulted first, the network second, and an *expired* cache entry
third — that last fallback is what lets a pre-commit run succeed offline
instead of cornering the user, since `--no-verify` is banned.
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from dep_freshness._tables import (
CARGO, GITTAG, GOMOD, MAX_WORKERS, NPM, PUB, PYPI, TOOLCHAIN,
)
from dep_freshness.cache import Cache
from dep_freshness.models import Dep
from dep_freshness.registries import cargo, gittag, gomod, npmjs, pub, pypi
from dep_freshness.registries import toolchain as tc
from dep_freshness.registries.http import Offline
_LOOKUP = {
PUB: pub.latest,
PYPI: pypi.latest,
NPM: npmjs.latest,
CARGO: cargo.latest,
GOMOD: gomod.latest,
GITTAG: gittag.latest,
}
@dataclass
class Answer:
"""Latest stable for one package, and how confident we are in it."""
version: str | None
stale_cache_days: float | None = None # served from an expired entry
unavailable: bool = False # no network and no cache at all
def _toolchain_latest(name: str) -> str | None:
if name == "flutter":
return tc.flutter_latest()[0]
if name == "dart":
return tc.flutter_latest()[1]
if name == "node":
return tc.node_latest()
if name == "python":
return tc.python_installed()
return None
def _fetch(ecosystem: str, package: str) -> str | None:
if ecosystem == TOOLCHAIN:
return _toolchain_latest(package)
handler = _LOOKUP.get(ecosystem)
return handler(package) if handler else None
class Resolver:
"""Batch version lookups behind one shared on-disk cache."""
def __init__(self, cache: Cache | None = None, refresh: bool = False) -> None:
self.cache = cache if cache is not None else Cache()
if refresh:
self.cache.clear()
self.degraded: list[str] = []
def prefetch(self, deps: list[Dep]) -> None:
"""Warm the cache for everything not already fresh, eight at a time."""
wanted = {
(d.ecosystem, d.name)
for d in deps
if not (entry := self.cache.get(d.ecosystem, d.name))
or not entry.fresh(d.ecosystem)
}
if not wanted:
return
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = {
pool.submit(_fetch, eco, name): (eco, name) for eco, name in wanted
}
for future, (eco, name) in futures.items():
try:
self.cache.put(eco, name, future.result())
except Offline as exc:
self.degraded.append(str(exc))
except Exception as exc:
# Deliberately broad: one malformed registry payload
# must degrade that single package, not abort a run
# spanning ~900 lookups.
self.degraded.append(f"{eco}:{name}: {exc}")
self.cache.save()
def latest(self, dep: Dep) -> Answer:
entry = self.cache.get(dep.ecosystem, dep.name)
if entry and entry.fresh(dep.ecosystem):
return Answer(entry.version)
try:
version = _fetch(dep.ecosystem, dep.name)
except Offline:
version = None
else:
self.cache.put(dep.ecosystem, dep.name, version)
return Answer(version)
if entry is not None:
return Answer(entry.version, stale_cache_days=entry.age() / 86400)
return Answer(None, unavailable=True)