Skip to content

Codex-generated pull request#15

Open
NguyenCuong1989 wants to merge 2 commits into
mainfrom
codex/create-shared-config-helper-for-allow_stubs-ufl8br
Open

Codex-generated pull request#15
NguyenCuong1989 wants to merge 2 commits into
mainfrom
codex/create-shared-config-helper-for-allow_stubs-ufl8br

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

Summary by Sourcery

Bảo vệ việc sử dụng các bản triển khai stub cho runtime lõi và các thành phần giao thức bằng một cờ cấu hình dùng chung.

Tính năng mới:

  • Giới thiệu một helper cấu hình dùng chung để kiểm soát việc cho phép sử dụng các bản triển khai stub thông qua biến môi trường HYPERAI_ALLOW_STUBS.

Sửa lỗi:

  • Ngăn chặn việc fallback ngoài ý muốn sang các bản triển khai stub HAIOSRuntimeDRProtocol khi bản triển khai thật không khả dụng và stub không được cho phép một cách tường minh.

Kiểm thử:

  • Thêm các unit test để kiểm tra việc parse HYPERAI_ALLOW_STUBS và hành vi mặc định khi biến này không được thiết lập.
Original summary in English

Summary by Sourcery

Guard use of stub implementations for core runtime and protocol components behind a shared configuration flag.

New Features:

  • Introduce a shared configuration helper to control whether stub implementations are allowed via the HYPERAI_ALLOW_STUBS environment variable.

Bug Fixes:

  • Prevent unintended fallback to HAIOSRuntime and DRProtocol stub implementations when their real implementations are unavailable and stubs are not explicitly allowed.

Tests:

  • Add unit tests to validate HYPERAI_ALLOW_STUBS parsing and the default behavior when the variable is absent.

Sửa lỗi:

  • Ngăn việc sử dụng ngoài ý muốn các bản triển khai stub HAIOSRuntimeDRProtocol khi stub không được cho phép một cách rõ ràng.

Cải tiến:

  • Thêm một helper cấu hình dùng chung để kiểm soát việc các bản triển khai stub có được cho phép hay không thông qua biến môi trường.

Kiểm thử:

  • Thêm các unit test để kiểm tra việc parse HYPERAI_ALLOW_STUBS và hành vi mặc định.
Original summary in English

Summary by Sourcery

Bảo vệ việc sử dụng các bản triển khai stub cho runtime lõi và các thành phần giao thức bằng một cờ cấu hình dùng chung.

Tính năng mới:

  • Giới thiệu một helper cấu hình dùng chung để kiểm soát việc cho phép sử dụng các bản triển khai stub thông qua biến môi trường HYPERAI_ALLOW_STUBS.

Sửa lỗi:

  • Ngăn chặn việc fallback ngoài ý muốn sang các bản triển khai stub HAIOSRuntimeDRProtocol khi bản triển khai thật không khả dụng và stub không được cho phép một cách tường minh.

Kiểm thử:

  • Thêm các unit test để kiểm tra việc parse HYPERAI_ALLOW_STUBS và hành vi mặc định khi biến này không được thiết lập.
Original summary in English

Summary by Sourcery

Guard use of stub implementations for core runtime and protocol components behind a shared configuration flag.

New Features:

  • Introduce a shared configuration helper to control whether stub implementations are allowed via the HYPERAI_ALLOW_STUBS environment variable.

Bug Fixes:

  • Prevent unintended fallback to HAIOSRuntime and DRProtocol stub implementations when their real implementations are unavailable and stubs are not explicitly allowed.

Tests:

  • Add unit tests to validate HYPERAI_ALLOW_STUBS parsing and the default behavior when the variable is absent.

PR Type

Bug fix, Enhancement, Tests


Description

  • Add shared configuration helper to control stub implementation usage via environment variable

  • Prevent unintended use of stub HAIOSRuntime and DRProtocol when stubs not explicitly allowed

  • Add comprehensive unit tests for HYPERAI_ALLOW_STUBS parsing and default behavior


File Walkthrough

Relevant files
Enhancement
config.py
New shared config helper for stub control                               

src/hyperai/config.py

  • Create new shared configuration module with allow_stubs() function
  • Parse HYPERAI_ALLOW_STUBS environment variable supporting "1", "true",
    "yes", "on" values
  • Default to False when environment variable is missing or unset
+11/-0   
Bug fix
haios_runtime.py
Add stub allowance guard to HAIOSRuntime                                 

src/hyperai/core/haios_runtime.py

  • Import allow_stubs configuration helper from hyperai.config
  • Add guard to raise ImportError when stub is not allowed and real
    implementation missing
  • Preserve existing stub implementation when stubs are explicitly
    enabled
+5/-0     
dr_protocol.py
Add stub allowance guard to DRProtocol                                     

src/hyperai/protocols/dr_protocol.py

  • Import allow_stubs configuration helper from hyperai.config
  • Add guard to raise ImportError when stub is not allowed and real
    implementation missing
  • Preserve existing stub implementation when stubs are explicitly
    enabled
+5/-0     
Tests
test_config_allow_stubs.py
Unit tests for allow_stubs configuration parsing                 

tests/test_config_allow_stubs.py

  • Add comprehensive unit tests for allow_stubs() function behavior
  • Test truthy values ("1", "true", "yes", "on") with case variations and
    whitespace
  • Test falsy values and missing environment variable defaulting to False
  • Use setUp/tearDown to preserve and restore original environment state
+49/-0   

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Feb 18, 2026

Hướng dẫn cho người review

Thêm một helper cấu hình dùng chung để kiểm soát việc cho phép sử dụng các stub cho runtime/protocol thông qua biến môi trường HYPERAI_ALLOW_STUBS, dùng nó để kiểm soát các stub fallback của HAIOSRuntimeDRProtocol, và bổ sung các unit test cho hành vi cấu hình mới này.

Sơ đồ trình tự khi import HAIOSRuntime với stub fallback có thể cấu hình

sequenceDiagram
    actor PythonImporter
    participant haios_runtime as haios_runtime_module
    participant hyperai_config as hyperai_config_module
    participant HAIOSRuntimeImpl as HAIOSRuntimeImpl_module
    participant StubHAIOSRuntime as HAIOSRuntime_stub

    PythonImporter->>haios_runtime: import haios_runtime
    activate haios_runtime
    haios_runtime->>HAIOSRuntimeImpl: import HAIOSRuntimeImpl
    alt HAIOSRuntimeImpl import succeeds
        HAIOSRuntimeImpl-->>haios_runtime: HAIOSRuntimeImpl
        haios_runtime-->>PythonImporter: bind HAIOSRuntime = HAIOSRuntimeImpl
    else HAIOSRuntimeImpl raises ImportError
        HAIOSRuntimeImpl-->>haios_runtime: ImportError
        haios_runtime->>hyperai_config: allow_stubs()
        activate hyperai_config
        hyperai_config-->>haios_runtime: bool allow
        deactivate hyperai_config
        alt allow is false
            haios_runtime-->>PythonImporter: re_raise ImportError
        else allow is true
            haios_runtime-->>PythonImporter: define HAIOSRuntime_stub as HAIOSRuntime
        end
    end
    deactivate haios_runtime
Loading

Sơ đồ lớp cho cấu hình stub dùng chung và các module runtime/protocol

classDiagram
class hyperai_config {
  +bool allow_stubs()
}

class haios_runtime {
  +HAIOSRuntime
}

class dr_protocol {
  +DRProtocol
}

haios_runtime ..> hyperai_config : uses_allow_stubs
dr_protocol ..> hyperai_config : uses_allow_stubs
Loading

Sơ đồ luồng cho việc parse biến môi trường allow_stubs

flowchart TD
    A[Read HYPERAI_ALLOW_STUBS from environment
    default empty string] --> B[Strip whitespace
    and lower case value]
    B --> C{Value in
    1, true, yes, on?}
    C -- Yes --> D[Return True]
    C -- No --> E[Return False]
Loading

Thay đổi theo từng tệp

Thay đổi Chi tiết Tệp
Giới thiệu helper cấu hình dùng chung để kiểm soát việc cho phép sử dụng các stub implementation.
  • Tạo module hyperai.config với helper allow_stubs() đọc biến môi trường HYPERAI_ALLOW_STUBS.
  • Chỉ coi một số giá trị đã được chuẩn hóa cụ thể (1, true, yes, on) là tương đương True và mặc định là False khi biến không được đặt hoặc có bất kỳ giá trị nào khác.
  • Ghi rõ allow_stubs() là công tắc trung tâm để bật các stub implementation.
src/hyperai/config.py
Ràng buộc stub fallback của HAIOSRuntime theo cấu hình allow_stubs.
  • Import helper allow_stubs() vào module haios_runtime với một alias private.
  • Khi gặp ImportError trong lúc import HAIOSRuntimeImpl, re-raise lỗi nếu allow_stubs() trả về False, tránh việc sử dụng stub một cách im lặng.
  • Chỉ định nghĩa và sử dụng stub implementation cho HAIOSRuntime khi stub được cho phép một cách tường minh.
src/hyperai/core/haios_runtime.py
Ràng buộc stub fallback của DRProtocol theo cấu hình allow_stubs.
  • Import helper allow_stubs() vào module dr_protocol với một alias private.
  • Khi gặp ImportError hoặc AttributeError trong lúc import DRProtocolImpl, re-raise lỗi nếu allow_stubs() trả về False, ngăn việc sử dụng stub ngoài ý muốn.
  • Chỉ định nghĩa và sử dụng stub implementation cho DRProtocol khi stub được cho phép một cách tường minh.
src/hyperai/protocols/dr_protocol.py
Thêm test để kiểm tra hành vi cấu hình allow_stubs và việc parse biến môi trường.
  • Dynamic load module hyperai.config từ cây mã nguồn của project trong test để truy cập allow_stubs().
  • Xác minh rằng nhiều giá trị chuỗi được coi là truthy cho HYPERAI_ALLOW_STUBS khiến allow_stubs() trả về True.
  • Xác minh rằng các giá trị falsy hoặc không được nhận diện khiến allow_stubs() trả về False, bao gồm cả khi biến môi trường không tồn tại.
  • Đảm bảo trạng thái biến môi trường được lưu và khôi phục xung quanh mỗi test case.
tests/test_config_allow_stubs.py

Mẹo và các lệnh

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 reply vào comment đó. Bạn cũng có thể reply vào comment review 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 cứ 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 cứ lúc nào.
  • Tạo tóm tắt pull request: Viết @sourcery-ai summary ở bất kỳ đâu trong 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 cứ 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 cứ 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 của Sourcery. Hữu ích nếu bạn đã xử lý hết các 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ủa Sourcery. Đặ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 biến.
  • Đ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

Adds a shared configuration helper to control whether stub runtime/protocol implementations are allowed via the HYPERAI_ALLOW_STUBS environment variable, uses it to gate the HAIOSRuntime and DRProtocol stub fallbacks, and introduces unit tests for the new configuration behavior.

Sequence diagram for importing HAIOSRuntime with configurable stub fallback

sequenceDiagram
    actor PythonImporter
    participant haios_runtime as haios_runtime_module
    participant hyperai_config as hyperai_config_module
    participant HAIOSRuntimeImpl as HAIOSRuntimeImpl_module
    participant StubHAIOSRuntime as HAIOSRuntime_stub

    PythonImporter->>haios_runtime: import haios_runtime
    activate haios_runtime
    haios_runtime->>HAIOSRuntimeImpl: import HAIOSRuntimeImpl
    alt HAIOSRuntimeImpl import succeeds
        HAIOSRuntimeImpl-->>haios_runtime: HAIOSRuntimeImpl
        haios_runtime-->>PythonImporter: bind HAIOSRuntime = HAIOSRuntimeImpl
    else HAIOSRuntimeImpl raises ImportError
        HAIOSRuntimeImpl-->>haios_runtime: ImportError
        haios_runtime->>hyperai_config: allow_stubs()
        activate hyperai_config
        hyperai_config-->>haios_runtime: bool allow
        deactivate hyperai_config
        alt allow is false
            haios_runtime-->>PythonImporter: re_raise ImportError
        else allow is true
            haios_runtime-->>PythonImporter: define HAIOSRuntime_stub as HAIOSRuntime
        end
    end
    deactivate haios_runtime
Loading

Class diagram for shared stub configuration and runtime/protocol modules

classDiagram
class hyperai_config {
  +bool allow_stubs()
}

class haios_runtime {
  +HAIOSRuntime
}

class dr_protocol {
  +DRProtocol
}

haios_runtime ..> hyperai_config : uses_allow_stubs
dr_protocol ..> hyperai_config : uses_allow_stubs
Loading

Flow diagram for allow_stubs environment variable parsing

flowchart TD
    A[Read HYPERAI_ALLOW_STUBS from environment
    default empty string] --> B[Strip whitespace
    and lower case value]
    B --> C{Value in
    1, true, yes, on?}
    C -- Yes --> D[Return True]
    C -- No --> E[Return False]
Loading

File-Level Changes

Change Details Files
Introduce shared configuration helper to control whether stub implementations are allowed.
  • Create hyperai.config module with allow_stubs() helper that reads the HYPERAI_ALLOW_STUBS environment variable.
  • Treat only specific normalized values (1, true, yes, on) as truthy and default to False when the variable is unset or any other value.
  • Document allow_stubs() as the central toggle for enabling stub implementations.
src/hyperai/config.py
Gate HAIOSRuntime stub fallback on allow_stubs configuration.
  • Import allow_stubs() helper into haios_runtime module under a private alias.
  • On ImportError when importing HAIOSRuntimeImpl, re-raise the error if allow_stubs() returns False, preventing silent stub usage.
  • Only define and use the HAIOSRuntime stub implementation when stubs are explicitly allowed.
src/hyperai/core/haios_runtime.py
Gate DRProtocol stub fallback on allow_stubs configuration.
  • Import allow_stubs() helper into dr_protocol module under a private alias.
  • On ImportError or AttributeError when importing DRProtocolImpl, re-raise the error if allow_stubs() returns False, preventing unintended stub usage.
  • Only define and use the DRProtocol stub implementation when stubs are explicitly allowed.
src/hyperai/protocols/dr_protocol.py
Add tests to validate allow_stubs configuration behavior and environment parsing.
  • Dynamically load the hyperai.config module from the project source tree in tests to access allow_stubs().
  • Verify that a range of truthy string values for HYPERAI_ALLOW_STUBS cause allow_stubs() to return True.
  • Verify that falsy or unrecognized values result in allow_stubs() returning False, including when the environment variable is missing.
  • Ensure environment variable state is saved and restored around each test case.
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

@NguyenCuong1989 NguyenCuong1989 marked this pull request as ready for review February 19, 2026 09:45
@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.

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review Bot commented Feb 19, 2026

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
No custom compliance provided

Follow the guide to enable custom compliance check.

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

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review Bot commented Feb 19, 2026

PR Code Suggestions ✨

Latest suggestions up to d0bf5c7

CategorySuggestion                                                                                                                                    Impact
General
Warn when stub is used

Add a warnings.warn() call within the except ImportError block to notify
developers when the fallback stub implementation of HAIOSRuntime is being used.

src/hyperai/core/haios_runtime.py [25-35]

 except ImportError:
     if not _allow_stubs():
         raise
+
+    import warnings
+
+    warnings.warn(
+        "Falling back to stub HAIOSRuntime implementation because the real module could not be imported.",
+        RuntimeWarning,
+        stacklevel=2,
+    )
 
     # If haios_runtime doesn't exist, provide a stub
     class HAIOSRuntime:
         """Stub implementation of HAIOSRuntime"""
 
         def __init__(self):
             self.version = "1.0.0"
             self.creator = "alpha_prime_omega"
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion improves debuggability by adding a warning when a stub implementation is used, which makes it explicit that a fallback occurred, without being a critical error.

Medium
Possible issue
Replace assert with explicit checks

Replace the assert statement with an if condition that raises a RuntimeError to
ensure the test setup is robust, even when Python's optimization flag (-O) is
used.

tests/test_config_allow_stubs.py [12-16]

 spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
+if spec is None or spec.loader is None:
+    raise RuntimeError(f"Unable to load module spec from {CONFIG_MODULE_PATH}")
 config_module = importlib.util.module_from_spec(spec)
-assert spec is not None and spec.loader is not None
 spec.loader.exec_module(config_module)
 allow_stubs = config_module.allow_stubs
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that using assert for test setup logic is fragile, as it can be disabled, and proposes a more robust explicit check which improves test reliability.

Low
Incremental [*]
Cover empty and blank values

Add test cases for empty and whitespace-only strings to the test_falsy_values
test to ensure they are correctly handled as falsy.

tests/test_config_allow_stubs.py [38]

-for value in ("0", "false", "off", "no", "random", " false ", " NO ", " Off "):
+for value in ("", "   ", "0", "false", "off", "no", "random", " false ", " NO ", " Off "):
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies missing test coverage for empty and whitespace-only strings, which are common edge cases for environment variables and are handled by .strip().

Low
  • More

Previous suggestions

Suggestions up to commit d0ad92c
CategorySuggestion                                                                                                                                    Impact
General
Isolate test module loading logic

Move the dynamic module loading logic from the module level into the setUpClass
method to improve test isolation.

tests/test_config_allow_stubs.py [12-16]

-spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
-config_module = importlib.util.module_from_spec(spec)
-assert spec is not None and spec.loader is not None
-spec.loader.exec_module(config_module)
-allow_stubs = config_module.allow_stubs
+allow_stubs = None
 
+
+class TestAllowStubs(unittest.TestCase):
+    """Validate HYPERAI_ALLOW_STUBS parsing behavior."""
+
+    @classmethod
+    def setUpClass(cls):
+        """Load the module under test dynamically."""
+        spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
+        config_module = importlib.util.module_from_spec(spec)
+        assert spec is not None and spec.loader is not None
+        spec.loader.exec_module(config_module)
+        global allow_stubs
+        allow_stubs = config_module.allow_stubs
+
Suggestion importance[1-10]: 6

__

Why: This is a good practice suggestion that improves test robustness by moving module-level logic with side effects into setUpClass, ensuring better test isolation, especially for parallel test runners.

Low

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 đề và để lại một số phản hồi tổng quan:

  • Helper allow_stubs mới đọc biến môi trường ở mỗi lần gọi; nếu hàm này được dùng trên các đường chạy nóng (hot path) thì bạn có thể muốn cache giá trị đã được parse ngay khi import module (kèm theo một cách rõ ràng để ghi đè trong test) để tránh phải parse lặp lại.
  • Trong các bài test, thay vì tự tải config.py bằng importlib.util.spec_from_file_location, hãy cân nhắc import trực tiếp hyperai.config để các bài test sử dụng cùng đường import và hành vi đóng gói như code chạy trong môi trường production.
Prompt cho AI Agents
Please address the comments from this code review:

## Overall Comments
- Helper `allow_stubs` mới đọc biến môi trường ở mỗi lần gọi; nếu hàm này được dùng trên các đường chạy nóng (hot path) thì bạn có thể muốn cache giá trị đã được parse ngay khi import module (kèm theo một cách rõ ràng để ghi đè trong test) để tránh phải parse lặp lại.
- Trong các bài test, thay vì tự tải `config.py` bằng `importlib.util.spec_from_file_location`, hãy cân nhắc import trực tiếp `hyperai.config` để các bài test sử dụng cùng đường import và hành vi đóng gói như code chạy trong môi trường production.

## Individual Comments

### Comment 1
<location> `tests/test_config_allow_stubs.py:37-41` </location>
<code_context>
+                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())
+
+    def test_missing_env_var_defaults_false(self):
</code_context>

<issue_to_address>
**suggestion (testing):** Thêm các giá trị falsy với khoảng trắng và kiểu chữ khác nhau để phản chiếu các test truthy

Các test truthy hiện đã bao phủ trường hợp thay đổi khoảng trắng và kiểu chữ (ví dụ: `" yes "`, `"On"`), nhưng các test falsy chỉ dùng các giá trị chữ thường đơn giản. Để phản chiếu hành vi và kiểm thử đầy đủ logic `.strip().lower()`, hãy thêm các case falsy tương tự như `" false "`, `" NO "`, và `" Off "` vào `test_falsy_values`.

```suggestion
    def test_falsy_values(self):
        for value in ("0", "false", "off", "no", "random", " false ", " NO ", " Off "):
            with self.subTest(value=value):
                os.environ["HYPERAI_ALLOW_STUBS"] = value
                self.assertFalse(allow_stubs())
```
</issue_to_address>

Sourcery miễn phí cho mã nguồn mở - nếu bạn thấy review này hữu ích, hãy cân nhắc chia sẻ ✨
Hãy giúp mình hữu ích hơn! Vui lòng 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, and left some high level feedback:

  • The new allow_stubs helper reads the environment on every call; if this is used on hot paths you may want to cache the parsed value at module import time (with an explicit way to override in tests) to avoid repeated parsing.
  • In the tests, instead of manually loading config.py via importlib.util.spec_from_file_location, consider importing hyperai.config directly so the tests exercise the same import path and packaging behavior as production code.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `allow_stubs` helper reads the environment on every call; if this is used on hot paths you may want to cache the parsed value at module import time (with an explicit way to override in tests) to avoid repeated parsing.
- In the tests, instead of manually loading `config.py` via `importlib.util.spec_from_file_location`, consider importing `hyperai.config` directly so the tests exercise the same import path and packaging behavior as production code.

## Individual Comments

### Comment 1
<location> `tests/test_config_allow_stubs.py:37-41` </location>
<code_context>
+                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())
+
+    def test_missing_env_var_defaults_false(self):
</code_context>

<issue_to_address>
**suggestion (testing):** Add falsy value cases with varying whitespace and casing to mirror the truthy tests

The truthy tests already cover whitespace and case variations (e.g., `" yes "`, `"On"`), but the falsy tests only use plain lowercase values. To mirror the behavior and fully exercise the `.strip().lower()` logic, please add analogous falsy cases such as `" false "`, `" NO "`, and `" Off "` to `test_falsy_values`.

```suggestion
    def test_falsy_values(self):
        for value in ("0", "false", "off", "no", "random", " false ", " NO ", " Off "):
            with self.subTest(value=value):
                os.environ["HYPERAI_ALLOW_STUBS"] = value
                self.assertFalse(allow_stubs())
```
</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.

Comment thread tests/test_config_allow_stubs.py
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@NguyenCuong1989
Copy link
Copy Markdown
Collaborator Author

ok

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 7, 2026

👋 This pull request has been automatically marked as stale because it has not had recent activity.

What happens next:

  • This PR will be closed in 14 days if no further activity occurs
  • Push new commits or comment to remove the stale label
  • Request a review to keep it active

Tips to get your PR merged:

  • Ensure all CI checks pass ✅
  • Respond to review comments
  • Rebase on latest main if needed
  • Update documentation if applicable

Thank you for your contribution! 🙏

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR introduces a shared configuration flag to explicitly control whether stub implementations may be used when “real” runtime/protocol implementations are unavailable.

Changes:

  • Added allow_stubs() helper in src/hyperai/config.py to parse HYPERAI_ALLOW_STUBS.
  • Guarded stub fallbacks in HAIOSRuntime and DRProtocol behind the shared flag.
  • Added unit tests for HYPERAI_ALLOW_STUBS parsing/default behavior.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
src/hyperai/config.py Adds allow_stubs() env-var parsing helper.
src/hyperai/core/haios_runtime.py Blocks stub runtime fallback unless explicitly allowed.
src/hyperai/protocols/dr_protocol.py Blocks stub protocol fallback unless explicitly allowed.
tests/test_config_allow_stubs.py Adds tests for allow_stubs() parsing and defaults.

Comment on lines +14 to 18
from hyperai.config import allow_stubs as _allow_stubs

# Add root directory to path to import from root-level modules
root_dir = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(root_dir))
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

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

from hyperai.config ... is likely an invalid import in this codebase: modules are imported as src.hyperai... (e.g., tests import src.hyperai), so there may be no top-level hyperai package on sys.path. This will break import src.hyperai because src.hyperai.__init__ imports this module. Use a package-relative import (e.g., from ..config import allow_stubs) or import via src.hyperai.config so it resolves consistently in the existing module layout.

Copilot uses AI. Check for mistakes.
Comment on lines +14 to 18
from hyperai.config import allow_stubs as _allow_stubs

# Add root directory to path to import from root-level modules
root_dir = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(root_dir))
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

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

from hyperai.config ... is likely an invalid import in this repository’s module layout (tests import src.hyperai, not hyperai). Since src.hyperai.__init__ imports src.hyperai.protocols.dr_protocol, this will raise ModuleNotFoundError in normal test/runtime execution. Switch to a package-relative import (e.g., from ..config import allow_stubs) or import via src.hyperai.config to match the established src.hyperai namespace.

Copilot uses AI. Check for mistakes.
Comment on lines +4 to +16
import importlib.util
import os
import unittest
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
CONFIG_MODULE_PATH = PROJECT_ROOT / "src" / "hyperai" / "config.py"

spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
config_module = importlib.util.module_from_spec(spec)
assert spec is not None and spec.loader is not None
spec.loader.exec_module(config_module)
allow_stubs = config_module.allow_stubs
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

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

The test loads src/hyperai/config.py via importlib at import time and uses a bare assert to validate the loader. This bypasses the normal package import path (so it won’t catch issues with src.hyperai.config being unimportable) and assert can be stripped with python -O. Prefer importing allow_stubs through the same module namespace used by the codebase (e.g., from src.hyperai.config import allow_stubs after adjusting sys.path like other tests) and replace the assert with an explicit exception if the spec/loader is missing.

Suggested change
import importlib.util
import os
import unittest
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
CONFIG_MODULE_PATH = PROJECT_ROOT / "src" / "hyperai" / "config.py"
spec = importlib.util.spec_from_file_location("hyperai_config", CONFIG_MODULE_PATH)
config_module = importlib.util.module_from_spec(spec)
assert spec is not None and spec.loader is not None
spec.loader.exec_module(config_module)
allow_stubs = config_module.allow_stubs
import os
import sys
import unittest
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from src.hyperai.config import allow_stubs

Copilot uses AI. Check for mistakes.
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.

2 participants