Skip to content

fix(box): enforce allowed_import on from-imports of unloaded package submodules - #1016

Draft
haoruilee wants to merge 4 commits into
InferMatrixLab:mainfrom
haoruilee:fix/box-unloaded-package-from-import-policy
Draft

haoruilee wants to merge 4 commits into
InferMatrixLab:mainfrom
haoruilee:fix/box-unloaded-package-from-import-policy

Conversation

@haoruilee

@haoruilee haoruilee commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Governing Issue and delivery slice

Refs #1015

  • Accepted scope / delegation: Proposed in bug(box): enforce allowed_import for from-imports of submodules under unloaded packages #1015; this PR remains Draft until Box / Harness maintainers confirm scope, assign an accountable owner, and delegate implementation to @haoruilee.
  • Anchors touched: none
  • What this PR delivers:
    • src/inferrsi/box/kernel/transaction.py:
      • Adds pure read-only static package/spec inspection helpers (_path_finder, _find_spec_in_paths, _static_find_spec, _package_search_locations, using syntax.exact_type(paths, list, tuple)) that invoke sys.path_hooks into a per-call finder_cache dict without importing or executing any module, without calling PathFinder.invalidate_caches(), and without mutating sys.path_importer_cache or global FileFinder caches. Handles regular packages, multi-level unloaded packages, PEP 420 namespace packages (including split roots and nested namespace subpackages), zipimport, custom sys.meta_path finders, and already-loaded parent __path__ entries (rejecting non-inspectable custom __path__ objects), while still detecting newly written .py files even when a global cached FileFinder has a stale _path_mtime.
      • Updates TransactionLog._order_changes() so when loaded is None and source not in created and members and allowed(source), it resolves locations = _package_search_locations(source, finder_cache) and adds child = f"{source}.{member}" to names whenever _static_find_spec(child, locations, finder_cache)[0] is True. allowed(item) then rejects disallowed submodules at preflight with BoxError("restart_required", ...) without loading either source or child into sys.modules, while non-submodule attribute imports (from allowed_pkg import PUBLIC) and unloaded stdlib submodule imports (from wsgiref import headers) continue to pass.
    • tests/box/conformance/test_structural_transactions.py:
      • Adds test_unloaded_package_from_import_enforces_allowed_import_policy covering:
        • Observable import-execution marker file written on import by __init__.py and forbidden.py, asserting not marker.exists() and zero modules added to sys.modules across every rejected loader (top-level and multi-level unloaded regular packages, nested and top-level PEP 420 namespace packages, zip loader, and relative imports from unloaded subpackages), and confirming marker.exists() on positive execution.
        • Positive cases: allowed non-submodule attributes (from pkg import PUBLIC, from pkg.sub import SUB_PUBLIC), zip loader (from zip_pkg import ZIP_PUBLIC), PEP 420 namespace package (from ns_pkg import allowed_mod), and unloaded stdlib (from wsgiref import headers), all installing and uninstalling cleanly.
        • Process-wide cache invariance: asserts sys.path_importer_cache == before_cache after all preflight rejections.
  • What it does not deliver: Changes to allowed_import policies in repo adapters (vllm_omni, vllm_common), changes to swap.py closure tracking, or Issue closure.
  • Known limits:
    1. Static preflight cannot observe submodules exposed only by runtime __path__ mutation (for example, an unloaded pkgutil-style namespace package whose __init__.py extends __path__ at import time) or unloaded prefixes with no static spec (where _package_search_locations() returns None; already-loaded parents with non-inspectable custom __path__ objects are rejected explicitly).
    2. _path_finder() invokes sys.path_hooks directly into a per-call cache rather than reading or writing sys.path_importer_cache. This is read-only for the standard FileFinder and zipimporter hooks, whereas third-party custom sys.path_hooks registered by a host application will execute during preflight.

Knowledge authorship declaration

No path protected by docs/knowledge-model-policy.md is changed. The declaration is filled for completeness against the current head.

{
  "schema_version": 1,
  "head_sha": "118886cddfa57f270307a53ab2ed2f4e12cab25a",
  "human_only": false,
  "material_ai_authors": [
    {
      "tool": "antigravity-cli",
      "model_id": "gemini-4-neon",
      "effort": "xhigh",
      "role": "author"
    }
  ]
}

Changed artifacts and evidence

Requirement (#1015) Actual change Check / evidence and result Remaining gap
Enforce allowed_import at preflight for from <pkg> import <submodule> when <pkg> is unloaded, purely read-only without importing modules or mutating global import caches src/inferrsi/box/kernel/transaction.py: _path_finder, _find_spec_in_paths, _static_find_spec, _package_search_locations, and _order_changes() static submodule lookup over sys.path_hooks with a per-call cache Before (954ad306): from allowed_pkg import forbidden returned ok and executed allowed_pkg.forbidden (run: 99); after (118886cd): rejected at preflight with restart_required, observable init marker absent, zero modules loaded, sys.path_importer_cache unchanged, and metaclass __eq__ probe confirms 0 __eq__ calls; covered by test_unloaded_package_from_import_enforces_allowed_import_policy on Py3.10 & Py3.11 Upstream Ready CI for 118886cd pending; known limits documented above
Preserve non-submodule attributes, allowed zip/namespace/stdlib imports, and loaded-package semantics src/inferrsi/box/kernel/transaction.py: adds child only when static spec lookup succeeds; loaded-package branch unchanged Conformance tests cover from pkg import PUBLIC, from pkg.sub import SUB_PUBLIC, from zip_pkg import ZIP_PUBLIC, from ns_pkg import allowed_mod, from wsgiref import headers, and full tests/box/ + test_architecture_anchors.py (340 passed, 0 failed on Py3.10 & Py3.11) Upstream Ready CI for 118886cd pending

Checks and dependencies

  • Checks actually run (result and tested scope): Linux x86_64 on merge head 118886cddfa57f270307a53ab2ed2f4e12cab25a (merging origin/main 87bbfc77, under env -u PYTHONPATH):
    • ruff check src tests tools (Python 3.10.20 & 3.11.14): passed (All checks passed!).
    • git diff origin/main..HEAD --check: passed.
    • env -u PYTHONPATH pytest -n 4 tests/box/ tests/repository/test_architecture_anchors.py: 340 passed, 0 failed on both Python 3.10.20 (8.08s) and Python 3.11.14 (7.83s).
    • Prior heads 0a66bace and ce28a2fe passed upstream CI (all non-skipped jobs + knowledge-model-policy PASS) plus targeted stale-cache, zero-mutation, and metaclass __eq__ probes.
    • Local tools/check_pr_references.py, tools/check_knowledge_model_policy.py, and git merge-tree --write-tree origin/main HEAD (87bbfc77): passed.
  • Failed, skipped, timed-out or not-run checks (if applicable):
    • Not run locally: full Ready test suite (local host has git 2.43.0 < 2.45), Windows/macOS advisory host-compatibility, installed-package, dashboard-browser, and upstream GitHub Actions CI for 118886cd (triggered on push).
  • Dependencies / shared interfaces / integration assumptions (if applicable):

Remaining work and Issue closure

…submodules

In TransactionLog._order_changes(), from-imports against an allowed
package that is not yet in sys.modules previously had an empty namespace
dict and skipped adding f"{source}.{member}" to the checked import set,
allowing disallowed submodules to bypass allowed_import and execute at
commit time.

Resolve unloaded package search locations statically via
_package_search_locations(), _static_find_spec(), and
_find_spec_in_paths() without importing any module (covering regular
packages, multi-level packages, PEP 420 namespace packages, zipimport,
and custom meta-path finders), and add submodule candidates to names so
allowed_import rejects disallowed submodules at preflight while
preserving non-submodule attribute imports and stdlib imports.

Add conformance tests covering top-level and nested unloaded regular
packages, PEP 420 namespace packages, relative imports from unloaded
subpackages, and allowed non-submodule attributes.

Agent-assisted-by: antigravity-cli / gemini-4-neon [effort=xhigh] (author)
Signed-off-by: 李浩瑞 <haoruileee@gmail.com>

@jiangkuaixue123 jiangkuaixue123 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

静态复核 601ff8d1。这次改动在 Box 核心的导入预检,不是单个引擎的适配。PR 记录了多种加载器的本地验证,但提交中的新增回归主要覆盖普通文件包。建议把至少一个 namespace package 和一个 zip loader 的无害场景放进现有 conformance 测试,用可观测标记断言预检不会执行模块初始化,同时保留合法导入的正例。这样后续改预检或升级 Python 时,不必依赖本地探针才能发现跨加载器回退。目前仍是 Draft;未运行复现、设备或 CI,也不代 #1015 接受范围。

@Dong1017 Dong1017 added the area:harness Harness module: profile, A/B loop, quality gates, evidence reports label Dec 3, 2026
…ader tests

Replace pkgutil.get_importer() and the process-wide
PathFinder.invalidate_caches() call inside TransactionLog._order_changes()
with a local _path_finder(entry, finder_cache) helper that invokes
sys.path_hooks directly into a per-call cache. Preflight now leaves
sys.path_importer_cache and global FileFinder caches untouched while
still detecting newly written modules even when a cached FileFinder is
stale.

Expand test_unloaded_package_from_import_enforces_allowed_import_policy
with an observable import-execution marker verifying zero module
initialization runs during preflight, a zip loader positive and negative
case, a positive PEP 420 namespace submodule case, an unloaded stdlib
from-import case, and a sys.path_importer_cache invariance assertion.

Agent-assisted-by: antigravity-cli / gemini-4-neon [effort=xhigh] (author)
Signed-off-by: 李浩瑞 <haoruileee@gmail.com>
@haoruilee

Copy link
Copy Markdown
Contributor Author

Antigravity (Gemini 4 Neon, xhigh), acting for @haoruilee.

@jiangkuaixue123 Thanks for the review. In 0a66bace, we updated test_unloaded_package_from_import_enforces_allowed_import_policy in tests/box/conformance/test_structural_transactions.py to include:

  • A zipimport archive case (negative from zip_pkg import forbidden rejected with restart_required and positive from zip_pkg import ZIP_PUBLIC installing/uninstalling cleanly);
  • Both negative (from ns_pkg import forbidden) and positive (from ns_pkg import allowed_mod) PEP 420 namespace package cases, plus an unloaded stdlib case (from wsgiref import headers);
  • An observable import-execution marker file written by __init__.py and forbidden.py across all loaders, asserting not marker.exists() and zero modules added to sys.modules after every preflight rejection (and marker.exists() on positive execution);
  • Removal of PathFinder.invalidate_caches() / pkgutil.get_importer() in src/inferrsi/box/kernel/transaction.py in favor of a pure read-only per-call _path_finder() over sys.path_hooks, with a sys.path_importer_cache invariance assertion.

Verified locally on Linux x86_64 under env -u PYTHONPATH (257 passed across tests/box/ on Python 3.10.20 and 3.11.14). Keeping this PR Draft pending scope confirmation and delegation on #1015.

Resolve conflict in src/inferrsi/box/kernel/transaction.py against main by dropping removed _verify_contents, aligning _package_search_locations with syntax.exact_type(), and keeping all unloaded-package from-import policy checks and tests intact.

Agent-assisted-by: antigravity-cli / gemini-4-neon [effort=xhigh] (author)
Signed-off-by: 李浩瑞 <haoruileee@gmail.com>
Resolve EOF test conflict in tests/box/conformance/test_structural_transactions.py against main while keeping src/inferrsi/box/kernel/transaction.py auto-merged and unloaded-package from-import policy checks intact.

Agent-assisted-by: antigravity-cli / gemini-4-neon [effort=xhigh] (author)
Signed-off-by: 李浩瑞 <haoruileee@gmail.com>

Copy link
Copy Markdown
Collaborator

inferRSI, acting for @amy-why-3459.

I reviewed base 87bbfc77cf2bf60026b2ade85f1848d220df3ec9 and head 118886cddfa57f270307a53ab2ed2f4e12cab25a (this merge of current main; earlier commits 601ff8d1a88da21ae85f85453f581e70ae66bcf6 and 0a66bace35deab49be3f4c75e0acb3ece40a8b3a).

The preflight change in src/inferrsi/box/kernel/transaction.py looks right for the reported bypass: when the parent is allowed, unloaded, and not created in this transaction, _order_changes() now resolves package search locations with a per-call finder cache and adds source.member only when _static_find_spec finds a submodule, so a disallowed from <pkg> import <submodule> can fail with restart_required without loading the parent or child. The loaded-package and export branches are unchanged. test_unloaded_package_from_import_enforces_allowed_import_policy covers the zip, PEP 420, relative, multi-level, and stdlib cases requested on 601ff8d1, including the import-execution marker and sys.path_importer_cache invariance.

I am not Approving this head. #1015 is still proposed: no accountable owner or implementer delegation is recorded, and this PR remains Draft until that decision is made. Please have a Box / Harness maintainer accept the scope on #1015 (including the documented limits about runtime __path__ mutation and custom sys.path_hooks) and then request review again. I did not run the tests; Ready CI for 118886cd was still pending when I looked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:harness Harness module: profile, A/B loop, quality gates, evidence reports

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants