Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion autobot-slm-backend/tests/api/_real_orm_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,9 @@ def import_modules_with_real_orm(import_names: tuple, path_loaded: dict | None =
try:
with real_modules_swapped():
loaded = [load_real_module(name, path) for name, path in path_loaded.items()]
for name in import_names:
for name in import_names: # all evicted first: a name imported by an earlier one is bound once, not twice
sys.modules.pop(name, None)
for name in import_names:
loaded.append(importlib.import_module(name))
return tuple(loaded)
finally:
Expand Down Expand Up @@ -191,6 +192,69 @@ def _evict_stub_built_modules(exclude: tuple) -> dict:
continue
if any(isinstance(v, NonCallableMock) and id(_mock_root(v)) in stubs for v in vars(mod).values()):
evicted[name] = sys.modules.pop(name)
evicted.update(_evict_built_on_another_sqlalchemy(exclude, evicted))
return evicted


_SHARED_ROOTS = ("autobot_shared", "user_management")


def _built_on_another_sqlalchemy(mod) -> bool:
"""Whether *mod* holds a sqlalchemy name that is not the one ``REAL_MODULES`` carries.

A module first imported while another test module had its own private copy of sqlalchemy
swapped in (``test_deactivated_user_token_20443``) keeps that copy's ``Column`` and ``Mapped``.
Mixed with the copy used here, a model declares no primary key.
"""
homes = [REAL_MODULES[n] for n in ("sqlalchemy", "sqlalchemy.orm") if n in REAL_MODULES]
for value in vars(mod).values():
if not str(getattr(value, "__module__", "")).startswith("sqlalchemy"):
continue
for home in homes:
ours = getattr(home, getattr(value, "__name__", ""), value)
if ours is not value:
return True
return False


def _derives_from(mod, names: set) -> bool:
"""Whether *mod* holds a name defined in, or a class subclassing a class defined in, one of *names*."""
for value in vars(mod).values():
if isinstance(value, types.ModuleType):
if value.__name__ in names:
return True
continue
mro = value.__mro__ if isinstance(value, type) else (value,)
if any(getattr(k, "__module__", None) in names for k in mro):
return True
return False


def _evict_built_on_another_sqlalchemy(exclude: tuple, already: dict) -> dict:
"""Pop, and return, cached shared-model modules bound to a different sqlalchemy copy (see above).

Taken to a fixed point: a module that only subclasses an evicted ``Base`` (``organization``) holds no
sqlalchemy name itself, yet is bound to the same copy, and must be rebuilt with the rest.
"""
candidates = {
name: mod
for name, mod in sys.modules.items()
if name not in exclude
and name not in already
and name.split(".")[0] in _SHARED_ROOTS
and isinstance(mod, types.ModuleType)
and not hasattr(mod, "__path__")
}
evicted = {n: m for n, m in candidates.items() if _built_on_another_sqlalchemy(m)}
grew = True
while grew:
grew = False
for name, mod in candidates.items():
if name not in evicted and _derives_from(mod, set(evicted)):
evicted[name] = mod
grew = True
for name in evicted:
sys.modules.pop(name, None)
Comment on lines +256 to +257

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Low value

Supported by static analysis

Script executed:

rg -n 'from (autobot_shared|user_management)(\.[A-Za-z_][A-Za-z_0-9]*)* import|import (autobot_shared|user_management)' autobot_shared/user_management autobot-slm-backend/user_management autobot-slm-backend/services | head -150
sed -n '125,161p' autobot-slm-backend/tests/api/_real_orm_import.py
sed -n '233,303p' autobot-slm-backend/tests/api/_real_orm_import.py

Repository: mrveiss/AutoBot-AI

Length of output: 23317


Script executed:

git diff 8dca1dddf411a3e4e648be04aa2adb75308c891c fa080fb6133723d70059a013b9ef78acb2982187 -- autobot-slm-backend/tests/api/_real_orm_import.py
nl -ba autobot-slm-backend/tests/api/_real_orm_import.py | sed -n '1,340p'
nl -ba autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py | sed -n '1,240p'
rg -n -F -- 'import_modules_with_real_orm(' autobot-slm-backend
rg -n 'from (autobot_shared|user_management)(\.[A-Za-z_][A-Za-z_0-9]*)* import ' autobot_shared/user_management autobot-slm-backend/user_management autobot-slm-backend/services autobot-slm-backend/api | grep -E ' import (models|base|user|role|team|organization|audit|api_key|mfa|sso|user_service|password_epoch)( |,|$| as)'

Repository: mrveiss/AutoBot-AI

Length of output: 30662


Script executed:

nl -ba autobot-slm-backend/services/password_epoch_store.py
nl -ba autobot_shared/user_management/password_epoch.py | sed -n '1,260p'
nl -ba autobot-slm-backend/tests/api/test_scim_revocation_20443.py | sed -n '1,180p'
nl -ba autobot-slm-backend/tests/api/test_api_key_owner_standing_20446.py | sed -n '1,130p'
rg -n -F -e 'password_epoch_store' -e 'from autobot_shared.user_management import' -e 'from user_management import' -e 'from autobot_shared.user_management.models import' -e 'from user_management.models import' -- autobot-slm-backend/api autobot-slm-backend/services autobot-slm-backend/user_management autobot_shared/user_management
rg -n -F -- 'test_deactivated_user_token_20443' autobot-slm-backend/tests autobot-slm-backend
rg --files autobot-slm-backend | rg 'deactivated_user_token_20443|conftest.py$'

Repository: mrveiss/AutoBot-AI

Length of output: 34048


Script executed:

nl -ba autobot-slm-backend/user_management/services/organization_service.py | sed -n '1,260p'
nl -ba autobot_shared/user_management/organization_service.py | sed -n '1,200p'
nl -ba autobot-slm-backend/tests/services/test_deactivated_user_token_20443.py | sed -n '1,220p'
nl -ba autobot-slm-backend/api/scim.py | sed -n '1,125p'
nl -ba autobot-slm-backend/user_management/services/__init__.py
nl -ba autobot-slm-backend/user_management/__init__.py
nl -ba autobot_shared/user_management/__init__.py
python3 - <<'PY'
import ast, pathlib
roots=[pathlib.Path('autobot-slm-backend/api'),pathlib.Path('autobot-slm-backend/services'),pathlib.Path('autobot-slm-backend/user_management'),pathlib.Path('autobot_shared')]
for root in roots:
    for p in root.rglob('*.py'):
        if p.name.endswith('_test.py') or p.name.startswith('test_') or 'tests' in p.parts:
            continue
        try: tree=ast.parse(p.read_text())
        except (SyntaxError,UnicodeError): continue
        for n in ast.walk(tree):
            if not isinstance(n,ast.ImportFrom) or n.level or not n.module or not n.module.startswith(('autobot_shared','user_management')): continue
            for a in n.names:
                for base in (pathlib.Path('.'),pathlib.Path('autobot-slm-backend')):
                    path=base.joinpath(*n.module.split('.'),a.name+'.py')
                    if path.is_file():
                        print(f'{p}:{n.lineno}: from {n.module} import {a.name} [{path}]')
PY

Repository: mrveiss/AutoBot-AI

Length of output: 38662


Script executed:

nl -ba autobot-slm-backend/tests/services/conftest.py | sed -n '1,240p'
nl -ba autobot-slm-backend/conftest.py | sed -n '1,220p'
nl -ba autobot-slm-backend/user_management/models/__init__.py
nl -ba autobot-slm-backend/user_management/models/organization.py | sed -n '1,120p'
nl -ba autobot-slm-backend/user_management/models/user.py | sed -n '1,100p'
rg -n -i 'sqlalchemy[ =<>!~^"]' autobot-slm-backend/requirements* autobot-slm-backend/pyproject.toml pyproject.toml uv.lock requirements* 2>/dev/null
python3 - <<'PY'
import importlib.util
print("SQLAlchemy availability:", importlib.util.find_spec("sqlalchemy"))
PY

Repository: mrveiss/AutoBot-AI

Length of output: 21082


Web query:

SQLAlchemy 2.0 independent sqlalchemy module copies select ORM class ArgumentError inspected class duplicate imports coercions

Result:

Sources consulted:
- sqlalchemy/lib/sqlalchemy/sql/coercions.py at main · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/coercions.py
- ORM Exceptions — SQLAlchemy 2.1 Documentation — https://docs.sqlalchemy.org/en/21/orm/exceptions.html
- Core Exceptions — SQLAlchemy 2.0 Documentation — https://docs.sqlalchemy.org/en/20/core/exceptions.html
- 2.0 Changelog — SQLAlchemy 2.0 Documentation — https://docs.sqlalchemy.org/en/20/changelog/changelog_20.html
- What’s New in SQLAlchemy 2.0? — SQLAlchemy 2.1 Documentation — https://docs.sqlalchemy.org/en/21/changelog/whatsnew_20.html
- …and 37 more

Web query:

github SQLAlchemy rel_2_0_55 sqlalchemy inspection.py _registrars inspect mro coercions.py expect ColumnsClauseRole

Result:

Sources consulted:
- sqlalchemy/lib/sqlalchemy/inspection.py at rel_2_0_55 · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/rel_2_0_55/lib/sqlalchemy/inspection.py
- sqlalchemy/lib/sqlalchemy/sql/coercions.py at rel_2_0_55 · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/rel_2_0_55/lib/sqlalchemy/sql/coercions.py
- sqlalchemy/lib/sqlalchemy/sql/coercions.py at main · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/coercions.py
- …and 19 more

Script executed:

rg -n -F -e 'user_management' -e '_stub(' autobot-slm-backend/conftest.py autobot-slm-backend/tests/conftest.py autobot-slm-backend/tests/api/conftest.py autobot-slm-backend/tests/services/conftest.py
nl -ba autobot-slm-backend/tests/api/conftest.py | sed -n '1,220p'
nl -ba autobot-slm-backend/tests/conftest.py | sed -n '1,160p'
rg -n -F -e 'organization_service' -e 'user_management.services' autobot-slm-backend/tests/api autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py

Repository: mrveiss/AutoBot-AI

Length of output: 19150


Web query:

SQLAlchemy rel_2_0_55 orm base.py _inspect_mapped_class _inspect_mc _sa_class_manager inspection _inspects type sqlalchemy sql coercions inspection _raise_for_expected

Result:

Sources consulted:
- sqlalchemy/lib/sqlalchemy/orm/base.py at rel_2_0_55 · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/rel_2_0_55/lib/sqlalchemy/orm/base.py
- sqlalchemy/lib/sqlalchemy/sql/coercions.py at rel_2_0_55 · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/rel_2_0_55/lib/sqlalchemy/sql/coercions.py
- sqlalchemy/lib/sqlalchemy/inspection.py at rel_2_0_55 · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/rel_2_0_55/lib/sqlalchemy/inspection.py
- …and 24 more

Script executed:

python3 - <<'PY'
import importlib, sys, types
p = types.ModuleType("sample_parent")
p.__path__ = []
old = types.ModuleType("sample_parent.child")
p.child = old
sys.modules["sample_parent"] = p
from sample_parent import child
print("from-import retained evicted child:", child is old, "child key present:", "sample_parent.child" in sys.modules)
PY
nl -ba autobot-slm-backend/conftest.py | sed -n '515,550p'
nl -ba autobot_shared/user_management/base_service.py | sed -n '1,130p'
nl -ba autobot-slm-backend/user_management/services/base_service.py | sed -n '1,100p'

Repository: mrveiss/AutoBot-AI

Length of output: 7587


Web query:

SQLAlchemy rel_2_0_55 inspect mapped class class_mapper _inspect_mc manager_of_class _sa_class_manager coercions ColumnsClauseImpl _implicit_coercions

Result:

Sources consulted:
- https://raw.githubusercontent.com/sqlalchemy/sqlalchemy/rel_2_0_55/lib/sqlalchemy/orm/base.py
- https://raw.githubusercontent.com/sqlalchemy/sqlalchemy/rel_2_0_55/lib/sqlalchemy/sql/coercions.py
- https://raw.githubusercontent.com/sqlalchemy/sqlalchemy/rel_2_0_55/lib/sqlalchemy/orm/instrumentation.py
- …and 32 more

Web query:

site:raw.githubusercontent.com/sqlalchemy/sqlalchemy/rel_2_0_55/lib/sqlalchemy/sql/coercions.py "class _SelectIsNotFrom" "def _implicit_coercions" "class RoleImpl" "expect"

Result:

Sources consulted:
- https://raw.githubusercontent.com/sqlalchemy/sqlalchemy/rel_2_0_55/lib/sqlalchemy/sql/coercions.py
- sqlalchemy/lib/sqlalchemy/sql/coercions.py at main · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/coercions.py
- SQLAlchemy: lib/sqlalchemy/sql/coercions.py | Fossies — https://fossies.org/linux/sqlalchemy/lib/sqlalchemy/sql/coercions.py
- sqlalchemy/lib/sqlalchemy/sql/elements.py at main · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/elements.py
- sqlalchemy/lib/sqlalchemy/orm/relationships.py at main · sqlalchemy/sqlalchemy · GitHub — https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/orm/relationships.py
- …and 19 more

Clear evicted modules from their parent packages during loading.

If the helper loads the SLM organisation service after the shared service used another SQLAlchemy copy, the subclass retains the evicted service through its parent attribute. Its queries can then mix SQLAlchemy copies and fail. Clear those attributes during loading and restore them afterwards.

return evicted


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""SLM login needs nothing from the main app at request time (#21153, #10200, ADR-012).

The SLM authenticates against its own ``users`` table (the copy the main app keeps current
through ``/internal/person-copy``). Here a real in-memory database holds an admin, the one
outbound client the SLM has for the main app is made to raise a connection error, and the
login lookup still succeeds. A source guard pins that the login modules never import that
client, so a later request-time call would fail this file rather than a user.
"""

import ast
import secrets
import sys
import uuid
from pathlib import Path

import pytest

from autobot_shared.user_management.base_service import TenantContext

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "api"))
from _real_orm_import import import_modules_with_real_orm, real_modules_swapped # noqa: E402

_SLM = Path(__file__).resolve().parents[2]

# This directory's conftest stands in for sqlalchemy and the SLM's ``user_management`` package; the real ones are the
# system under test. The shared helper imports them once, for real, and the references are held for the whole module
# (SQLAlchemy's class registry is weak, so a dropped ``Organization`` would stop ``Role`` resolving it).
_LOADED = import_modules_with_real_orm(
import_names=(
"user_management",
"user_management.models",
"user_management.models.api_key",
"user_management.models.user",
"autobot_shared.user_management.user_service",
"services.main_backend_client",
)
)
User = _LOADED[3].User
UserService = _LOADED[-2].UserService
main_backend_client = _LOADED[-1]

with real_modules_swapped():
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.ext.compiler import compiles


# the JSONB class the models were declared with (a second import of the dialect would be a different class)
@compiles(type(User.metadata.tables["organizations"].c.settings.type), "sqlite")
def _jsonb_as_json(element, compiler, **kw): # noqa: ANN001
return "JSON"


class _SlmUserService(UserService):
user_model = User


@pytest.fixture()
async def session():
# the conftest stubs sqlalchemy; the dialect plugin and lazy ORM imports need the real one for the whole test
with real_modules_swapped():
engine = create_async_engine("sqlite+aiosqlite://") # canonical: ignore py-adhoc-db-engine
async with engine.begin() as conn:
await conn.run_sync(User.metadata.create_all)
maker = async_sessionmaker(engine, expire_on_commit=False) # canonical: ignore py-adhoc-db-engine
async with maker() as db:
yield db
await engine.dispose()


_PASSWORD = secrets.token_urlsafe(16)


async def _seed_admin(db):
svc = _SlmUserService(db, TenantContext(is_platform_admin=True))
db.add(
User(
id=uuid.uuid4(),
username="admin",
email="admin@example.test",
password_hash=svc.hash_password(_PASSWORD),
is_active=True,
is_platform_admin=True,
)
)
await db.commit()
return svc


@pytest.fixture()
def main_app_down(monkeypatch):
"""The SLM's one client for the main app, made to fail; ``awaited`` records every call that reaches it."""
awaited = []

async def _down(*args, **kwargs):
awaited.append((args, kwargs))
raise ConnectionError("main app unreachable")

monkeypatch.setattr(main_backend_client, "call_main_backend", _down)
return awaited
Comment on lines +102 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trivial · Maintainability & Code Quality · Low value

Supported by static analysis

Script executed:

for f in autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py autobot-slm-backend/tests/api/_real_orm_import.py autobot-slm-backend/services/main_backend_client.py autobot_shared/user_management/user_service_access.py autobot_shared/user_management/user_service_base.py autobot_shared/user_management/base_service.py; do
  echo "===== $f"
  case "$f" in
    *test_slm_login*) nl -ba "$f" | sed -n '1,175p';;
    *_real_orm_import.py) nl -ba "$f" | sed -n '90,170p';;
    *main_backend_client.py) nl -ba "$f" | sed -n '1,150p';;
    *user_service_access.py) nl -ba "$f" | sed -n '1,120p';;
    *user_service_base.py) nl -ba "$f" | sed -n '1,55p;150,190p';;
    *base_service.py) nl -ba "$f" | sed -n '1,100p';;
  esac
