Skip to content

Conversation

@joamag
Copy link
Contributor

@joamag joamag commented Jun 8, 2025

Summary

  • add Python stub files for agent, container, observer, poll, service, stream and util modules

Testing

  • black .
  • pytest -q

https://chatgpt.com/codex/tasks/task_e_6845c99064488328bb41065c4cffb391

Summary by CodeRabbit

  • New Features

    • Introduced enhanced type hinting and interface definitions for core networking, threading, event handling, and utility components.
    • Added type stub support for client, server, container, service, stream, polling, and observer classes, improving static analysis and IDE autocompletion.
    • Included typed utility functions for string formatting and condition verification.
    • Added automated stub testing to ensure type consistency across multiple modules.
  • Documentation

    • Provided comprehensive type annotations for public interfaces, aiding in code clarity and maintainability.

@coderabbitai
Copy link

coderabbitai bot commented Jun 8, 2025

Walkthrough

This update introduces a comprehensive set of Python type stub (.pyi) files for the netius.base module. These stubs provide type annotations and interface specifications for classes and functions related to networking, event loops, threading, polling, containers, servers, services, streams, observables, and utility functions, enabling static type checking and improved IDE support.

Changes

File(s) Change Summary
src/netius/base/agent.pyi Added type stubs for Agent, ClientAgent, and ServerAgent classes, including methods and class attributes.
src/netius/base/client.pyi Added type stubs for Client and DatagramClient classes, with constructors, class methods, and instance methods.
src/netius/base/common.pyi Added type stubs for threading/event loop utilities, including BaseThread and multiple loop/control functions.
src/netius/base/container.pyi Added type stubs for Container and ContainerServer classes, with attributes and lifecycle/management methods.
src/netius/base/observer.pyi Added type stubs for Observable class with event management methods and attributes.
src/netius/base/poll.pyi Added type stubs for polling abstraction: Poll, EpollPoll, KqueuePoll, PollPoll, SelectPoll.
src/netius/base/server.pyi Added type stubs for Server and DatagramServer classes, with network/SSL attributes and methods.
src/netius/base/service.pyi Added type stubs for Service class, including network attributes and event handler method.
src/netius/base/stream.pyi Added type stubs for Stream class, status constants, and state/info methods.
src/netius/base/util.pyi Added type stubs for utility functions: camel_to_underscore and verify.
src/netius/test/base/stubs.py Added StubsTest class with methods to run mypy.stubtest on netius.base modules for stub validation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API
    participant TypeChecker

    User->>API: Imports or uses netius.base components
    API->>TypeChecker: Provides .pyi stubs for static analysis
    TypeChecker-->>User: Reports type errors, autocompletion, and interface info
Loading

Poem

In the warren of code, type stubs appear,
With signatures clear, the future is here!
Rabbits can hop from class to class,
Knowing each method, nothing to pass.
With static checks and hints so bright,
Our burrow of code is typed just right!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 222aae3 and 13ec289.

