Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(ci): let a recorded api_surface.json edit satisfy the import-surface check (#4230)

Dmytro Mishkin3f102790ae7f
diff --git a/.github/scripts/check_import_surface.py b/.github/scripts/check_import_surface.py
index add9d504f..5835cc337 100644
--- a/.github/scripts/check_import_surface.py
+++ b/.github/scripts/check_import_surface.py
@@ -34,11 +34,13 @@ Usage::
python3 .github/scripts/check_import_surface.py --base-ref origin/main
-Exit status is 1 only when a name is removed from ``__all__`` (a break of
-documented public API, per the stability policy). Names that disappear from
-module scope but were never in ``__all__`` are reported for visibility but do
-not fail the check -- hard-failing on those would make every incidental
-third-party re-export permanent API. Two exemptions from the hard-fail path:
+Exit status is 1 when a name is removed from ``__all__`` (a break of documented
+public API, per the stability policy), when the change drops a module that
+``tests/api_surface.json`` tracks, or when a removal record does not match an
+actual export delta in this change. Names that disappear from module scope but
+were never in ``__all__`` are reported for visibility but do not fail the check
+-- hard-failing on those would make every incidental third-party re-export
+permanent API. Three exemptions from the hard-fail path:
- A module with a module-level ``__getattr__`` in the new revision is
presumed to be using it as a deprecation shim (the pattern
@@ -46,12 +48,27 @@ third-party re-export permanent API. Two exemptions from the hard-fail path:
- ``kornia.contrib`` is the Experimental tier per
``docs/source/get-started/stability.rst`` ("No stability promise") --
its removals are reported, not fatal.
+- An exact module/name removal recorded in this change is reported, not fatal.
+ Drop the name from that module's ``tests/api_surface.json`` entry, or add an
+ exact pair to ``tests/api_surface_removals.json`` for a submodule or API the
+ inventory does not cover. Ancestor inventory entries never authorize a
+ descendant's removal. Existing inventory coverage still needs updating.
+ Only newly added explicit pairs count, and each must match a direct
+ ``__all__`` removal in this diff. See #4190.
+
+Dropping a *module* from that inventory is the mirror image and is always
+fatal: its key is what puts the module in
+``test_no_public_name_removed``'s parametrization, so deleting the key ends
+that guard silently, and this check cannot stand in for it -- a package whose
+public names arrive through ``from .sub import *`` has no static ``__all__``
+here to compare.
"""
from __future__ import annotations
import argparse
import ast
+import json
import subprocess
import sys
from dataclasses import dataclass, field
@@ -237,6 +254,370 @@ def _alternate_path(path: str) -> str:
return stem + "/__init__.py"
+# tests/api_surface.json is the checked-in inventory of the stable-core modules'
+# public names, and tests/test_api_surface.py::test_no_public_name_removed tells a
+# contributor to edit it when a deprecation window has passed. Dropping a name from
+# it in the same change is therefore the acknowledgement this check honors (#4190).
+INVENTORY_PATH = "tests/api_surface.json"
+REMOVALS_PATH = "tests/api_surface_removals.json"
+
+
+def _parse_inventory(source: bytes | None) -> dict[str, set[str]] | None:
+ """Parse the api_surface.json inventory into {module: names}.
+
+ Returns ``None`` -- distinct from an empty mapping -- for anything that is not
+ exactly ``dict[str, list[str]]``: absent, invalid JSON, a different top-level
+ structure, an entry whose key is not a string, an entry whose value is not a list,
+ or a list holding anything but strings. The distinction is the whole safety
+ property. An unreadable inventory at the new revision makes every recorded name
+ look *removed*, which would open the escape hatch for the entire surface; the
+ caller turns ``None`` into "acknowledge nothing" instead.
+
+ Rejecting one bad *entry* rather than skipping it matters just as much as rejecting
+ a bad top-level value: skipping ``"kornia.color": {}`` would drop that module from
+ the parsed mapping, and a dropped module reads downstream exactly like one that lost
+ every name -- so a single wrong-shaped entry would launder every removal in it.
+ """
+ if source is None:
+ return None
+ try:
+ data = json.loads(source)
+ except (ValueError, UnicodeDecodeError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ inventory: dict[str, set[str]] = {}
+ for module, names in data.items():
+ if not isinstance(module, str) or not isinstance(names, list):
+ return None
+ if not all(isinstance(name, str) for name in names):
+ return None
+ inventory[module] = set(names)
+ return inventory
+
+
+def _parse_removals(source: bytes | None, *, missing_is_empty: bool = False) -> dict[str, set[str]] | None:
+ """Parse the explicit removal acknowledgement, rejecting every ambiguous shape."""
+ if source is None:
+ return {} if missing_is_empty else None
+ return _parse_inventory(source)
+
+
+def _removal_ends(base_ref: str) -> tuple[dict[str, set[str]] | None, dict[str, set[str]] | None]:
+ old = _parse_removals(_git_show(base_ref, REMOVALS_PATH), missing_is_empty=True)
+ try:
+ new_source: bytes | None = _read_source(REMOVALS_PATH)
+ except (FileNotFoundError, NotADirectoryError, IsADirectoryError):
+ new_source = None
+ return old, _parse_removals(new_source, missing_is_empty=True)
+
+
+def removal_acknowledgements(base_ref: str) -> dict[str, set[str]] | None:
+ """Return acknowledgement names newly added by this diff, or ``None`` if invalid.
+
+ Only additions grant approval. Old entries may be removed when an API is
+ restored, so that a later removal receives its own review moment.
+ """
+ old, new = _removal_ends(base_ref)
+ if old is None or new is None:
+ return None
+ return {module: names - old.get(module, set()) for module, names in new.items() if names - old.get(module, set())}
+
+
+def _inventory_ends(
+ base_ref: str, inventory_path: str
+) -> tuple[dict[str, set[str]] | None, dict[str, set[str]] | None]:
+ """The parsed inventory at `base_ref` and in the working tree (`None` = unusable).
+
+ Working tree, not `HEAD`, for the same reason `_changed_kornia_files` diffs the
+ working tree: an uncommitted inventory edit has to count during a local run, and
+ on CI's clean checkout the two are identical.
+ """
+ old = _parse_inventory(_git_show(base_ref, inventory_path))
+ try:
+ new_source: bytes | None = _read_source(inventory_path)
+ except (FileNotFoundError, NotADirectoryError, IsADirectoryError):
+ new_source = None
+ return old, _parse_inventory(new_source)
+
+
+def untracked_modules(base_ref: str, inventory_path: str = INVENTORY_PATH) -> set[str]:
+ """Modules the base inventory tracks that the working tree's inventory no longer does.
+
+ Every key in the inventory is a stable-core module that
+ ``tests/test_api_surface.py::test_no_public_name_removed`` imports and compares against
+ the live library. Deleting a key does not fail that test -- it removes the module from
+ its parametrization, so the module simply stops being guarded, quietly and permanently.
+ This check cannot stand in for it either: a package that re-exports through
+ ``from .sub import *`` (``kornia.geometry``, ``kornia.morphology``) has no ``__all__``
+ for `diff_surfaces` to compare, so dropping such a re-export produces no report at all.
+ The two holes line up, which is why the key deletion itself has to be fatal.
+
+ An inventory that is unreadable at the working tree -- absent, unparsable, or
+ wrong-shaped anywhere -- stops tracking *every* module, so it returns all of them.
+ An inventory unreadable at `base_ref` tracks nothing to begin with, so nothing is lost.
+ """
+ old, new = _inventory_ends(base_ref, inventory_path)
+ if old is None:
+ return set()
+ if new is None:
+ return set(old)
+ return set(old) - set(new)
+
+
+def inventory_removals(base_ref: str, inventory_path: str = INVENTORY_PATH) -> dict[str, set[str]]:
+ """Names each inventory module lost between `base_ref` and the working tree.
+
+ Only a name dropped from an entry that is well-shaped at *both* ends counts; every
+ other way the inventory can change -- unreadable, wrong-shaped, or a tracked module
+ key deleted -- acknowledges nothing, because each of those makes recorded names look
+ removed without anyone recording them. The last two are also fatal in their own right
+ (`untracked_modules`, and `_parse_inventory` for the shape); acknowledging nothing is
+ what keeps them from laundering an `__all__` removal on the way out.
+ """
+ old, new = _inventory_ends(base_ref, inventory_path)
+
+ if old is None or new is None:
+ # Deleting or corrupting the inventory is not a way to acknowledge a removal:
+ # without a readable file at *both* ends there is no recorded intent to read.
+ return {}
+
+ removals: dict[str, set[str]] = {}
+ for module, names in old.items():
+ if module not in new:
+ # Deleting a tracked module's entry is not an acknowledgement either: it would
+ # make every name recorded for that module look removed at once. `main` fails
+ # the check on the deletion itself (see `untracked_modules`); refusing to
+ # acknowledge here is what stops the same edit from excusing an `__all__`
+ # removal in passing. A change that really removes every public name of a module
+ # records that with an empty list, which keeps the module tracked by both this
+ # check and test_no_public_name_removed.
+ continue
+ gone = names - new[module]
+ if gone:
+ removals[module] = gone
+ return removals
+
+
+class _ExportResolver:
+ """Resolve static export membership without importing the library.
+
+ This is intentionally a small, conservative interpreter. It follows only
+ ordered module-level imports, assignments, definitions, and literal
+ ``__all__`` declarations. A conditional, dynamic export, missing module,
+ or wildcard import it cannot resolve makes that module unknown; an unknown
+ surface never proves that an inventory name was removed.
+ """
+
+ def __init__(self, base_ref: str | None) -> None:
+ self.base_ref = base_ref
+ self.cache: dict[str, set[str] | None] = {}
+ self.visiting: set[str] = set()
+
+ def _source(self, module: str) -> tuple[bytes, bool] | None:
+ stem = module.replace(".", "/")
+ paths = ((f"{stem}/__init__.py", True), (f"{stem}.py", False))
+ for path, is_package in paths:
+ try:
+ source = _git_show(self.base_ref, path) if self.base_ref is not None else _read_source(path)
+ except (FileNotFoundError, NotADirectoryError, IsADirectoryError):
+ source = None
+ if source is not None:
+ return source, is_package
+ return None
+
+ @staticmethod
+ def _literal_all(value: ast.expr | None) -> list[str] | None:
+ if isinstance(value, ast.BinOp) and isinstance(value.op, ast.Add):
+ left = _ExportResolver._literal_all(value.left)
+ right = _ExportResolver._literal_all(value.right)
+ return left + right if left is not None and right is not None else None
+ if not isinstance(value, (ast.List, ast.Tuple, ast.Set)):
+ return None
+ names = _string_literals(value)
+ return names if len(names) == len(value.elts) else None
+
+ def _relative(self, module: str, is_package: bool, node: ast.ImportFrom) -> str | None:
+ if node.level == 0:
+ return node.module
+ package = module if is_package else module.rpartition(".")[0]
+ parts = package.split(".") if package else []
+ if node.level - 1 > len(parts):
+ return None
+ base = ".".join(parts[: len(parts) - (node.level - 1)])
+ return f"{base}.{node.module}" if node.module else base
+
+ def resolve(self, module: str) -> set[str] | None:
+ if module in self.cache:
+ return self.cache[module]
+ if module in self.visiting:
+ return None
+ self.visiting.add(module)
+ found = self._source(module)
+ if found is None:
+ result = None
+ else:
+ source, is_package = found
+ try:
+ tree = ast.parse(source)
+ except (SyntaxError, ValueError):
+ result = None
+ else:
+ result = self._resolve_tree(tree, module, is_package)
+ self.visiting.discard(module)
+ self.cache[module] = result
+ return result
+
+ def _resolve_tree(self, tree: ast.Module, module: str, is_package: bool) -> set[str] | None:
+ # A literal __all__ is the export contract by itself. Do this
+ # before resolving imports: package membership must not become
+ # unknowable because an unrelated dependency is dynamic.
+ all_values = [
+ node.value
+ for node in tree.body
+ if isinstance(node, (ast.Assign, ast.AnnAssign))
+ and any(
+ isinstance(target, ast.Name) and target.id == "__all__"
+ for target in (node.targets if isinstance(node, ast.Assign) else [node.target])
+ )
+ ]
+
+ def touches_all(node: ast.AST) -> bool:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
+ return False
+ return any(isinstance(child, ast.Name) and child.id == "__all__" for child in ast.walk(node))
+
+ mutates_all = any(
+ touches_all(node)
+ and not (
+ isinstance(node, (ast.Assign, ast.AnnAssign))
+ and any(
+ isinstance(target, ast.Name) and target.id == "__all__"
+ for target in (node.targets if isinstance(node, ast.Assign) else [node.target])
+ )
+ )
+ for node in tree.body
+ )
+ if mutates_all:
+ return None
+ if all_values:
+ names = self._literal_all(all_values[-1])
+ result = None if names is None else set(names)
+ return result
+ return self._bound_exports(tree, module, is_package)
+
+ def _import_bindings(self, node: ast.Import | ast.ImportFrom, module: str, is_package: bool) -> set[str] | None:
+ bindings: set[str] = set()
+
+ def bind_child(target: str) -> None:
+ # Importing a descendant attaches its first component to this
+ # package, independently of the import's explicit alias or __all__.
+ if is_package and target.startswith(module + "."):
+ bindings.add(target[len(module) + 1 :].split(".", maxsplit=1)[0])
+
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ bind_child(alias.name)
+ bindings.add(alias.asname or alias.name.split(".")[0])
+ return bindings
+ target = self._relative(module, is_package, node)
+ if target is None:
+ return None
+ bind_child(target)
+ for alias in node.names:
+ if alias.name == "*":
+ imported = self.resolve(target) if target == "kornia" or target.startswith("kornia.") else None
+ if imported is None:
+ return None
+ bindings.update(imported)
+ else:
+ child = f"{target}.{alias.name}"
+ if target == module and self._source(child) is not None:
+ bind_child(child)
+ # Explicit imports bind their alias regardless of the source's
+ # __all__. Third-party imports are terminal bindings too.
+ bindings.add(alias.asname or alias.name)
+ return bindings
+
+ @staticmethod
+ def _has_dynamic_bindings(node: ast.AST) -> bool:
+ """Reject executable expressions whose effects on globals are unknown.
+
+ Function bodies run later, but defaults, annotations and decorators run
+ while defining them. Class bodies execute immediately as well.
+ """
+ if isinstance(node, (ast.Call, ast.NamedExpr)):
+ return True
+ children = (
+ child
+ for field, value in ast.iter_fields(node)
+ if not (field == "body" and isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)))
+ for child in (value if isinstance(value, list) else [value])
+ if isinstance(child, ast.AST)
+ )
+ return any(_ExportResolver._has_dynamic_bindings(child) for child in children)
+
+ def _bound_exports(self, tree: ast.Module, module: str, is_package: bool) -> set[str] | None:
+ bindings: set[str] = set()
+ for node in tree.body:
+ if isinstance(node, ast.If) and _is_type_checking(node.test) and not node.orelse:
+ continue
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ if self._has_dynamic_bindings(node):
+ return None
+ bindings.add(node.name)
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
+ imported = self._import_bindings(node, module, is_package)
+ if imported is None:
+ return None
+ bindings.update(imported)
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
+ if self._has_dynamic_bindings(node):
+ return None
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+ for target in targets:
+ if not isinstance(target, ast.Name):
+ return None
+ bindings.add(target.id)
+ elif isinstance(node, ast.Pass):
+ continue
+ elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
+ # Docstrings and literal expressions cannot create bindings.
+ continue
+ else:
+ # Calls and assignment expressions can populate globals without
+ # an ordinary assignment (globals().update(...)). Unsupported
+ # statements, including control flow, cannot prove names absent.
+ return None
+ return {name for name in bindings if not name.startswith("_")}
+
+
+def export_removals(base_ref: str, paths: list[str]) -> dict[str, set[str]]:
+ """Exact module/name export deltas caused by this change.
+
+ Include package ancestors of a changed module: removing a leaf from a
+ wildcard re-export changes the package's public surface even if its
+ ``__init__.py`` text is unchanged.
+ """
+ modules: set[str] = set()
+ for path in paths:
+ module = _module_name(path)
+ parts = module.split(".")
+ modules.update(".".join(parts[:depth]) for depth in range(1, len(parts) + 1))
+ old = _ExportResolver(base_ref)
+ new = _ExportResolver(None)
+ removed: dict[str, set[str]] = {}
+ for module in modules:
+ old_exports = old.resolve(module)
+ new_exports = new.resolve(module)
+ if old_exports is None or new_exports is None:
+ continue
+ names = set(old_exports) - set(new_exports)
+ if names:
+ removed[module] = names
+ return removed
+
+
@dataclass
class FileReport:
path: str
@@ -245,6 +626,9 @@ class FileReport:
fatal: bool
"""Whether removed_from_all should actually fail the check for this file."""
+ acknowledged: set[str] = field(default_factory=set)
+ """Subset of removed_from_all acknowledged by either record file."""
+
def diff_surfaces(old: ModuleSurface, new: ModuleSurface) -> tuple[set[str], set[str]]:
"""Return (removed_from_all, removed_undocumented) between two surfaces."""
@@ -253,12 +637,21 @@ def diff_surfaces(old: ModuleSurface, new: ModuleSurface) -> tuple[set[str], set
return removed_from_all, removed_undocumented
-def check_file(base_ref: str, path: str) -> FileReport | None:
+def check_file(
+ base_ref: str,
+ path: str,
+ removals: dict[str, set[str]] | None = None,
+ explicit_removals: dict[str, set[str]] | None = None,
+) -> FileReport | None:
"""Compare `path`'s module surface between `base_ref` and the working tree.
A deleted file is diffed against an empty surface, so removing a whole
module is reported (and can be fatal) just like emptying its `__all__`.
+ `removals` is `inventory_removals`' mapping for the same diff; a name it
+ records for this exact module is reported rather than fatal. Explicit records
+ supply the same exact-module acknowledgement for APIs outside the inventory.
+
Returns None if there's nothing to report (new file, unparsable source,
or no names removed).
"""
@@ -291,15 +684,24 @@ def check_file(base_ref: str, path: str) -> FileReport | None:
if not removed_from_all and not removed_undocumented:
return None
+ module = _module_name(path)
+ # Only exact module/name pairs authorize removals. An ancestor's inventory
+ # entry cannot identify which same-named descendant API was removed.
+ acknowledged = removed_from_all & (
+ (removals or {}).get(module, set()) | (explicit_removals or {}).get(module, set())
+ )
+
# A module-level __getattr__ in the new revision is presumed to be
# serving these names as a deprecation shim (kornia.utils's pattern) --
- # don't punish the one thing done right.
- fatal = bool(removed_from_all) and not new_surface.has_getattr and not _is_experimental(_module_name(path))
+ # don't punish the one thing done right. Same for a removal this change
+ # already recorded in the inventory: only the *unrecorded* ones are fatal.
+ fatal = bool(removed_from_all - acknowledged) and not new_surface.has_getattr and not _is_experimental(module)
return FileReport(
path=path,
removed_from_all=removed_from_all,
removed_undocumented=removed_undocumented,
fatal=fatal,
+ acknowledged=acknowledged,
)
@@ -331,17 +733,134 @@ def main(argv: list[str] | None = None) -> int:
print(f"::error::could not list changed files against {base}: {exc.stderr.strip() or exc}")
return 1
- reports = [r for r in (check_file(base, path) for path in files) if r is not None]
+ removals = inventory_removals(base)
+ base_inventory = _inventory_ends(base, INVENTORY_PATH)[0] or {}
+ explicit_removals = removal_acknowledgements(base)
+ old_explicit = _removal_ends(base)[0] or {}
+ exports_removed = export_removals(base, files)
+ reports = [
+ r
+ for r in (
+ check_file(base, path, removals, explicit_removals if explicit_removals is not None else {})
+ for path in files
+ )
+ if r is not None
+ ]
hard_fail = False
+
+ dropped = untracked_modules(base)
+ if dropped:
+ hard_fail = True
+ if _inventory_ends(base, INVENTORY_PATH)[1] is None:
+ # Absent, unparsable, or wrong-shaped anywhere: it records nothing for anyone now.
+ print(
+ f"::error file={INVENTORY_PATH}::{INVENTORY_PATH} is missing, unparsable, or "
+ f"wrong-shaped, so it tracks nothing and every module it recorded "
+ f"({sorted(dropped)}) stops being guarded. It has to stay a JSON object mapping "
+ f"each stable-core module to a list of its public names."
+ )
+ else:
+ print(
+ f"::error file={INVENTORY_PATH}::No longer tracked in {INVENTORY_PATH}: "
+ f"{sorted(dropped)}. Each key there is a stable-core module that "
+ f"tests/test_api_surface.py::test_no_public_name_removed imports and guards, so "
+ f"dropping the key ends that guard instead of failing it -- and this check cannot "
+ f"replace it, because a package that re-exports through `from .sub import *` has "
+ f"no __all__ here to compare. To record removing every public name of a module, "
+ f"set its list to [] -- that keeps the module tracked. Removing a stable-core "
+ f"module itself is a policy decision (docs/source/get-started/stability.rst), not "
+ f"a routine recorded removal."
+ )
+
+ # An inventory row is aggregate package coverage, so it is only meaningful
+ # when the package's *own* resolved export surface loses that exact name.
+ # A touched sibling is no evidence; unknown static membership is deliberately
+ # not treated as a match.
+ unmatched_inventory = {
+ module: names - exports_removed.get(module, set())
+ for module, names in removals.items()
+ if names - exports_removed.get(module, set())
+ }
+ if unmatched_inventory:
+ hard_fail = True
+ listed = ", ".join(f"{module}: {sorted(names)}" for module, names in sorted(unmatched_inventory.items()))
+ print(
+ f"::error file={INVENTORY_PATH}::Recorded removals without an exact resolved export delta in "
+ f"this change ({listed}). A touched file under the package is insufficient. Keep the inventory "
+ f"entry until the package export is statically demonstrably removed; dynamic exports need a "
+ f"maintainer-reviewed guard change rather than this acknowledgement."
+ )
+
+ if explicit_removals is None:
+ hard_fail = True
+ print(
+ f"::error file={REMOVALS_PATH}::{REMOVALS_PATH} must be a JSON object mapping modules to lists "
+ f"of strings. A malformed acknowledgement authorizes nothing."
+ )
+ explicit_removals = {}
+
+ direct_removed: dict[str, set[str]] = {}
for report in reports:
- if report.removed_from_all:
- names = sorted(report.removed_from_all)
+ direct_removed.setdefault(_module_name(report.path), set()).update(report.removed_from_all)
+ for module, names in direct_removed.items():
+ missing_inventory = (names & base_inventory.get(module, set())) - removals.get(module, set())
+ if missing_inventory & explicit_removals.get(module, set()):
+ hard_fail = True
+ print(
+ f"::error file={INVENTORY_PATH}::Explicit acknowledgements do not replace this module's "
+ f"inventory update: remove {sorted(missing_inventory)} from {module}'s entry in the same change."
+ )
+ invalid_explicit = {
+ module: names - direct_removed.get(module, set())
+ for module, names in explicit_removals.items()
+ if names - direct_removed.get(module, set())
+ }
+ if invalid_explicit:
+ hard_fail = True
+ listed = ", ".join(f"{module}: {sorted(names)}" for module, names in sorted(invalid_explicit.items()))
+ print(
+ f"::error file={REMOVALS_PATH}::Explicit acknowledgements must match an exact __all__ removal "
+ f"from the same module in this diff; unmatched entries: {listed}."
+ )
+
+ for report in reports:
+ if report.acknowledged:
+ explicit = report.acknowledged & explicit_removals.get(_module_name(report.path), set())
+ acknowledgement_file = REMOVALS_PATH if explicit else INVENTORY_PATH
+ print(
+ f"::notice file={report.path}::Removed from __all__ and acknowledged in "
+ f"{acknowledgement_file} in this same change: {sorted(report.acknowledged)}"
+ )
+ unrecorded = sorted(report.removed_from_all - report.acknowledged)
+ if unrecorded:
if report.fatal:
hard_fail = True
- print(f"::error file={report.path}::Removed from __all__: {names}")
+ tracked = set(unrecorded) & base_inventory.get(_module_name(report.path), set())
+ untracked = set(unrecorded) - tracked
+ if tracked:
+ print(
+ f"::error file={report.path}::Removed from __all__: {sorted(tracked)}. If deliberate, "
+ f"drop these names from this module's {INVENTORY_PATH} entry in this PR. "
+ f"Honor the deprecation window and document the removal in CHANGELOG.md."
+ )
+ stale = untracked & old_explicit.get(_module_name(report.path), set())
+ if stale:
+ print(
+ f"::error file={REMOVALS_PATH}::These acknowledgements already existed at the merge base "
+ f"and cannot be reused: {sorted(stale)}. Clear obsolete records in a separate cleanup "
+ f"change before recording this removal; restoration of an API should clear its old record."
+ )
+ untracked -= stale
+ if untracked:
+ print(
+ f"::error file={report.path}::Removed from __all__: {sorted(untracked)}. Add these exact "
+ f"module/name pairs to {REMOVALS_PATH}; they have no exact-module inventory entry. "
+ f"Update affected package inventory entries too, honor the deprecation window, "
+ f"and document the removal in CHANGELOG.md."
+ )
else:
- print(f"::notice file={report.path}::Removed from __all__ (exempt, see comment above): {names}")
+ print(f"::notice file={report.path}::Removed from __all__ (exempt, see comment above): {unrecorded}")
if report.removed_undocumented:
names = sorted(report.removed_undocumented)
print(
diff --git a/.github/workflows/import-surface.yml b/.github/workflows/import-surface.yml
index cbf2fc667..3fac74fee 100644
--- a/.github/workflows/import-surface.yml
+++ b/.github/workflows/import-surface.yml
@@ -6,6 +6,11 @@ on:
- main
paths:
- 'kornia/**/*.py'
+ # The check reads this inventory both ways: a recorded removal is the escape hatch,
+ # and dropping a module's key from it is fatal on its own -- so a change that touches
+ # only the inventory still has to run.
+ - 'tests/api_surface.json'
+ - 'tests/api_surface_removals.json'
- '.github/scripts/check_import_surface.py'
- '.github/workflows/import-surface.yml'
diff --git a/AGENTS.md b/AGENTS.md
index eb5087543..9b25e49b2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -110,7 +110,7 @@ when more than one virtualenv is in play: name the interpreter explicitly rather
- Keep numerical correctness tests self-contained. For expected values produced by an optional reference library, prefer a hardcoded literal plus the small generation snippet and source. Optional-dependency integration tests, including ONNX tests, may still use `pytest.importorskip`.
- For a new algorithm, name the source that defines it, such as a paper or a reference implementation in PyTorch, OpenCV, or scikit-image.
- Public APIs need type hints, docstrings, and exports.
-- `tests/api_surface.json` is a checked-in inventory of the public names of the stable-core modules, and `tests/test_api_surface.py` fails when one of them disappears β€” the deliberate review moment the stability policy (`docs/source/get-started/stability.rst`) requires. Removing or renaming a public name means editing that JSON in the same change; additions do not fail the test, and `tests.test_api_surface.regenerate()` rewrites the inventory from the live library once new public API has landed.
+- `tests/api_surface.json` inventories the public names of stable-core modules; `tests/test_api_surface.py` rejects their removal until the inventory is updated in the same change. Run `tests.test_api_surface.regenerate()` to regenerate it. Keep tracked module keys (use `[]` when removing every name). The `Import Surface` workflow also checks that each inventory removal corresponds to an actual export removal in the same diff. An inventory edit acknowledges an `__all__` removal only for the exact same module and name. For submodule APIs recorded only under an ancestor package, or APIs absent from the inventory, add the exact module and name to `tests/api_surface_removals.json`, a JSON object mapping module names to lists of removed names (for example, `{"kornia.geometry.boxes": ["Boxes"]}`). Only entries newly added relative to the merge base count, and each must match an actual `__all__` removal in that change; an unrelated source edit or a previously recorded acknowledgement does not count. Explicit acknowledgements do not replace updates to existing inventory entries, the deprecation window, or release notes.
- The codebase keeps a 120-character line length and Apache 2.0 source headers. Ruff and `ty` enforce the current style and types.
- JIT-compatible modules have stricter typing constraints. Follow nearby annotations and use `torch.Tensor` directly where TorchScript expects it.
- For non-JIT modules, use `from __future__ import annotations`.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c2c5ca964..8165d4771 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -249,6 +249,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* The `Import Surface` CI check accepts deliberate public-name removals recorded in the same change.
+ Edits to `tests/api_surface.json` must correspond to actual export removals and acknowledge only the exact
+ recorded module/name. Submodule APIs recorded only under an ancestor, and APIs outside the inventory, use
+ exact module/name entries in `tests/api_surface_removals.json`; only new entries matching a current
+ `__all__` removal count. Malformed records, deleted inventory module keys, unrelated Python edits, and
+ acknowledgements staged in earlier changes cannot authorize removals. Both record files trigger the workflow.
+ The export resolver includes implicit submodule bindings and rejects unsupported dynamic binding expressions
+ as evidence of removal. Deprecation windows and release notes still apply. (#4190, #4230)
+
* `validate_bbox` and `validate_bbox3d` flatten rank-4 `(B, N, 4, 2)` / `(B, N, 8, 3)` input with `reshape`
instead of `view`, so a non-contiguous leading-dimension stride (a transpose, a slice that drops boxes, an
`expand`) returns a boolean as documented instead of raising `RuntimeError`. (#4174)
diff --git a/docs/source/get-started/stability.rst b/docs/source/get-started/stability.rst
index d6caf5f3c..795528f4c 100644
--- a/docs/source/get-started/stability.rst
+++ b/docs/source/get-started/stability.rst
@@ -101,3 +101,28 @@ Escape hatch
A change that fixes a correctness bug (wrong math, wrong convention versus
the documented one) or a security issue may ship without a deprecation
window. When that happens the release notes say so explicitly.
+
+Recording a completed deprecation
+---------------------------------
+
+Once the deprecation window has passed, remove the API and describe the removal
+in ``CHANGELOG.md``. Update any existing entries in ``tests/api_surface.json``
+in the same pull request; keep the module key, using an empty list if necessary.
+The import-surface check verifies that recorded names leave the export surface
+in that change. An inventory edit acknowledges an ``__all__`` removal only for
+the exact same module and name; it does not authorize submodule removals.
+
+For a submodule API recorded only under an ancestor package, or an API absent
+from the inventory, record the exact module and removed ``__all__`` name in
+``tests/api_surface_removals.json``. For example::
+
+ {
+ "kornia.geometry.boxes": ["Boxes"]
+ }
+
+Only module/name pairs newly added relative to the pull request's merge base
+can acknowledge removals, and each must match an actual ``__all__`` removal in
+the same change. Existing entries cannot authorize a later removal. When reintroducing an API,
+remove its obsolete acknowledgement so a future removal requires a fresh entry.
+This file does not replace updates to the inventory or the deprecation and release-note
+requirements above.
diff --git a/tests/api_surface_removals.json b/tests/api_surface_removals.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/tests/api_surface_removals.json
@@ -0,0 +1 @@
+{}
diff --git a/tests/scripts/test_check_import_surface.py b/tests/scripts/test_check_import_surface.py
index 6937b0942..afc8959ee 100644
--- a/tests/scripts/test_check_import_surface.py
+++ b/tests/scripts/test_check_import_surface.py
@@ -14,20 +14,28 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+import json
import os
import subprocess
import sys
from pathlib import Path
+import pytest
+
sys.path.insert(0, str(Path(__file__).parent.parent.parent / ".github" / "scripts"))
from check_import_surface import (
+ INVENTORY_PATH,
+ REMOVALS_PATH,
_changed_kornia_files,
_is_experimental,
_module_name,
check_file,
diff_surfaces,
+ export_removals,
+ inventory_removals,
main,
parse_module_surface,
+ untracked_modules,
)
@@ -538,3 +546,697 @@ def test_check_file_honors_a_declared_source_encoding(tmp_path):
assert report is not None
assert report.removed_from_all == {"a"}
assert report.fatal is True
+
+
+def _repo_with_inventory(tmp_path, *, module="kornia/mymodule.py", exports=("a", "b"), inventory=None):
+ """A throwaway repo whose base commit has `exports` in __all__ and in the inventory.
+
+ Returns the repo path with the base commit made and a `base` branch pointing at it.
+ The caller edits the working tree and runs the check against `base`.
+ """
+ repo = tmp_path / "repo"
+ (repo / module).parent.mkdir(parents=True, exist_ok=True)
+ (repo / INVENTORY_PATH).parent.mkdir(parents=True, exist_ok=True)
+ _git("init", "-q", cwd=repo)
+ _git("config", "user.email", "[email protected]", cwd=repo)
+ _git("config", "user.name", "Test", cwd=repo)
+
+ body = "".join(f"def {name}():\n pass\n\n" for name in exports)
+ (repo / module).write_text(f"__all__ = {list(exports)!r}\n\n{body}")
+ recorded = inventory if inventory is not None else {_module_name(module): sorted(exports)}
+ (repo / INVENTORY_PATH).write_text(json.dumps(recorded, indent=2, sort_keys=True) + "\n")
+
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-q", "-m", "base", cwd=repo)
+ _git("branch", "base", cwd=repo)
+ return repo
+
+
+def _in_repo(repo, fn):
+ original_cwd = Path.cwd()
+ try:
+ os.chdir(repo)
+ return fn()
+ finally:
+ os.chdir(original_cwd)
+
+
+def _write_inventory(repo, mapping):
+ (repo / INVENTORY_PATH).write_text(json.dumps(mapping, indent=2, sort_keys=True) + "\n")
+
+
+def _write_removals(repo, mapping):
+ (repo / REMOVALS_PATH).write_text(json.dumps(mapping, indent=2, sort_keys=True) + "\n")
+
+
+def _repo_with_package(tmp_path, *, init_body, submodules, inventory):
+ """A throwaway repo whose base commit has a `kornia/pkg` package re-exporting submodules."""
+ repo = tmp_path / "repo"
+ (repo / "kornia" / "pkg").mkdir(parents=True)
+ (repo / "tests").mkdir(parents=True)
+ _git("init", "-q", cwd=repo)
+ _git("config", "user.email", "[email protected]", cwd=repo)
+ _git("config", "user.name", "Test", cwd=repo)
+
+ (repo / "kornia" / "pkg" / "__init__.py").write_text(init_body)
+ for name, body in submodules.items():
+ (repo / "kornia" / "pkg" / f"{name}.py").write_text(body)
+ _write_inventory(repo, inventory)
+
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-q", "-m", "base", cwd=repo)
+ _git("branch", "base", cwd=repo)
+ return repo
+
+
+def _exports(*names):
+ return f"__all__ = {list(names)!r}\n\n" + "".join(f"def {n}():\n pass\n\n" for n in names)
+
+
+def test_check_file_ancestor_entry_does_not_excuse_a_sibling_of_the_same_name(tmp_path):
+ # kornia.pkg re-exports `thing` from pkg.a; pkg.b has an unrelated symbol of the same
+ # name. Recording the package losing `thing` says nothing about pkg.b's, and matching on
+ # the spelling alone let the second removal ride along on the first.
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="from .a import thing\nfrom .b import other\n",
+ submodules={"a": _exports("thing"), "b": _exports("thing", "other")},
+ inventory={"kornia.pkg": ["other", "thing"]},
+ )
+ (repo / "kornia" / "pkg" / "__init__.py").write_text("from .b import other\n")
+ (repo / "kornia" / "pkg" / "b.py").write_text(_exports("other"))
+ _write_inventory(repo, {"kornia.pkg": ["other"]})
+
+ report = _in_repo(repo, lambda: check_file("base", "kornia/pkg/b.py", inventory_removals("base"), {}))
+
+ assert report is not None
+ assert report.removed_from_all == {"thing"}
+ assert report.acknowledged == set()
+ assert report.fatal is True
+
+
+def test_check_file_explicit_entry_excuses_only_its_exact_module(tmp_path):
+ # The other half of the same rule: the module the package actually re-exports from is
+ # acknowledged, including through a wildcard, or the hatch would not work for
+ # kornia.geometry at all.
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="from .a import *\n",
+ submodules={"a": _exports("thing", "other")},
+ inventory={"kornia.pkg": ["other", "thing"]},
+ )
+ (repo / "kornia" / "pkg" / "a.py").write_text(_exports("other"))
+ _write_inventory(repo, {"kornia.pkg": ["other"]})
+
+ report = _in_repo(
+ repo, lambda: check_file("base", "kornia/pkg/a.py", inventory_removals("base"), {"kornia.pkg.a": {"thing"}})
+ )
+
+ assert report is not None
+ assert report.acknowledged == {"thing"}
+ assert report.fatal is False
+
+
+def test_check_file_inventory_removal_is_not_fatal(tmp_path):
+ # #4190's live case (#4143 dropping AUTUMN): the contributor follows the procedure
+ # test_no_public_name_removed's own assertion message spells out, and the check has
+ # to see that edit rather than hard-failing on a policy-compliant removal.
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ _write_inventory(repo, {"kornia.mymodule": ["b"]})
+
+ report = _in_repo(repo, lambda: check_file("base", "kornia/mymodule.py", inventory_removals("base")))
+
+ assert report is not None
+ assert report.removed_from_all == {"a"}
+ assert report.acknowledged == {"a"}
+ assert report.fatal is False
+
+
+def test_check_file_unrecorded_removal_is_still_fatal(tmp_path):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ # inventory untouched: the removal is not recorded anywhere
+
+ report = _in_repo(repo, lambda: check_file("base", "kornia/mymodule.py", inventory_removals("base")))
+
+ assert report is not None
+ assert report.removed_from_all == {"a"}
+ assert report.acknowledged == set()
+ assert report.fatal is True
+
+
+def test_check_file_recording_a_different_name_does_not_excuse_this_one(tmp_path):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ _write_inventory(repo, {"kornia.mymodule": ["a"]}) # records 'b' leaving, not 'a'
+
+ report = _in_repo(repo, lambda: check_file("base", "kornia/mymodule.py", inventory_removals("base")))
+
+ assert report is not None
+ assert report.removed_from_all == {"a"}
+ assert report.acknowledged == set()
+ assert report.fatal is True
+
+
+def test_check_file_partially_recorded_removal_is_fatal_for_the_rest(tmp_path):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = []\n")
+ _write_inventory(repo, {"kornia.mymodule": ["b"]}) # records 'a' only
+
+ report = _in_repo(repo, lambda: check_file("base", "kornia/mymodule.py", inventory_removals("base")))
+
+ assert report is not None
+ assert report.removed_from_all == {"a", "b"}
+ assert report.acknowledged == {"a"}
+ assert report.fatal is True
+
+
+def test_inventory_removals_ignores_a_corrupt_inventory(tmp_path):
+ # Fail closed. An unparsable inventory at the new revision makes every recorded name
+ # look removed, which would acknowledge the entire public surface at once.
+ repo = _repo_with_inventory(tmp_path)
+ (repo / INVENTORY_PATH).write_text("{ this is not json\n")
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {}
+
+
+def test_inventory_removals_ignores_a_deleted_inventory(tmp_path):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / INVENTORY_PATH).unlink()
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {}
+
+
+def test_inventory_removals_ignores_an_inventory_of_the_wrong_shape(tmp_path):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / INVENTORY_PATH).write_text('["a", "b"]\n') # a list, not {module: names}
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {}
+
+
+def test_inventory_removals_rejects_an_entry_whose_value_is_not_a_list(tmp_path):
+ # Fail closed on a *partially* wrong-shaped inventory too. Skipping the bad entry would
+ # drop the module from the parsed mapping, and a dropped module reads exactly like one
+ # that lost every name -- so `"kornia.mymodule": {}` would launder every removal in it
+ # while test_no_public_name_removed still passes vacuously on `set({}) == set()`.
+ repo = _repo_with_inventory(tmp_path)
+ _write_inventory(repo, {"kornia.mymodule": {}})
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {}
+
+
+def test_inventory_removals_rejects_an_entry_holding_a_non_string(tmp_path):
+ repo = _repo_with_inventory(tmp_path)
+ _write_inventory(repo, {"kornia.mymodule": [1, 2]})
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {}
+
+
+def test_inventory_removals_one_bad_entry_rejects_the_whole_inventory(tmp_path):
+ # The rejection is not per-entry: an inventory that cannot be trusted at one key cannot
+ # be trusted to speak for another, so an honest edit next to a wrong-shaped entry
+ # acknowledges nothing either.
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a", "b"], "kornia.other": ["z"]})
+ _write_inventory(repo, {"kornia.mymodule": ["b"], "kornia.other": {}})
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {}
+
+
+def test_inventory_removals_ignores_a_deleted_module_entry(tmp_path):
+ # Deleting a tracked module's key is not an acknowledgement: it would excuse every name
+ # recorded for that module at once, and it silently drops the module from
+ # test_no_public_name_removed's parametrization, so nothing guards it afterwards.
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a", "b"], "kornia.other": ["z"]})
+ _write_inventory(repo, {"kornia.other": ["z"]})
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {}
+
+
+def test_untracked_modules_reports_a_deleted_key(tmp_path):
+ # Refusing to *acknowledge* a deleted key is only half the guard. The deletion itself has
+ # to fail, because it drops the module from test_no_public_name_removed's parametrization
+ # and nothing else notices.
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a", "b"], "kornia.other": ["z"]})
+ _write_inventory(repo, {"kornia.other": ["z"]})
+
+ assert _in_repo(repo, lambda: untracked_modules("base")) == {"kornia.mymodule"}
+
+
+def test_untracked_modules_ignores_an_emptied_entry(tmp_path):
+ # `[]` is the recorded-removal-of-everything spelling and keeps the module tracked, so it
+ # must not read as a dropped key -- the two are exactly the cases the error message
+ # contrasts.
+ repo = _repo_with_inventory(tmp_path)
+ _write_inventory(repo, {"kornia.mymodule": []})
+
+ assert _in_repo(repo, lambda: untracked_modules("base")) == set()
+
+
+def test_untracked_modules_reports_every_module_for_an_emptied_inventory(tmp_path):
+ # `{}` parses and is well-shaped, so nothing else rejects it -- and it parametrizes
+ # test_no_public_name_removed with zero modules, which passes.
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a", "b"], "kornia.other": ["z"]})
+ _write_inventory(repo, {})
+
+ assert _in_repo(repo, lambda: untracked_modules("base")) == {"kornia.mymodule", "kornia.other"}
+
+
+def test_untracked_modules_reports_every_module_for_an_unreadable_inventory(tmp_path):
+ # Absent, unparsable or wrong-shaped: the working tree tracks nothing, so nothing is
+ # guarded any more.
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a", "b"], "kornia.other": ["z"]})
+ (repo / INVENTORY_PATH).unlink()
+
+ assert _in_repo(repo, lambda: untracked_modules("base")) == {"kornia.mymodule", "kornia.other"}
+
+ _write_inventory(repo, {"kornia.mymodule": ["a", "b"], "kornia.other": {}})
+
+ assert _in_repo(repo, lambda: untracked_modules("base")) == {"kornia.mymodule", "kornia.other"}
+
+
+def test_untracked_modules_ignores_an_inventory_absent_from_the_base(tmp_path):
+ # A base revision that predates the inventory tracks nothing, so the working tree cannot
+ # have dropped anything -- an inventory that is simply not there yet must not read as
+ # every module being removed.
+ repo = _repo_with_inventory(tmp_path)
+
+ assert _in_repo(repo, lambda: untracked_modules("base", "tests/not_yet_added.json")) == set()
+
+
+def test_inventory_removals_reads_an_emptied_entry_as_removing_every_name(tmp_path):
+ # The remedy the deleted-key rule points at: an empty list records losing every public
+ # name while keeping the module tracked by both this check and the pytest inventory.
+ repo = _repo_with_inventory(tmp_path)
+ _write_inventory(repo, {"kornia.mymodule": []})
+
+ assert _in_repo(repo, lambda: inventory_removals("base")) == {"kornia.mymodule": {"a", "b"}}
+
+
+def test_main_wrong_shaped_entry_does_not_acknowledge_a_removal(tmp_path, capsys):
+ # End to end on the concrete bypass: swap the module's list for `{}` while dropping a
+ # name from __all__, and the check must still hard-fail.
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ _write_inventory(repo, {"kornia.mymodule": {}})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert "::error" in captured.out
+ assert "'a'" in captured.out
+
+
+def test_main_deleted_module_entry_does_not_acknowledge_a_removal(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a", "b"], "kornia.other": ["z"]})
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ _write_inventory(repo, {"kornia.other": ["z"]})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert "::error" in captured.out
+ assert "'a'" in captured.out
+
+
+def test_main_fails_on_a_deleted_inventory_key_with_no_kornia_change(tmp_path, capsys):
+ # The workflow's path filter lists tests/api_surface.json for this: an inventory-only
+ # change reaches no kornia file, so the deletion has to fail on its own rather than only
+ # as a side effect of some file report.
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a", "b"], "kornia.other": ["z"]})
+ _write_inventory(repo, {"kornia.other": ["z"]})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert "::error" in captured.out
+ assert "'kornia.mymodule'" in captured.out
+ assert INVENTORY_PATH in captured.out
+
+
+def test_main_fails_when_a_wildcard_reexport_and_its_inventory_key_go_together(tmp_path, capsys):
+ # The bypass the deleted-key rule exists for. `from .bbox import *` is deliberately
+ # invisible to parse_module_surface, so dropping it from a package __init__ produces no
+ # report at all; deleting the package's inventory key in the same change used to remove
+ # the runtime guard too, and the pair exited 0 in silence. kornia.geometry and
+ # kornia.morphology are shaped exactly like this.
+ repo = tmp_path / "repo"
+ (repo / "kornia" / "geometry").mkdir(parents=True)
+ (repo / "tests").mkdir(parents=True)
+ _git("init", "-q", cwd=repo)
+ _git("config", "user.email", "[email protected]", cwd=repo)
+ _git("config", "user.name", "Test", cwd=repo)
+
+ pkg = repo / "kornia" / "geometry" / "__init__.py"
+ pkg.write_text("from .bbox import *\nfrom .linalg import *\n")
+ (repo / "kornia" / "geometry" / "bbox.py").write_text("__all__ = ['bbox_thing']\n\ndef bbox_thing():\n pass\n")
+ (repo / "kornia" / "geometry" / "linalg.py").write_text(
+ "__all__ = ['linalg_thing']\n\ndef linalg_thing():\n pass\n"
+ )
+ _write_inventory(repo, {"kornia.geometry": ["bbox_thing", "linalg_thing"]})
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-q", "-m", "base", cwd=repo)
+ _git("branch", "base", cwd=repo)
+
+ pkg.write_text("from .linalg import *\n") # kornia.geometry stops exporting bbox_thing
+ _write_inventory(repo, {})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert "::error" in captured.out
+ assert "'kornia.geometry'" in captured.out
+
+
+def test_main_fails_on_an_unreadable_inventory_and_says_so(tmp_path, capsys):
+ # Same fatal path, different cause, so the message has to name the real one rather than
+ # reading as "somebody deleted all twelve keys".
+ repo = _repo_with_inventory(tmp_path)
+ (repo / INVENTORY_PATH).write_text("{ this is not json\n")
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert "unparsable" in captured.out
+ assert "'kornia.mymodule'" in captured.out
+
+
+def test_main_fails_on_an_inventory_removal_this_change_does_not_make(tmp_path, capsys):
+ # Staging the acknowledgement in its own PR takes the review moment off the PR that
+ # removes the API: record `a` leaving now, and a later PR dropping a `from .sub import *`
+ # re-export has nothing left to fail on, because wildcards are invisible to the parser.
+ repo = _repo_with_inventory(tmp_path)
+ _write_inventory(repo, {"kornia.mymodule": ["b"]}) # no kornia/ file touched
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert "::error" in captured.out
+ assert "exact resolved export delta" in captured.out
+ assert "'a'" in captured.out
+
+
+def test_main_untracked_name_removal_does_not_prescribe_an_impossible_edit(tmp_path, capsys):
+ # The inventory records twelve package aggregates, so 132 public __all__ names under them
+ # are in no entry (#4236). Telling their remover to "drop the same name from the
+ # inventory" sends them after an edit that cannot be made.
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.other": ["z"]})
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert REMOVALS_PATH in captured.out
+ assert "drop these names" not in captured.out
+
+
+def test_main_exits_zero_and_reports_a_recorded_removal(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ _write_inventory(repo, {"kornia.mymodule": ["b"]})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 0
+ assert "::notice" in captured.out
+ assert INVENTORY_PATH in captured.out
+ assert "'a'" in captured.out
+ assert "::error" not in captured.out
+
+
+def test_main_error_message_names_the_escape_hatch(tmp_path, capsys):
+ # #4190: the pytest assertion tells contributors the procedure and this check did not,
+ # so a contributor could satisfy the test that names it and still be blocked here with
+ # no idea what to do about it.
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert "::error" in captured.out
+ assert INVENTORY_PATH in captured.out
+ assert REMOVALS_PATH not in captured.out
+
+
+def test_main_still_reports_an_undocumented_removal_alongside_a_recorded_one(tmp_path, capsys):
+ # An undocumented removal (the pyramid.py/#3986 case) was never fatal and is reported
+ # for visibility. The inventory hatch must not swallow that line: it speaks only for
+ # names that were in __all__, and the two reports are independent.
+ repo = tmp_path / "repo"
+ (repo / "kornia").mkdir(parents=True)
+ (repo / "tests").mkdir(parents=True)
+ _git("init", "-q", cwd=repo)
+ _git("config", "user.email", "[email protected]", cwd=repo)
+ _git("config", "user.name", "Test", cwd=repo)
+
+ mod = repo / "kornia" / "mymodule.py"
+ mod.write_text("from torch.nn.functional import pad\n\n__all__ = ['a']\n\ndef a():\n pass\n")
+ _write_inventory(repo, {"kornia.mymodule": ["a"]})
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-q", "-m", "base", cwd=repo)
+ _git("branch", "base", cwd=repo)
+
+ mod.write_text("__all__ = []\n") # drops the documented 'a' AND the undocumented 'pad'
+ _write_inventory(repo, {"kornia.mymodule": []}) # records only 'a'
+ _write_removals(repo, {"kornia.mymodule": ["a"]})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 0
+ assert "::error" not in captured.out
+ assert "'pad'" in captured.out
+ assert "No longer bound at module scope" in captured.out
+
+
+def test_main_rejects_inventory_staging_beside_an_unrelated_package_touch(tmp_path, capsys):
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="from .a import *\n",
+ submodules={"a": _exports("thing"), "b": "# unrelated\n"},
+ inventory={"kornia.pkg": ["thing"]},
+ )
+ _write_inventory(repo, {"kornia.pkg": []})
+ (repo / "kornia" / "pkg" / "b.py").write_text("# still unrelated\n")
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ assert exit_code == 1
+ assert "exact resolved export delta" in capsys.readouterr().out
+
+
+def test_export_removals_follows_nested_wildcards_without_authorizing_a_sibling(tmp_path):
+ repo = tmp_path / "repo"
+ (repo / "kornia" / "pkg" / "a").mkdir(parents=True)
+ (repo / "tests").mkdir()
+ _git("init", "-q", cwd=repo)
+ _git("config", "user.email", "[email protected]", cwd=repo)
+ _git("config", "user.name", "Test", cwd=repo)
+ (repo / "kornia" / "pkg" / "__init__.py").write_text("from .a import *\n")
+ (repo / "kornia" / "pkg" / "a" / "__init__.py").write_text("from .real import *\n")
+ (repo / "kornia" / "pkg" / "a" / "real.py").write_text(_exports("thing"))
+ (repo / "kornia" / "pkg" / "a" / "unrelated.py").write_text(_exports("thing"))
+ _write_inventory(repo, {"kornia.pkg": ["thing"]})
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-q", "-m", "base", cwd=repo)
+ _git("branch", "base", cwd=repo)
+
+ (repo / "kornia" / "pkg" / "a" / "real.py").write_text(_exports())
+ removed = _in_repo(repo, lambda: export_removals("base", ["kornia/pkg/a/real.py"]))
+
+ assert removed["kornia.pkg"] == {"thing"}
+ assert removed["kornia.pkg.a"] == {"thing"}
+ assert removed["kornia.pkg.a.real"] == {"thing"}
+ assert "kornia.pkg.a.unrelated" not in removed
+ (repo / "kornia/pkg/a/unrelated.py").write_text(_exports())
+ _write_inventory(repo, {"kornia.pkg": []})
+ _write_removals(repo, {"kornia.pkg.a.real": ["thing"]})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1
+ _write_removals(repo, {"kornia.pkg.a.real": ["thing"], "kornia.pkg.a.unrelated": ["thing"]})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 0
+
+
+def test_explicit_acknowledgement_requires_an_exact_same_module_removal(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.other": ["z"]})
+ _write_removals(repo, {"kornia.mymodule": ["a"]})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ assert exit_code == 1
+ assert "exact __all__ removal" in capsys.readouterr().out
+
+
+def test_explicit_acknowledgement_opens_a_route_for_uninventoried_api(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.other": ["z"]})
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ _write_removals(repo, {"kornia.mymodule": ["a"]})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ assert exit_code == 0
+ assert REMOVALS_PATH in capsys.readouterr().out
+
+
+def test_malformed_explicit_acknowledgement_fails_closed(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.other": ["z"]})
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+ (repo / REMOVALS_PATH).write_text('{"kornia.mymodule": {}}\n')
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ assert exit_code == 1
+ assert "malformed acknowledgement" in capsys.readouterr().out
+
+
+def test_explicit_acknowledgement_is_new_only_and_can_be_cleaned_up(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.other": ["z"]})
+ _write_removals(repo, {"kornia.mymodule": ["a"]})
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-q", "-m", "old acknowledgement", cwd=repo)
+ _git("branch", "-f", "base", "HEAD", cwd=repo)
+ (repo / "kornia" / "mymodule.py").write_text("__all__ = ['b']\n\ndef b():\n pass\n")
+
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1
+ assert "cannot be reused" in capsys.readouterr().out
+ (repo / "kornia" / "mymodule.py").write_text(_exports("a", "b"))
+ _write_removals(repo, {}) # restoring an API clears its old acknowledgement.
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 0
+ assert capsys.readouterr().out == ""
+
+
+def test_mixed_removals_have_separate_actionable_remedies(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path, inventory={"kornia.mymodule": ["a"]})
+ (repo / "kornia/mymodule.py").write_text("__all__ = []\n")
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1
+ errors = [line for line in capsys.readouterr().out.splitlines() if "Removed from __all__" in line]
+ assert len(errors) == 2
+ assert "['a']" in errors[0] and INVENTORY_PATH in errors[0] and REMOVALS_PATH not in errors[0]
+ assert "['b']" in errors[1] and REMOVALS_PATH in errors[1]
+
+
+def test_explicit_record_does_not_replace_exact_inventory_update(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia/mymodule.py").write_text(_exports("b"))
+ _write_removals(repo, {"kornia.mymodule": ["a"]})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1
+ assert "do not replace" in capsys.readouterr().out
+
+
+def test_explicit_sibling_removal_preserves_unrelated_package_export(tmp_path, capsys):
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="from .a import thing\n",
+ submodules={"a": _exports("thing"), "b": _exports("thing")},
+ inventory={"kornia.pkg": ["thing"]},
+ )
+ (repo / "kornia/pkg/b.py").write_text(_exports())
+ _write_removals(repo, {"kornia.pkg.b": ["thing"]})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 0
+ assert "::error" not in capsys.readouterr().out
+
+
+def test_inventory_acknowledges_an_unbound_all_entry(tmp_path, capsys):
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="__all__ = ['AUTUMN']\n",
+ submodules={},
+ inventory={"kornia.pkg": ["AUTUMN"]},
+ )
+ (repo / "kornia/pkg/__init__.py").write_text("__all__ = []\n")
+ _write_inventory(repo, {"kornia.pkg": []})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 0
+ assert INVENTORY_PATH in capsys.readouterr().out
+
+
+def test_dynamic_all_cannot_prove_an_inventory_removal(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia/mymodule.py").write_text("__all__ = ['b']\n__all__.append('a')\n")
+ _write_inventory(repo, {"kornia.mymodule": ["b"]})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1
+ assert "exact resolved export delta" in capsys.readouterr().out
+
+
+ "import_line",
+ [
+ "from .a import *",
+ "from .a import thing",
+ "from .a import thing as alias",
+ "import kornia.pkg.a as alias",
+ "from . import a as alias",
+ ],
+)
+def test_inventory_acknowledges_implicit_submodule_removal(tmp_path, capsys, import_line):
+ alias = "alias" if "as alias" in import_line else "thing"
+ repo = _repo_with_package(
+ tmp_path,
+ init_body=import_line + "\n",
+ submodules={"a": _exports("thing")},
+ inventory={"kornia.pkg": ["a", alias]},
+ )
+ (repo / "kornia/pkg/__init__.py").write_text('"""An empty package."""\npass\n')
+ (repo / "kornia/pkg/a.py").unlink()
+ _write_inventory(repo, {"kornia.pkg": []})
+ _write_removals(repo, {"kornia.pkg.a": ["thing"]})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 0
+ assert "::error" not in capsys.readouterr().out
+
+
+ "expression",
+ [
+ "globals().update(thing=1)",
+ "(thing := 1)",
+ "sentinel = (thing := 1)",
+ "sentinel = globals().update(thing=1)",
+ "def f(value=(thing := 1)): pass",
+ "@(globals().update(thing=1) or (lambda f: f))\ndef f(): pass",
+ "class C:\n globals().update(thing=1)",
+ ],
+)
+def test_dynamic_binding_cannot_stage_inventory_removal(tmp_path, capsys, expression):
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="thing = 1\n",
+ submodules={},
+ inventory={"kornia.pkg": ["thing"]},
+ )
+ (repo / "kornia/pkg/__init__.py").write_text(expression + "\n")
+ _write_inventory(repo, {"kornia.pkg": []})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1
+ assert "exact resolved export delta" in capsys.readouterr().out
+
+
+def test_retained_submodule_binding_cannot_stage_inventory_removal(tmp_path, capsys):
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="from .a import *\n",
+ submodules={"a": _exports("thing")},
+ inventory={"kornia.pkg": ["a", "thing"]},
+ )
+ (repo / "kornia/pkg/__init__.py").write_text("from .a import thing\n")
+ _write_inventory(repo, {"kornia.pkg": ["thing"]})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1
+ assert "exact resolved export delta" in capsys.readouterr().out
+
+
+def test_function_body_does_not_make_package_exports_unknown(tmp_path):
+ repo = _repo_with_package(
+ tmp_path,
+ init_body="thing = 1\n",
+ submodules={},
+ inventory={"kornia.pkg": ["thing"]},
+ )
+ (repo / "kornia/pkg/__init__.py").write_text("def f():\n globals().update(thing=1)\n")
+ _write_inventory(repo, {"kornia.pkg": []})
+ assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 0
diff --git a/tests/test_api_surface.py b/tests/test_api_surface.py
index 363da87c1..c73387fd6 100644
--- a/tests/test_api_surface.py
+++ b/tests/test_api_surface.py
@@ -54,6 +54,24 @@ def regenerate() -> None:
INVENTORY.write_text(json.dumps(surface, indent=2, sort_keys=True) + "\n")
+def test_inventory_is_a_mapping_of_module_to_public_names():
+ """Guard the inventory's shape, so the removal test below cannot pass vacuously.
+
+ ``set(recorded) - current`` is empty for an entry mangled into ``{}``, so that entry
+ silently stops guarding its module while still parametrizing this file. A list
+ holding non-strings fails the removal test instead, but with a message about
+ "removed" names that names nothing a reader can act on. Asserting the shape here
+ reports the real problem in both cases -- and the ``Import Surface`` check reads the
+ same file, where a wrong-shaped entry acknowledges nothing at all.
+ """
+ inventory = json.loads(INVENTORY.read_text())
+ assert isinstance(inventory, dict)
+ for module_name, names in inventory.items():
+ assert isinstance(module_name, str), f"non-string inventory key: {module_name!r}"
+ assert isinstance(names, list), f"{module_name} must record a list of names, got {type(names).__name__}"
+ assert all(isinstance(name, str) for name in names), f"{module_name} records a non-string name"
+
+
@pytest.mark.parametrize("module_name", sorted(json.loads(INVENTORY.read_text())))
def test_no_public_name_removed(module_name):
recorded = set(json.loads(INVENTORY.read_text())[module_name])