done

Repository: mrveiss/AutoBot-AI

Length of output: 31816


Script executed:

rg -n -F -e 'def node_client' -e 'def internal_api_key' -e 'def resolve_node_url' -e 'AsyncClient' -- autobot_shared/node_proxy.py
rg -n -F -e 'AUTOBOT_INTERNAL_API_KEY' -e 'AUTOBOT_BACKEND_URL' -e 'authority_base_url' -e 'httpx' -- autobot-slm-backend/tests/services/conftest.py autobot-slm-backend/conftest.py autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py autobot-slm-backend/config.py
nl -ba autobot_shared/node_proxy.py | sed -n '1,240p'

Repository: mrveiss/AutoBot-AI

Length of output: 9437


Intercept requests from other client bindings.

If an unlisted authentication helper uses a cached client binding and handles its failure, main_app_down can remain empty. Intercept httpx.AsyncClient.request as well, and configure a test key and URL so the client reaches that boundary.

Suggested fix

--- "a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py"
+++ "b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py"
@@ -91,16 +91,21 @@
 
 
 @pytest.fixture()
 def main_app_down(monkeypatch):
     """The SLM's one client for the main app, made to fail; ``awaited`` records every call that reaches it."""
+    import httpx
+
     awaited = []
 
     async def _down(*args, **kwargs):
         awaited.append((args, kwargs))
         raise ConnectionError("main app unreachable")
 
