Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test: expand API inventory to public modules (#5887)

Hsned8729f5fc1a
diff --git a/.github/scripts/check_import_surface.py b/.github/scripts/check_import_surface.py
index fdf538ff6..8866d4245 100755
--- a/.github/scripts/check_import_surface.py
+++ b/.github/scripts/check_import_surface.py
@@ -609,6 +609,10 @@ def export_removals(base_ref: str, paths: list[str]) -> dict[str, set[str]]:
for module in modules:
old_exports = old.resolve(module)
new_exports = new.resolve(module)
+ if new_exports is None and new._source(module) is None:
+ # Neither spelling of the module exists any more: a deleted module exports nothing.
+ # That is a known surface, unlike a dynamic one, so its emptied inventory row can match.
+ new_exports = set()
if old_exports is None or new_exports is None:
continue
names = set(old_exports) - set(new_exports)
diff --git a/AGENTS.md b/AGENTS.md
index 939b0e92f..19ccfd4e7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -120,7 +120,7 @@ when more than one virtualenv is in play: name the interpreter explicitly rather
- For a new algorithm, name the source that defines it, such as a paper or a reference implementation in PyTorch, OpenCV, or scikit-image.
- Do not keep or copy a bug just because the original implementation has it. When a port differs from its reference, decide which behaviour is correct before changing anything: "the reference does it" is not a justification on its own. For example, a non-maxima suppression that keeps positions equal to their window maximum (`>=`), or that re-admits positions once their stronger neighbours are suppressed, is unstable and wrong in principle; kornia keeps strict maxima. When kornia departs from a reference on purpose, say so in the docstring and give the reason.
- Public APIs need type hints, docstrings, and exports.
-- `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.
+- `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). Every module that declares `__all__` under a recorded package root has its own key; deleting such a module empties its key, and that empty key stays as the record. 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 an `__all__` name of a module without its own key, such as a module outside the recorded package roots, 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.feature.dedode": ["DeDoDe"]}`). 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/docs/source/get-started/stability.rst b/docs/source/get-started/stability.rst
index aa0ad6d3a..f06f74efc 100644
--- a/docs/source/get-started/stability.rst
+++ b/docs/source/get-started/stability.rst
@@ -112,12 +112,16 @@ 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
+Each module that declares ``__all__`` under a recorded package root has its own row.
+To delete such a module, keep its key with an empty list: an empty row for a module
+that no longer exists records the deletion, and stays in the inventory.
+
+For an ``__all__`` name of a module that has no row of its own, such as a module
+outside the recorded package roots, record the exact module and removed name in
``tests/api_surface_removals.json``. For example::
{
- "kornia.geometry.boxes": ["Boxes"]
+ "kornia.feature.dedode": ["DeDoDe"]
}
Only module/name pairs newly added relative to the pull request's merge base
diff --git a/tests/api_surface.json b/tests/api_surface.json
index ee16cc4ac..c27a87315 100644
--- a/tests/api_surface.json
+++ b/tests/api_surface.json
@@ -91,6 +91,59 @@
"auto",
"container"
],
+ "kornia.augmentation.auto": [
+ "AutoAugment",
+ "PolicyAugmentBase",
+ "PolicySequential",
+ "RandAugment",
+ "TrivialAugment"
+ ],
+ "kornia.augmentation.auto.operations.ops": [
+ "AutoContrast",
+ "Brightness",
+ "Contrast",
+ "Equalize",
+ "Gray",
+ "HorizontalFlip",
+ "Hue",
+ "Invert",
+ "Posterize",
+ "Rotate",
+ "Saturate",
+ "Sharpness",
+ "ShearX",
+ "ShearY",
+ "Solarize",
+ "SolarizeAdd",
+ "TranslateX",
+ "TranslateY",
+ "VerticalFlip"
+ ],
+ "kornia.augmentation.container.augment": [
+ "AugmentationSequential"
+ ],
+ "kornia.augmentation.container.base": [
+ "BasicSequentialBase",
+ "ImageSequentialBase",
+ "SequentialBase"
+ ],
+ "kornia.augmentation.container.image": [
+ "ImageSequential"
+ ],
+ "kornia.augmentation.container.params": [
+ "ParamItem",
+ "PatchParamItem"
+ ],
+ "kornia.augmentation.container.patch": [
+ "PatchSequential"
+ ],
+ "kornia.augmentation.container.video": [
+ "VideoSequential"
+ ],
+ "kornia.augmentation.utils": [
+ "deepcopy_dict",
+ "override_parameters"
+ ],
"kornia.color": [
"ApplyColorMap",
"BgrToGrayscale",
@@ -192,6 +245,42 @@
"load_state_dict_from_url",
"vec_like"
],
+ "kornia.core.check": [
+ "BaseError",
+ "DeviceError",
+ "ImageError",
+ "KORNIA_CHECK",
+ "KORNIA_CHECK_DM_DESC",
+ "KORNIA_CHECK_IS_COLOR",
+ "KORNIA_CHECK_IS_GRAY",
+ "KORNIA_CHECK_IS_IMAGE",
+ "KORNIA_CHECK_IS_LIST_OF_TENSOR",
+ "KORNIA_CHECK_IS_TENSOR",
+ "KORNIA_CHECK_LAF",
+ "KORNIA_CHECK_SAME_DEVICE",
+ "KORNIA_CHECK_SAME_DEVICES",
+ "KORNIA_CHECK_SHAPE",
+ "KORNIA_CHECK_TYPE",
+ "KORNIA_UNWRAP",
+ "ShapeError",
+ "TypeCheckError",
+ "ValueCheckError",
+ "are_checks_enabled",
+ "disable_checks",
+ "enable_checks"
+ ],
+ "kornia.core.exceptions": [
+ "BaseError",
+ "DeviceError",
+ "ImageError",
+ "ShapeError",
+ "TypeCheckError",
+ "ValueCheckError"
+ ],
+ "kornia.core.safetensors": [
+ "check_safetensors",
+ "load_safetensors"
+ ],
"kornia.enhance": [
"AddWeighted",
"AdjustBrightness",
@@ -249,6 +338,26 @@
"zca_mean",
"zca_whiten"
],
+ "kornia.enhance.jpeg": [
+ "JPEGCodecDifferentiable",
+ "jpeg_codec_differentiable"
+ ],
+ "kornia.enhance.normalize": [
+ "Denormalize",
+ "Normalize",
+ "denormalize",
+ "normalize",
+ "normalize_min_max"
+ ],
+ "kornia.enhance.zca": [
+ "ZCAWhitening",
+ "linear_transform",
+ "zca_mean",
+ "zca_whiten"
+ ],
+ "kornia.feature.sift": [
+ "SIFTDescriptorFromPyramid"
+ ],
"kornia.filters": [
"BilateralBlur",
"BlurPool2D",
@@ -318,6 +427,14 @@
"spatial_gradient3d",
"unsharp_mask"
],
+ "kornia.filters.blur_pool": [
+ "BlurPool2D",
+ "EdgeAwareBlurPool2D",
+ "MaxBlurPool2D",
+ "blur_pool2d",
+ "edge_aware_blur_pool2d",
+ "max_blur_pool2d"
+ ],
"kornia.geometry": [
"ARKitQTVecs_to_ColmapQTVecs",
"AdaptiveQuadInterp3d",
@@ -602,6 +719,333 @@
"warp_points_tps",
"worldtocam_to_camtoworld_Rt"
],
+ "kornia.geometry.bbox": [
+ "bbox_generator",
+ "bbox_generator3d",
+ "bbox_to_mask",
+ "bbox_to_mask3d",
+ "infer_bbox_shape",
+ "infer_bbox_shape3d",
+ "nms",
+ "transform_bbox",
+ "validate_bbox",
+ "validate_bbox3d"
+ ],
+ "kornia.geometry.boxes": [
+ "Boxes",
+ "Boxes3D",
+ "VideoBoxes"
+ ],
+ "kornia.geometry.calibration": [
+ "distort_points",
+ "solve_pnp_dlt",
+ "tilt_projection",
+ "undistort_image",
+ "undistort_points"
+ ],
+ "kornia.geometry.camera": [
+ "PinholeCamera",
+ "StereoCamera",
+ "cam2pixel",
+ "distort_points_affine",
+ "distort_points_kannala_brandt",
+ "dx_distort_points_affine",
+ "dx_distort_points_kannala_brandt",
+ "dx_project_points_orthographic",
+ "dx_project_points_z1",
+ "pixel2cam",
+ "project_points",
+ "project_points_orthographic",
+ "project_points_z1",
+ "undistort_points_affine",
+ "undistort_points_kannala_brandt",
+ "unproject_points",
+ "unproject_points_orthographic",
+ "unproject_points_z1"
+ ],
+ "kornia.geometry.conversions": [
+ "ARKitQTVecs_to_ColmapQTVecs",
+ "Rt_to_matrix4x4",
+ "angle_axis_to_quaternion",
+ "angle_axis_to_rotation_matrix",
+ "angle_to_rotation_matrix",
+ "axis_angle_to_quaternion",
+ "axis_angle_to_rotation_matrix",
+ "camtoworld_graphics_to_vision_4x4",
+ "camtoworld_graphics_to_vision_Rt",
+ "camtoworld_to_worldtocam_Rt",
+ "camtoworld_vision_to_graphics_4x4",
+ "camtoworld_vision_to_graphics_Rt",
+ "cart2pol",
+ "convert_affinematrix_to_homography",
+ "convert_affinematrix_to_homography3d",
+ "convert_points_from_homogeneous",
+ "convert_points_to_homogeneous",
+ "deg2rad",
+ "denormalize_homography",
+ "denormalize_pixel_coordinates",
+ "denormalize_pixel_coordinates3d",
+ "denormalize_points_with_intrinsics",
+ "euler_from_quaternion",
+ "matrix4x4_to_Rt",
+ "normal_transform_pixel",
+ "normal_transform_pixel3d",
+ "normalize_homography",
+ "normalize_homography3d",
+ "normalize_pixel_coordinates",
+ "normalize_pixel_coordinates3d",
+ "normalize_points_with_intrinsics",
+ "normalize_quaternion",
+ "pol2cart",
+ "quaternion_exp_to_log",
+ "quaternion_from_euler",
+ "quaternion_log_to_exp",
+ "quaternion_to_angle_axis",
+ "quaternion_to_axis_angle",
+ "quaternion_to_rotation_matrix",
+ "rad2deg",
+ "rotation_matrix_to_angle_axis",
+ "rotation_matrix_to_axis_angle",
+ "rotation_matrix_to_quaternion",
+ "vector_to_skew_symmetric_matrix",
+ "worldtocam_to_camtoworld_Rt"
+ ],
+ "kornia.geometry.depth": [
+ "DepthWarper",
+ "depth_from_disparity",
+ "depth_from_plane_equation",
+ "depth_to_3d",
+ "depth_to_3d_v2",
+ "depth_to_normals",
+ "depth_warp",
+ "unproject_meshgrid",
+ "warp_frame_depth"
+ ],
+ "kornia.geometry.epipolar": [
+ "KRt_from_projection",
+ "compute_correspond_epilines",
+ "cross_product_matrix",
+ "decompose_essential_matrix",
+ "decompose_essential_matrix_no_svd",
+ "depth_from_point",
+ "essential_from_Rt",
+ "essential_from_fundamental",
+ "find_essential",
+ "find_fundamental",
+ "fundamental_from_essential",
+ "fundamental_from_projections",
+ "generate_scene",
+ "get_closest_point_on_epipolar_line",
+ "get_perpendicular",
+ "intrinsics_like",
+ "left_to_right_epipolar_distance",
+ "motion_from_essential",
+ "motion_from_essential_choose_solution",
+ "normalize_points",
+ "normalize_transformation",
+ "project_to_essential",
+ "projection_from_KRt",
+ "projections_from_fundamental",
+ "random_intrinsics",
+ "relative_camera_motion",
+ "right_to_left_epipolar_distance",
+ "sampson_epipolar_distance",
+ "scale_intrinsics",
+ "symmetrical_epipolar_distance",
+ "triangulate_points"
+ ],
+ "kornia.geometry.epipolar.essential": [
+ "decompose_essential_matrix",
+ "decompose_essential_matrix_no_svd",
+ "essential_from_Rt",
+ "essential_from_fundamental",
+ "find_essential",
+ "motion_from_essential",
+ "motion_from_essential_choose_solution",
+ "project_to_essential",
+ "relative_camera_motion"
+ ],
+ "kornia.geometry.grid": [
+ "create_meshgrid",
+ "create_meshgrid3d"
+ ],
+ "kornia.geometry.homography": [
+ "find_homography_dlt",
+ "find_homography_dlt_iterated",
+ "find_homography_lines_dlt",
+ "find_homography_lines_dlt_iterated",
+ "line_segment_transfer_error_one_way",
+ "oneway_transfer_error",
+ "sample_is_valid_for_homography",
+ "sampson_homography_distance",
+ "symmetric_transfer_error"
+ ],
+ "kornia.geometry.keypoints": [
+ "Keypoints",
+ "Keypoints3D"
+ ],
+ "kornia.geometry.liegroup": [
+ "Se2",
+ "Se3",
+ "So2",
+ "So3"
+ ],
+ "kornia.geometry.linalg": [
+ "batched_dot_product",
+ "batched_squared_norm",
+ "compose_transformations",
+ "euclidean_distance",
+ "inverse_transformation",
+ "point_line_distance",
+ "relative_transformation",
+ "squared_norm",
+ "transform_points"
+ ],
+ "kornia.geometry.line": [
+ "ParametrizedLine",
+ "fit_line"
+ ],
+ "kornia.geometry.plane": [
+ "Hyperplane",
+ "fit_plane"
+ ],
+ "kornia.geometry.pointcloud": [
+ "load_pointcloud_ply",
+ "load_pointcloud_ply_binary",
+ "save_pointcloud_ply",
+ "save_pointcloud_ply_binary"
+ ],
+ "kornia.geometry.pose": [
+ "NamedPose"
+ ],
+ "kornia.geometry.ransac": [
+ "RANSAC"
+ ],
+ "kornia.geometry.solvers": [
+ "determinant_to_polynomial",
+ "multiply_deg_one_poly",
+ "multiply_deg_two_one_poly",
+ "null_vector_3x4",
+ "solve_cubic",
+ "solve_quadratic",
+ "solve_quartic"
+ ],
+ "kornia.geometry.subpix": [
+ "AdaptiveQuadInterp3d",
+ "ConvQuadInterp3d",
+ "ConvSoftArgmax2d",
+ "ConvSoftArgmax3d",
+ "IterativeQuadInterp3d",
+ "NonMaximaSuppression2d",
+ "NonMaximaSuppression3d",
+ "SpatialSoftArgmax2d",
+ "conv_quad_interp3d",
+ "conv_soft_argmax2d",
+ "conv_soft_argmax3d",
+ "iterative_quad_interp3d",
+ "nms2d",
+ "nms3d",
+ "nms3d_minmax",
+ "render_gaussian2d",
+ "spatial_expectation2d",
+ "spatial_soft_argmax2d",
+ "spatial_softmax2d"
+ ],
+ "kornia.geometry.transform.affwarp": [
+ "Affine",
+ "Rescale",
+ "Resize",
+ "Rotate",
+ "Scale",
+ "Shear",
+ "Translate",
+ "affine",
+ "affine3d",
+ "rescale",
+ "resize",
+ "resize_to_be_divisible",
+ "rotate",
+ "rotate3d",
+ "scale",
+ "shear",
+ "translate"
+ ],
+ "kornia.geometry.transform.crop2d": [
+ "CenterCrop2D",
+ "center_crop",
+ "crop_and_resize",
+ "crop_by_boxes",
+ "crop_by_indices",
+ "crop_by_transform_mat"
+ ],
+ "kornia.geometry.transform.crop3d": [
+ "center_crop3d",
+ "crop_and_resize3d",
+ "crop_by_boxes3d",
+ "crop_by_transform_mat3d"
+ ],
+ "kornia.geometry.transform.elastic_transform": [
+ "elastic_transform2d"
+ ],
+ "kornia.geometry.transform.flips": [
+ "Hflip",
+ "Rot180",
+ "Vflip",
+ "hflip",
+ "rot180",
+ "vflip"
+ ],
+ "kornia.geometry.transform.homography_warper": [
+ "BaseWarper",
+ "HomographyWarper"
+ ],
+ "kornia.geometry.transform.image_registrator": [
+ "BaseModel",
+ "Homography",
+ "ImageRegistrator",
+ "Similarity"
+ ],
+ "kornia.geometry.transform.imgwarp": [
+ "get_affine_matrix2d",
+ "get_affine_matrix3d",
+ "get_perspective_transform",
+ "get_perspective_transform3d",
+ "get_projective_transform",
+ "get_rotation_matrix2d",
+ "get_shear_matrix2d",
+ "get_shear_matrix3d",
+ "get_translation_matrix2d",
+ "homography_warp",
+ "homography_warp3d",
+ "invert_affine_transform",
+ "projection_from_Rt",
+ "remap",
+ "warp_affine",
+ "warp_affine3d",
+ "warp_grid",
+ "warp_grid3d",
+ "warp_perspective",
+ "warp_perspective3d"
+ ],
+ "kornia.geometry.transform.pyramid": [
+ "PyrDown",
+ "PyrUp",
+ "ScalePyramid",
+ "build_laplacian_pyramid",
+ "build_pyramid",
+ "pyrdown",
+ "pyrup"
+ ],
+ "kornia.geometry.transform.thin_plate_spline": [
+ "get_tps_transform",
+ "warp_image_tps",
+ "warp_points_tps"
+ ],
+ "kornia.geometry.vector": [
+ "Scalar",
+ "Vector2",
+ "Vector3"
+ ],
"kornia.image": [
"ChannelsOrder",
"ColorSpace",
@@ -629,6 +1073,9 @@
"load_image",
"write_image"
],
+ "kornia.io.sample": [
+ "get_sample_images"
+ ],
"kornia.losses": [
"BinaryFocalLossWithLogits",
"CauchyLoss",
@@ -716,6 +1163,16 @@
"reconstruction",
"top_hat"
],
+ "kornia.morphology.morphology": [
+ "bottom_hat",
+ "closing",
+ "dilation",
+ "erosion",
+ "gradient",
+ "opening",
+ "reconstruction",
+ "top_hat"
+ ],
"kornia.utils": [
"CachedDownloader",
"ImageToTensor",
diff --git a/tests/scripts/test_check_import_surface.py b/tests/scripts/test_check_import_surface.py
index 4dff2efb1..e2eb092d6 100644
--- a/tests/scripts/test_check_import_surface.py
+++ b/tests/scripts/test_check_import_surface.py
@@ -972,6 +972,30 @@ def test_main_exits_zero_and_reports_a_recorded_removal(tmp_path, capsys):
assert "::error" not in captured.out
+def test_main_accepts_a_deleted_module_recorded_by_an_emptied_entry(tmp_path, capsys):
+ # A tracked submodule deleted after its deprecation window: dropping its key is fatal, so the
+ # emptied entry is the record, and a module that no longer exists exports nothing.
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").unlink()
+ _write_inventory(repo, {"kornia.mymodule": []})
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ captured = capsys.readouterr()
+ assert exit_code == 0, captured.out
+ assert "::error" not in captured.out
+
+
+def test_main_deleted_module_without_emptied_entry_is_still_fatal(tmp_path, capsys):
+ repo = _repo_with_inventory(tmp_path)
+ (repo / "kornia" / "mymodule.py").unlink()
+
+ exit_code = _in_repo(repo, lambda: main(["--base-ref", "base"]))
+
+ assert exit_code == 1
+ assert "::error" in capsys.readouterr().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
diff --git a/tests/test_api_surface.py b/tests/test_api_surface.py
index af3b19902..513286e8c 100644
--- a/tests/test_api_surface.py
+++ b/tests/test_api_surface.py
@@ -15,25 +15,30 @@
# limitations under the License.
#
-"""Guard the public API surface of the stable-core modules.
+"""Guard aggregate and public-module API surfaces within the recorded package roots.
The 0.8.3 release removed 20 of the 34 public ``kornia.utils`` names with no
deprecation window β€” nobody noticed until an audit months later, because
nothing in CI compared the public surface against the previous state. This
test is that comparison: ``tests/api_surface.json`` is the checked-in
inventory, and removing a public name fails here until the inventory is
-edited in the same PR β€” which is exactly the deliberate review moment the
+edited explicitly in the same PR β€” which is exactly the deliberate review moment the
stability policy (docs/source/get-started/stability.rst) requires.
-Additions are fine and do not fail the test; run this file with
-``--update-api-surface`` semantics by regenerating the JSON (see
-``regenerate()`` below) whenever new public API lands.
+A new name in a tracked module does not fail. A new module that declares ``__all__`` under one of
+the recorded package roots does, until its row is added: run
+``python -c "from tests.test_api_surface import regenerate; regenerate()"`` from the repository root
+and commit the regenerated JSON. Deleting a whole tracked module, after its deprecation window,
+empties its row rather than dropping it; the empty row stays behind as the record of the removal.
"""
+import ast
import contextlib
import importlib
+import importlib.util
import json
import pkgutil
+import sys
import types
import warnings
from pathlib import Path
@@ -41,6 +46,21 @@ from pathlib import Path
import pytest
INVENTORY = Path(__file__).parent / "api_surface.json"
+INVENTORY_ROOTS = (
+ "kornia.augmentation",
+ "kornia.color",
+ "kornia.core",
+ "kornia.enhance",
+ "kornia.feature.sift",
+ "kornia.filters",
+ "kornia.geometry",
+ "kornia.image",
+ "kornia.io",
+ "kornia.losses",
+ "kornia.metrics",
+ "kornia.morphology",
+ "kornia.utils",
+)
def _current_surface(module_name: str) -> set:
@@ -51,13 +71,183 @@ def _current_surface(module_name: str) -> set:
return set(names)
+def _declared_inventory_modules(package_root: Path) -> list[str]:
+ """Find explicit export declarations from source without importing optional dependencies."""
+ found = []
+ for path in package_root.rglob("*.py"):
+ parts = list(path.relative_to(package_root).with_suffix("").parts)
+ if parts[-1] == "__init__":
+ parts.pop()
+ tree = ast.parse(path.read_bytes(), filename=str(path))
+ if any(
+ (
+ isinstance(node, ast.Assign)
+ and any(isinstance(target, ast.Name) and target.id == "__all__" for target in node.targets)
+ )
+ or (isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == "__all__")
+ for node in tree.body
+ ):
+ found.append(".".join(["kornia", *parts]))
+ return sorted(found)
+
+
+def _inventory_modules(recorded: dict) -> list[str]:
+ """Retain existing rows and discover public modules within fixed package roots.
+
+ The SIFT descriptor module is classical feature API. Pretrained wrappers,
+ private paths and packages outside these roots keep their existing policy.
+ """
+ roots = set(INVENTORY_ROOTS)
+ discovered = {
+ name
+ for name in _declared_inventory_modules(Path(__file__).resolve().parents[1] / "kornia")
+ if not any(part.startswith("_") for part in name.split(".")[1:])
+ and any(name == root or name.startswith(root + ".") for root in roots)
+ }
+ return sorted(set(recorded) | roots | discovered)
+
+
+def _is_removed_module(module_name: str, recorded: dict) -> bool:
+ """Whether the inventory records a completed module removal: an empty row for a module that is gone.
+
+ The Import Surface check fails when a key is dropped, so a deliberate module deletion (after its
+ deprecation window) empties the row instead, and the empty row stays behind as the record.
+ """
+ if recorded.get(module_name) != []:
+ return False
+ try:
+ return importlib.util.find_spec(module_name) is None
+ except ModuleNotFoundError:
+ return True
+
+
def regenerate() -> None:
- """Rewrite the inventory from the live library (run manually after adding public API)."""
+ """Add live public exports to the inventory; deliberate removals must be edited explicitly."""
recorded = json.loads(INVENTORY.read_text())
- surface = {name: sorted(_current_surface(name)) for name in recorded}
+ surface = {
+ name: []
+ if _is_removed_module(name, recorded)
+ else sorted(set(recorded.get(name, [])) | {item for item in _current_surface(name) if not item.startswith("_")})
+ for name in _inventory_modules(recorded)
+ }
INVENTORY.write_text(json.dumps(surface, indent=2, sort_keys=True) + "\n")
+def test_inventory_includes_public_modules_declaring_all():
+ recorded = json.loads(INVENTORY.read_text())
+ missing = sorted(set(_inventory_modules(recorded)) - set(recorded))
+ assert not missing, (
+ f"Public modules absent from the inventory: {missing}. From the repository root, run "
+ '`python -c "from tests.test_api_surface import regenerate; regenerate()"` and commit tests/api_surface.json.'
+ )
+
+
+def test_inventory_module_discovery_preserves_scope(monkeypatch):
+ module = sys.modules[__name__]
+ recorded = {"kornia.geometry": [], "kornia.utils": []}
+ monkeypatch.setattr(module, "INVENTORY_ROOTS", ("kornia.geometry", "kornia.feature.sift"))
+ monkeypatch.setattr(
+ module,
+ "_declared_inventory_modules",
+ lambda path: [
+ "kornia.geometry.boxes",
+ "kornia.geometry._private",
+ "kornia.geometry._private.child",
+ "kornia.feature.sift",
+ "kornia.contrib",
+ "kornia.models",
+ ],
+ )
+ assert _inventory_modules(recorded) == [
+ "kornia.feature.sift",
+ "kornia.geometry",
+ "kornia.geometry.boxes",
+ "kornia.utils",
+ ]
+
+
+def test_inventory_discovery_does_not_import_optional_dependencies(tmp_path):
+ package = tmp_path / "kornia"
+ package.mkdir()
+ (package / "__init__.py").write_text("__all__ = []")
+ (package / "optional.py").write_text("import unavailable_dependency\n__all__: list[str] = ['Export']")
+ (package / "unrelated.py").write_text("value = 1")
+ assert _declared_inventory_modules(package) == ["kornia", "kornia.optional"]
+
+
+def test_inventory_roots_do_not_depend_on_existing_rows(monkeypatch):
+ monkeypatch.setattr(sys.modules[__name__], "_declared_inventory_modules", lambda path: [])
+ assert _inventory_modules({}) == sorted(INVENTORY_ROOTS)
+
+
+ "module_name,name",
+ [
+ ("kornia.geometry.boxes", "Boxes"),
+ ("kornia.geometry.boxes", "VideoBoxes"),
+ ("kornia.augmentation.auto", "AutoAugment"),
+ ],
+)
+def test_removal_guard_covers_previously_unrecorded_modules(monkeypatch, module_name, name):
+ module = importlib.import_module(module_name)
+ monkeypatch.setattr(module, "__all__", [item for item in module.__all__ if item != name])
+ with pytest.raises(AssertionError, match=f"Public names removed from {module_name}"):
+ test_no_public_name_removed(module_name)
+
+
+def test_regenerate_discovers_modules_without_losing_aggregate_rows(monkeypatch, tmp_path):
+ module = sys.modules[__name__]
+ inventory = tmp_path / "api_surface.json"
+ inventory.write_text(json.dumps({"kornia.geometry": ["old"]}))
+ monkeypatch.setattr(module, "INVENTORY", inventory)
+ monkeypatch.setattr(module, "INVENTORY_ROOTS", ("kornia.geometry",))
+ monkeypatch.setattr(module, "_declared_inventory_modules", lambda path: ["kornia.geometry.boxes"])
+ monkeypatch.setattr(module, "_current_surface", lambda name: {name.rsplit(".", 1)[-1], "_private"})
+ regenerate()
+ assert json.loads(inventory.read_text()) == {
+ "kornia.geometry": ["geometry", "old"],
+ "kornia.geometry.boxes": ["boxes"],
+ }
+ first = inventory.read_bytes()
+ regenerate()
+ assert inventory.read_bytes() == first
+
+
+def test_regenerate_import_failure_preserves_inventory(monkeypatch, tmp_path):
+ module = sys.modules[__name__]
+ inventory = tmp_path / "api_surface.json"
+ inventory.write_text(json.dumps({"kornia.geometry": ["old"]}))
+ original = inventory.read_bytes()
+ monkeypatch.setattr(module, "INVENTORY", inventory)
+ monkeypatch.setattr(module, "INVENTORY_ROOTS", ("kornia.geometry",))
+ monkeypatch.setattr(module, "_declared_inventory_modules", lambda path: ["kornia.geometry.optional"])
+
+ def unavailable(name):
+ raise ImportError("missing optional dependency")
+
+ monkeypatch.setattr(module, "_current_surface", unavailable)
+ with pytest.raises(ImportError, match="missing optional dependency"):
+ regenerate()
+ assert inventory.read_bytes() == original
+
+
[email protected]("row,removed", [([], True), (["Gone"], False)])
+def test_an_empty_row_records_a_deleted_module(monkeypatch, tmp_path, row, removed):
+ module = sys.modules[__name__]
+ inventory = tmp_path / "api_surface.json"
+ inventory.write_text(json.dumps({"kornia.geometry.no_such_module": row}))
+ monkeypatch.setattr(module, "INVENTORY", inventory)
+ assert _is_removed_module("kornia.geometry.no_such_module", {"kornia.geometry.no_such_module": row}) is removed
+ if removed:
+ test_no_public_name_removed("kornia.geometry.no_such_module")
+ test_no_foreign_name_leaks_into_the_surface("kornia.geometry.no_such_module")
+ else:
+ with pytest.raises(ModuleNotFoundError):
+ test_no_public_name_removed("kornia.geometry.no_such_module")
+ # An emptied row for a module that still exists is an ordinary row.
+ assert _is_removed_module("kornia.geometry.boxes", {"kornia.geometry.boxes": []}) is False
+
+
def test_inventory_is_a_mapping_of_module_to_public_names():
"""Guard the inventory's shape, so the removal test below cannot pass vacuously.
@@ -78,6 +268,8 @@ def test_inventory_is_a_mapping_of_module_to_public_names():
@pytest.mark.parametrize("module_name", sorted(json.loads(INVENTORY.read_text())))
def test_no_public_name_removed(module_name):
+ if _is_removed_module(module_name, json.loads(INVENTORY.read_text())):
+ return
recorded = set(json.loads(INVENTORY.read_text())[module_name])
current = _current_surface(module_name)
removed = sorted(recorded - current)
@@ -85,8 +277,8 @@ def test_no_public_name_removed(module_name):
f"Public names removed from {module_name}: {removed}. Per the API stability policy "
"(docs/source/get-started/stability.rst), a public symbol must spend at least one minor "
"release as a deprecated shim before removal. If this removal is deliberate and the "
- "deprecation window has passed, update tests/api_surface.json in this PR (run "
- "tests.test_api_surface.regenerate()) and list the removal in the release notes."
+ "deprecation window has passed, edit the affected tests/api_surface.json row in this PR "
+ "and list the removal in the release notes."
)
@@ -116,6 +308,9 @@ def _foreign_names(module_name: str) -> set:
mod = importlib.import_module(module_name)
found = set()
for name in _current_surface(module_name):
+ if name.startswith("_"):
+ # regenerate() never records an underscore name, so it could not resolve a failure here.
+ continue
obj = getattr(mod, name, None)
if isinstance(obj, types.ModuleType):
if obj.__name__ != "kornia" and not obj.__name__.startswith("kornia."):
@@ -140,7 +335,10 @@ def test_no_foreign_name_leaks_into_the_surface(module_name):
record a leaked ``sys`` as a guarded public name. Names already in the inventory are
exempt: removing one is a deliberate API change, not something this test should force.
"""
- recorded = set(json.loads(INVENTORY.read_text())[module_name])
+ inventory = json.loads(INVENTORY.read_text())
+ if _is_removed_module(module_name, inventory):
+ return
+ recorded = set(inventory[module_name])
leaked = sorted(_foreign_names(module_name) - recorded)
assert not leaked, (
f"{module_name} exposes {leaked}, which are imports rather than kornia API. Give the "
@@ -152,10 +350,9 @@ def test_no_foreign_name_leaks_into_the_surface(module_name):
def _modules_declaring_all() -> list:
"""Every importable ``kornia`` submodule that declares ``__all__``.
- The inventory tracks the stable-core modules, but an unbound name is a problem
- wherever it sits: the breakage that motivated this guard (#4026, the
- ComfyUI-LTXVideo report in #3986) was in ``kornia.geometry.transform.pyramid``,
- which the inventory does not cover. Walking the package finds every module that
+ An unbound name is a problem even outside the inventory: the breakage that
+ motivated this guard (#4026, the ComfyUI-LTXVideo report in #3986) was in
+ ``kornia.geometry.transform.pyramid``. Walking the package finds every module that
declares a public surface, costs a fraction of a second, and needs no upkeep as
modules come and go.
"""