Skip to content

Codex-generated pull request#16

Open
NguyenCuong1989 wants to merge 1 commit into
mainfrom
codex/create-shared-config-helper-for-allow_stubs-e64zu4
Open

Codex-generated pull request#16
NguyenCuong1989 wants to merge 1 commit into
mainfrom
codex/create-shared-config-helper-for-allow_stubs-e64zu4

Conversation

@NguyenCuong1989
Copy link
Copy Markdown
Collaborator

@NguyenCuong1989 NguyenCuong1989 commented Feb 18, 2026

User description

Codex generated this pull request, but encountered an unexpected error after generation. This is a placeholder PR message.


Codex Task


PR Type

Enhancement, Tests


Description

  • Add shared allow_stubs() configuration helper function

  • Integrate helper into stub fallback logic for graceful degradation

  • Provide comprehensive test coverage for environment variable parsing

  • Allow conditional stub usage via HYPERAI_ALLOW_STUBS environment variable


Diagram Walkthrough

flowchart LR
  A["HYPERAI_ALLOW_STUBS env var"] -->|parsed by| B["allow_stubs() helper"]
  B -->|controls stub fallback| C["HAIOSRuntime"]
  B -->|controls stub fallback| D["DRProtocol"]
  E["Test suite"] -->|validates| B
Loading

File Walkthrough

Relevant files
Enhancement
config.py
Create shared allow_stubs configuration helper                     

src/hyperai/config.py

  • New module for shared configuration helpers
  • Implements allow_stubs() function that reads HYPERAI_ALLOW_STUBS
    environment variable
  • Returns True for values: "1", "true", "yes", "on" (case-insensitive)
  • Returns False for missing or unrecognized values
+11/-0   
haios_runtime.py
Integrate allow_stubs check into HAIOSRuntime                       

src/hyperai/core/haios_runtime.py

  • Import allow_stubs helper from shared config module
  • Add conditional check in ImportError handler to raise exception if
    stubs not allowed
  • Preserve existing stub implementation when stubs are enabled
+5/-0     
dr_protocol.py
Integrate allow_stubs check into DRProtocol                           

src/hyperai/protocols/dr_protocol.py

  • Import allow_stubs helper from shared config module
  • Add conditional check in ImportError/AttributeError handler to raise
    exception if stubs not allowed
  • Preserve existing stub implementation when stubs are enabled
+5/-0     
Tests
test_config_allow_stubs.py
Add comprehensive tests for allow_stubs helper                     

tests/test_config_allow_stubs.py

  • New test module for allow_stubs() function validation
  • Test truthy values: "1", "true", "TRUE", " yes ", "On"
  • Test falsy values: "0", "false", "off", "no", "random"
  • Test default behavior when environment variable is missing
  • Proper setup/teardown to preserve original environment state
+49/-0   

@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Feb 18, 2026

Hướng dẫn dành cho người review (Reviewer's Guide)

Giới thiệu một helper cấu hình dùng chung để kiểm soát việc có cho phép sử dụng các stub implementation hay không, tích hợp nó vào HAIOS runtime và DR protocol loader để chúng có thể tùy chọn “fail fast” thay vì quay về stub, và thêm các bài kiểm thử để xác nhận hành vi cấu hình.

Biểu đồ tuần tự cho quá trình HAIOSRuntime load với stub tùy chọn

sequenceDiagram
    participant Importer
    participant HAIOSRuntimeModule as src_hyperai_core_haios_runtime
    participant Config as hyperai_config
    participant Env as OS_env
    participant Impl as haios_runtime_impl
    participant Stub as HAIOSRuntime_stub

    Importer->>HAIOSRuntimeModule: import HAIOSRuntime
    HAIOSRuntimeModule->>Config: call allow_stubs()
    Config->>Env: read HYPERAI_ALLOW_STUBS
    Env-->>Config: value
    Config-->>HAIOSRuntimeModule: allow_stubs_result

    HAIOSRuntimeModule->>Impl: import HAIOSRuntimeImpl
    alt Import succeeds
        Impl-->>HAIOSRuntimeModule: HAIOSRuntimeImpl
        HAIOSRuntimeModule-->>Importer: HAIOSRuntime = HAIOSRuntimeImpl
    else ImportError
        alt allow_stubs_result is False
            HAIOSRuntimeModule-->>Importer: raise ImportError
        else allow_stubs_result is True
            HAIOSRuntimeModule->>Stub: define stub class HAIOSRuntime
            Stub-->>HAIOSRuntimeModule: HAIOSRuntime_stub
            HAIOSRuntimeModule-->>Importer: HAIOSRuntime = HAIOSRuntime_stub
        end
    end
Loading

Biểu đồ tuần tự cho quá trình DRProtocol load với stub tùy chọn

sequenceDiagram
    participant Importer
    participant DRProtocolModule as src_hyperai_protocols_dr_protocol
    participant Config as hyperai_config
    participant Env as OS_env
    participant Impl as dr_protocol_impl
    participant Stub as DRProtocol_stub

    Importer->>DRProtocolModule: import DRProtocol
    DRProtocolModule->>Config: call allow_stubs()
    Config->>Env: read HYPERAI_ALLOW_STUBS
    Env-->>Config: value
    Config-->>DRProtocolModule: allow_stubs_result

    DRProtocolModule->>Impl: import DRProtocolImpl
    alt Import succeeds
        Impl-->>DRProtocolModule: DRProtocolImpl
        DRProtocolModule-->>Importer: DRProtocol = DRProtocolImpl
    else ImportError or AttributeError
        alt allow_stubs_result is False
            DRProtocolModule-->>Importer: raise ImportError or AttributeError
        else allow_stubs_result is True
            DRProtocolModule->>Stub: define stub class DRProtocol
            Stub-->>DRProtocolModule: DRProtocol_stub
            DRProtocolModule-->>Importer: DRProtocol = DRProtocol_stub
        end
    end
Loading

Biểu đồ lớp cho config helper và các loader dùng stub

classDiagram
    class hyperai_config {
        +bool allow_stubs()
    }

    class src_hyperai_core_haios_runtime {
        +HAIOSRuntime
        -root_dir
        -_allow_stubs()
    }

    class HAIOSRuntimeImpl {
    }

    class HAIOSRuntime_stub {
        +HAIOSRuntime
    }

    class src_hyperai_protocols_dr_protocol {
        +DRProtocol
        -root_dir
        -_allow_stubs()
    }

    class DRProtocolImpl {
    }

    class DRProtocol_stub {
        +DRProtocol
    }

    hyperai_config ..> src_hyperai_core_haios_runtime : uses
    hyperai_config ..> src_hyperai_protocols_dr_protocol : uses

    src_hyperai_core_haios_runtime ..> HAIOSRuntimeImpl : imports
    src_hyperai_core_haios_runtime ..> HAIOSRuntime_stub : falls_back_to

    src_hyperai_protocols_dr_protocol ..> DRProtocolImpl : imports
    src_hyperai_protocols_dr_protocol ..> DRProtocol_stub : falls_back_to
Loading

Các thay đổi ở mức file (File-Level Changes)

Change Details Files
Thêm một helper cấu hình dùng chung để điều khiển việc sử dụng stub thông qua biến môi trường.
  • Tạo module hyperai.config với helper allow_stubs() đọc biến môi trường HYPERAI_ALLOW_STUBS.
  • Diễn giải các chuỗi “truthy” phổ biến (1, true, yes, on) là bật cho phép stub và coi tất cả giá trị khác hoặc thiếu là tắt stub.
src/hyperai/config.py
Ràng buộc (gate) việc fallback sang stub implementation trong các module runtime và protocol dựa trên cờ cấu hình.
  • Import helper allow_stubs dùng chung trong các module runtime và protocol.
  • Trong các handler ImportError/AttributeError, ném lại (re-raise) exception khi không cho phép stub, ngược lại thì fallback về các stub implementation hiện có.
src/hyperai/core/haios_runtime.py
src/hyperai/protocols/dr_protocol.py
Thêm các bài test để xác nhận hành vi điều khiển stub dựa trên cấu hình.
  • Load động (dynamically load) module cấu hình từ project root trong test để tránh vấn đề đường dẫn import.
  • Kiểm tra allow_stubs() trả về True cho nhiều giá trị môi trường “truthy” khác nhau và False cho các giá trị “falsy”, ngẫu nhiên, hoặc khi thiếu, và khôi phục trạng thái môi trường giữa các bài test.
tests/test_config_allow_stubs.py

Tips and commands

Tương tác với Sourcery

  • Kích hoạt một lượt review mới: Comment @sourcery-ai review trên pull request.
  • Tiếp tục thảo luận: Trả lời trực tiếp vào các comment review của Sourcery.
  • Tạo GitHub issue từ một review comment: Yêu cầu Sourcery tạo issue từ một review comment bằng cách trả lời comment đó. Bạn cũng có thể trả lời một review comment với @sourcery-ai issue để tạo issue từ comment đó.
  • Tạo tiêu đề pull request: Viết @sourcery-ai ở bất kỳ đâu trong tiêu đề pull request để tạo tiêu đề bất kỳ lúc nào. Bạn cũng có thể comment @sourcery-ai title trên pull request để (tái) tạo tiêu đề bất kỳ lúc nào.
  • Tạo tóm tắt pull request: Viết @sourcery-ai summary ở bất kỳ đâu trong phần nội dung pull request để tạo tóm tắt PR tại đúng vị trí bạn muốn. Bạn cũng có thể comment @sourcery-ai summary trên pull request để (tái) tạo tóm tắt bất kỳ lúc nào.
  • Tạo reviewer's guide: Comment @sourcery-ai guide trên pull request để (tái) tạo reviewer's guide bất kỳ lúc nào.
  • Resolve tất cả comment của Sourcery: Comment @sourcery-ai resolve trên pull request để resolve tất cả comment hiện có của Sourcery. Hữu ích nếu bạn đã xử lý hết comment và không muốn thấy chúng nữa.
  • Dismiss tất cả review của Sourcery: Comment @sourcery-ai dismiss trên pull request để dismiss tất cả review hiện có. Đặc biệt hữu ích nếu bạn muốn bắt đầu lại với một lượt review mới – đừng quên comment @sourcery-ai review để kích hoạt review mới!

Tùy chỉnh trải nghiệm của bạn

Truy cập dashboard để:

  • Bật hoặc tắt các tính năng review như tóm tắt pull request do Sourcery tạo, reviewer's guide, và các tính năng khác.
  • Thay đổi ngôn ngữ review.
  • Thêm, xóa hoặc chỉnh sửa các hướng dẫn review tùy chỉnh.
  • Điều chỉnh các thiết lập review khác.

Nhận hỗ trợ

Original review guide in English

Reviewer's Guide

Introduce a shared configuration helper to control whether stub implementations are allowed, wire it into the HAIOS runtime and DR protocol loaders so they can optionally fail fast instead of falling back to stubs, and add tests to validate the configuration behavior.

Sequence diagram for HAIOSRuntime loading with optional stubs

sequenceDiagram
    participant Importer
    participant HAIOSRuntimeModule as src_hyperai_core_haios_runtime
    participant Config as hyperai_config
    participant Env as OS_env
    participant Impl as haios_runtime_impl
    participant Stub as HAIOSRuntime_stub

    Importer->>HAIOSRuntimeModule: import HAIOSRuntime
    HAIOSRuntimeModule->>Config: call allow_stubs()
    Config->>Env: read HYPERAI_ALLOW_STUBS
    Env-->>Config: value
    Config-->>HAIOSRuntimeModule: allow_stubs_result

    HAIOSRuntimeModule->>Impl: import HAIOSRuntimeImpl
    alt Import succeeds
        Impl-->>HAIOSRuntimeModule: HAIOSRuntimeImpl
        HAIOSRuntimeModule-->>Importer: HAIOSRuntime = HAIOSRuntimeImpl
    else ImportError
        alt allow_stubs_result is False
            HAIOSRuntimeModule-->>Importer: raise ImportError
        else allow_stubs_result is True
            HAIOSRuntimeModule->>Stub: define stub class HAIOSRuntime
            Stub-->>HAIOSRuntimeModule: HAIOSRuntime_stub
            HAIOSRuntimeModule-->>Importer: HAIOSRuntime = HAIOSRuntime_stub
        end
    end
Loading

Sequence diagram for DRProtocol loading with optional stubs

sequenceDiagram
    participant Importer
    participant DRProtocolModule as src_hyperai_protocols_dr_protocol
    participant Config as hyperai_config
    participant Env as OS_env
    participant Impl as dr_protocol_impl
    participant Stub as DRProtocol_stub

    Importer->>DRProtocolModule: import DRProtocol
    DRProtocolModule->>Config: call allow_stubs()
    Config->>Env: read HYPERAI_ALLOW_STUBS
    Env-->>Config: value
    Config-->>DRProtocolModule: allow_stubs_result

    DRProtocolModule->>Impl: import DRProtocolImpl
    alt Import succeeds
        Impl-->>DRProtocolModule: DRProtocolImpl
        DRProtocolModule-->>Importer: DRProtocol = DRProtocolImpl
    else ImportError or AttributeError
        alt allow_stubs_result is False
            DRProtocolModule-->>Importer: raise ImportError or AttributeError
        else allow_stubs_result is True
            DRProtocolModule->>Stub: define stub class DRProtocol
            Stub-->>DRProtocolModule: DRProtocol_stub
            DRProtocolModule-->>Importer: DRProtocol = DRProtocol_stub
        end
    end
Loading

Class diagram for config helper and stubbed loaders

classDiagram
    class hyperai_config {
        +bool allow_stubs()
    }

    class src_hyperai_core_haios_runtime {
        +HAIOSRuntime
        -root_dir
        -_allow_stubs()
    }

    class HAIOSRuntimeImpl {
    }

    class HAIOSRuntime_stub {
        +HAIOSRuntime
    }

    class src_hyperai_protocols_dr_protocol {
        +DRProtocol
        -root_dir
        -_allow_stubs()
    }

    class DRProtocolImpl {
    }

    class DRProtocol_stub {
        +DRProtocol
    }

    hyperai_config ..> src_hyperai_core_haios_runtime : uses
    hyperai_config ..> src_hyperai_protocols_dr_protocol : uses

    src_hyperai_core_haios_runtime ..> HAIOSRuntimeImpl : imports
    src_hyperai_core_haios_runtime ..> HAIOSRuntime_stub : falls_back_to

    src_hyperai_protocols_dr_protocol ..> DRProtocolImpl : imports
    src_hyperai_protocols_dr_protocol ..> DRProtocol_stub : falls_back_to
Loading

File-Level Changes

Change Details Files
Add shared configuration helper for controlling stub usage via environment variable.
  • Create hyperai.config module with an allow_stubs() helper that reads HYPERAI_ALLOW_STUBS.
  • Interpret common truthy strings (1, true, yes, on) as enabling stubs and treat all other or missing values as disabling stubs.
src/hyperai/config.py
Gate fallback to stub implementations in runtime and protocol modules on configuration flag.
  • Import the shared allow_stubs helper in the runtime and protocol modules.
  • In the ImportError/AttributeError handlers, re-raise the exception when stubs are not allowed, otherwise fall back to the existing stub implementations.
src/hyperai/core/haios_runtime.py
src/hyperai/protocols/dr_protocol.py
Add tests to validate configuration-based stub control behavior.
  • Dynamically load the configuration module from the project root in tests to avoid import path issues.
  • Verify allow_stubs() returns True for various truthy environment values and False for falsy, random, or missing values, and restore environment state between tests.
tests/test_config_allow_stubs.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-code-review
Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status:
Raw ImportError raised: The new logic re-raises the original ImportError when stubs are disabled, which may expose
internal module details to end-users depending on how exceptions are surfaced by the
calling layer.

Referred Code
if not _allow_stubs():
    raise

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Refactor project structure to avoid sys.path manipulation

Replace the current runtime sys.path modifications with a standard, installable
Python package structure. This will enable robust, standard imports and improve
overall project maintainability.

Examples:

src/hyperai/core/haios_runtime.py [17-24]
root_dir = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(root_dir))

# Import from root-level implementation
try:
    from haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl

    HAIOSRuntime = HAIOSRuntimeImpl
src/hyperai/protocols/dr_protocol.py [17-24]
root_dir = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(root_dir))

# Import from root-level implementation if exists
try:
    from digital_ai_organism_framework import DRProtocol as DRProtocolImpl

    DRProtocol = DRProtocolImpl

Solution Walkthrough:

Before:

# In src/hyperai/core/haios_runtime.py
import sys
from pathlib import Path

# Manipulate sys.path to import from project root
root_dir = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(root_dir))

# Import from the now-available root-level module
try:
    from haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
    HAIOSRuntime = HAIOSRuntimeImpl
except ImportError:
    # Fallback to stub
    ...

After:

# In src/hyperai/core/haios_runtime.py

# No more sys.path manipulation.
# Project is structured as an installable package.

# Use standard absolute imports
try:
    # Assuming the module is now part of the package structure
    from hyperai.vendor.haios_runtime import HAIOSRuntime as HAIOSRuntimeImpl
    HAIOSRuntime = HAIOSRuntimeImpl
except ImportError:
    # Fallback to stub
    ...
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical architectural flaw (sys.path manipulation) in files modified by the PR, and fixing it would significantly improve the project's robustness and maintainability.

High
General
Improve test isolation using mocks

Refactor tests to use unittest.mock.patch.dict for managing the os.environ,
which improves test isolation and removes the need for setUp/tearDown methods.

tests/test_config_allow_stubs.py [19-45]

+from unittest.mock import patch
+
+
 class TestAllowStubs(unittest.TestCase):
     """Validate HYPERAI_ALLOW_STUBS parsing behavior."""
-
-    def setUp(self):
-        self._original = os.environ.get("HYPERAI_ALLOW_STUBS")
-
-    def tearDown(self):
-        if self._original is None:
-            os.environ.pop("HYPERAI_ALLOW_STUBS", None)
-        else:
-            os.environ["HYPERAI_ALLOW_STUBS"] = self._original
 
     def test_truthy_values(self):
         for value in ("1", "true", "TRUE", " yes ", "On"):
             with self.subTest(value=value):
-                os.environ["HYPERAI_ALLOW_STUBS"] = value
-                self.assertTrue(allow_stubs())
+                with patch.dict(os.environ, {"HYPERAI_ALLOW_STUBS": value}):
+                    self.assertTrue(allow_stubs())
 
     def test_falsy_values(self):
         for value in ("0", "false", "off", "no", "random"):
             with self.subTest(value=value):
-                os.environ["HYPERAI_ALLOW_STUBS"] = value
-                self.assertFalse(allow_stubs())
+                with patch.dict(os.environ, {"HYPERAI_ALLOW_STUBS": value}):
+                    self.assertFalse(allow_stubs())
 
     def test_missing_env_var_defaults_false(self):
