# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AST boundary guards for `a2ui.experimental.decision` public SDK seam usage.""" from __future__ import annotations import ast import importlib from pathlib import Path import pytest SRC_ROOT = Path(__file__).resolve().parents[1] / "src" TESTS_ROOT = Path(__file__).resolve().parents[1] / "tests" EXPERIMENTAL_ROOT = SRC_ROOT / "a2ui" / "experimental" SOURCE_FILES = sorted(EXPERIMENTAL_ROOT.rglob("*.py")) TEST_FILES = [ p for p in sorted(TESTS_ROOT.rglob("*.py")) if p != Path(__file__).resolve() ] _REFLECTIVE_ATTR_FUNCS = frozenset({"getattr", "hasattr", "setattr", "delattr"}) _ALLOWED_PUBLIC_FACADES = frozenset({ "a2ui.builder.v0_9", "a2ui.builder.v1_0", "a2ui.catalog_transformers", "a2ui.core", "a2ui.core.basic_catalog", "a2ui.core.basic_catalog.v1_0", "a2ui.core.schema", "a2ui.core.schema.v0_8", "a2ui.core.schema.v0_9", "a2ui.core.schema.v1_0", "a2ui.inference_formats", "a2ui.inference_formats.direct_json", "a2ui.inference_formats.express", "a2ui.parser", "a2ui.processor", "a2ui.rpc", "a2ui.transformers", "a2ui.transformers.macros", "a2ui.utils", "a2ui.utils.experimental", }) _ALLOWED_TEST_FACADES = _ALLOWED_PUBLIC_FACADES | frozenset({ "a2ui.experimental.decision", "a2ui.experimental.decision.binder", "a2ui.experimental.decision.cascade", "a2ui.experimental.decision.gated", "a2ui.experimental.decision.payload", "a2ui.experimental.decision.prose", "a2ui.experimental.decision.rpc", }) def _owner_package_name(rel_path: Path) -> str: """Returns the `a2ui.experimental.` owning `rel_path`.""" if len(rel_path.parts) >= 3 and rel_path.parts[:2] == ("a2ui", "experimental"): return f"a2ui.experimental.{rel_path.parts[2]}" return "a2ui.experimental" def _has_private_segment(module: str) -> bool: """Returns whether any dotted segment in `module` is private (`_*`).""" return any(part.startswith("_") for part in module.split(".")) def _is_external_a2ui_module(module: str, owner_package: str) -> bool: """Returns whether `module` is an `a2ui` module outside `owner_package`. Sibling packages under `a2ui.experimental` count as external, so one experiment cannot deep-import another. """ if module == "a2ui": return True if not module.startswith("a2ui."): return False return module != owner_package and not module.startswith(owner_package + ".") def _absolute_module(node: ast.ImportFrom, rel_path: Path) -> str: """Returns the absolute module `node` imports from. Resolves a relative import against the package of `rel_path` (a path relative to `SRC_ROOT`), so `from ..sibling import x` cannot bypass the boundary checks. """ if node.level == 0: return node.module or "" package = rel_path.parts[:-1] base = package[: len(package) - (node.level - 1)] return ".".join([*base, *([node.module] if node.module else [])]) def _check_external_module( module: str, lineno: int, rel_path: Path, allowed_facades: frozenset[str], violations: list[str], ) -> object | None: """Validates that `module` is an allowed public facade and returns it.""" if _has_private_segment(module): violations.append( f"{rel_path}:{lineno}: external module '{module}' contains a" " private segment (deep internal import)" ) return None if module not in allowed_facades: violations.append( f"{rel_path}:{lineno}: external module '{module}' is not an" " allowed top-level public facade (deep internal import)" ) return None mod_obj = importlib.import_module(module) if getattr(mod_obj, "__all__", None) is None: violations.append( f"{rel_path}:{lineno}: external module '{module}' does not" " define __all__ (deep internal import)" ) return None return mod_obj def _check_import_from( node: ast.ImportFrom, rel_path: Path, violations: list[str], *, owner_package: str | None = None, allowed_facades: frozenset[str] = _ALLOWED_PUBLIC_FACADES, ) -> None: """Validates a `from a2ui.* import ...` statement against allowed facades.""" owner = ( owner_package if owner_package is not None else _owner_package_name(rel_path) ) module = _absolute_module(node, rel_path) if not _is_external_a2ui_module(module, owner): return mod_obj = _check_external_module( module, node.lineno, rel_path, allowed_facades, violations ) if mod_obj is None: return public_all = set(getattr(mod_obj, "__all__", ())) for alias in node.names: if alias.name == "*": violations.append( f"{rel_path}:{node.lineno}: wildcard import from '{module}'" " is forbidden" ) continue if alias.name not in public_all: violations.append( f"{rel_path}:{node.lineno}: '{alias.name}' is not in '{module}.__all__'" ) def _check_import( node: ast.Import, rel_path: Path, violations: list[str], *, owner_package: str | None = None, allowed_facades: frozenset[str] = _ALLOWED_PUBLIC_FACADES, ) -> None: """Validates an `import a2ui.*` statement targets an allowed public facade.""" owner = ( owner_package if owner_package is not None else _owner_package_name(rel_path) ) for alias in node.names: if not _is_external_a2ui_module(alias.name, owner): continue _check_external_module( alias.name, node.lineno, rel_path, allowed_facades, violations ) def _check_import_module_call( node: ast.Call, rel_path: Path, violations: list[str], *, owner_package: str | None = None, allowed_facades: frozenset[str] = _ALLOWED_PUBLIC_FACADES, ) -> None: """Flags `importlib.import_module('a2ui....')` targeting non-facade modules.""" is_import_module = ( isinstance(node.func, ast.Attribute) and node.func.attr == "import_module" ) or (isinstance(node.func, ast.Name) and node.func.id == "import_module") if not is_import_module or not node.args: return first = node.args[0] if not isinstance(first, ast.Constant) or not isinstance(first.value, str): return module = first.value owner = ( owner_package if owner_package is not None else _owner_package_name(rel_path) ) if not _is_external_a2ui_module(module, owner): return _check_external_module(module, node.lineno, rel_path, allowed_facades, violations) def _is_macro_dunder_call(node: ast.Call) -> bool: """Returns whether `node` calls `getattr`/`hasattr` for `__a2ui_macro__`.""" if ( not isinstance(node.func, ast.Name) or node.func.id not in _REFLECTIVE_ATTR_FUNCS or len(node.args) < 2 ): return False second = node.args[1] return isinstance(second, ast.Constant) and second.value == "__a2ui_macro__" def test_source_files_present_and_pep420_namespace_preserved() -> None: assert SOURCE_FILES, f"No source files found under {EXPERIMENTAL_ROOT}" subpackages = [ p for p in EXPERIMENTAL_ROOT.iterdir() if p.is_dir() and not p.name.startswith("_") ] assert subpackages, f"No experimental subpackages found under {EXPERIMENTAL_ROOT}" for subpkg in subpackages: assert (subpkg / "__init__.py").is_file() for namespace_dir in (SRC_ROOT / "a2ui", EXPERIMENTAL_ROOT): assert not (namespace_dir / "__init__.py").exists(), ( "PEP 420 namespace package must not define" f" {(namespace_dir / '__init__.py').relative_to(SRC_ROOT.parent)}" ) @pytest.mark.parametrize( ("module", "expected"), [ ("a2ui.experimental.decision", False), ("a2ui.experimental.decision.models", False), ("a2ui.experimental", True), ("a2ui.experimental.decision_extras", True), ("a2ui.experimental.other", True), ("a2ui.utils", True), ("a2ui", True), ("json", False), ], ) def test_only_the_decision_experiment_is_exempt(module: str, expected: bool) -> None: assert _is_external_a2ui_module(module, "a2ui.experimental.decision") is expected def test_private_module_segments_are_rejected_even_with_dunder_all() -> None: assert _has_private_segment("a2ui.inference_formats._shared.catalogs") is True assert _has_private_segment("a2ui.core.schema") is False def test_relative_imports_resolve_against_the_importing_package() -> None: rel_path = Path("a2ui/experimental/decision/ask.py") def resolve(source: str) -> str: node = ast.parse(source).body[0] assert isinstance(node, ast.ImportFrom) return _absolute_module(node, rel_path) assert resolve("from a2ui.utils import x") == "a2ui.utils" assert resolve("from .models import x") == "a2ui.experimental.decision.models" assert resolve("from . import models") == "a2ui.experimental.decision" assert resolve("from ..other import x") == "a2ui.experimental.other" assert resolve("from .. import other") == "a2ui.experimental" def _scan_ast_for_violations( source: str, rel_path: Path, *, owner_package: str | None = None, allowed_facades: frozenset[str] = _ALLOWED_PUBLIC_FACADES, ) -> list[str]: """Scans Python `source` for public API boundary violations.""" tree = ast.parse(source, filename=str(rel_path)) violations: list[str] = [] for node in ast.walk(tree): if isinstance(node, ast.ImportFrom): _check_import_from( node, rel_path, violations, owner_package=owner_package, allowed_facades=allowed_facades, ) elif isinstance(node, ast.Import): _check_import( node, rel_path, violations, owner_package=owner_package, allowed_facades=allowed_facades, ) elif isinstance(node, ast.Attribute) and node.attr == "__a2ui_macro__": violations.append( f"{rel_path}:{node.lineno}: direct '__a2ui_macro__' attribute" " access is forbidden; read macro schemas through" " a2ui.transformers.macros.MacroExpander.to_catalog" ) elif isinstance(node, ast.Call): if _is_macro_dunder_call(node): violations.append( f"{rel_path}:{node.lineno}: reflective '__a2ui_macro__' access" " is forbidden; read macro schemas through" " a2ui.transformers.macros.MacroExpander.to_catalog" ) _check_import_module_call( node, rel_path, violations, owner_package=owner_package, allowed_facades=allowed_facades, ) return violations def test_boundary_guard_rejects_deep_and_dynamic_imports() -> None: rel_path = Path("a2ui/experimental/decision/probe.py") assert _scan_ast_for_violations( "from a2ui.utils.catalog_inspector import CatalogSchemaInspector\n", rel_path, ) assert _scan_ast_for_violations( "import a2ui.utils.catalog_inspector as ci\n", rel_path, ) assert _scan_ast_for_violations( "import importlib\nimportlib.import_module('a2ui.utils._schema_helper')\n", rel_path, ) assert _scan_ast_for_violations( "from a2ui.utils._schema_helper import X\n", rel_path, ) assert not _scan_ast_for_violations( "from a2ui.utils.experimental import CatalogSchemaInspector\n", rel_path, ) @pytest.mark.parametrize( "path", SOURCE_FILES, ids=[str(p.relative_to(SRC_ROOT)) for p in SOURCE_FILES], ) def test_external_a2ui_imports_stay_on_public_facades(path: Path) -> None: rel_path = path.relative_to(SRC_ROOT) violations = _scan_ast_for_violations( path.read_text(encoding="utf-8"), rel_path, ) assert not violations, "Public API boundary violations found:\n" + "\n".join( violations ) @pytest.mark.parametrize( "path", TEST_FILES, ids=[str(p.relative_to(TESTS_ROOT)) for p in TEST_FILES], ) def test_test_files_stay_on_public_facades(path: Path) -> None: rel_path = Path("tests") / path.relative_to(TESTS_ROOT) violations = _scan_ast_for_violations( path.read_text(encoding="utf-8"), rel_path, owner_package="__tests__", allowed_facades=_ALLOWED_TEST_FACADES, ) assert not violations, "Public API boundary violations in tests:\n" + "\n".join( violations ) def test_allowed_public_facades_are_importable_and_define_all() -> None: import importlib for module_name in sorted(_ALLOWED_PUBLIC_FACADES): mod = importlib.import_module(module_name) assert hasattr( mod, "__all__" ), f"Allowlisted facade {module_name!r} lacks __all__"