+    monkeypatch.setenv("AUTOBOT_INTERNAL_API_KEY", "test-key")
+    monkeypatch.setenv("AUTOBOT_BACKEND_URL", "https://main-app.invalid")
+    monkeypatch.setattr(httpx.AsyncClient, "request", _down)
     monkeypatch.setattr(main_backend_client, "call_main_backend", _down)
     return awaited
 
 
 @pytest.mark.asyncio



@pytest.mark.asyncio
async def test_login_works_from_the_local_copy_with_the_main_app_unreachable(session, main_app_down):
svc = await _seed_admin(session)
user = await svc.authenticate("admin", _PASSWORD)
by_email = await svc.authenticate("admin@example.test", _PASSWORD)
assert user is not None and user.username == "admin" and user.is_platform_admin
assert by_email is not None and by_email.id == user.id
assert main_app_down == []
Comment on lines +109 to +113

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trivial · Stability & Availability · Low value

Supported by static analysis

Script executed:

rg -n -F -e 'async def authenticate' -e 'await self._audit_log' -- autobot_shared/user_management/user_service*.py
nl -ba autobot-slm-backend/api/auth.py | sed -n '145,205p'
rg -n -F -e 'def create_audit_log' -e 'from api.security import' -- autobot-slm-backend/api/auth.py autobot-slm-backend/api/security.py

Repository: mrveiss/AutoBot-AI

Length of output: 4156


Script executed:

nl -ba autobot_shared/user_management/user_service_access.py | sed -n '45,115p'
nl -ba autobot-slm-backend/api/security.py | sed -n '60,98p'
nl -ba autobot-slm-backend/api/auth.py | sed -n '130,149p'

Repository: mrveiss/AutoBot-AI

Length of output: 5903


Test the login handler with the main app unavailable.

The direct authentication tests exercise the service audit, but not the handler’s separate audit or token response. Add a handler-level test that blocks the main-app outbound boundary, checks that no call was attempted, and asserts that login returns a token. This would detect a future dependency in the post-authentication path.

Tools

Ruff (0.17.1)

[warning] 111-111: Assertion should be broken down into multiple parts

Break down assertion into multiple parts

(PT018)


[warning] 112-112: Assertion should be broken down into multiple parts

Break down assertion into multiple parts

(PT018)



@pytest.mark.asyncio
async def test_a_wrong_password_is_refused_not_an_error_with_the_main_app_unreachable(session, main_app_down):
svc = await _seed_admin(session)
assert await svc.authenticate("admin", _PASSWORD + "x") is None
assert main_app_down == []


_LOGIN_PATH = (
"api/auth.py",
"api/login_rate_limit.py",
"services/auth.py",
"services/token_denylist.py",
"user_management/services/__init__.py",
# the shared user service ``authenticate`` runs: the class, its two mixins, the base and what they import
*(
f"../autobot_shared/user_management/{m}.py"
for m in (
"user_service",
"user_service_access",
"user_service_base",
"user_service_lifecycle",
"user_service_conflict",
"user_service_errors",
"login_eligibility",
"audit_rows",
"grant_scope",
"role_permission_query",
)
),
"../autobot_shared/auth/jwt_core.py",
)
_FORBIDDEN = ("main_backend_client", "httpx", "aiohttp", "requests", "urllib3")


@pytest.mark.parametrize("rel", _LOGIN_PATH)
def test_the_login_path_imports_no_client_for_the_main_app(rel):
tree = ast.parse((_SLM / rel).read_text(encoding="utf-8"))
imported = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
imported += [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom):
imported.append(node.module or "")
imported += [a.name for a in node.names]
bad = [m for m in imported if any(m == f or m.startswith(f + ".") or m.endswith("." + f) for f in _FORBIDDEN)]
assert not bad, f"{rel} reaches the main app at request time: {bad}"