-        os.environ.pop("HYPERAI_ALLOW_STUBS", None)
-        self.assertFalse(allow_stubs())
+        with patch.dict(os.environ):
+            os.environ.pop("HYPERAI_ALLOW_STUBS", None)
+            self.assertFalse(allow_stubs())
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly proposes using unittest.mock.patch.dict to improve test isolation and robustness, which is a better practice than manually modifying os.environ via setUp and tearDown.

Low
  • More

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - mình đã tìm thấy 1 vấn đề

Prompt cho AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `tests/test_config_allow_stubs.py:19` </location>
<code_context>
+allow_stubs = config_module.allow_stubs
+
+
+class TestAllowStubs(unittest.TestCase):
+    """Validate HYPERAI_ALLOW_STUBS parsing behavior."""
+
</code_context>

<issue_to_address>
**suggestion (testing):** Hãy cân nhắc bổ sung các bài test bao phủ việc `allow_stubs()` thực sự ảnh hưởng như thế nào tới các import `haios_runtime``dr_protocol`

Các bài test hiện tại chỉ kiểm tra việc parse `allow_stubs()`, chứ chưa kiểm tra tác động của nó lên các import. Vui lòng thêm các bài test end-to-end để xác minh:

- Khi `HYPERAI_ALLOW_STUBS` không được đặt/false, việc import `hyperai.core.haios_runtime` / `hyperai.protocols.dr_protocol` sẽ thất bại nếu thiếu các implementation thật.
- Khi `HYPERAI_ALLOW_STUBS` là true, các import này sẽ thành công và cung cấp các lớp stub.

Bạn có thể dùng `importlib.reload` hoặc chạy dưới dạng subprocess để tránh cache import khi chuyển trạng thái biến môi trường.

Gợi ý triển khai:

```python
import importlib
import importlib.util
import os
import sys
import unittest
from pathlib import Path

```

```python
spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
config_module = importlib.util.module_from_spec(spec)


class TestAllowStubsImports(unittest.TestCase):
    """End-to-end tests for allow_stubs() effect on haios_runtime and dr_protocol imports."""

    MODULES_UNDER_TEST = (
        "hyperai.core.haios_runtime",
        "hyperai.protocols.dr_protocol",
    )

    def _set_env_allow_stubs(self, value: str | None) -> None:
        """Set or clear HYPERAI_ALLOW_STUBS, restoring it after the test."""
        prev = os.environ.get("HYPERAI_ALLOW_STUBS")
        if value is None:
            os.environ.pop("HYPERAI_ALLOW_STUBS", None)
        else:
            os.environ["HYPERAI_ALLOW_STUBS"] = value

        def restore() -> None:
            if prev is None:
                os.environ.pop("HYPERAI_ALLOW_STUBS", None)
            else:
                os.environ["HYPERAI_ALLOW_STUBS"] = prev

        self.addCleanup(restore)

    def _clear_import_caches(self) -> None:
        """Ensure subsequent imports reflect the current env var value."""
        importlib.invalidate_caches()
        for module_name in self.MODULES_UNDER_TEST:
            sys.modules.pop(module_name, None)

    def test_imports_fail_without_allow_stubs(self) -> None:
        """Without HYPERAI_ALLOW_STUBS, importing stub-only modules should fail."""
        self._set_env_allow_stubs(None)
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                with self.assertRaises(ImportError):
                    importlib.import_module(module_name)

    def test_imports_succeed_with_allow_stubs(self) -> None:
        """With HYPERAI_ALLOW_STUBS enabled, stub modules should import successfully."""
        self._set_env_allow_stubs("1")
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                module = importlib.import_module(module_name)
                # Basic sanity check that the module loaded and exposes some attributes.
                # More specific assertions about stub classes can be added as needed.
                self.assertIsNotNone(module)
                self.assertTrue(
                    bool(
                        {
                            name
                            for name in dir(module)
                            if not name.startswith("_")
                        }
                    ),
                    f"{module_name} should expose at least one public attribute when stubs are enabled",
                )

```

1. Nếu các module stub của bạn cung cấp những class quen thuộc (ví dụ `HaiOSRuntimeStub`, `DeepResearchProtocolStub`, hoặc tương tự), hãy tăng độ chặt chẽ của các assert trong `test_imports_succeed_with_allow_stubs` bằng cách kiểm tra rõ ràng các thuộc tính đó thay vì check chung chung "có public attribute nào đó".
2. Nếu trong file này đã có các bài test khác cũng thao tác với `HYPERAI_ALLOW_STUBS` hoặc import `hyperai.core.haios_runtime` / `hyperai.protocols.dr_protocol`, hãy đảm bảo chúng cũng sử dụng các helper `_set_env_allow_stubs` / `_clear_import_caches` hoặc tránh can thiệp lẫn nhau với các bài test mới này.
3. Nếu implementation của bạn dùng tên biến môi trường khác hoặc có thêm flag để điều khiển hành vi stub, hãy điều chỉnh `MODULES_UNDER_TEST` và logic `_set_env_allow_stubs` cho phù hợp.
</issue_to_address>

Sourcery miễn phí cho các dự án mã nguồn mở - nếu bạn thấy hữu ích, hãy cân nhắc chia sẻ ✨
Giúp mình hữu ích hơn nhé! Hãy bấm 👍 hoặc 👎 trên từng comment và mình sẽ dùng phản hồi đó để cải thiện các review sau.
Original comment in English

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `tests/test_config_allow_stubs.py:19` </location>
<code_context>
+allow_stubs = config_module.allow_stubs
+
+
+class TestAllowStubs(unittest.TestCase):
+    """Validate HYPERAI_ALLOW_STUBS parsing behavior."""
+
</code_context>

<issue_to_address>
**suggestion (testing):** Consider adding tests that cover how `allow_stubs()` actually affects `haios_runtime` and `dr_protocol` imports

Current tests only cover parsing of `allow_stubs()`, not its effect on imports. Please add end-to-end tests that verify:

- With `HYPERAI_ALLOW_STUBS` unset/false, importing `hyperai.core.haios_runtime` / `hyperai.protocols.dr_protocol` fails if real implementations are missing.
- With `HYPERAI_ALLOW_STUBS` true, the same imports succeed and expose the stub classes.

You can use `importlib.reload` or subprocesses to avoid import caching when toggling the env var.

Suggested implementation:

```python
import importlib
import importlib.util
import os
import sys
import unittest
from pathlib import Path

```

```python
spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
config_module = importlib.util.module_from_spec(spec)


class TestAllowStubsImports(unittest.TestCase):
    """End-to-end tests for allow_stubs() effect on haios_runtime and dr_protocol imports."""

    MODULES_UNDER_TEST = (
        "hyperai.core.haios_runtime",
        "hyperai.protocols.dr_protocol",
    )

    def _set_env_allow_stubs(self, value: str | None) -> None:
        """Set or clear HYPERAI_ALLOW_STUBS, restoring it after the test."""
        prev = os.environ.get("HYPERAI_ALLOW_STUBS")
        if value is None:
            os.environ.pop("HYPERAI_ALLOW_STUBS", None)
        else:
            os.environ["HYPERAI_ALLOW_STUBS"] = value

        def restore() -> None:
            if prev is None:
                os.environ.pop("HYPERAI_ALLOW_STUBS", None)
            else:
                os.environ["HYPERAI_ALLOW_STUBS"] = prev

        self.addCleanup(restore)

    def _clear_import_caches(self) -> None:
        """Ensure subsequent imports reflect the current env var value."""
        importlib.invalidate_caches()
        for module_name in self.MODULES_UNDER_TEST:
            sys.modules.pop(module_name, None)

    def test_imports_fail_without_allow_stubs(self) -> None:
        """Without HYPERAI_ALLOW_STUBS, importing stub-only modules should fail."""
        self._set_env_allow_stubs(None)
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                with self.assertRaises(ImportError):
                    importlib.import_module(module_name)

    def test_imports_succeed_with_allow_stubs(self) -> None:
        """With HYPERAI_ALLOW_STUBS enabled, stub modules should import successfully."""
        self._set_env_allow_stubs("1")
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                module = importlib.import_module(module_name)
                # Basic sanity check that the module loaded and exposes some attributes.
                # More specific assertions about stub classes can be added as needed.
                self.assertIsNotNone(module)
                self.assertTrue(
                    bool(
                        {
                            name
                            for name in dir(module)
                            if not name.startswith("_")
                        }
                    ),
                    f"{module_name} should expose at least one public attribute when stubs are enabled",
                )

```

1. If your stub modules expose well-known classes (e.g. `HaiOSRuntimeStub`, `DeepResearchProtocolStub`, or similar), strengthen the assertions in `test_imports_succeed_with_allow_stubs` to explicitly check for those attributes instead of the generic "has some public attribute" check.
2. If there are existing tests in this file that also manipulate `HYPERAI_ALLOW_STUBS` or import `hyperai.core.haios_runtime` / `hyperai.protocols.dr_protocol`, ensure they either use the `_set_env_allow_stubs` / `_clear_import_caches` helpers or otherwise avoid interference with these new tests.
3. If your implementation uses a different environment variable name or additional flags to control stub behavior, adjust the `MODULES_UNDER_TEST` and `_set_env_allow_stubs` logic accordingly.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

allow_stubs = config_module.allow_stubs


class TestAllowStubs(unittest.TestCase):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (testing): Hãy cân nhắc bổ sung các bài test bao phủ việc allow_stubs() thực sự ảnh hưởng như thế nào tới các import haios_runtimedr_protocol

Các bài test hiện tại chỉ kiểm tra việc parse allow_stubs(), chứ chưa kiểm tra tác động của nó lên các import. Vui lòng thêm các bài test end-to-end để xác minh:

  • Khi HYPERAI_ALLOW_STUBS không được đặt/false, việc import hyperai.core.haios_runtime / hyperai.protocols.dr_protocol sẽ thất bại nếu thiếu các implementation thật.
  • Khi HYPERAI_ALLOW_STUBS là true, các import này sẽ thành công và cung cấp các lớp stub.

Bạn có thể dùng importlib.reload hoặc chạy dưới dạng subprocess để tránh cache import khi chuyển trạng thái biến môi trường.

Gợi ý triển khai:

import importlib
import importlib.util
import os
import sys
import unittest
from pathlib import Path
spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
config_module = importlib.util.module_from_spec(spec)


class TestAllowStubsImports(unittest.TestCase):
    """End-to-end tests for allow_stubs() effect on haios_runtime and dr_protocol imports."""

    MODULES_UNDER_TEST = (
        "hyperai.core.haios_runtime",
        "hyperai.protocols.dr_protocol",
    )

    def _set_env_allow_stubs(self, value: str | None) -> None:
        """Set or clear HYPERAI_ALLOW_STUBS, restoring it after the test."""
        prev = os.environ.get("HYPERAI_ALLOW_STUBS")
        if value is None:
            os.environ.pop("HYPERAI_ALLOW_STUBS", None)
        else:
            os.environ["HYPERAI_ALLOW_STUBS"] = value

        def restore() -> None:
            if prev is None:
                os.environ.pop("HYPERAI_ALLOW_STUBS", None)
            else:
                os.environ["HYPERAI_ALLOW_STUBS"] = prev

        self.addCleanup(restore)

    def _clear_import_caches(self) -> None:
        """Ensure subsequent imports reflect the current env var value."""
        importlib.invalidate_caches()
        for module_name in self.MODULES_UNDER_TEST:
            sys.modules.pop(module_name, None)

    def test_imports_fail_without_allow_stubs(self) -> None:
        """Without HYPERAI_ALLOW_STUBS, importing stub-only modules should fail."""
        self._set_env_allow_stubs(None)
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                with self.assertRaises(ImportError):
                    importlib.import_module(module_name)

    def test_imports_succeed_with_allow_stubs(self) -> None:
        """With HYPERAI_ALLOW_STUBS enabled, stub modules should import successfully."""
        self._set_env_allow_stubs("1")
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                module = importlib.import_module(module_name)
                # Basic sanity check that the module loaded and exposes some attributes.
                # More specific assertions about stub classes can be added as needed.
                self.assertIsNotNone(module)
                self.assertTrue(
                    bool(
                        {
                            name
                            for name in dir(module)
                            if not name.startswith("_")
                        }
                    ),
                    f"{module_name} should expose at least one public attribute when stubs are enabled",
                )
  1. Nếu các module stub của bạn cung cấp những class quen thuộc (ví dụ HaiOSRuntimeStub, DeepResearchProtocolStub, hoặc tương tự), hãy tăng độ chặt chẽ của các assert trong test_imports_succeed_with_allow_stubs bằng cách kiểm tra rõ ràng các thuộc tính đó thay vì check chung chung "có public attribute nào đó".
  2. Nếu trong file này đã có các bài test khác cũng thao tác với HYPERAI_ALLOW_STUBS hoặc import hyperai.core.haios_runtime / hyperai.protocols.dr_protocol, hãy đảm bảo chúng cũng sử dụng các helper _set_env_allow_stubs / _clear_import_caches hoặc tránh can thiệp lẫn nhau với các bài test mới này.
  3. Nếu implementation của bạn dùng tên biến môi trường khác hoặc có thêm flag để điều khiển hành vi stub, hãy điều chỉnh MODULES_UNDER_TEST và logic _set_env_allow_stubs cho phù hợp.
Original comment in English

suggestion (testing): Consider adding tests that cover how allow_stubs() actually affects haios_runtime and dr_protocol imports

Current tests only cover parsing of allow_stubs(), not its effect on imports. Please add end-to-end tests that verify:

  • With HYPERAI_ALLOW_STUBS unset/false, importing hyperai.core.haios_runtime / hyperai.protocols.dr_protocol fails if real implementations are missing.
  • With HYPERAI_ALLOW_STUBS true, the same imports succeed and expose the stub classes.

You can use importlib.reload or subprocesses to avoid import caching when toggling the env var.

Suggested implementation:

import importlib
import importlib.util
import os
import sys
import unittest
from pathlib import Path
spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
config_module = importlib.util.module_from_spec(spec)


class TestAllowStubsImports(unittest.TestCase):
    """End-to-end tests for allow_stubs() effect on haios_runtime and dr_protocol imports."""

    MODULES_UNDER_TEST = (
        "hyperai.core.haios_runtime",
        "hyperai.protocols.dr_protocol",
    )

    def _set_env_allow_stubs(self, value: str | None) -> None:
        """Set or clear HYPERAI_ALLOW_STUBS, restoring it after the test."""
        prev = os.environ.get("HYPERAI_ALLOW_STUBS")
        if value is None:
            os.environ.pop("HYPERAI_ALLOW_STUBS", None)
        else:
            os.environ["HYPERAI_ALLOW_STUBS"] = value

        def restore() -> None:
            if prev is None:
                os.environ.pop("HYPERAI_ALLOW_STUBS", None)
            else:
                os.environ["HYPERAI_ALLOW_STUBS"] = prev

        self.addCleanup(restore)

    def _clear_import_caches(self) -> None:
        """Ensure subsequent imports reflect the current env var value."""
        importlib.invalidate_caches()
        for module_name in self.MODULES_UNDER_TEST:
            sys.modules.pop(module_name, None)

    def test_imports_fail_without_allow_stubs(self) -> None:
        """Without HYPERAI_ALLOW_STUBS, importing stub-only modules should fail."""
        self._set_env_allow_stubs(None)
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                with self.assertRaises(ImportError):
                    importlib.import_module(module_name)

    def test_imports_succeed_with_allow_stubs(self) -> None:
        """With HYPERAI_ALLOW_STUBS enabled, stub modules should import successfully."""
        self._set_env_allow_stubs("1")
        self._clear_import_caches()

        for module_name in self.MODULES_UNDER_TEST:
            with self.subTest(module=module_name):
                module = importlib.import_module(module_name)
                # Basic sanity check that the module loaded and exposes some attributes.
                # More specific assertions about stub classes can be added as needed.
                self.assertIsNotNone(module)
                self.assertTrue(
                    bool(
                        {
                            name
                            for name in dir(module)
                            if not name.startswith("_")
                        }
                    ),
                    f"{module_name} should expose at least one public attribute when stubs are enabled",
                )
  1. If your stub modules expose well-known classes (e.g. HaiOSRuntimeStub, DeepResearchProtocolStub, or similar), strengthen the assertions in test_imports_succeed_with_allow_stubs to explicitly check for those attributes instead of the generic "has some public attribute" check.
  2. If there are existing tests in this file that also manipulate HYPERAI_ALLOW_STUBS or import hyperai.core.haios_runtime / hyperai.protocols.dr_protocol, ensure they either use the _set_env_allow_stubs / _clear_import_caches helpers or otherwise avoid interference with these new tests.
  3. If your implementation uses a different environment variable name or additional flags to control stub behavior, adjust the MODULES_UNDER_TEST and _set_env_allow_stubs logic accordingly.

@NguyenCuong1989 NguyenCuong1989 self-assigned this Feb 18, 2026
@NguyenCuong1989
Copy link
Copy Markdown
Collaborator Author

Ok merge now

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Update README Quick Start to document two local run modes and correct import examples [QUESTION] [DOCS]

1 participant