📒 Files selected for processing (1)
  • src/netius/test/base/stubs.py (1 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/netius/test/base/stubs.py

[refactor] 1-1: Useless option value for '--disable', 'C0326' was removed from pylint, see pylint-dev/pylint#3577.

(R0022)


[refactor] 1-1: Useless option value for '--disable', 'C0330' was removed from pylint, see pylint-dev/pylint#3571.

(R0022)

🔇 Additional comments (3)
src/netius/test/base/stubs.py (3)

1-35: LGTM! Standard header and imports are correct.

The file header, license information, and imports are properly structured and appropriate for the test functionality.

🧰 Tools
🪛 Pylint (3.3.7)

[refactor] 1-1: Useless option value for '--disable', 'C0326' was removed from pylint, see pylint-dev/pylint#3577.

(R0022)


[refactor] 1-1: Useless option value for '--disable', 'C0330' was removed from pylint, see pylint-dev/pylint#3571.

(R0022)


37-49: LGTM! Module list is comprehensive and well-organized.

The MODULES list covers all the key netius.base components and follows a logical alphabetical ordering.


70-74: LGTM! Test method correctly handles mypy availability.

The test method properly checks for mypy.stubtest availability using importlib.util.find_spec() and gracefully skips the test if not found. The iteration over all modules is implemented correctly.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@joamag joamag requested a review from Copilot June 8, 2025 17:58
@joamag joamag self-assigned this Jun 8, 2025
@joamag joamag added the risky ❕ Seems to be risky label Jun 8, 2025
Copy link

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

Adds stub (.pyi) files to provide type definitions for the base modules of the netius package.

  • Introduce Python stubs for utility functions, streaming, services, servers, polling, observables, containers, common infrastructure, clients, and agents.
  • Define classes, method signatures, and constants to improve type checking and IDE support.
  • Wire up inter-module references through imports of base classes and components.

Reviewed Changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/netius/base/util.pyi Add utility function stubs (camel_to_underscore, verify).
src/netius/base/stream.pyi Define Stream constants and method signatures.
src/netius/base/service.pyi Add Service class signature and on_socket_c hook.
src/netius/base/server.pyi Add Server and DatagramServer stubs with serve.
src/netius/base/poll.pyi Stub out Poll base and its implementations.
src/netius/base/observer.pyi Add Observable events and lifecycle methods.
src/netius/base/container.pyi Define Container and ContainerServer interfaces.
src/netius/base/common.pyi Add threading and loop-factory utility stubs.
src/netius/base/client.pyi Stub Client and DatagramClient patterns.
src/netius/base/agent.pyi Add Agent, ClientAgent, and ServerAgent.
Comments suppressed due to low confidence (5)

src/netius/base/server.pyi:12

  • Likely a typo: cer_file should be cert_file to match the convention for certificate file names.
    cer_file: str | None

src/netius/base/common.pyi:1

  • Several stubs reference a Base class imported from .common, but common.pyi does not define Base. You should add a class Base: ... stub or adjust imports to use the correct symbol.
from typing import Any, Callable, Iterable

src/netius/base/container.pyi:4

  • StreamServer is not defined in server.pyi. Update the import to the correct class name (e.g., Server) or add a StreamServer stub in server.pyi.
from .server import StreamServer

src/netius/base/server.pyi:3

  • Base is imported from .common but not defined in common.pyi. Add a Base stub or correct the import target.
from .common import Base

src/netius/base/client.pyi:3

  • Base is imported here but missing from common.pyi. Either define Base in common.pyi or remove it from this import.
from .common import Base, BaseThread

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/netius/base/service.pyi (2)

6-16: Refine port type to reflect actual usage.

Currently port: Any | None; if this represents a numeric port, consider int | None for stronger typing.


31-32: Strengthen on_socket_c parameter types.

You have address: Any—if it’s always a (host, port) pair, consider tuple[str, int].

src/netius/base/poll.pyi (1)

30-87: Reduce duplication across platform‐specific subclasses.

Since each subclass redefines the same signatures, consider using a shared Protocol or mixin to DRY up these stubs.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b551be1 and 4b5c694.

📒 Files selected for processing (10)
  • src/netius/base/agent.pyi (1 hunks)
  • src/netius/base/client.pyi (1 hunks)
  • src/netius/base/common.pyi (1 hunks)
  • src/netius/base/container.pyi (1 hunks)
  • src/netius/base/observer.pyi (1 hunks)
  • src/netius/base/poll.pyi (1 hunks)
  • src/netius/base/server.pyi (1 hunks)
  • src/netius/base/service.pyi (1 hunks)
  • src/netius/base/stream.pyi (1 hunks)
  • src/netius/base/util.pyi (1 hunks)
🔇 Additional comments (23)
src/netius/base/util.pyi (1)

1-4: Stub signatures are accurate. The camel_to_underscore and verify declarations correctly express parameter types, default ellipses, and return types for improved editor and type‐checker support.

src/netius/base/server.pyi (3)

1-14: Server attribute annotations are consistent. The imported Any and Mapping types cover the socket and info fields, and the attributes (socket, host, port, etc.) match expected runtime members.


16-40: serve method signature is comprehensive. All parameters for networking, SSL, and runtime options are clearly typed, enabling precise IDE and static‐analysis support.


42-48: DatagramServer stubs align with implementation. The read/write/error list methods and overloaded serve signature correctly mirror expected callbacks.

src/netius/base/agent.pyi (3)

1-5: Imports and base class linkage are correct. Observable and Client are properly imported to establish class hierarchies.


6-11: Agent lifecycle methods are well-typed. Both class and instance cleanup/destruction methods are declared with correct signatures.


12-19: ClientAgent stubs are precise. The _clients mapping and the get_client_s factory method return the proper Client type.

src/netius/base/stream.pyi (2)

1-8: Stream constants and imports are solid. The OPEN, CLOSED, and PENDING annotations plus the Any and Observable imports form a clear foundation.


9-22: Stream interface is complete. State attributes and lifecycle methods (open, close, reset, etc.) are all properly declared for static typing.

src/netius/base/observer.pyi (2)

1-5: Observable imports and event dict type are correct. Using Callable[..., Any] for handlers covers all callback signatures.


6-14: Event management methods are fully typed. The bind, unbind, unbind_all, and trigger signatures accurately reflect the intended API.

src/netius/base/container.pyi (3)

1-5: Verify PEP604 union usage and Python version compatibility.

You’re using Base | None and list[Base] (PEP604 syntax) in a stub file—ensure your build and type‐checking toolchain targets Python 3.10+ or that your stubs are processed in a forward‐annotation context.


6-26: Container interface stub looks solid.

All lifecycle and collection methods are clearly annotated, and required imports are in scope.


28-35: ContainerServer stub is consistent.

Inheritance from StreamServer and the add_base signature align with Container.

src/netius/base/service.pyi (1)

18-30: Service constructor stub is clear.

Parameters and defaults are well‐annotated. No further issues spotted.

src/netius/base/client.pyi (4)

1-3: Imports look good.

Any, Base, and BaseThread are correctly imported for use below.


5-7: Class‐level client cache stub is fine.


8-29: Potential typo in connect signature.

The parameter cer_file may be intended as cert_file. Please verify the underlying implementation or rename for clarity.


31-33: DatagramClient stub is straightforward.

src/netius/base/common.pyi (3)

1-3: Imports and typing support are appropriate.


4-9: BaseThread stub is correct.


10-49: Core event‐loop and loop‐management stubs look comprehensive.

src/netius/base/poll.pyi (1)

3-29: Base Poll interface stub is solid.

Comment on lines +1 to +5
from typing import Any

from .observer import Observable
from .transport import Transport

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing stub for transport.

You import Transport from .transport but no transport.pyi is included in this PR. Please confirm that a stub exists for this module or add it here.

🤖 Prompt for AI Agents
In src/netius/base/service.pyi around lines 1 to 5, you import Transport from
.transport but there is no transport.pyi stub file included in this PR. Verify
if transport.pyi exists in the codebase; if it does not, create a transport.pyi
stub file defining the Transport class or relevant types to ensure proper type
checking and completeness of type stubs.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/netius/test/base/stubs.py (1)

69-71: Enhance test reporting and fix formatting.

Consider improving the test method to provide better failure context and fix the missing newline:

    def test_stubtest(self):
        for module in self.MODULES:
-            self._run_stubtest(module)
+            with self.subTest(module=module):
+                self._run_stubtest(module)
+

Using subTest will provide clearer failure reporting when specific modules fail stubtest validation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b5c694 and 222aae3.

📒 Files selected for processing (1)
  • src/netius/test/base/stubs.py (1 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/netius/test/base/stubs.py

[refactor] 1-1: Useless option value for '--disable', 'C0326' was removed from pylint, see pylint-dev/pylint#3577.

(R0022)


[refactor] 1-1: Useless option value for '--disable', 'C0330' was removed from pylint, see pylint-dev/pylint#3571.

(R0022)

🪛 GitHub Actions: Main Workflow
src/netius/test/base/stubs.py

[error] 1-1: Test failure detected in this file during pytest run.

🔇 Additional comments (2)
src/netius/test/base/stubs.py (2)

1-33: LGTM! Standard header and appropriate imports.

The file header follows standard conventions and the imports are appropriate for subprocess-based testing.

🧰 Tools
🪛 Pylint (3.3.7)

[refactor] 1-1: Useless option value for '--disable', 'C0326' was removed from pylint, see pylint-dev/pylint#3577.

(R0022)


[refactor] 1-1: Useless option value for '--disable', 'C0330' was removed from pylint, see pylint-dev/pylint#3571.

(R0022)

🪛 GitHub Actions: Main Workflow

[error] 1-1: Test failure detected in this file during pytest run.


36-48: LGTM! Well-structured test class and comprehensive module list.

The module list appropriately covers all the base modules mentioned in the PR objectives.

Comment on lines 50 to 71
def _run_stubtest(self, module: str) -> None:
result = subprocess.run(
[
sys.executable,
"-m",
"mypy.stubtest",
module,
"--mypy-config-file",
"/dev/null",
"--ignore-missing-stub",
"--allowlist",
"/dev/null",
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
self.assertEqual(result.returncode, 0, result.stdout)

def test_stubtest(self):
for module in self.MODULES:
self._run_stubtest(module)
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Investigate the pipeline failure root cause.

The pipeline failure suggests that stubtest is failing during execution. This could be due to:

  1. Platform compatibility issues (addressed above)
  2. Missing mypy dependency in the test environment
  3. Actual issues with the stub files themselves

Run this script to verify the stub files and dependencies:


🏁 Script executed:

#!/bin/bash
# Check if mypy and stubtest are available
python -m pip list | grep mypy || echo "mypy not installed"

# Check if the stub files exist
for module in agent client common container observer poll server service stream util; do
    if [ -f "src/netius/base/${module}.pyi" ]; then
        echo "${module}.pyi exists"
    else
        echo "${module}.pyi missing"
    fi
done

# Try running stubtest on one module to see the specific error
python -m mypy.stubtest netius.base.common --ignore-missing-stub 2>&1 || echo "stubtest failed"

Length of output: 2074


Install mypy in the CI/test environment

The stubtest invocation is failing with:

ModuleNotFoundError: No module named 'mypy'

which indicates mypy isn’t installed in the test runner. To fix this, ensure mypy is listed among your development/test dependencies and is installed before running stubtest:

• In your dev requirements (e.g. requirements-dev.txt or pyproject.toml extras), add:

mypy>=1.0

• In your CI workflow (e.g. .github/workflows/test.yml), install dev deps:

- name: Install dependencies
  run: pip install -r requirements-dev.txt

• Optionally pin a specific mypy version to ensure consistency across runs.

Once mypy is available, rerun python -m mypy.stubtest … to confirm all stubs pass.

🤖 Prompt for AI Agents
In src/netius/test/base/stubs.py around lines 50 to 71, the stubtest subprocess
call fails because the 'mypy' module is not installed in the test environment.
To fix this, add 'mypy>=1.0' to your development dependencies file (e.g.,
requirements-dev.txt or pyproject.toml extras) and ensure the CI workflow
installs these dev dependencies before running tests. This will make the
'mypy.stubtest' command available and prevent the ModuleNotFoundError during
stubtest execution.

Comment on lines +50 to +67
def _run_stubtest(self, module: str) -> None:
result = subprocess.run(
[
sys.executable,
"-m",
"mypy.stubtest",
module,
"--mypy-config-file",
"/dev/null",
"--ignore-missing-stub",
"--allowlist",
"/dev/null",
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
self.assertEqual(result.returncode, 0, result.stdout)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix platform compatibility and add error handling.

The current implementation has several issues that likely contribute to the pipeline failure:

  1. /dev/null is Unix-specific and will fail on Windows
  2. No error handling if mypy.stubtest is not installed
  3. Hard-coded paths may not work in CI environments

Consider this more robust implementation:

    def _run_stubtest(self, module: str) -> None:
+        import os
+        null_device = os.devnull
+        
+        # Check if mypy.stubtest is available
+        try:
+            subprocess.run([sys.executable, "-m", "mypy.stubtest", "--help"], 
+                          capture_output=True, check=True)
+        except (subprocess.CalledProcessError, FileNotFoundError):
+            self.skipTest("mypy.stubtest not available")
+            
        result = subprocess.run(
            [
                sys.executable,
                "-m",
                "mypy.stubtest",
                module,
                "--mypy-config-file",
-                "/dev/null",
+                null_device,
                "--ignore-missing-stub",
                "--allowlist",
-                "/dev/null",
+                null_device,
            ],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
        )
        self.assertEqual(result.returncode, 0, result.stdout)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _run_stubtest(self, module: str) -> None:
result = subprocess.run(
[
sys.executable,
"-m",
"mypy.stubtest",
module,
"--mypy-config-file",
"/dev/null",
"--ignore-missing-stub",
"--allowlist",
"/dev/null",
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
self.assertEqual(result.returncode, 0, result.stdout)
def _run_stubtest(self, module: str) -> None:
import os
null_device = os.devnull
# Check if mypy.stubtest is available
try:
subprocess.run(
[sys.executable, "-m", "mypy.stubtest", "--help"],
capture_output=True,
check=True,
)
except (subprocess.CalledProcessError, FileNotFoundError):
self.skipTest("mypy.stubtest not available")
result = subprocess.run(
[
sys.executable,
"-m",
"mypy.stubtest",
module,
"--mypy-config-file",
null_device,
"--ignore-missing-stub",
"--allowlist",
null_device,
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
self.assertEqual(result.returncode, 0, result.stdout)
🤖 Prompt for AI Agents
In src/netius/test/base/stubs.py around lines 50 to 67, replace the hard-coded
Unix-specific "/dev/null" paths with a platform-independent approach using
tempfile or appropriate null device handling for Windows. Add error handling to
catch exceptions if "mypy.stubtest" is not installed or subprocess.run fails,
and provide informative error messages. Avoid hard-coded paths by dynamically
determining or mocking necessary files to ensure compatibility and reliability
in CI environments.

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

Labels

codex risky ❕ Seems to be risky

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants