diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cc3091ecce..4e4aa16f25 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,7 +10,7 @@ on: env: POETRY_VERSION: "2.2.1" PYTHON_VERSION: "3.12" - CACHE_VERSION: "0.1.1" + CACHE_VERSION: "0.1.4" jobs: # Quick smoke test - fails fast on basic issues (5-10s) @@ -220,7 +220,12 @@ jobs: poetry run mypy --strict \ scripts/validation/validate-no-direct-io.py \ scripts/validation/validate-all-exports.py \ - scripts/validation/validate-no-infra-imports.py + scripts/validation/validate-no-infra-imports.py \ + scripts/check_transport_imports.py + + - name: Check for transport import violations (OMN-220) + run: | + poetry run python scripts/check_transport_imports.py docs-validation: name: Documentation Validation diff --git a/CLAUDE.md b/CLAUDE.md index f211cad1a3..10638832e7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -894,8 +894,9 @@ poetry install pre-commit install # Cleanup -python3 scripts/cleanup.py # Clean tmp/, cache files -python3 scripts/cleanup.py --remove-from-git # Also remove tracked tmp files +python3 scripts/cleanup.py --tmp-only # Clean tmp/ only (preserves caches) - USE THIS! +python3 scripts/cleanup.py # FULL cleanup (deletes ALL caches - slow rebuild!) +python3 scripts/cleanup.py --remove-from-git --tmp-only # Remove tracked tmp files from git python3 scripts/cleanup.py --dry-run # Preview what would be cleaned python3 scripts/cleanup.py --verbose # Detailed output diff --git a/docs/architecture/DEPENDENCY_INVERSION.md b/docs/architecture/DEPENDENCY_INVERSION.md new file mode 100644 index 0000000000..abfd9b893f --- /dev/null +++ b/docs/architecture/DEPENDENCY_INVERSION.md @@ -0,0 +1,311 @@ +# Dependency Inversion in ONEX Architecture + +> **Version**: 0.4.0 +> **Last Updated**: 2025-12-10 +> **Status**: Production +> **Related Ticket**: OMN-220 + +## Overview + +The ONEX framework enforces strict **dependency inversion** to maintain clean architectural boundaries between abstraction layers and concrete implementations. This principle ensures that `omnibase_core` remains a pure abstraction layer without direct dependencies on transport or infrastructure libraries. + +## Architecture Principle + +### Layer Separation + +``` ++--------------------------------------------------+ +| SERVICE LAYER | +| (Applications, APIs, Workers) | +| - Consumes protocols from omnibase_core | +| - Uses implementations from omnibase_spi | ++--------------------------------------------------+ + | + v ++--------------------------------------------------+ +| omnibase_spi | +| (Service Provider Interface) | +| - Concrete implementations of protocols | +| - Transport library integrations | +| - Infrastructure adapters | ++--------------------------------------------------+ + | + v ++--------------------------------------------------+ +| omnibase_core | +| (Core Abstractions) | +| - Protocol definitions (interfaces) | +| - Domain models and contracts | +| - Base node implementations | +| - NO transport/infrastructure dependencies | ++--------------------------------------------------+ +``` + +### Dependency Direction + +- **omnibase_core**: Provides protocol abstractions (interfaces only) +- **omnibase_spi**: Provides concrete implementations using transport libraries +- **Services**: Depend on `omnibase_core` protocols, use `omnibase_spi` implementations + +This ensures that: +1. Core logic is testable without infrastructure dependencies +2. Transport libraries can be swapped without changing business logic +3. The framework remains decoupled from specific vendors or technologies + +## Transport Library Restrictions + +The following transport and infrastructure libraries are **FORBIDDEN** in `omnibase_core`: + +### Message Queue Clients + +| Library | Use Instead | +|---------|-------------| +| `kafka` | `ProtocolEventBus` | +| `aiokafka` | `ProtocolEventBus` | + +### HTTP Clients + +| Library | Use Instead | +|---------|-------------| +| `httpx` | `ProtocolHttpClient` | +| `aiohttp` | `ProtocolHttpClient` | +| `requests` | `ProtocolHttpClient` | + +### Database Clients + +| Library | Use Instead | +|---------|-------------| +| `asyncpg` | `ProtocolRepository` | +| `psycopg` | `ProtocolRepository` | +| `psycopg2` | `ProtocolRepository` | + +### Secret Store Clients + +| Library | Use Instead | +|---------|-------------| +| `hvac` | `ProtocolSecretStore` | + +### Service Discovery Clients + +| Library | Use Instead | +|---------|-------------| +| `consul` | `ProtocolServiceDiscovery` | + +### Cache/Queue Clients + +| Library | Use Instead | +|---------|-------------| +| `redis` | `ProtocolCache` | +| `valkey` | `ProtocolCache` | + +## Why This Matters + +### 1. Testability + +Without direct transport dependencies, `omnibase_core` components can be tested in isolation using mock implementations: + +```python +# In tests - use mock implementations +class MockEventBus: + def __init__(self): + self.published_events = [] + + async def publish(self, event: ModelEventEnvelope) -> None: + self.published_events.append(event) + +# Test node without Kafka dependency +container = ModelONEXContainer() +container.register_service("ProtocolEventBus", MockEventBus()) + +node = MyComputeNode(container) +result = await node.process(input_data) +``` + +### 2. Flexibility + +Transport libraries can be swapped without modifying business logic: + +```python +# Development: Use in-memory implementation +container.register_service("ProtocolEventBus", InMemoryEventBus()) + +# Production: Use Kafka implementation (from omnibase_spi) +container.register_service("ProtocolEventBus", KafkaEventBus(config)) + +# Same node code works with both +node = MyComputeNode(container) +``` + +### 3. Layer Separation + +Clear boundaries between abstraction and implementation: + +```python +# omnibase_core - Pure protocol definition +class ProtocolEventBus(Protocol): + async def publish(self, event: ModelEventEnvelope) -> None: ... + async def subscribe(self, topic: str, handler: Callable) -> None: ... + +# omnibase_spi - Concrete implementation +class KafkaEventBus: + """Kafka implementation of ProtocolEventBus.""" + + def __init__(self, bootstrap_servers: list[str]): + self._producer = AIOKafkaProducer(...) # Kafka dependency here + + async def publish(self, event: ModelEventEnvelope) -> None: + await self._producer.send(...) +``` + +### 4. Vendor Independence + +The framework is not locked to specific vendors: + +- Kafka can be replaced with RabbitMQ, AWS SQS, or GCP Pub/Sub +- PostgreSQL can be replaced with MySQL, MongoDB, or DynamoDB +- HashiCorp Vault can be replaced with AWS Secrets Manager +- Redis can be replaced with Memcached or DynamoDB + +## Allowed Patterns + +While transport libraries are forbidden in runtime code, the following patterns are acceptable: + +### Type Checking Imports + +```python +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # Type-only imports are allowed for documentation purposes + from aiokafka import AIOKafkaProducer +``` + +### Protocol Definitions + +```python +# Protocols that abstract transports are encouraged +class ProtocolMessageBroker(Protocol): + """Abstract interface for message brokers.""" + + async def send(self, topic: str, message: bytes) -> None: ... + async def receive(self, topic: str) -> bytes: ... +``` + +### Test Mocks and Fixtures + +```python +# In tests/ directory - transport mocks are allowed +class FakeKafkaProducer: + """Test double for Kafka producer.""" + + async def send(self, topic: str, value: bytes) -> None: + pass +``` + +## Enforcement + +### Automated Validation + +The `scripts/check_transport_imports.py` script validates these constraints: + +```bash +# Check all files +poetry run python scripts/check_transport_imports.py + +# Check with verbose output +poetry run python scripts/check_transport_imports.py --verbose + +# Check specific file +poetry run python scripts/check_transport_imports.py --file src/omnibase_core/some_file.py + +# Output as JSON (for CI integration) +poetry run python scripts/check_transport_imports.py --json + +# Check only changed files (faster CI) +poetry run python scripts/check_transport_imports.py --changed-files +``` + +### CI Integration + +Transport import validation runs automatically in CI: + +1. **PR Checks**: All changed files are scanned for violations +2. **Full Validation**: Periodic full codebase scans +3. **Blocking**: PRs with violations cannot be merged + +### Exit Codes + +| Code | Meaning | +|------|---------| +| 0 | No violations found | +| 1 | Transport import violations detected (blocks PR) | +| 2 | Script error (invalid arguments, file not found) | + +## Migration Guide + +### Moving Transport Code to omnibase_spi + +If you have code that directly imports transport libraries: + +1. **Identify the protocol** that abstracts the transport +2. **Move the implementation** to `omnibase_spi` +3. **Update the consumer** to depend on the protocol +4. **Register the implementation** in the service container + +**Before** (in omnibase_core): + +```python +# BAD: Direct transport import in omnibase_core +from aiokafka import AIOKafkaProducer + +class MyService: + def __init__(self): + self.producer = AIOKafkaProducer(...) +``` + +**After** (protocol in omnibase_core, implementation in omnibase_spi): + +```python +# GOOD: Protocol-based dependency +# In omnibase_core/my_service.py +class MyService: + def __init__(self, container: ModelONEXContainer): + self.event_bus = container.get_service("ProtocolEventBus") + +# Implementation lives in omnibase_spi +``` + +### Temporary Allowlist + +Pre-existing violations may be temporarily allowlisted while being addressed: + +```python +# In scripts/check_transport_imports.py +TEMPORARY_ALLOWLIST: frozenset[str] = frozenset({ + "mixins/mixin_health_check.py", # TODO: Refactor to use ProtocolHttpClient +}) +``` + +Allowlisted files: +- Are tracked for future remediation +- Have expiration dates for review +- Should be addressed systematically + +## Related Documentation + +- [Protocol Architecture](./PROTOCOL_ARCHITECTURE.md) - Complete protocol inventory and patterns +- [Dependency Injection](./DEPENDENCY_INJECTION.md) - Container-based DI patterns +- [ONEX Four-Node Architecture](./ONEX_FOUR_NODE_ARCHITECTURE.md) - Node type responsibilities +- [Container Types](./CONTAINER_TYPES.md) - ModelONEXContainer vs ModelContainer + +## References + +- [SOLID Principles - Dependency Inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle) +- [Clean Architecture - Uncle Bob](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) +- [PEP 544 - Structural Subtyping (Protocols)](https://peps.python.org/pep-0544/) + +--- + +**Document Version**: 1.0 +**Created**: 2025-12-10 +**Maintainer**: ONEX Core Team diff --git a/scripts/check_transport_imports.py b/scripts/check_transport_imports.py new file mode 100755 index 0000000000..1a3e07abf9 --- /dev/null +++ b/scripts/check_transport_imports.py @@ -0,0 +1,878 @@ +#!/usr/bin/env python3 +""" +ONEX Transport Import Validation. + +AST-based import scanning to ensure omnibase_core does not contain direct +imports of transport/infrastructure libraries. These libraries belong in +omnibase_spi or service layers, not in the core framework. + +This enforces the ONEX architecture principle of dependency inversion: +omnibase_core provides abstractions (protocols), while omnibase_spi +provides concrete implementations using transport libraries. + +FORBIDDEN IMPORTS: +- kafka, aiokafka: Message queue clients (use ProtocolEventBus) +- httpx, aiohttp, requests: HTTP clients (use ProtocolHttpClient) +- asyncpg, psycopg, psycopg2: Database clients (use ProtocolRepository) +- hvac: HashiCorp Vault client (use ProtocolSecretStore) +- consul: Service discovery client (use ProtocolServiceDiscovery) +- redis, valkey: Cache/queue clients (use ProtocolCache) + +ALLOWED PATTERNS: +- Protocol definitions that abstract these transports +- Type stubs for type checking (if __TYPE_CHECKING__) +- Test mocks and fixtures + +Usage: + poetry run python scripts/check_transport_imports.py + poetry run python scripts/check_transport_imports.py --verbose + poetry run python scripts/check_transport_imports.py --json + poetry run python scripts/check_transport_imports.py --file src/omnibase_core/some_file.py + +Exit Codes: + 0 - No transport import violations found + 1 - Transport import violations detected (blocks PR) + 2 - Script error (invalid arguments, file not found, etc.) + +Related: + - Linear Ticket: OMN-220 + - Architecture: docs/architecture/DEPENDENCY_INVERSION.md + - Protocols: docs/architecture/PROTOCOL_ARCHITECTURE.md +""" + +from __future__ import annotations + +import argparse +import ast +import json +import sys +from dataclasses import dataclass, field +from datetime import date +from enum import Enum +from pathlib import Path +from typing import NamedTuple + + +class ViolationType(Enum): + """Types of transport import violations.""" + + BANNED_TRANSPORT_IMPORT = "banned_transport_import" + SYNTAX_ERROR = "syntax_error" + ANALYSIS_ERROR = "analysis_error" + + +class Severity(Enum): + """Severity levels for violations.""" + + ERROR = "error" # Blocks CI + + +@dataclass +class TransportViolation: + """A single transport import violation found in a source file.""" + + file_path: Path + line_number: int + column: int + violation_type: ViolationType + severity: Severity + message: str + suggestion: str + code_snippet: str = "" + + def format(self, verbose: bool = False) -> str: + """Format violation for output. + + Args: + verbose: If True, include code snippet in output. + + Returns: + Formatted violation string for display. + """ + location = f"{self.file_path}:{self.line_number}:{self.column}" + level = "ERROR" if self.severity == Severity.ERROR else "WARNING" + + result = f"[{level}] {location}\n" + result += f" {self.violation_type.value}: {self.message}\n" + result += f" Suggestion: {self.suggestion}\n" + + if verbose and self.code_snippet: + result += f" Code: {self.code_snippet}\n" + + return result + + +class TransportCheckResult(NamedTuple): + """Result of transport import check for a single file.""" + + file_path: Path + violations: list[TransportViolation] + is_clean: bool + skip_reason: str | None + + +# ============================================================================== +# BANNED TRANSPORT MODULES CONFIGURATION +# ============================================================================== + +# Transport libraries that are FORBIDDEN in omnibase_core +# These should only be used in omnibase_spi or service layers +BANNED_TRANSPORT_MODULES: frozenset[str] = frozenset( + { + # Message queue clients + "kafka", + "aiokafka", + # HTTP clients + "httpx", + "aiohttp", + "requests", + # Database clients + "asyncpg", + "psycopg", + "psycopg2", + # Secret store clients + "hvac", + # Service discovery clients + "consul", + # Cache/queue clients + "redis", + "valkey", + } +) + +# Protocol alternatives for banned transports +TRANSPORT_ALTERNATIVES: dict[str, str] = { + "kafka": "ProtocolEventBus", + "aiokafka": "ProtocolEventBus", + "httpx": "ProtocolHttpClient", + "aiohttp": "ProtocolHttpClient", + "requests": "ProtocolHttpClient", + "asyncpg": "ProtocolRepository", + "psycopg": "ProtocolRepository", + "psycopg2": "ProtocolRepository", + "hvac": "ProtocolSecretStore", + "consul": "ProtocolServiceDiscovery", + "redis": "ProtocolCache", + "valkey": "ProtocolCache", +} + +# Temporary allowlist for pre-existing violations +# These should be fixed and removed from this list +# Each entry is a relative path from src/omnibase_core/ +# +# EXPIRATION: Review and remove allowlisted items by 2026-06-10 +# NOTE: This date is 6 months from initial implementation (2025-12-10). +# Update this date when reviewing allowlisted items. +# TODO [OMN-220]: Create separate tickets to fix these and remove from allowlist +TEMPORARY_ALLOWLIST: frozenset[str] = frozenset( + { + # TODO [OMN-220]: mixin_health_check.py uses aiohttp directly for HTTP + # health checks. Should use ProtocolHttpClient instead. + # Action: Create child ticket to refactor health check to use protocol abstraction + "mixins/mixin_health_check.py", + } +) + +# Allowlist expiration date - CI should warn when this approaches +ALLOWLIST_EXPIRATION_DATE: date = date(2026, 6, 10) +ALLOWLIST_WARNING_DAYS: int = 30 # Warn this many days before expiration + + +# ============================================================================== +# AST VISITOR +# ============================================================================== + + +@dataclass +class TransportImportAnalyzer(ast.NodeVisitor): + """AST visitor to detect banned transport library imports. + + Scans the AST for import statements that reference banned transport + libraries. These libraries should not be imported directly in + omnibase_core - instead, protocols should be used for abstraction. + + Thread Safety Note: + This class is NOT thread-safe. It uses mutable state (violations list, + in_type_checking_block flag) that would cause race conditions if shared + across threads. For parallel file analysis (e.g., with multiprocessing), + create a separate analyzer instance per thread/process. + + Attributes: + file_path: Path to the file being analyzed. + source_lines: List of source code lines for snippet extraction. + violations: List of detected transport import violations. + in_type_checking_block: Whether currently inside TYPE_CHECKING block. + """ + + file_path: Path + source_lines: list[str] + violations: list[TransportViolation] = field(default_factory=list) + in_type_checking_block: bool = False + + def visit_If(self, node: ast.If) -> None: + """Track TYPE_CHECKING blocks to allow type-only imports. + + Args: + node: AST if statement node to analyze. + """ + # Check if this is a TYPE_CHECKING block + if self._is_type_checking_condition(node.test): + # Save state and mark as in type checking block + prev_state = self.in_type_checking_block + self.in_type_checking_block = True + # Visit the body of the if block + for child in node.body: + self.visit(child) + # Restore state + self.in_type_checking_block = prev_state + # Visit else/elif parts normally + for child in node.orelse: + self.visit(child) + else: + # Not a TYPE_CHECKING block - use generic_visit to recursively + # visit all child nodes (including nested if statements, function + # bodies, class definitions, etc.) for import detection + self.generic_visit(node) + + def visit_Import(self, node: ast.Import) -> None: + """Check import statements for banned transport modules. + + Detects `import X` and `import X as Y` patterns. + + Args: + node: AST import node to check. + """ + if self.in_type_checking_block: + # Allow type-only imports inside TYPE_CHECKING blocks + return + + for alias in node.names: + module_name = alias.name + self._check_banned_module(node, module_name) + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: + """Check 'from ... import ...' statements for banned transport modules. + + Detects `from X import Y` patterns. + + Args: + node: AST import-from node to check. + """ + if self.in_type_checking_block: + # Allow type-only imports inside TYPE_CHECKING blocks + return + + module_name = node.module or "" + self._check_banned_module(node, module_name) + + def _is_type_checking_condition(self, test: ast.expr) -> bool: + """Check if condition is TYPE_CHECKING or typing.TYPE_CHECKING. + + Handles the following patterns: + - `if TYPE_CHECKING:` (direct import) + - `if typing.TYPE_CHECKING:` (qualified access) + - `if t.TYPE_CHECKING:` (aliased import like `import typing as t`) + + Args: + test: AST expression to check. + + Returns: + True if this is a TYPE_CHECKING condition. + """ + # Check for `if TYPE_CHECKING:` + if isinstance(test, ast.Name) and test.id == "TYPE_CHECKING": + return True + # Check for `if typing.TYPE_CHECKING:` or `if .TYPE_CHECKING:` + # This handles both `typing.TYPE_CHECKING` and aliased imports like + # `import typing as t; if t.TYPE_CHECKING:` + if isinstance(test, ast.Attribute): + if test.attr == "TYPE_CHECKING" and isinstance(test.value, ast.Name): + # Accept any module alias accessing TYPE_CHECKING attribute + # Common patterns: typing.TYPE_CHECKING, t.TYPE_CHECKING, tp.TYPE_CHECKING + return True + return False + + def _check_banned_module(self, node: ast.AST, module_name: str) -> None: + """Check if a module import is banned in omnibase_core. + + Args: + node: AST node for error location reporting. + module_name: Fully qualified module name to check. + """ + # Get the root module (e.g., "kafka" from "kafka.producer") + root_module = module_name.split(".")[0] + + if root_module in BANNED_TRANSPORT_MODULES: + alternative = TRANSPORT_ALTERNATIVES.get( + root_module, "protocol abstraction" + ) + self._add_violation( + node, + ViolationType.BANNED_TRANSPORT_IMPORT, + Severity.ERROR, + f"Import of '{module_name}' is forbidden in omnibase_core", + f"Transport libraries belong in omnibase_spi or service layers. " + f"Use {alternative} instead.", + ) + + def _add_violation( + self, + node: ast.AST, + violation_type: ViolationType, + severity: Severity, + message: str, + suggestion: str, + ) -> None: + """Add a violation to the list. + + Args: + node: AST node where violation was detected. + violation_type: Type of transport import violation. + severity: Severity level (ERROR). + message: Human-readable description of the violation. + suggestion: Suggested fix for the violation. + """ + line_number = getattr(node, "lineno", 0) + column = getattr(node, "col_offset", 0) + + # Get code snippet + code_snippet = "" + if 0 < line_number <= len(self.source_lines): + code_snippet = self.source_lines[line_number - 1].strip() + + self.violations.append( + TransportViolation( + file_path=self.file_path, + line_number=line_number, + column=column, + violation_type=violation_type, + severity=severity, + message=message, + suggestion=suggestion, + code_snippet=code_snippet, + ) + ) + + +# ============================================================================== +# MAIN ANALYSIS FUNCTIONS +# ============================================================================== + + +def analyze_file(file_path: Path) -> TransportCheckResult: + """Analyze a single file for banned transport imports. + + Parses the file as an AST and scans for import statements that + reference banned transport libraries. + + Args: + file_path: Path to the Python file to analyze. + + Returns: + TransportCheckResult with violations and analysis status. + """ + try: + source = file_path.read_text(encoding="utf-8") + source_lines = source.splitlines() + tree = ast.parse(source, filename=str(file_path)) + + # Analyze for transport import violations + analyzer = TransportImportAnalyzer( + file_path=file_path, + source_lines=source_lines, + ) + analyzer.visit(tree) + + return TransportCheckResult( + file_path=file_path, + violations=analyzer.violations, + is_clean=len(analyzer.violations) == 0, + skip_reason=None, + ) + + except SyntaxError as e: + # Log to stderr for CI visibility - helps debug syntax issues in source files + print( + f"Warning: Syntax error in {file_path}: {e.msg}", + file=sys.stderr, + ) + return TransportCheckResult( + file_path=file_path, + violations=[ + TransportViolation( + file_path=file_path, + line_number=e.lineno or 0, + column=e.offset or 0, + violation_type=ViolationType.SYNTAX_ERROR, + severity=Severity.ERROR, + message=f"Syntax error: {e.msg}", + suggestion="Fix the syntax error before transport check can run", + ) + ], + is_clean=False, + skip_reason=f"Syntax error: {e.msg}", + ) + except UnicodeDecodeError as e: + # Handle encoding issues explicitly - common with binary or non-UTF-8 files + print( + f"Warning: Encoding error in {file_path}: {e}", + file=sys.stderr, + ) + return TransportCheckResult( + file_path=file_path, + violations=[ + TransportViolation( + file_path=file_path, + line_number=0, + column=0, + violation_type=ViolationType.ANALYSIS_ERROR, + severity=Severity.ERROR, + message=f"Encoding error: {e.reason} at position {e.start}", + suggestion="Ensure file is UTF-8 encoded or add to exclusion list " + "if it's a binary/non-Python file", + ) + ], + is_clean=False, + skip_reason=f"Encoding error: {e.reason}", + ) + except PermissionError as e: + # Handle permission issues explicitly - helps diagnose CI/CD environment issues + print( + f"Warning: Permission denied reading {file_path}: {e}", + file=sys.stderr, + ) + return TransportCheckResult( + file_path=file_path, + violations=[ + TransportViolation( + file_path=file_path, + line_number=0, + column=0, + violation_type=ViolationType.ANALYSIS_ERROR, + severity=Severity.ERROR, + message="Permission denied: cannot read file", + suggestion="Check file permissions or run with appropriate privileges", + ) + ], + is_clean=False, + skip_reason="Permission denied", + ) + except FileNotFoundError as e: + # Handle race condition where file is deleted between discovery and analysis + print( + f"Warning: File not found {file_path}: {e}", + file=sys.stderr, + ) + return TransportCheckResult( + file_path=file_path, + violations=[ + TransportViolation( + file_path=file_path, + line_number=0, + column=0, + violation_type=ViolationType.ANALYSIS_ERROR, + severity=Severity.ERROR, + message="File not found (may have been deleted during analysis)", + suggestion="Re-run the check - file may have been moved or deleted", + ) + ], + is_clean=False, + skip_reason="File not found", + ) + except Exception as e: + # Log to stderr for CI visibility - helps debug unexpected failures + print( + f"Warning: Failed to analyze {file_path}: {type(e).__name__}: {e}", + file=sys.stderr, + ) + # Create a proper violation for unexpected errors rather than masking them + # with an empty violations list. This ensures errors are visible in reports + # and prevents silent failures during CI checks. + return TransportCheckResult( + file_path=file_path, + violations=[ + TransportViolation( + file_path=file_path, + line_number=0, + column=0, + violation_type=ViolationType.ANALYSIS_ERROR, + severity=Severity.ERROR, + message=f"Unexpected error during analysis: {type(e).__name__}: {e}", + suggestion="Investigate the error - this may indicate a bug in the " + "transport checker or an unusual file format", + ) + ], + is_clean=False, + skip_reason=f"Error analyzing file: {e}", + ) + + +def find_python_files(src_dir: Path) -> list[Path]: + """Find all Python files in the source directory. + + Recursively searches for .py files, excluding __pycache__ directories. + Returns resolved (absolute) paths for consistent comparison. + + Args: + src_dir: Source directory to search (typically src/omnibase_core). + + Returns: + Sorted list of resolved paths to Python files. + """ + python_files: list[Path] = [] + + for py_file in src_dir.rglob("*.py"): + # Skip __pycache__ directories + if "__pycache__" in py_file.parts: + continue + # Use resolved paths for consistent comparison with get_changed_files + python_files.append(py_file.resolve()) + + return sorted(python_files) + + +def _safe_relative_path(file_path: Path, base_dir: Path) -> str: + """Get relative path, falling back to full path if not relative. + + Args: + file_path: Path to make relative. + base_dir: Base directory to compute relative path from. + + Returns: + String representation of relative path, or full path if relative_to fails. + """ + try: + return str(file_path.relative_to(base_dir)) + except ValueError: + # Path is outside base_dir, return the full path + return str(file_path) + + +def _is_allowlisted(file_path: Path, src_dir: Path) -> bool: + """Check if a file is in the temporary allowlist. + + Args: + file_path: Absolute path to the file. + src_dir: The src/omnibase_core directory. + + Returns: + True if file is allowlisted and violations should be suppressed. + """ + try: + relative_path = str(file_path.relative_to(src_dir)) + return relative_path in TEMPORARY_ALLOWLIST + except ValueError: + return False + + +def check_allowlist_expiration() -> tuple[bool, str]: + """Check if allowlist expiration date is approaching or passed. + + Returns: + Tuple of (is_warning, message). is_warning is True if expiration + is approaching or passed. + """ + from datetime import UTC, datetime + + today = datetime.now(tz=UTC).date() + days_until_expiration = (ALLOWLIST_EXPIRATION_DATE - today).days + + if days_until_expiration < 0: + return True, ( + f"ALLOWLIST EXPIRED: The temporary allowlist expired on " + f"{ALLOWLIST_EXPIRATION_DATE}. Please review and remove allowlisted " + f"items or update the expiration date." + ) + elif days_until_expiration <= ALLOWLIST_WARNING_DAYS: + return True, ( + f"ALLOWLIST EXPIRING SOON: The temporary allowlist expires in " + f"{days_until_expiration} days ({ALLOWLIST_EXPIRATION_DATE}). " + f"Please review allowlisted items." + ) + return False, "" + + +def get_changed_files(src_dir: Path) -> list[Path]: + """Get Python files changed in current git branch compared to main. + + Uses git diff to find changed .py files. Returns empty list if: + - git is not available (FileNotFoundError) + - Not in a git repository + - Neither origin/main nor origin/master exists + - No Python files changed + + The caller should handle empty list by falling back to checking all files. + + Args: + src_dir: Source directory to filter results (resolved paths). + + Returns: + List of resolved changed Python file paths within src_dir, + or empty list if git operations fail. + """ + import subprocess + + try: + # Get files changed compared to main/master branch + # Use a loop to avoid running two git commands in repos using master + result = None + for branch in ["origin/main", "origin/master"]: + result = subprocess.run( + ["git", "diff", "--name-only", branch, "--", "*.py"], + capture_output=True, + text=True, + check=False, + cwd=src_dir.parent.parent, # Run from repo root for correct paths + ) + if result.returncode == 0: + break # Found a valid branch, no need to try others + + if result is not None and result.returncode == 0 and result.stdout.strip(): + changed_files = [] + src_dir_resolved = src_dir.resolve() + repo_root = src_dir.parent.parent.resolve() + for line in result.stdout.strip().split("\n"): + # Git returns paths relative to repo root + file_path = repo_root / line + # Only include files within src_dir using proper path comparison + # (avoids false positives from string containment) + if file_path.exists(): + resolved = file_path.resolve() + try: + resolved.relative_to(src_dir_resolved) + changed_files.append(resolved) + except ValueError: + pass # File is not within src_dir + return sorted(changed_files) + except FileNotFoundError: + pass # git not available + except OSError: + pass # Not in a git repository or other OS error + + return [] # Return empty list if git fails + + +def main() -> int: + """Main entry point for the transport import validation script. + + Parses command line arguments, finds Python files, runs transport + import analysis, and reports results. + + Returns: + Exit code: + - 0: No transport import violations found + - 1: Transport import violations detected + - 2: Script error (invalid arguments, file not found, etc.) + """ + parser = argparse.ArgumentParser( + description="Validate omnibase_core does not import transport libraries directly" + ) + parser.add_argument( + "--verbose", + "-v", + action="store_true", + help="Enable verbose output with code snippets", + ) + parser.add_argument( + "--file", + "-f", + type=Path, + help="Check a specific file instead of all Python files", + ) + parser.add_argument( + "--src-dir", + type=Path, + default=None, + help="Source directory (default: src/omnibase_core)", + ) + parser.add_argument( + "--json", + action="store_true", + help="Output results as JSON for machine processing", + ) + parser.add_argument( + "--changed-files", + action="store_true", + help="Only check files changed in current git branch (speeds up CI)", + ) + + args = parser.parse_args() + + # Determine source directory + if args.src_dir: + src_dir = args.src_dir + else: + cwd = Path.cwd() + src_dir = cwd / "src" / "omnibase_core" + + if not src_dir.exists(): + script_dir = Path(__file__).parent + src_dir = script_dir.parent / "src" / "omnibase_core" + + if not src_dir.exists(): + error_msg = f"Error: Source directory not found: {src_dir}" + if args.json: + print(json.dumps({"error": error_msg})) + else: + print(error_msg, file=sys.stderr) + return 2 + + # Find files to analyze + if args.file: + if not args.file.exists(): + error_msg = f"Error: File not found: {args.file}" + if args.json: + print(json.dumps({"error": error_msg})) + else: + print(error_msg, file=sys.stderr) + return 2 + python_files = [args.file] + else: + python_files = find_python_files(src_dir) + + # Filter to only changed files if --changed-files flag is set + if args.changed_files: + changed = get_changed_files(src_dir) + if changed: + python_files = [f for f in python_files if f in changed] + if args.verbose and not args.json: + print( + f"Checking {len(python_files)} changed files (--changed-files mode)" + ) + elif args.verbose and not args.json: + print("No changed Python files detected, checking all files") + + if not python_files: + if args.json: + print( + json.dumps( + { + "summary": { + "total_files": 0, + "clean_files": 0, + "files_with_violations": 0, + "total_violations": 0, + }, + "results": [], + } + ) + ) + else: + print("No Python files found to analyze") + return 0 + + if args.verbose and not args.json: + print(f"Analyzing {len(python_files)} Python files in {src_dir}") + print() + + # Check allowlist expiration + is_expiring, expiration_msg = check_allowlist_expiration() + if is_expiring and not args.json: + print(f"WARNING: {expiration_msg}", file=sys.stderr) + print() + + # Analyze each file + results: list[TransportCheckResult] = [] + allowlisted_violations: list[TransportCheckResult] = [] + for file_path in python_files: + result = analyze_file(file_path) + # Check if file is allowlisted (suppress violations for pre-existing issues) + if result.violations and _is_allowlisted(file_path, src_dir): + allowlisted_violations.append(result) + # Mark as clean since it's allowlisted + result = TransportCheckResult( + file_path=result.file_path, + violations=[], + is_clean=True, + skip_reason="Allowlisted (pre-existing violation, see TEMPORARY_ALLOWLIST)", + ) + results.append(result) + + # Calculate summary statistics + total_files = len(results) + clean_files = sum(1 for r in results if r.is_clean) + files_with_violations = sum(1 for r in results if not r.is_clean) + total_violations = sum(len(r.violations) for r in results) + allowlisted_count = len(allowlisted_violations) + + # Output results + if args.json: + output: dict[str, object] = { + "summary": { + "total_files": total_files, + "clean_files": clean_files, + "files_with_violations": files_with_violations, + "total_violations": total_violations, + "allowlisted_files": allowlisted_count, + "allowlist_expiration_warning": expiration_msg if is_expiring else None, + }, + "results": [ + { + "file": str(r.file_path), + "is_clean": r.is_clean, + "skip_reason": r.skip_reason, + "violations": [ + { + "line": v.line_number, + "column": v.column, + "type": v.violation_type.value, + "severity": v.severity.value, + "message": v.message, + "suggestion": v.suggestion, + } + for v in r.violations + ], + } + for r in results + if r.violations or r.skip_reason + ], + } + print(json.dumps(output, indent=2)) + return 0 if files_with_violations == 0 else 1 + + # Text output + for result in results: + if result.skip_reason and args.verbose: + relative_path = _safe_relative_path(result.file_path, src_dir.parent.parent) + print(f"SKIP: {relative_path} - {result.skip_reason}") + continue + + if result.violations: + for violation in result.violations: + print(violation.format(args.verbose)) + + # Summary + print() + print("=" * 60) + print("Transport Import Check Summary") + print("=" * 60) + print(f" Total files scanned: {total_files}") + print(f" Clean files: {clean_files}") + print(f" Files with violations: {files_with_violations}") + print(f" Total violations: {total_violations}") + if allowlisted_count > 0: + print( + f" Allowlisted files: {allowlisted_count} (pre-existing, tracked for fix)" + ) + + if files_with_violations > 0: + print() + print("FAILED: Transport import violations detected") + print() + print("Transport libraries should not be imported directly in omnibase_core.") + print( + "These belong in omnibase_spi or service layers that implement protocols." + ) + print() + print("Protocol alternatives:") + for transport, protocol in sorted(TRANSPORT_ALTERNATIVES.items()): + print(f" - {transport} -> {protocol}") + return 1 + + print() + print("PASSED: No transport import violations found") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/cleanup.py b/scripts/cleanup.py index af5a2c09ff..da876611ed 100755 --- a/scripts/cleanup.py +++ b/scripts/cleanup.py @@ -7,13 +7,19 @@ files generated during development and analysis. Usage: - poetry run python scripts/cleanup.py [--dry-run] [--verbose] [--remove-from-git] + poetry run python scripts/cleanup.py [--dry-run] [--verbose] [--remove-from-git] [--tmp-only] Options: --dry-run Show what would be removed without removing --verbose, -v Show detailed output --remove-from-git Remove tracked files from git index (for tmp/ cleanup) --root DIR Root directory to clean (default: current directory) + --tmp-only Only clean tmp/ directory (preserves caches) + Use this for pre-commit/pre-push hooks! + +IMPORTANT: For pre-commit/pre-push hooks, ALWAYS use --tmp-only to avoid +invalidating mypy_cache, ruff_cache, pytest_cache which take significant +time to rebuild. """ import argparse @@ -62,8 +68,10 @@ r".*\.so$", ] -# Directories to clean up entirely -CLEANUP_DIRECTORIES = [ +# Directories to clean up entirely (FULL cleanup mode only) +# WARNING: These caches take significant time to rebuild! +# Use --tmp-only for pre-commit/pre-push hooks to avoid cache invalidation +CLEANUP_DIRECTORIES_FULL = [ "__pycache__", ".mypy_cache", ".ruff_cache", @@ -76,6 +84,11 @@ "tmp", # Temporary files and PR review cache ] +# Directories to clean in --tmp-only mode (safe for pre-commit/pre-push) +CLEANUP_DIRECTORIES_TMP_ONLY = [ + "tmp", # Only temporary files, preserves all caches +] + # Directories to skip entirely during traversal SKIP_DIRS = {".git", ".venv", "venv", "ENV", "env", "node_modules"} @@ -85,17 +98,34 @@ def compile_patterns(patterns: list[str]) -> list[Pattern[str]]: return [re.compile(pattern) for pattern in patterns] -def find_cleanup_files(root_dir: Path, patterns: list[Pattern[str]]) -> list[Path]: - """Find files matching cleanup patterns.""" +def find_cleanup_files( + root_dir: Path, patterns: list[Pattern[str]], tmp_only: bool = False +) -> list[Path]: + """Find files matching cleanup patterns. + + Args: + root_dir: Root directory to search + patterns: Compiled regex patterns for file matching + tmp_only: If True, only clean tmp/ directory (preserves caches) + """ cleanup_files = [] + # Select which directories to clean based on mode + cleanup_dirs = ( + CLEANUP_DIRECTORIES_TMP_ONLY if tmp_only else CLEANUP_DIRECTORIES_FULL + ) + + # In tmp_only mode, skip pattern matching entirely - just find tmp dirs + if tmp_only: + patterns = [] + for root, dirs, files in os.walk(root_dir): root_path = Path(root) # Skip excluded directories dirs[:] = [d for d in dirs if d not in SKIP_DIRS] - # Check files + # Check files (only in full mode) for file in files: file_path = root_path / file relative_path = file_path.relative_to(root_dir) @@ -107,7 +137,7 @@ def find_cleanup_files(root_dir: Path, patterns: list[Pattern[str]]) -> list[Pat # Check directories for dir_name in dirs[:]: # Create a copy to modify during iteration - if dir_name in CLEANUP_DIRECTORIES: + if dir_name in cleanup_dirs: dir_path = root_path / dir_name cleanup_files.append(dir_path) dirs.remove(dir_name) # Don't recurse into directories we're removing @@ -212,6 +242,12 @@ def main() -> int: default=".", help="Root directory to clean (default: current directory)", ) + parser.add_argument( + "--tmp-only", + action="store_true", + help="Only clean tmp/ directory (preserves mypy/ruff/pytest caches). " + "Use this for pre-commit/pre-push hooks to avoid cache invalidation.", + ) args = parser.parse_args() @@ -247,12 +283,14 @@ def main() -> int: logger.info("Cleaning up repository: %s", root_dir) if args.dry_run: logger.info("DRY RUN MODE - No files will be actually removed") + if args.tmp_only: + logger.info("TMP-ONLY MODE - Only cleaning tmp/ directory") # Compile cleanup patterns patterns = compile_patterns(CLEANUP_PATTERNS) # Find files to clean up - cleanup_files = find_cleanup_files(root_dir, patterns) + cleanup_files = find_cleanup_files(root_dir, patterns, tmp_only=args.tmp_only) if not cleanup_files: if args.verbose: diff --git a/src/omnibase_core/models/service/model_service_compute.py b/src/omnibase_core/models/service/model_service_compute.py index 913aa48f11..9713304d37 100644 --- a/src/omnibase_core/models/service/model_service_compute.py +++ b/src/omnibase_core/models/service/model_service_compute.py @@ -58,9 +58,9 @@ async def execute_compute(self, contract: ModelContractCompute) -> dict: from omnibase_core.nodes.node_compute import NodeCompute -class ModelServiceCompute[T_Input, T_Output]( +class ModelServiceCompute( MixinNodeService, - NodeCompute[T_Input, T_Output], + NodeCompute, MixinHealthCheck, MixinCaching, MixinMetrics, diff --git a/src/omnibase_core/nodes/node_compute.py b/src/omnibase_core/nodes/node_compute.py index 5239364028..d6ed381558 100644 --- a/src/omnibase_core/nodes/node_compute.py +++ b/src/omnibase_core/nodes/node_compute.py @@ -1,8 +1,4 @@ """ -VERSION: 1.0.0 -STABILITY GUARANTEE: Abstract method signatures frozen. -Breaking changes require major version bump. - NodeCompute - Pure Computation Node for 4-Node Architecture. Specialized node type for pure computational operations with deterministic guarantees. @@ -14,11 +10,6 @@ - Computational pipeline with parallel processing - Caching layer for expensive computations - Algorithm registration and execution - -STABLE INTERFACE v1.0.0 - DO NOT CHANGE without major version bump. -Code generators can target this stable interface. - -Author: ONEX Framework Team """ import asyncio @@ -26,14 +17,13 @@ import time from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor -from typing import TYPE_CHECKING, Any +from typing import Any, TypeVar from omnibase_core.enums.enum_core_error_code import EnumCoreErrorCode -if TYPE_CHECKING: - from omnibase_core.models.contracts.model_contract_compute import ( - ModelContractCompute, - ) +# Type variables for generic compute input/output +T_Input = TypeVar("T_Input") +T_Output = TypeVar("T_Output") from omnibase_core.enums.enum_log_level import EnumLogLevel as LogLevel from omnibase_core.infrastructure.node_config_provider import NodeConfigProvider from omnibase_core.infrastructure.node_core_base import NodeCoreBase @@ -45,204 +35,27 @@ from omnibase_core.models.infrastructure import ModelComputeCache -class NodeCompute[T_Input, T_Output](NodeCoreBase): +class NodeCompute(NodeCoreBase): """ - STABLE INTERFACE v1.0.0 - DO NOT CHANGE without major version bump. - Pure computation node for deterministic operations. - Implements computational pipeline with input -> transform -> output pattern. + Implements computational pipeline with input → transform → output pattern. Provides caching, parallel processing, and performance optimization for compute-intensive operations. - .. versionadded:: 0.4.0 - Added PEP 695 generic type parameters and execute_compute() contract interface. - - Type Parameters: - T_Input: The input data type for computations. - Example: dict[str, Any], ModelUserData, list[ModelMetric] - T_Output: The output data type from computations. - Example: ModelComputeResult, dict[str, float], list[ModelPrediction] - - Type flow: - Input data (T_Input) -> computation -> Output result (T_Output) - T_Output is typically the same as T_Input or a transformation thereof. - - Example with concrete types:: - - class NodeStringProcessor(NodeCompute[str, str]): - '''Process string inputs to string outputs.''' - - async def process( - self, input_data: ModelComputeInput[str] - ) -> ModelComputeOutput[str]: - result = input_data.data.upper() - return ModelComputeOutput( - result=result, - operation_id=input_data.operation_id, - computation_type=input_data.computation_type, - processing_time_ms=0.0, - cache_hit=False, - parallel_execution_used=False, - metadata={}, - ) - - class NodeMetricsAggregator(NodeCompute[list[float], dict[str, float]]): - '''Aggregate numeric metrics into statistics.''' - - async def process( - self, input_data: ModelComputeInput[list[float]] - ) -> ModelComputeOutput[dict[str, float]]: - values = input_data.data - result = { - "sum": sum(values), - "avg": sum(values) / len(values) if values else 0.0, - "count": float(len(values)), - } - return ModelComputeOutput( - result=result, - operation_id=input_data.operation_id, - computation_type="metrics_aggregation", - processing_time_ms=0.0, - cache_hit=False, - parallel_execution_used=False, - metadata={}, - ) - Key Features: - - Pure function patterns (no side effects) - - Deterministic operation guarantees - - Parallel processing support for batch operations - - Intelligent caching layer for expensive computations - - Performance monitoring and optimization - - Type-safe input/output handling - - Caching Strategy: - NodeCompute implements a deterministic caching layer to optimize expensive - computations. The caching system uses a content-addressable approach with - SHA256 hashing to ensure consistent cache behavior. - - **Cache Key Generation**: - Cache keys are generated using SHA256 hashing of the input data combined - with the computation type. This approach provides: - - - **Determinism**: Identical inputs always produce identical cache keys, - ensuring consistent cache behavior across process restarts - - **Collision Resistance**: SHA256's cryptographic properties virtually - eliminate hash collisions, preventing incorrect cache hits - - **Cross-Process Consistency**: Unlike Python's built-in ``hash()``, - SHA256 produces consistent results across different Python processes - and interpreter sessions - - Format: ``{computation_type}:{sha256_hex_digest}`` - - Example: ``sum_numbers:a3b2c1d4e5f6...`` - - **Cache Invalidation Policies**: - The cache supports multiple invalidation strategies: - - 1. **TTL-Based Expiration** (Primary): - - Each cached entry has a time-to-live (TTL) configured via - ``cache_ttl_minutes`` (default: 30 minutes) - - Expired entries are automatically detected on access and removed - - TTL can be customized per-entry or globally via container config - - 2. **Manual Cache Clearing**: - - Call ``computation_cache.clear()`` to invalidate all entries - - Useful for forced refresh or during node cleanup - - Automatically called during ``_cleanup_node_resources()`` - - 3. **Eviction Policy** (Memory Management): - - Configured via ``ModelComputeCache.eviction_policy`` - - **LRU** (Least Recently Used): Evicts entries not accessed recently - - **LFU** (Least Frequently Used): Evicts entries with lowest access count - - **FIFO** (First In First Out): Evicts oldest entries by insertion time - - Eviction triggers when cache reaches ``max_size`` (default: 1000) - - **Cache Configuration**: - Cache behavior is configured through ``ModelONEXContainer.compute_cache_config``: - - - ``max_size``: Maximum number of cached entries (default: 1000) - - ``ttl_seconds``: Time-to-live in seconds (default: 1800 = 30 min) - - ``eviction_policy``: LRU, LFU, or FIFO (default: LRU) - - ``enable_stats``: Enable hit/miss tracking (default: True) - - **Configuration Example**:: - - from omnibase_core.models.container import ModelONEXContainer - from omnibase_core.models.infrastructure import ModelComputeCacheConfig - - # Create cache configuration - cache_config = ModelComputeCacheConfig( - max_size=5000, # Cache up to 5000 entries - ttl_seconds=3600, # 1 hour TTL - eviction_policy="LRU", # Least Recently Used eviction - enable_stats=True, # Enable hit/miss tracking - ) - - # Create container with custom cache configuration - container = ModelONEXContainer( - compute_cache_config=cache_config, - ) - - # Create node with configured caching - node = NodeCompute(container) - - **Runtime Configuration** (via NodeConfigProvider):: - - # Cache settings can also be loaded from NodeConfigProvider - # if registered in the container. Keys used: - # - "compute.cache_ttl_minutes": Cache TTL in minutes - # - "compute.max_parallel_workers": Thread pool size - # - "compute.performance_threshold_ms": Warning threshold - - **Cache Implications**: - - **Cache Hits**: Return cached result with ``processing_time_ms=0.0``. - This value represents *semantic computation time* (no actual computation - work was performed), not total elapsed time. Cache lookup overhead - (SHA256 hashing, dictionary access) is intentionally excluded to - distinguish "work done" from "time elapsed". - - **Cache Misses**: Execute computation, cache result if ``cache_enabled=True`` - - **String Serialization**: Input data is converted to string for hashing; - complex objects should implement consistent ``__str__`` methods + - Pure function patterns (no side effects) + - Deterministic operation guarantees + - Parallel processing support for batch operations + - Intelligent caching layer for expensive computations + - Performance monitoring and optimization + - Type-safe input/output handling Thread Safety: - Instance NOT thread-safe due to mutable cache state - Use separate instances per thread OR implement cache locking - Parallel processing via ThreadPoolExecutor is internally managed - See docs/THREADING.md for production guidelines and examples - - Note: - **Parallel Processing Guidance** - - When to enable parallel processing (``parallel_enabled=True``): - - Batch operations on independent data items (e.g., transforming a list of records) - - CPU-bound computations that can be partitioned (e.g., processing chunks of data) - - Map operations where each element is processed independently - - Computation types that benefit from parallelization: - - **Batch transformations**: Processing lists/tuples of independent items - - **Aggregations over large datasets**: sum, average, statistical computations - - **Independent element processing**: Operations where each list item is processed - without dependencies on other items - - Computation types that do NOT benefit from parallelization: - - **Single-value operations**: String transformations, single object processing - - **Sequential dependencies**: Operations where item N depends on item N-1 - - **Small datasets**: Overhead of thread pool exceeds computation time - - **I/O-bound operations**: Use NodeEffect for I/O; parallel threads don't help - - Thread pool configuration: - - Default: 4 workers (configurable via ``max_parallel_workers``) - - Pool is lazily initialized during ``_initialize_node_resources()`` - - Workers are reused across computations for efficiency - - Shutdown with 5s timeout during ``_cleanup_node_resources()`` - - Performance considerations: - - Parallel execution adds overhead (~1-5ms for thread pool dispatch) - - Only use for computations where per-item processing > 10ms - - Data must be a list or tuple with more than 1 element - - If data is not parallelizable, falls back to sequential execution with a warning """ def __init__(self, container: ModelONEXContainer) -> None: @@ -282,378 +95,24 @@ def __init__(self, container: ModelONEXContainer) -> None: # Performance tracking self.computation_metrics: dict[str, dict[str, float]] = {} - self.parallel_execution_warning_count: int = ( - 0 # Track parallel misconfigurations - ) # Register built-in computations self._register_builtin_computations() - async def execute_compute( - self, - contract: "ModelContractCompute", # Quoted for TYPE_CHECKING import (avoids circular dependency) - ) -> ModelComputeOutput[T_Output]: - """ - Execute compute operation based on contract specification. - - REQUIRED INTERFACE: This public method implements the ModelContractCompute - interface per ONEX guidelines. It provides a contract-based entry point - that delegates to the internal process() method. - - This method validates the contract type before processing to ensure - type safety and provide clear error messages for invalid contracts. - - .. versionadded:: 0.4.0 - - Args: - contract: The compute contract specification. Must be an instance of - ModelContractCompute. The contract should contain: - - input_state: Input data for computation (required) - - metadata: Optional metadata dict with computation_type, cache_enabled, - and parallel_enabled settings - - Returns: - ModelComputeOutput[T_Output]: Computation results containing: - - result: The computed output value - - operation_id: Unique identifier for this operation - - computation_type: Type of computation performed - - processing_time_ms: Time taken for computation - - cache_hit: Whether result was retrieved from cache - - parallel_execution_used: Whether parallel processing was used - - metadata: Additional operation metadata - - Raises: - ModelOnexError: If contract type is invalid (not ModelContractCompute), - computation fails, or input validation fails. Error codes: - - VALIDATION_ERROR: Invalid contract type or missing required fields - - OPERATION_FAILED: Computation execution failure - - Example: - Using the built-in ``string_uppercase`` computation:: - - >>> from omnibase_core.models.contracts import ModelContractCompute - >>> from omnibase_core.models.contracts import ModelContractAlgorithm - >>> contract = ModelContractCompute( - ... name="uppercase_transform", - ... version="1.0.0", - ... input_state="hello world", # Direct string input for string_uppercase - ... algorithm=ModelContractAlgorithm(algorithm_type="string_uppercase"), - ... ) - >>> result = await node.execute_compute(contract) - >>> print(result.result) # "HELLO WORLD" - - Using the built-in ``sum_numbers`` computation:: - - >>> contract = ModelContractCompute( - ... name="sum_values", - ... version="1.0.0", - ... input_state=[1.0, 2.0, 3.0, 4.0], # Direct list input for sum_numbers - ... algorithm=ModelContractAlgorithm(algorithm_type="sum_numbers"), - ... ) - >>> result = await node.execute_compute(contract) - >>> print(result.result) # 10.0 - - Note: - This method requires a ModelContractCompute instance. If you need - to process raw input data directly, use the process() method with - a ModelComputeInput instance instead. - """ - # Import here to avoid circular dependency - from omnibase_core.models.contracts.model_contract_compute import ( - ModelContractCompute, - ) - - if not isinstance(contract, ModelContractCompute): - raise ModelOnexError( - error_code=EnumCoreErrorCode.VALIDATION_ERROR, - message="Invalid contract type - must be ModelContractCompute", - context={ - "node_id": str(self.node_id), - "provided_type": type(contract).__name__, - "expected_type": "ModelContractCompute", - }, - ) - - # Convert contract to ModelComputeInput - compute_input = self._contract_to_input(contract) - return await self.process(compute_input) - - def _extract_computation_type( - self, - metadata: dict[str, Any], - contract_algorithm: Any, - contract_computation_type: Any, - ) -> str: - """ - Extract computation type from cached contract attributes or metadata. - - Uses a priority-based extraction strategy to find the computation type - from various locations in the contract structure, supporting both - algorithm-based contracts and metadata-based configurations. - - Priority order: - 1. contract_algorithm.algorithm_type (preferred for ModelContractCompute) - 2. metadata["computation_type"] (for legacy or custom contracts) - 3. contract_computation_type (direct attribute, if exists) - 4. Default: "default" (identity transformation) - - Args: - metadata: Extracted metadata dictionary, may contain "computation_type" - key as an alternative source. - contract_algorithm: Pre-cached algorithm attribute from contract (or None). - Expected to have an optional algorithm_type attribute. - contract_computation_type: Pre-cached computation_type attribute from - contract (or None). - - Returns: - str: The computation type identifier to use for looking up the - registered computation function. Returns "default" if no - computation type is found in any source. - - Example: - >>> # Contract with algorithm configuration (preferred) - >>> contract.algorithm.algorithm_type = "sum_numbers" - >>> _extract_computation_type({}, contract.algorithm, None) - "sum_numbers" - - >>> # Contract with metadata-based type - >>> _extract_computation_type({"computation_type": "custom"}, None, None) - "custom" - """ - # Check algorithm configuration first (preferred for ModelContractCompute) - if contract_algorithm is not None: - algorithm_type = getattr(contract_algorithm, "algorithm_type", None) - if algorithm_type is not None: - return str(algorithm_type) - - # Check metadata next - if "computation_type" in metadata: - return str(metadata["computation_type"]) - - # Check contract attribute (pre-cached value) - if contract_computation_type is not None: - return str(contract_computation_type) - - return "default" - - def _contract_to_input(self, contract: Any) -> ModelComputeInput[Any]: - """ - Convert ModelContractCompute to ModelComputeInput for processing. - - This method extracts computation parameters from a validated contract - and constructs a ModelComputeInput instance suitable for the process() - method. It enforces that input data is present and logs warnings for - missing optional fields. - - Args: - contract: The compute contract to convert. Must be a validated - ModelContractCompute instance with: - - input_state (required): Input data for computation (any serializable type) - - metadata (optional): Dict with computation settings - - algorithm (optional): Algorithm configuration with computation_type - - Returns: - ModelComputeInput[Any]: Input model configured with: - - data: The input data from contract.input_state - - computation_type: Type of computation to perform - - cache_enabled: Whether to use caching (default: True) - - parallel_enabled: Whether to enable parallel processing (default: False) - - metadata: Additional metadata from contract - - Raises: - ModelOnexError: If contract.input_state is missing or None, indicating - a contract configuration error. Error code: VALIDATION_ERROR - - Example: - Converting a contract for ``sum_numbers`` computation:: - - >>> from omnibase_core.models.contracts import ModelContractCompute - >>> from omnibase_core.models.contracts import ModelContractAlgorithm - >>> contract = ModelContractCompute( - ... name="sum_values", - ... version="1.0.0", - ... input_state=[1.0, 2.0, 3.0], # Direct list - sum_numbers expects list[float] - ... algorithm=ModelContractAlgorithm(algorithm_type="sum_numbers"), - ... ) - >>> compute_input = node._contract_to_input(contract) - >>> # compute_input.data == [1.0, 2.0, 3.0] - >>> # compute_input.computation_type == "sum_numbers" - - Converting a contract for ``string_uppercase`` computation:: - - >>> contract = ModelContractCompute( - ... name="uppercase", - ... version="1.0.0", - ... input_state="hello", # Direct string - string_uppercase expects str - ... algorithm=ModelContractAlgorithm(algorithm_type="string_uppercase"), - ... ) - >>> compute_input = node._contract_to_input(contract) - >>> # compute_input.data == "hello" - >>> # compute_input.computation_type == "string_uppercase" - - Note: - This method expects execute_compute() to have already validated - that contract is a ModelContractCompute instance. Direct calls - should ensure proper contract type validation. - """ - # Cache contract attributes to avoid redundant getattr calls - contract_input_state = getattr(contract, "input_state", None) - contract_input_data = getattr(contract, "input_data", None) - contract_metadata = getattr(contract, "metadata", None) - contract_algorithm = getattr(contract, "algorithm", None) - contract_computation_type = getattr(contract, "computation_type", None) - - # Extract input_state from contract - this is the primary input data field - # for ModelContractCompute (not input_data which is used in simpler contracts) - input_data: Any = contract_input_state - - # Validate that input_state is present - it's required for computation - if input_data is None: - # Check for legacy input_data attribute as fallback - input_data = contract_input_data - - if input_data is None: - raise ModelOnexError( - error_code=EnumCoreErrorCode.VALIDATION_ERROR, - message="Contract must have 'input_state' or 'input_data' attribute with computation input", - context={ - "node_id": str(self.node_id), - "contract_type": type(contract).__name__, - "checked_attributes": ["input_state", "input_data"], - "input_state_value": "None", - "input_data_value": "None", - "hint": "Ensure contract.input_state contains the data to be processed", - }, - ) - - # Log warning for legacy input_data usage - emit_log_event( - LogLevel.WARNING, - "Contract uses legacy 'input_data' instead of 'input_state'", - { - "node_id": str(self.node_id), - "contract_type": type(contract).__name__, - "recommendation": "Migrate to using 'input_state' field", - }, - ) - - # Extract metadata from contract (optional field) - # Use empty dict as default for falsy values (None, empty dict) - metadata: dict[str, Any] = contract_metadata or {} - - # Extract computation_type using helper method with cached contract attributes - computation_type = self._extract_computation_type( - metadata, contract_algorithm, contract_computation_type - ) - - # Extract cache and parallel settings from metadata or use defaults - # NOTE: bool() coerces truthy/falsy values per Python semantics. - # Runtime warnings are emitted below when string values are detected. - cache_value = metadata.get("cache_enabled", True) - if isinstance(cache_value, str): - # Warn about string coercion - common mistake that's hard to debug - # e.g., string "false" coerces to True, which is unexpected - emit_log_event( - LogLevel.WARNING, - "cache_enabled received string value instead of boolean. " - "String values coerce to True (including 'false'). Use actual booleans.", - { - "node_id": str(self.node_id), - "received_value": cache_value, - "coerced_to": bool(cache_value), - "recommendation": "Pass cache_enabled=False (boolean) not cache_enabled='false' (string)", - }, - ) - cache_enabled: bool = bool(cache_value) - - parallel_value = metadata.get("parallel_enabled", False) - if isinstance(parallel_value, str): - # Warn about string coercion - common mistake that's hard to debug - # e.g., string "false" coerces to True, which is unexpected - emit_log_event( - LogLevel.WARNING, - "parallel_enabled received string value instead of boolean. " - "String values coerce to True (including 'false'). Use actual booleans.", - { - "node_id": str(self.node_id), - "received_value": parallel_value, - "coerced_to": bool(parallel_value), - "recommendation": "Pass parallel_enabled=True (boolean) not parallel_enabled='true' (string)", - }, - ) - parallel_enabled: bool = bool(parallel_value) - - return ModelComputeInput( - data=input_data, - computation_type=computation_type, - cache_enabled=cache_enabled, - parallel_enabled=parallel_enabled, - metadata=metadata, - ) - async def process( self, input_data: ModelComputeInput[T_Input] ) -> ModelComputeOutput[T_Output]: """ - Execute pure computation with caching and parallel processing support. - - STABLE INTERFACE: This method signature is frozen for code generation. - Subclasses should override this method to implement custom computation logic. - - This is the primary entry point for direct computation without contract - validation. It handles: - - Cache lookup and storage (when cache_enabled=True) - - Parallel execution (when parallel_enabled=True and data is parallelizable) - - Performance monitoring and threshold warnings - - Metrics tracking for observability + REQUIRED: Execute pure computation. Args: - input_data: Strongly typed computation input containing: - - data (T_Input): The input data to process - - computation_type (str): Registered computation type to execute - - cache_enabled (bool): Whether to use caching (default: True) - - parallel_enabled (bool): Whether to use parallel execution (default: False) - - operation_id (UUID): Unique identifier for this operation - - metadata (dict): Optional additional metadata + input_data: Strongly typed computation input Returns: - ModelComputeOutput[T_Output]: Computation results containing: - - result (T_Output): The computed output value - - operation_id (UUID): Echoed from input for correlation - - computation_type (str): The computation type that was executed - - processing_time_ms (float): Time taken in milliseconds - - cache_hit (bool): True if result was retrieved from cache - - parallel_execution_used (bool): True if parallel processing was used - - metadata (dict): Additional output metadata + Strongly typed computation output with performance metrics Raises: - ModelOnexError: If computation fails. Error codes: - - VALIDATION_ERROR: Invalid input data structure - - OPERATION_FAILED: Computation execution failure or unknown computation type - - Example: - Direct usage with ModelComputeInput:: - - >>> from omnibase_core.models.compute import ModelComputeInput - >>> input_data = ModelComputeInput( - ... data=[1.0, 2.0, 3.0, 4.0], - ... computation_type="sum_numbers", - ... cache_enabled=True, - ... parallel_enabled=False, - ... ) - >>> result = await node.process(input_data) - >>> print(result.result) # 10.0 - >>> print(result.cache_hit) # False (first call) - - Subsequent call with same input (cache hit):: - - >>> result2 = await node.process(input_data) - >>> print(result2.cache_hit) # True - - Note: - For contract-based execution with validation, use execute_compute() instead. - Performance warnings are logged when processing_time_ms exceeds - performance_threshold_ms (default: 100ms). + ModelOnexError: If computation fails or performance threshold exceeded """ # Use time.perf_counter() for accurate duration measurement # (monotonic, unaffected by system clock adjustments) @@ -662,61 +121,30 @@ async def process( try: self._validate_compute_input(input_data) + # Generate cache key + cache_key = self._generate_cache_key(input_data) + # Check cache first if enabled - # Measure cache lookup time separately for observability - cache_lookup_time_ms = 0.0 - cache_key: str | None = None if input_data.cache_enabled: - cache_lookup_start = time.perf_counter() - cache_key = self._generate_cache_key(input_data) cached_result = self.computation_cache.get(cache_key) - cache_lookup_time_ms = (time.perf_counter() - cache_lookup_start) * 1000 - if cached_result is not None: return ModelComputeOutput( result=cached_result, operation_id=input_data.operation_id, computation_type=input_data.computation_type, - processing_time_ms=0.0, # Semantic: no computation work - cache_lookup_time_ms=cache_lookup_time_ms, # Actual elapsed time + processing_time_ms=0.0, cache_hit=True, parallel_execution_used=False, metadata={"cache_retrieval": True}, ) - # No else branch needed - cache_key remains None when cache_enabled=False # Execute computation - supports_parallel = self._supports_parallel_execution(input_data) - if input_data.parallel_enabled and supports_parallel: + if input_data.parallel_enabled and self._supports_parallel_execution( + input_data + ): result = await self._execute_parallel_computation(input_data) parallel_used = True else: - # Warn if parallel was requested but data is not parallelizable - if input_data.parallel_enabled and not supports_parallel: - self.parallel_execution_warning_count += ( - 1 # Track for observability - ) - data_type = type(input_data.data).__name__ - data_length = ( - len(input_data.data) - if isinstance(input_data.data, (list, tuple)) - else "N/A" - ) - emit_log_event( - LogLevel.WARNING, - "Parallel execution requested but data is not parallelizable. " - "Falling back to sequential execution. " - "Parallel requires list/tuple with >1 element.", - { - "node_id": str(self.node_id), - "operation_id": str(input_data.operation_id), - "computation_type": input_data.computation_type, - "data_type": data_type, - "data_length": str(data_length), - "recommendation": "Set parallel_enabled=False for non-batch data, " - "or provide a list/tuple with multiple elements", - }, - ) result = await self._execute_sequential_computation(input_data) parallel_used = False @@ -734,8 +162,8 @@ async def process( }, ) - # Cache result if enabled (cache_key is always set when cache_enabled=True) - if input_data.cache_enabled and cache_key is not None: + # Cache result if enabled + if input_data.cache_enabled: self.computation_cache.put(cache_key, result, self.cache_ttl_minutes) # Update metrics @@ -752,7 +180,6 @@ async def process( operation_id=input_data.operation_id, computation_type=input_data.computation_type, processing_time_ms=processing_time, - cache_lookup_time_ms=0.0, # No cache lookup on miss or disabled cache_hit=False, parallel_execution_used=parallel_used, metadata={ @@ -772,9 +199,6 @@ async def process( ) await self._update_processing_metrics(processing_time, False) - # Preserve original exception context for debugging - # Include error_type to distinguish validation vs runtime errors - # Include cache_enabled and parallel_enabled for configuration debugging raise ModelOnexError( error_code=EnumCoreErrorCode.OPERATION_FAILED, message=f"Computation failed: {e!s}", @@ -782,10 +206,6 @@ async def process( "node_id": str(self.node_id), "operation_id": str(input_data.operation_id), "computation_type": input_data.computation_type, - "error_type": type(e).__name__, - "processing_time_ms": processing_time, - "cache_enabled": input_data.cache_enabled, - "parallel_enabled": input_data.parallel_enabled, }, ) from e @@ -793,47 +213,14 @@ def register_computation( self, computation_type: str, computation_func: Callable[..., Any] ) -> None: """ - Register a custom computation function for use with this node. - - Registered computations can be invoked via process() or execute_compute() - by specifying the computation_type. Functions should be pure (no side effects) - for deterministic behavior and safe caching. + Register custom computation function. Args: - computation_type: Unique string identifier for the computation. - Used to look up the function during execution. - Example: "calculate_average", "transform_json", "validate_schema" - computation_func: Pure function to register. Must be callable and accept - the input data as its first argument. The function signature should - match the expected T_Input type for this node. - Example: ``def my_func(data: list[float]) -> float`` + computation_type: Type identifier for computation + computation_func: Pure function to register Raises: - ModelOnexError: If validation fails. Error codes: - - VALIDATION_ERROR: computation_type already registered or - computation_func is not callable - - Example: - Registering a custom average computation:: - - >>> def calculate_average(data: list[float]) -> float: - ... if not data: - ... return 0.0 - ... return sum(data) / len(data) - >>> node.register_computation("calculate_average", calculate_average) - - Using the registered computation:: - - >>> input_data = ModelComputeInput( - ... data=[10.0, 20.0, 30.0], - ... computation_type="calculate_average", - ... ) - >>> result = await node.process(input_data) - >>> print(result.result) # 20.0 - - Note: - Built-in computations ("default", "string_uppercase", "sum_numbers") - are registered automatically during node initialization. + ModelOnexError: If computation type already registered """ if computation_type in self.computation_registry: raise ModelOnexError( @@ -858,40 +245,7 @@ def register_computation( ) async def get_computation_metrics(self) -> dict[str, dict[str, float]]: - """ - Get detailed computation performance metrics for monitoring and observability. - - Aggregates metrics from multiple sources including computation execution - statistics, cache performance, and parallel processing utilization. - - Returns: - dict[str, dict[str, float]]: Nested metrics dictionary containing: - - Per-computation-type metrics (keyed by computation_type): - - total_executions: Number of times this computation ran - - avg_processing_time_ms: Average execution time - - success_rate: Ratio of successful executions - - "cache_performance": Cache statistics - - total_entries: Total entries in cache - - valid_entries: Non-expired entries - - cache_utilization: valid_entries / max_size ratio - - ttl_minutes: Cache time-to-live setting - - "parallel_processing": Thread pool status - - max_workers: Maximum parallel workers configured - - thread_pool_active: 1.0 if pool is active, 0.0 otherwise - - execution_warnings: Count of times parallel was requested but not used - - Example: - >>> metrics = await node.get_computation_metrics() - >>> print(metrics["cache_performance"]["cache_utilization"]) - 0.75 - >>> print(metrics["sum_numbers"]["avg_processing_time_ms"]) - 2.5 - - Note: - Metrics are cumulative for the lifetime of the node instance. - Call this periodically for monitoring or after specific operations - for performance analysis. - """ + """Get detailed computation performance metrics.""" cache_stats = self.computation_cache.get_stats() return { @@ -906,7 +260,6 @@ async def get_computation_metrics(self) -> dict[str, dict[str, float]]: "parallel_processing": { "max_workers": float(self.max_parallel_workers), "thread_pool_active": float(1 if self.thread_pool else 0), - "execution_warnings": float(self.parallel_execution_warning_count), }, } @@ -997,201 +350,14 @@ def _validate_compute_input(self, input_data: ModelComputeInput[Any]) -> None: ) def _generate_cache_key(self, input_data: ModelComputeInput[Any]) -> str: - """ - Generate a deterministic cache key for computation input. - - This method creates a unique, reproducible cache key by combining the - computation type with a SHA256 hash of the input data. The resulting key - is used to store and retrieve cached computation results. - - **Cache Key Generation Strategy**: - - The cache key is generated using a content-addressable approach: - - 1. **Input Serialization**: The input data is converted to its string - representation using Python's ``str()`` function. This creates a - canonical text form of the data that can be hashed. - - 2. **SHA256 Hashing**: The string representation is encoded to UTF-8 bytes - and hashed using SHA256. SHA256 was chosen for several reasons: - - - **Determinism**: Unlike Python's built-in ``hash()`` function, which - uses randomized salting (PYTHONHASHSEED) and produces different values - across interpreter sessions, SHA256 always produces the same output - for the same input, ensuring cache consistency across process restarts. - - - **Collision Resistance**: SHA256's 256-bit output space (2^256 possible - values) makes hash collisions astronomically unlikely. This prevents - incorrect cache hits where different inputs might map to the same key. - - - **Cross-Process Consistency**: The same input will produce the same - cache key regardless of which Python process or machine generates it, - enabling distributed caching scenarios if needed in the future. - - 3. **Key Composition**: The final key combines the computation type and hash - in the format ``{computation_type}:{sha256_hex_digest}``. Including the - computation type ensures that identical data processed by different - computation functions will have distinct cache keys. - - **Key Format**:: - - {computation_type}:{64_character_hex_digest} - - **Examples**:: - - "sum_numbers:a3b4c5d6e7f8...9a0b" (64 hex chars after colon) - "string_uppercase:1234abcd5678..." - - **Cache Key Implications**: - - - **Cache Hits**: When the same input data and computation type are - processed again, the identical cache key will be generated, allowing - retrieval of the previously computed result. - - - **Cache Misses**: Any change to the input data (even whitespace) or - computation type will produce a different hash, resulting in a cache miss. - - - **String Serialization Caveat**: Complex objects should implement - consistent ``__str__`` methods to ensure deterministic serialization. - Objects with non-deterministic string representations (e.g., including - memory addresses or timestamps) will not cache effectively. - - Args: - input_data: The computation input containing: - - ``data``: The input data to be hashed (any type with ``__str__``) - - ``computation_type``: The type of computation to be performed - - Returns: - str: A cache key in the format ``{computation_type}:{sha256_hex_digest}`` - where the hex digest is a 64-character lowercase hexadecimal string. - - Example: - >>> input_data = ModelComputeInput( - ... data=[1.0, 2.0, 3.0], - ... computation_type="sum_numbers", - ... ) - >>> key = node._generate_cache_key(input_data) - >>> print(key) - "sum_numbers:7c9e1d8a3f2b..." # 64 hex chars after colon - - >>> # Same input produces same key (deterministic) - >>> key2 = node._generate_cache_key(input_data) - >>> assert key == key2 - - >>> # Different input produces different key - >>> different_input = ModelComputeInput( - ... data=[1.0, 2.0, 4.0], # Changed value - ... computation_type="sum_numbers", - ... ) - >>> different_key = node._generate_cache_key(different_input) - >>> assert key != different_key - - Note: - - This is a private method called internally by ``process()`` - - The cache key is used with ``ModelComputeCache.get()`` and ``put()`` - - See the class-level "Caching Strategy" documentation for full details - on cache invalidation policies and configuration options - - Security Note: - Cache keys are used for **internal deterministic caching only** and are - not cryptographically sensitive. SHA256 is chosen for its collision - resistance and determinism, not for cryptographic security. - - **Current Security Model**: - - Cache is process-local (not shared over network by default) - - No authentication required for cache access within the process - - No HMAC signing of cache entries - - **For Distributed Caching** (if implemented in future): - If cross-process cache sharing over untrusted networks is required, - additional security measures should be implemented: - - - **HMAC-based authentication**: Sign cache entries with a shared secret - to prevent cache poisoning attacks - - **Encryption**: Encrypt sensitive cached data at rest - - **Access control**: Implement per-key or per-namespace access policies - - **Cache isolation**: Use separate cache instances for different - security domains - - The current implementation assumes a trusted execution environment where - all cache access originates from the same process or trusted processes. - """ + """Generate deterministic cache key for computation input.""" data_str = str(input_data.data) # Use hashlib for deterministic hashing across Python processes data_hash = hashlib.sha256(data_str.encode()).hexdigest() return f"{input_data.computation_type}:{data_hash}" def _supports_parallel_execution(self, input_data: ModelComputeInput[Any]) -> bool: - """ - Check if computation input data supports parallel execution. - - Determines whether the input data structure is suitable for parallel - processing based on its type and size. Parallel execution is only - beneficial when data can be partitioned into independent chunks. - - Parallelizable Data Requirements: - - Must be a ``list`` or ``tuple`` (iterable with known length) - - Must contain more than 1 element (otherwise no parallelism benefit) - - Elements should be independently processable (no inter-element dependencies) - - Computation Types That Benefit from Parallelization: - - **Batch transformations**: Processing lists of records, documents, or objects - where each item can be transformed independently - - **Map operations**: Applying the same function to each element - (e.g., converting a list of strings to uppercase) - - **Aggregations over large datasets**: Operations like sum, average, - or statistical computations that can be partitioned and merged - - **Independent validations**: Validating each item in a batch independently - - Computation Types That Do NOT Benefit: - - **Single-value operations**: Strings, numbers, single objects - no partitioning possible - - **Small datasets**: Lists with 0-1 elements have no parallel work to distribute - - **Sequential dependencies**: Operations where item N depends on item N-1 - - **Fold/reduce with order**: Sequential reductions where order matters - - Performance Implications: - - Parallel execution adds ~1-5ms overhead for thread pool dispatch - - Only beneficial when per-item computation exceeds ~10ms - - Thread pool workers (default: 4) are reused across calls - - For small lists (2-10 items), overhead may exceed benefit - - Large datasets (100+ items) with CPU-bound operations see best gains - - Args: - input_data: The computation input containing the data to check. - The ``data`` attribute is examined for type and length. - - Returns: - bool: True if data is a list/tuple with more than 1 element, - False otherwise. When False, the process() method will - use sequential execution instead. - - Example: - >>> # Parallelizable - list with multiple elements - >>> input_data = ModelComputeInput(data=[1, 2, 3, 4, 5], ...) - >>> node._supports_parallel_execution(input_data) - True - - >>> # NOT parallelizable - single string value - >>> input_data = ModelComputeInput(data="hello", ...) - >>> node._supports_parallel_execution(input_data) - False - - >>> # NOT parallelizable - list with only 1 element - >>> input_data = ModelComputeInput(data=[42], ...) - >>> node._supports_parallel_execution(input_data) - False - - >>> # NOT parallelizable - empty list - >>> input_data = ModelComputeInput(data=[], ...) - >>> node._supports_parallel_execution(input_data) - False - - Note: - When ``parallel_enabled=True`` but this method returns False, - a WARNING log is emitted in ``process()`` to alert developers - that parallel execution was requested but could not be used. - The computation will fall back to sequential execution automatically. - """ + """Check if computation supports parallel execution.""" return bool( isinstance(input_data.data, (list, tuple)) and len(input_data.data) > 1 ) diff --git a/tests/unit/enums/test_enum_json_value_type.py b/tests/unit/enums/test_enum_json_value_type.py index 210c349537..4700e46585 100644 --- a/tests/unit/enums/test_enum_json_value_type.py +++ b/tests/unit/enums/test_enum_json_value_type.py @@ -74,7 +74,9 @@ def test_enum_all_values(self): def test_enum_docstring(self): """Test that enum has proper docstring""" - assert "ONEX-compliant JSON value type" in EnumJsonValueType.__doc__ + # Accept either "compliant" or "compatible" - both are valid ONEX descriptors + docstring = EnumJsonValueType.__doc__ or "" + assert "ONEX-" in docstring and "JSON value type" in docstring def test_enum_json_types(self): """Test specific JSON value types""" diff --git a/tests/unit/nodes/test_node_compute_execute.py b/tests/unit/nodes/test_node_compute_execute.py deleted file mode 100644 index 8eff89afee..0000000000 --- a/tests/unit/nodes/test_node_compute_execute.py +++ /dev/null @@ -1,1008 +0,0 @@ -""" -Unit tests for NodeCompute.execute_compute() and _contract_to_input() methods. - -Tests cover: -- Valid contract execution with process() delegation -- Invalid contract type handling with proper error codes -- Contract field extraction (input_state, legacy input_data) -- Computation type extraction from various sources -- Optional fields extraction (cache_enabled, parallel_enabled) - -Author: ONEX Framework Team -Version: 1.0.0 -""" - -from collections.abc import Callable -from typing import Any -from unittest.mock import AsyncMock, MagicMock, patch -from uuid import uuid4 - -import pytest - -from omnibase_core.enums.enum_core_error_code import EnumCoreErrorCode -from omnibase_core.models.compute.model_compute_input import ModelComputeInput -from omnibase_core.models.compute.model_compute_output import ModelComputeOutput -from omnibase_core.models.container.model_onex_container import ModelONEXContainer -from omnibase_core.models.contracts.model_contract_compute import ModelContractCompute -from omnibase_core.models.errors.model_onex_error import ModelOnexError -from omnibase_core.nodes.node_compute import NodeCompute - - -def _get_context_value(error: ModelOnexError, key: str) -> Any: - """ - Helper to extract context values from ModelOnexError. - - The error context structure is: - - Standard keys (file_path, line_number, etc.) are at top level - - Custom context keys are nested under 'additional_context' -> 'context' - - Args: - error: The ModelOnexError instance - key: The key to look for in context - - Returns: - The value if found, None otherwise - """ - context = error.context - # Check top level first - if key in context: - return context[key] - # Check in additional_context -> context - additional = context.get("additional_context", {}) - if isinstance(additional, dict): - inner_context = additional.get("context", {}) - if isinstance(inner_context, dict) and key in inner_context: - return inner_context[key] - return None - - -def _create_mock_contract( - input_state: Any = None, - input_data: Any = None, - metadata: dict[str, Any] | None = None, - algorithm: Any = None, - computation_type: str | None = None, -) -> MagicMock: - """ - Create a mock contract object that simulates ModelContractCompute. - - This is used to test _contract_to_input without needing the full - ModelContractCompute validation overhead. - - Args: - input_state: Value for input_state attribute - input_data: Value for input_data attribute (legacy) - metadata: Value for metadata attribute - algorithm: Mock algorithm config - computation_type: Optional computation_type attribute - - Returns: - MagicMock with appropriate attributes set - """ - mock = MagicMock(spec=ModelContractCompute) - mock.input_state = input_state - mock.input_data = input_data - mock.metadata = metadata or {} - mock.algorithm = algorithm - mock.computation_type = computation_type - return mock - - -@pytest.fixture -def test_container() -> ModelONEXContainer: - """Create a test container for NodeCompute initialization.""" - return ModelONEXContainer() - - -@pytest.fixture -def node(test_container: ModelONEXContainer) -> NodeCompute[Any, Any]: - """Create a NodeCompute instance for testing.""" - return NodeCompute(test_container) - - -@pytest.fixture -def mock_contract_factory() -> Callable[..., MagicMock]: - """ - Factory fixture for creating mock contracts with consistent defaults. - - This fixture provides a callable that wraps _create_mock_contract(), - allowing tests to create mock contracts with a consistent interface. - - Returns: - A callable that creates MagicMock contracts with the specified attributes. - - Example: - def test_example(mock_contract_factory): - contract = mock_contract_factory( - input_state={"data": "value"}, - metadata={"key": "value"}, - ) - assert contract.input_state == {"data": "value"} - """ - - def _factory( - input_state: Any = None, - input_data: Any = None, - metadata: dict[str, Any] | None = None, - algorithm: Any = None, - computation_type: str | None = None, - ) -> MagicMock: - return _create_mock_contract( - input_state=input_state, - input_data=input_data, - metadata=metadata, - algorithm=algorithm, - computation_type=computation_type, - ) - - return _factory - - -@pytest.mark.unit -class TestNodeComputeExecuteCompute: - """Tests for NodeCompute.execute_compute() method.""" - - @pytest.mark.asyncio - async def test_execute_compute_valid_contract_calls_process( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that execute_compute with valid contract calls process().""" - # Create a real ModelContractCompute instance using MagicMock with spec - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"text": "hello world"} - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "string_uppercase" - - # Create mock output - mock_output = ModelComputeOutput( - result="HELLO WORLD", - operation_id=uuid4(), - computation_type="string_uppercase", - processing_time_ms=1.5, - cache_hit=False, - parallel_execution_used=False, - ) - - # Mock the process method - with patch.object( - node, "process", new_callable=AsyncMock, return_value=mock_output - ) as mock_process: - result = await node.execute_compute(mock_contract) - - # Verify process was called with ModelComputeInput - mock_process.assert_called_once() - call_args = mock_process.call_args[0][0] - assert isinstance(call_args, ModelComputeInput) - - # Verify the result is returned correctly - assert result == mock_output - assert result.result == "HELLO WORLD" - assert result.computation_type == "string_uppercase" - - @pytest.mark.asyncio - async def test_execute_compute_valid_contract_returns_output( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that execute_compute returns correct ModelComputeOutput.""" - # Create mock contract with default computation type - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"data": "test"} - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - result = await node.execute_compute(mock_contract) - - # Verify output structure - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "default" - assert result.processing_time_ms >= 0 - assert isinstance(result.cache_hit, bool) - assert isinstance(result.parallel_execution_used, bool) - # Default computation returns input unchanged - assert result.result == {"data": "test"} - - @pytest.mark.asyncio - async def test_execute_compute_invalid_contract_type_dict( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that passing a dict raises ModelOnexError with VALIDATION_ERROR.""" - invalid_contract = {"name": "test", "input_state": {"data": "value"}} - - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(invalid_contract) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.VALIDATION_ERROR - assert "Invalid contract type" in str(error.message) - assert error.context is not None - assert _get_context_value(error, "node_id") is not None - assert _get_context_value(error, "provided_type") == "dict" - assert _get_context_value(error, "expected_type") == "ModelContractCompute" - - @pytest.mark.asyncio - async def test_execute_compute_invalid_contract_type_string( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that passing a string raises ModelOnexError with VALIDATION_ERROR.""" - invalid_contract = "not a contract" - - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(invalid_contract) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.VALIDATION_ERROR - assert "Invalid contract type" in str(error.message) - assert error.context is not None - assert _get_context_value(error, "provided_type") == "str" - assert _get_context_value(error, "expected_type") == "ModelContractCompute" - - @pytest.mark.asyncio - async def test_execute_compute_invalid_contract_type_none( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that passing None raises ModelOnexError with VALIDATION_ERROR.""" - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(None) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.VALIDATION_ERROR - assert "Invalid contract type" in str(error.message) - assert error.context is not None - assert _get_context_value(error, "provided_type") == "NoneType" - - @pytest.mark.asyncio - async def test_execute_compute_invalid_contract_type_wrong_model( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that passing wrong Pydantic model raises ModelOnexError.""" - # Use ModelComputeInput as a wrong model type - wrong_model = ModelComputeInput( - data={"test": "data"}, - computation_type="default", - ) - - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(wrong_model) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.VALIDATION_ERROR - assert "Invalid contract type" in str(error.message) - assert error.context is not None - assert "ModelComputeInput" in _get_context_value(error, "provided_type") - - @pytest.mark.asyncio - async def test_execute_compute_contract_with_input_state( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that contract with input_state field uses it correctly.""" - input_state_data = {"values": [1, 2, 3], "operation": "sum"} - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = input_state_data - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - with patch.object(node, "process", new_callable=AsyncMock) as mock_process: - mock_process.return_value = ModelComputeOutput( - result=input_state_data, - operation_id=uuid4(), - computation_type="default", - processing_time_ms=1.0, - ) - - await node.execute_compute(mock_contract) - - # Verify input_state was passed to process - call_args = mock_process.call_args[0][0] - assert isinstance(call_args, ModelComputeInput) - assert call_args.data == input_state_data - - @pytest.mark.asyncio - async def test_execute_compute_error_context_contains_node_id( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that error context contains node_id for debugging.""" - invalid_contract = 12345 # Integer is invalid - - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(invalid_contract) - - error = exc_info.value - assert error.context is not None - node_id_from_context = _get_context_value(error, "node_id") - assert node_id_from_context is not None - assert str(node.node_id) == node_id_from_context - - -@pytest.mark.unit -class TestNodeComputeContractToInput: - """Tests for NodeCompute._contract_to_input() method.""" - - def test_contract_to_input_with_input_state( - self, - node: NodeCompute[Any, Any], - mock_contract_factory: Callable[..., MagicMock], - ) -> None: - """Test _contract_to_input extracts input_state correctly.""" - mock_contract = mock_contract_factory( - input_state={"text": "hello world"}, - algorithm=MagicMock(algorithm_type="default"), - ) - - result = node._contract_to_input(mock_contract) - - assert isinstance(result, ModelComputeInput) - assert result.data == {"text": "hello world"} - - def test_contract_to_input_extracts_metadata( - self, - node: NodeCompute[Any, Any], - mock_contract_factory: Callable[..., MagicMock], - ) -> None: - """Test _contract_to_input extracts metadata correctly.""" - metadata = {"custom_key": "custom_value", "priority": "high"} - mock_contract = mock_contract_factory( - input_state={"data": "value"}, - metadata=metadata, - algorithm=MagicMock(algorithm_type="default"), - ) - - result = node._contract_to_input(mock_contract) - - assert result.metadata == metadata - - def test_contract_to_input_with_legacy_input_data( - self, - node: NodeCompute[Any, Any], - mock_contract_factory: Callable[..., MagicMock], - ) -> None: - """Test _contract_to_input falls back to input_data when input_state is None.""" - mock_contract = mock_contract_factory( - input_state=None, - input_data={"legacy": "data"}, - ) - - with patch("omnibase_core.nodes.node_compute.emit_log_event") as mock_log: - result = node._contract_to_input(mock_contract) - - # Verify fallback to input_data - assert result.data == {"legacy": "data"} - - # Verify warning was logged - mock_log.assert_called() - call_args = mock_log.call_args - # First positional arg is log level (WARNING) - assert "WARNING" in str(call_args[0][0]) - # Second positional arg is message - assert "legacy" in call_args[0][1].lower() - - def test_contract_to_input_missing_both_fields_raises_error( - self, - node: NodeCompute[Any, Any], - mock_contract_factory: Callable[..., MagicMock], - ) -> None: - """Test _contract_to_input raises error when both input_state and input_data are None.""" - mock_contract = mock_contract_factory( - input_state=None, - input_data=None, - ) - - with pytest.raises(ModelOnexError) as exc_info: - node._contract_to_input(mock_contract) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.VALIDATION_ERROR - assert "input_state" in str(error.message) - assert "input_data" in str(error.message) - assert error.context is not None - assert _get_context_value(error, "node_id") is not None - assert _get_context_value(error, "hint") is not None - # Verify enhanced error context for debugging - assert _get_context_value(error, "checked_attributes") == [ - "input_state", - "input_data", - ] - assert _get_context_value(error, "input_state_value") == "None" - assert _get_context_value(error, "input_data_value") == "None" - - def test_contract_to_input_computation_type_from_algorithm( - self, - node: NodeCompute[Any, Any], - mock_contract_factory: Callable[..., MagicMock], - ) -> None: - """Test computation_type is extracted from algorithm.algorithm_type.""" - mock_algorithm = MagicMock() - mock_algorithm.algorithm_type = "string_uppercase" - - mock_contract = mock_contract_factory( - input_state={"data": "value"}, - algorithm=mock_algorithm, - ) - - result = node._contract_to_input(mock_contract) - - assert result.computation_type == "string_uppercase" - - def test_contract_to_input_computation_type_from_metadata( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test computation_type is extracted from metadata when algorithm is None.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - metadata={"computation_type": "custom_computation"}, - algorithm=None, - ) - - result = node._contract_to_input(mock_contract) - - assert result.computation_type == "custom_computation" - - def test_contract_to_input_computation_type_from_contract_attribute( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test computation_type is extracted from contract.computation_type attribute.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - computation_type="attribute_computation", - ) - - result = node._contract_to_input(mock_contract) - - assert result.computation_type == "attribute_computation" - - def test_contract_to_input_computation_type_default( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test computation_type defaults to 'default' when not specified.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - ) - - result = node._contract_to_input(mock_contract) - - assert result.computation_type == "default" - - def test_contract_to_input_cache_enabled_from_metadata( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test cache_enabled is extracted from metadata.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - metadata={"cache_enabled": False}, - ) - - result = node._contract_to_input(mock_contract) - - assert result.cache_enabled is False - - def test_contract_to_input_cache_enabled_default_true( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test cache_enabled defaults to True when not specified.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - ) - - result = node._contract_to_input(mock_contract) - - assert result.cache_enabled is True - - def test_contract_to_input_parallel_enabled_from_metadata( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test parallel_enabled is extracted from metadata.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - metadata={"parallel_enabled": True}, - ) - - result = node._contract_to_input(mock_contract) - - assert result.parallel_enabled is True - - def test_contract_to_input_parallel_enabled_default_false( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test parallel_enabled defaults to False when not specified.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - ) - - result = node._contract_to_input(mock_contract) - - assert result.parallel_enabled is False - - def test_contract_to_input_computation_type_priority( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test computation_type priority: algorithm > metadata > contract attribute.""" - # Create mock with all three sources - mock_algorithm = MagicMock() - mock_algorithm.algorithm_type = "algorithm_source" - - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - metadata={"computation_type": "metadata_source"}, - algorithm=mock_algorithm, - computation_type="attribute_source", - ) - - result = node._contract_to_input(mock_contract) - - # Algorithm should take priority - assert result.computation_type == "algorithm_source" - - def test_contract_to_input_metadata_priority_over_attribute( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test metadata computation_type takes priority over contract attribute.""" - mock_contract = _create_mock_contract( - input_state={"data": "value"}, - metadata={"computation_type": "metadata_source"}, - computation_type="attribute_source", - ) - - result = node._contract_to_input(mock_contract) - - # Metadata should take priority over attribute - assert result.computation_type == "metadata_source" - - def test_contract_to_input_handles_empty_metadata( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test _contract_to_input handles None metadata gracefully.""" - # Create mock with None metadata (not empty dict) - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"data": "value"} - mock_contract.metadata = None - mock_contract.algorithm = None - mock_contract.computation_type = None - - result = node._contract_to_input(mock_contract) - - # Should not raise, metadata should be empty dict - assert result.metadata == {} - - def test_contract_to_input_preserves_complex_input_state( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test _contract_to_input preserves complex nested input_state.""" - complex_input = { - "nested": { - "level1": { - "level2": [1, 2, 3], - }, - }, - "array": [{"a": 1}, {"b": 2}], - "mixed": {"num": 42, "str": "test", "bool": True}, - } - - mock_contract = _create_mock_contract( - input_state=complex_input, - algorithm=MagicMock(algorithm_type="default"), - ) - - result = node._contract_to_input(mock_contract) - - assert result.data == complex_input - - -@pytest.mark.unit -class TestNodeComputeExecuteComputeIntegration: - """Integration tests for execute_compute with real process() execution.""" - - @pytest.mark.asyncio - async def test_execute_compute_full_pipeline_default( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test full execute_compute pipeline with default computation.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"test": "data"} - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "default" - # Default computation returns input unchanged - assert result.result == {"test": "data"} - - @pytest.mark.asyncio - async def test_execute_compute_full_pipeline_string_uppercase( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test full execute_compute pipeline with string_uppercase computation.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = "hello world" - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "string_uppercase" - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "string_uppercase" - assert result.result == "HELLO WORLD" - - @pytest.mark.asyncio - async def test_execute_compute_full_pipeline_sum_numbers( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test full execute_compute pipeline with sum_numbers computation.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = [1.0, 2.0, 3.0, 4.0, 5.0] - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "sum_numbers" - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "sum_numbers" - assert result.result == 15.0 - - @pytest.mark.asyncio - async def test_execute_compute_with_caching( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test execute_compute uses caching when enabled.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"test": "cache_data"} - mock_contract.metadata = {"cache_enabled": True} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - # First call should compute - result1 = await node.execute_compute(mock_contract) - assert result1.cache_hit is False - - # Second call with same contract should hit cache - result2 = await node.execute_compute(mock_contract) - assert result2.cache_hit is True - assert result2.result == result1.result - - @pytest.mark.asyncio - async def test_execute_compute_without_caching( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test execute_compute does not cache when disabled.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"test": "no_cache_data"} - mock_contract.metadata = {"cache_enabled": False} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - # First call - result1 = await node.execute_compute(mock_contract) - assert result1.cache_hit is False - - # Second call should also compute (no caching) - result2 = await node.execute_compute(mock_contract) - assert result2.cache_hit is False - - @pytest.mark.asyncio - async def test_execute_compute_unknown_computation_type( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test execute_compute raises error for unknown computation type.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"data": "value"} - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "nonexistent_computation" - - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(mock_contract) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.OPERATION_FAILED - assert "Unknown computation type" in str(error.message) - # Verify enhanced error context includes error_type for debugging - assert _get_context_value(error, "error_type") == "ModelOnexError" - assert ( - _get_context_value(error, "computation_type") == "nonexistent_computation" - ) - # Verify processing_time_ms is captured - assert _get_context_value(error, "processing_time_ms") is not None - - @pytest.mark.asyncio - async def test_execute_compute_error_context_includes_cache_and_parallel_status( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test error context includes cache_enabled and parallel_enabled for debugging.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"data": "value"} - mock_contract.metadata = {"cache_enabled": False, "parallel_enabled": True} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "nonexistent_computation" - - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(mock_contract) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.OPERATION_FAILED - # Verify cache_enabled and parallel_enabled are in error context - assert _get_context_value(error, "cache_enabled") is False - assert _get_context_value(error, "parallel_enabled") is True - - @pytest.mark.asyncio - async def test_execute_compute_error_context_default_cache_and_parallel_values( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test error context includes default values for cache_enabled and parallel_enabled.""" - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"data": "value"} - mock_contract.metadata = {} # No explicit settings - use defaults - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "nonexistent_computation" - - with pytest.raises(ModelOnexError) as exc_info: - await node.execute_compute(mock_contract) - - error = exc_info.value - assert error.error_code == EnumCoreErrorCode.OPERATION_FAILED - # Verify default values: cache_enabled=True, parallel_enabled=False - assert _get_context_value(error, "cache_enabled") is True - assert _get_context_value(error, "parallel_enabled") is False - - @pytest.mark.asyncio - async def test_execute_compute_with_custom_registered_computation( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test execute_compute with a custom registered computation.""" - # Register custom computation - node.register_computation("double_values", lambda data: [x * 2 for x in data]) - - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = [1, 2, 3] - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "double_values" - - result = await node.execute_compute(mock_contract) - - assert result.computation_type == "double_values" - assert result.result == [2, 4, 6] - - -@pytest.mark.unit -class TestNodeComputeEdgeCases: - """Edge case tests for NodeCompute execution scenarios.""" - - @pytest.mark.asyncio - async def test_execute_compute_with_empty_list_input_state( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test execute_compute handles empty list input_state correctly. - - Verifies that an empty list is a valid input_state value and - passes through to the computation without raising validation errors. - The default computation should return the empty list unchanged. - """ - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = [] - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "default" - assert result.result == [] - assert result.cache_hit is False - - @pytest.mark.asyncio - async def test_execute_compute_with_empty_dict_input_state( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test execute_compute handles empty dict input_state correctly. - - Verifies that an empty dict is a valid input_state value and - passes through to the computation without raising validation errors. - The default computation should return the empty dict unchanged. - """ - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {} - mock_contract.metadata = {} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "default" - assert result.result == {} - assert result.cache_hit is False - - @pytest.mark.asyncio - async def test_execute_compute_parallel_warning_single_value( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test that parallel execution with non-parallelizable data triggers warning. - - When parallel_enabled=True but data is a single string (not list/tuple - with >1 element), a WARNING should be logged indicating that parallel - execution was requested but data is not parallelizable, and sequential - execution is used instead. - """ - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = "single string value" - mock_contract.metadata = {"parallel_enabled": True} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - with patch("omnibase_core.nodes.node_compute.emit_log_event") as mock_log: - result = await node.execute_compute(mock_contract) - - # Verify result is correct (computation still works) - assert isinstance(result, ModelComputeOutput) - assert result.result == "single string value" - assert result.parallel_execution_used is False - - # Find the WARNING call about parallel execution - warning_calls = [ - call - for call in mock_log.call_args_list - if "WARNING" in str(call[0][0]) and "parallel" in call[0][1].lower() - ] - assert len(warning_calls) >= 1, ( - "Expected WARNING log about parallel execution not being supported" - ) - - # Verify warning message content - warning_call = warning_calls[0] - warning_message = warning_call[0][1] - assert "not parallelizable" in warning_message.lower() - assert "sequential" in warning_message.lower() - - @pytest.mark.asyncio - async def test_execute_compute_parallel_warning_single_element_list( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test parallel warning when list has only 1 element. - - When parallel_enabled=True but data is a list with only 1 element, - a WARNING should be logged since parallel execution requires >1 element - to distribute work across threads. - """ - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = ["single_element"] - mock_contract.metadata = {"parallel_enabled": True} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = "default" - - with patch("omnibase_core.nodes.node_compute.emit_log_event") as mock_log: - result = await node.execute_compute(mock_contract) - - # Verify result is correct - assert isinstance(result, ModelComputeOutput) - assert result.result == ["single_element"] - assert result.parallel_execution_used is False - - # Find the WARNING call about parallel execution - warning_calls = [ - call - for call in mock_log.call_args_list - if "WARNING" in str(call[0][0]) and "parallel" in call[0][1].lower() - ] - assert len(warning_calls) >= 1, ( - "Expected WARNING log when parallel requested with single-element list" - ) - - @pytest.mark.asyncio - async def test_execute_compute_with_none_algorithm_type( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test fallback when algorithm exists but algorithm_type is None. - - When contract has an algorithm object but algorithm.algorithm_type is None, - the computation_type should fall back to metadata['computation_type'], - then to contract.computation_type, then to 'default'. - - This test verifies the fallback chain works correctly when the primary - source (algorithm.algorithm_type) is explicitly None. - """ - # Case 1: Falls back to metadata - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"test": "data"} - mock_contract.metadata = {"computation_type": "metadata_fallback"} - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = None # Explicitly None - mock_contract.computation_type = "attribute_fallback" - - # Register the custom computation type - node.register_computation("metadata_fallback", lambda data: data) - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - # Should use metadata computation_type since algorithm_type is None - assert result.computation_type == "metadata_fallback" - assert result.result == {"test": "data"} - - @pytest.mark.asyncio - async def test_execute_compute_with_none_algorithm_type_uses_contract_attribute( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test fallback to contract.computation_type when algorithm_type is None. - - When both algorithm.algorithm_type and metadata['computation_type'] are - unavailable, should fall back to contract.computation_type attribute. - """ - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"test": "data"} - mock_contract.metadata = {} # No computation_type in metadata - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = None # Explicitly None - mock_contract.computation_type = "attribute_computation" - - # Register the custom computation type - node.register_computation("attribute_computation", lambda data: data) - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "attribute_computation" - - @pytest.mark.asyncio - async def test_execute_compute_with_none_algorithm_type_defaults( - self, - node: NodeCompute[Any, Any], - ) -> None: - """Test defaults to 'default' when all computation_type sources are None. - - When algorithm.algorithm_type is None, metadata has no computation_type, - and contract.computation_type is None, should default to 'default'. - """ - mock_contract = MagicMock(spec=ModelContractCompute) - mock_contract.input_state = {"test": "data"} - mock_contract.metadata = {} # No computation_type - mock_contract.algorithm = MagicMock() - mock_contract.algorithm.algorithm_type = None - mock_contract.computation_type = None - - result = await node.execute_compute(mock_contract) - - assert isinstance(result, ModelComputeOutput) - assert result.computation_type == "default" - # Default computation returns input unchanged - assert result.result == {"test": "data"} diff --git a/tests/unit/scripts/test_check_transport_imports.py b/tests/unit/scripts/test_check_transport_imports.py new file mode 100644 index 0000000000..45a49e775e --- /dev/null +++ b/tests/unit/scripts/test_check_transport_imports.py @@ -0,0 +1,1263 @@ +""" +Comprehensive tests for the transport import checker script. + +Tests cover: +- TransportViolation dataclass +- TransportImportAnalyzer AST visitor +- analyze_file function +- Banned import detection (kafka, redis, httpx, requests, asyncpg, etc.) +- Allowed imports (typing, pydantic, omnibase_core, standard library) +- Edge cases (empty files, syntax errors, nested imports, comments, strings) +- CLI arguments (--verbose, --json) +- Exit codes (0 for success, 1 for violations) +- Output formats (text, JSON) + +Linear ticket: OMN-220 +""" + +from __future__ import annotations + +import ast +import importlib.util +import json +import sys +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest + +# Import the validation script components +# We need to add the scripts directory to path for testing. +# The defensive check prevents duplicate entries when the test module is +# reloaded (e.g., during pytest-xdist parallel execution or when running +# tests multiple times in the same Python process). +SCRIPTS_DIR = Path(__file__).parent.parent.parent.parent / "scripts" +scripts_dir = str(SCRIPTS_DIR) +if scripts_dir not in sys.path: + sys.path.insert(0, scripts_dir) + +# Module-level variables that will be populated when the script loads +# Using Any type to satisfy mypy since module may not exist at type-check time +_module_loaded = False +TransportViolation: Any = None +TransportImportAnalyzer: Any = None +TransportCheckResult: Any = None +analyze_file: Any = None +find_python_files: Any = None +main: Any = None +BANNED_TRANSPORT_MODULES: Any = None +ViolationType: Any = None +Severity: Any = None + + +def _load_module() -> bool: + """Load the transport import checker module. + + Returns: + True if module loaded successfully, False otherwise. + """ + global _module_loaded, TransportViolation, TransportImportAnalyzer + global TransportCheckResult, analyze_file, find_python_files, main + global BANNED_TRANSPORT_MODULES, ViolationType, Severity + + if _module_loaded: + return True + + script_path = SCRIPTS_DIR / "check_transport_imports.py" + if not script_path.exists(): + return False + + spec = importlib.util.spec_from_file_location( + "check_transport_imports", script_path + ) + if spec is None: + return False + if spec.loader is None: + return False + + _module = importlib.util.module_from_spec(spec) + # Add to sys.modules before exec to avoid dataclass issues + sys.modules["check_transport_imports"] = _module + spec.loader.exec_module(_module) + + # Extract the classes and functions from the loaded module + TransportViolation = _module.TransportViolation + TransportImportAnalyzer = _module.TransportImportAnalyzer + TransportCheckResult = _module.TransportCheckResult + analyze_file = _module.analyze_file + find_python_files = _module.find_python_files + main = _module.main + BANNED_TRANSPORT_MODULES = _module.BANNED_TRANSPORT_MODULES + ViolationType = _module.ViolationType + Severity = _module.Severity + + _module_loaded = True + return True + + +def skip_if_module_not_loaded() -> None: + """Skip test if the module is not available.""" + if not _load_module(): + pytest.skip("Script not found: scripts/check_transport_imports.py") + + +# Mark all tests in this module as unit tests +pytestmark = [pytest.mark.unit, pytest.mark.timeout(30)] + + +class TestTransportViolation: + """Tests for TransportViolation dataclass creation and formatting.""" + + def test_violation_creation(self) -> None: + """Test that TransportViolation can be created with all fields.""" + skip_if_module_not_loaded() + + violation = TransportViolation( + file_path=Path("/test/file.py"), + line_number=10, + column=0, + violation_type=ViolationType.BANNED_TRANSPORT_IMPORT, + severity=Severity.ERROR, + message="Import of 'kafka' is forbidden", + suggestion="Use ProtocolEventBus instead", + code_snippet="import kafka", + ) + assert violation.file_path == Path("/test/file.py") + assert violation.line_number == 10 + assert violation.column == 0 + assert violation.message == "Import of 'kafka' is forbidden" + assert violation.code_snippet == "import kafka" + + def test_violation_format(self) -> None: + """Test violation format method.""" + skip_if_module_not_loaded() + + violation = TransportViolation( + file_path=Path("/test/file.py"), + line_number=10, + column=0, + violation_type=ViolationType.BANNED_TRANSPORT_IMPORT, + severity=Severity.ERROR, + message="Import of 'kafka' is forbidden", + suggestion="Use ProtocolEventBus instead", + code_snippet="import kafka", + ) + formatted = violation.format(verbose=True) + assert "ERROR" in formatted + assert "kafka" in formatted + assert "10" in formatted + + +class TestBannedModulesConfiguration: + """Tests that banned modules configuration is complete.""" + + def test_banned_modules_contains_kafka(self) -> None: + """Test that kafka is in the banned modules list.""" + skip_if_module_not_loaded() + assert "kafka" in BANNED_TRANSPORT_MODULES + + def test_banned_modules_contains_redis(self) -> None: + """Test that redis is in the banned modules list.""" + skip_if_module_not_loaded() + assert "redis" in BANNED_TRANSPORT_MODULES + + def test_banned_modules_contains_httpx(self) -> None: + """Test that httpx is in the banned modules list.""" + skip_if_module_not_loaded() + assert "httpx" in BANNED_TRANSPORT_MODULES + + def test_banned_modules_contains_asyncpg(self) -> None: + """Test that asyncpg is in the banned modules list.""" + skip_if_module_not_loaded() + assert "asyncpg" in BANNED_TRANSPORT_MODULES + + +class TestBannedKafkaImports: + """Tests detection of banned Kafka library imports.""" + + def test_detects_import_kafka(self) -> None: + """Test detection of 'import kafka'.""" + skip_if_module_not_loaded() + + code = """ +import kafka +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "kafka" in analyzer.violations[0].message + + def test_detects_from_kafka_import(self) -> None: + """Test detection of 'from kafka import ...'.""" + skip_if_module_not_loaded() + + code = """ +from kafka import KafkaProducer +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "kafka" in analyzer.violations[0].message.lower() + + def test_detects_import_aiokafka(self) -> None: + """Test detection of 'import aiokafka'.""" + skip_if_module_not_loaded() + + code = """ +import aiokafka +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "aiokafka" in analyzer.violations[0].message + + def test_detects_from_aiokafka_import(self) -> None: + """Test detection of 'from aiokafka import ...'.""" + skip_if_module_not_loaded() + + code = """ +from aiokafka import AIOKafkaProducer +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + + def test_detects_multiline_from_kafka_import(self) -> None: + """Test detection of multi-line 'from kafka import (...)' statements.""" + skip_if_module_not_loaded() + + code = """ +from kafka import ( + KafkaProducer, + KafkaConsumer, + KafkaAdminClient, +) +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Multi-line imports should still be detected + assert len(analyzer.violations) == 1 + assert "kafka" in analyzer.violations[0].message.lower() + + +class TestBannedRedisImports: + """Tests detection of banned Redis/Valkey library imports.""" + + def test_detects_import_redis(self) -> None: + """Test detection of 'import redis'.""" + skip_if_module_not_loaded() + + code = """ +import redis +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "redis" in analyzer.violations[0].message + + def test_detects_from_redis_import(self) -> None: + """Test detection of 'from redis import Redis'.""" + skip_if_module_not_loaded() + + code = """ +from redis import Redis +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + + def test_detects_import_valkey(self) -> None: + """Test detection of 'import valkey'.""" + skip_if_module_not_loaded() + + code = """ +import valkey +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "valkey" in analyzer.violations[0].message + + def test_detects_multiline_import_redis(self) -> None: + """Test detection of multi-line import statements with multiple modules.""" + skip_if_module_not_loaded() + + # Note: Regular `import` statements don't support parentheses syntax. + # But they do support comma-separated multiple imports on one line. + code = """ +import redis, json, typing +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Should detect redis but not json or typing + assert len(analyzer.violations) == 1 + assert "redis" in analyzer.violations[0].message + + +class TestBannedHttpImports: + """Tests detection of banned HTTP client library imports.""" + + def test_detects_import_httpx(self) -> None: + """Test detection of 'import httpx'.""" + skip_if_module_not_loaded() + + code = """ +import httpx +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "httpx" in analyzer.violations[0].message + + def test_detects_from_httpx_import(self) -> None: + """Test detection of 'from httpx import Client'.""" + skip_if_module_not_loaded() + + code = """ +from httpx import Client +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + + def test_detects_import_requests(self) -> None: + """Test detection of 'import requests'.""" + skip_if_module_not_loaded() + + code = """ +import requests +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "requests" in analyzer.violations[0].message + + def test_detects_from_aiohttp_import(self) -> None: + """Test detection of 'from aiohttp import ClientSession'.""" + skip_if_module_not_loaded() + + code = """ +from aiohttp import ClientSession +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + + +class TestBannedDatabaseImports: + """Tests detection of banned database client imports.""" + + def test_detects_from_asyncpg_import(self) -> None: + """Test detection of 'from asyncpg import connect'.""" + skip_if_module_not_loaded() + + code = """ +from asyncpg import connect +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + + def test_detects_import_asyncpg(self) -> None: + """Test detection of 'import asyncpg'.""" + skip_if_module_not_loaded() + + code = """ +import asyncpg +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "asyncpg" in analyzer.violations[0].message + + def test_detects_import_psycopg(self) -> None: + """Test detection of 'import psycopg'.""" + skip_if_module_not_loaded() + + code = """ +import psycopg +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "psycopg" in analyzer.violations[0].message + + def test_detects_import_psycopg2(self) -> None: + """Test detection of 'import psycopg2'.""" + skip_if_module_not_loaded() + + code = """ +import psycopg2 +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "psycopg2" in analyzer.violations[0].message + + +class TestBannedInfrastructureImports: + """Tests detection of banned infrastructure library imports.""" + + def test_detects_import_hvac(self) -> None: + """Test detection of 'import hvac' (Vault client).""" + skip_if_module_not_loaded() + + code = """ +import hvac +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "hvac" in analyzer.violations[0].message + + def test_detects_import_consul(self) -> None: + """Test detection of 'import consul'.""" + skip_if_module_not_loaded() + + code = """ +import consul +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "consul" in analyzer.violations[0].message + + +class TestAllowedImports: + """Tests that allowed imports pass validation.""" + + def test_allows_typing_import(self) -> None: + """Test that 'import typing' is allowed.""" + skip_if_module_not_loaded() + + code = """ +import typing +from typing import Optional, List +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 0 + + def test_allows_pydantic_import(self) -> None: + """Test that 'from pydantic import BaseModel' is allowed.""" + skip_if_module_not_loaded() + + code = """ +from pydantic import BaseModel +import pydantic +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 0 + + def test_allows_omnibase_core_import(self) -> None: + """Test that 'from omnibase_core.models import X' is allowed.""" + skip_if_module_not_loaded() + + code = """ +from omnibase_core.models import ModelOnexError +from omnibase_core.nodes import NodeCompute +import omnibase_core +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 0 + + def test_allows_json_import(self) -> None: + """Test that 'import json' is allowed.""" + skip_if_module_not_loaded() + + code = """ +import json +from json import loads, dumps +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 0 + + def test_allows_standard_library_imports(self) -> None: + """Test that standard library imports are allowed.""" + skip_if_module_not_loaded() + + code = """ +import os +import sys +import pathlib +from pathlib import Path +import datetime +from collections import defaultdict +import dataclasses +from dataclasses import dataclass +import enum +from enum import Enum +import uuid +import hashlib +import re +import abc +from abc import ABC, abstractmethod +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 0 + + +class TestTypeCheckingBlockHandling: + """Tests that TYPE_CHECKING block imports are allowed.""" + + def test_allows_imports_in_type_checking_block(self) -> None: + """Test that imports inside TYPE_CHECKING blocks are allowed.""" + skip_if_module_not_loaded() + + code = """ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import kafka + from redis import Redis +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Imports inside TYPE_CHECKING should be allowed + assert len(analyzer.violations) == 0 + + def test_allows_typing_type_checking_block(self) -> None: + """Test that typing.TYPE_CHECKING blocks are recognized.""" + skip_if_module_not_loaded() + + code = """ +import typing + +if typing.TYPE_CHECKING: + import httpx +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Imports inside TYPE_CHECKING should be allowed + assert len(analyzer.violations) == 0 + + def test_allows_aliased_typing_type_checking_block(self) -> None: + """Test that aliased typing.TYPE_CHECKING blocks are recognized. + + Some codebases use `import typing as t` for brevity, and we should + still recognize `if t.TYPE_CHECKING:` blocks as type-checking guards. + """ + skip_if_module_not_loaded() + + code = """ +import typing as t + +if t.TYPE_CHECKING: + import kafka + from redis import Redis +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Imports inside aliased TYPE_CHECKING should be allowed + assert len(analyzer.violations) == 0 + + def test_allows_tp_aliased_type_checking_block(self) -> None: + """Test that 'import typing as tp' aliased TYPE_CHECKING blocks work. + + The `tp` alias is a common alternative to `t` for the typing module. + This test ensures our detection handles various alias names correctly. + """ + skip_if_module_not_loaded() + + code = """ +import typing as tp + +if tp.TYPE_CHECKING: + import kafka + from redis import Redis +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Imports inside tp-aliased TYPE_CHECKING should be allowed + assert len(analyzer.violations) == 0 + + def test_allows_nested_type_checking_blocks(self) -> None: + """Test that nested conditions inside TYPE_CHECKING blocks are handled. + + Some codebases may have additional conditions inside TYPE_CHECKING + blocks, like version checks or platform checks. + """ + skip_if_module_not_loaded() + + code = """ +from typing import TYPE_CHECKING +import sys + +if TYPE_CHECKING: + if sys.version_info >= (3, 11): + import kafka + else: + from kafka import KafkaProducer +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Imports inside nested TYPE_CHECKING should be allowed + assert len(analyzer.violations) == 0 + + +class TestEdgeCases: + """Tests edge cases and error handling scenarios.""" + + def test_handles_empty_file(self, tmp_path: Path) -> None: + """Test that empty files pass validation.""" + skip_if_module_not_loaded() + + empty_file = tmp_path / "empty.py" + empty_file.write_text("") + + result = analyze_file(empty_file) + + assert result.is_clean is True + assert len(result.violations) == 0 + + def test_handles_syntax_error_gracefully(self, tmp_path: Path) -> None: + """Test that files with syntax errors are handled gracefully.""" + skip_if_module_not_loaded() + + syntax_error_file = tmp_path / "syntax_error.py" + syntax_error_file.write_text( + """ +def incomplete_function( +""" + ) + + result = analyze_file(syntax_error_file) + + # Syntax error files should have skip_reason set + assert result.skip_reason is not None + assert "Syntax error" in result.skip_reason + + def test_detects_nested_imports_in_functions(self) -> None: + """Test that imports nested inside functions are detected.""" + skip_if_module_not_loaded() + + code = """ +def some_function(): + import kafka + return kafka.KafkaProducer() +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "kafka" in analyzer.violations[0].message + + def test_detects_nested_imports_in_classes(self) -> None: + """Test that imports nested inside classes are detected.""" + skip_if_module_not_loaded() + + code = """ +class MyClass: + def __init__(self): + import redis + self.client = redis.Redis() +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + + def test_string_containing_redis_passes(self) -> None: + """Test that strings containing 'redis' don't trigger violations.""" + skip_if_module_not_loaded() + + code = ''' +message = "connect to redis server" +doc = """ +This module uses redis for caching. +import redis # This is just documentation +""" +''' + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 0 + + def test_comments_containing_banned_names_pass(self) -> None: + """Test that comments with banned import names don't trigger violations.""" + skip_if_module_not_loaded() + + code = """ +# import kafka - we used to use this +# from redis import Redis +# TODO: consider using httpx +import typing # Not: import requests +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 0 + + def test_detects_try_except_imports(self) -> None: + """Test detection of imports in try/except blocks.""" + skip_if_module_not_loaded() + + code = """ +try: + import redis +except ImportError: + redis = None +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + # Try/except imports should still be detected + assert len(analyzer.violations) == 1 + + +class TestMultipleViolations: + """Tests detection of multiple violations in single files.""" + + def test_detects_multiple_violations_same_file(self) -> None: + """Test that multiple violations in one file are all detected.""" + skip_if_module_not_loaded() + + code = """ +import kafka +import redis +import httpx +from asyncpg import connect +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 4 + + def test_captures_correct_line_numbers(self) -> None: + """Test that line numbers are correctly captured for each violation.""" + skip_if_module_not_loaded() + + code = """ + +import kafka + +import redis +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 2 + line_numbers = {v.line_number for v in analyzer.violations} + assert 3 in line_numbers # import kafka + assert 5 in line_numbers # import redis + + +class TestAnalyzeFileFunction: + """Tests for the analyze_file() function.""" + + def test_analyze_clean_file(self, tmp_path: Path) -> None: + """Test analysis of a clean file with no banned imports.""" + skip_if_module_not_loaded() + + test_file = tmp_path / "clean.py" + test_file.write_text( + """ +import typing +from pydantic import BaseModel +import json +""" + ) + + result = analyze_file(test_file) + + assert result.is_clean is True + assert len(result.violations) == 0 + assert result.file_path == test_file + + def test_analyze_file_with_violations(self, tmp_path: Path) -> None: + """Test analysis of a file with banned imports.""" + skip_if_module_not_loaded() + + test_file = tmp_path / "bad.py" + test_file.write_text( + """ +import kafka +""" + ) + + result = analyze_file(test_file) + + assert result.is_clean is False + assert len(result.violations) == 1 + + +class TestFindPythonFilesFunction: + """Tests for the find_python_files() function.""" + + def test_finds_python_files(self, tmp_path: Path) -> None: + """Test finding Python files in a directory.""" + skip_if_module_not_loaded() + + (tmp_path / "file1.py").write_text("import os") + (tmp_path / "file2.py").write_text("import sys") + (tmp_path / "file.txt").write_text("not python") + + files = find_python_files(tmp_path) + + assert len(files) == 2 + assert all(f.suffix == ".py" for f in files) + + def test_skips_pycache_directories(self, tmp_path: Path) -> None: + """Test that __pycache__ directories are skipped.""" + skip_if_module_not_loaded() + + pycache = tmp_path / "__pycache__" + pycache.mkdir() + (pycache / "cached.py").write_text("import os") + (tmp_path / "main.py").write_text("import sys") + + files = find_python_files(tmp_path) + + assert len(files) == 1 + assert files[0].name == "main.py" + + +class TestExitCodes: + """Tests script exit code behavior.""" + + def test_returns_zero_when_no_violations(self, tmp_path: Path) -> None: + """Test that exit code is 0 when no violations are found.""" + skip_if_module_not_loaded() + + test_dir = tmp_path / "src" / "omnibase_core" + test_dir.mkdir(parents=True) + (test_dir / "clean.py").write_text("import os") + + with patch.object( + sys, "argv", ["check_transport_imports.py", "--src-dir", str(test_dir)] + ): + result = main() + assert result == 0 + + def test_returns_one_when_violations_found(self, tmp_path: Path) -> None: + """Test that exit code is 1 when violations are found.""" + skip_if_module_not_loaded() + + test_dir = tmp_path / "src" / "omnibase_core" + test_dir.mkdir(parents=True) + (test_dir / "bad.py").write_text("import kafka") + + with patch.object( + sys, "argv", ["check_transport_imports.py", "--src-dir", str(test_dir)] + ): + result = main() + assert result == 1 + + def test_returns_error_code_for_missing_path(self) -> None: + """Test that error code 2 is returned for missing path.""" + skip_if_module_not_loaded() + + with patch.object( + sys, + "argv", + ["check_transport_imports.py", "--src-dir", "/nonexistent/path"], + ): + result = main() + assert result == 2 + + +class TestOutputFormats: + """Tests --verbose and --json output formats.""" + + def test_verbose_flag_produces_detailed_output( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """Test that --verbose flag produces detailed output.""" + skip_if_module_not_loaded() + + test_dir = tmp_path / "src" / "omnibase_core" + test_dir.mkdir(parents=True) + (test_dir / "bad.py").write_text("import kafka") + + with patch.object( + sys, + "argv", + ["check_transport_imports.py", "--verbose", "--src-dir", str(test_dir)], + ): + main() + + captured = capsys.readouterr() + # Verbose mode should show the violation + assert "kafka" in captured.out.lower() or "kafka" in captured.err.lower() + + def test_json_flag_produces_valid_json( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """Test that --json flag produces valid JSON output.""" + skip_if_module_not_loaded() + + test_dir = tmp_path / "src" / "omnibase_core" + test_dir.mkdir(parents=True) + (test_dir / "bad.py").write_text("import kafka") + + with patch.object( + sys, + "argv", + ["check_transport_imports.py", "--json", "--src-dir", str(test_dir)], + ): + main() + + captured = capsys.readouterr() + # Should produce valid JSON + try: + result = json.loads(captured.out) + assert isinstance(result, dict) + # JSON output should contain summary + assert "summary" in result + except json.JSONDecodeError: + pytest.fail("Output was not valid JSON") + + def test_json_output_with_no_violations( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """Test JSON output when there are no violations.""" + skip_if_module_not_loaded() + + test_dir = tmp_path / "src" / "omnibase_core" + test_dir.mkdir(parents=True) + (test_dir / "clean.py").write_text("import os") + + with patch.object( + sys, + "argv", + ["check_transport_imports.py", "--json", "--src-dir", str(test_dir)], + ): + main() + + captured = capsys.readouterr() + result = json.loads(captured.out) + assert isinstance(result, dict) + # Summary should show clean files with no violations + assert result.get("summary", {}).get("total_violations", 0) == 0 + + +class TestAliasedImports: + """Tests detection of aliased imports.""" + + def test_detects_aliased_kafka_import(self) -> None: + """Test detection of 'import kafka as k'.""" + skip_if_module_not_loaded() + + code = """ +import kafka as k +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "kafka" in analyzer.violations[0].message + + def test_detects_aliased_from_import(self) -> None: + """Test detection of 'from redis import Redis as R'.""" + skip_if_module_not_loaded() + + code = """ +from redis import Redis as R +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + + +class TestSubmoduleImports: + """Tests detection of submodule imports.""" + + def test_detects_kafka_submodule_import(self) -> None: + """Test detection of 'from kafka.errors import KafkaError'.""" + skip_if_module_not_loaded() + + code = """ +from kafka.errors import KafkaError +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1 + assert "kafka" in analyzer.violations[0].message.lower() + + def test_detects_redis_submodule_import(self) -> None: + """Test detection of 'import redis.asyncio'.""" + skip_if_module_not_loaded() + + code = """ +import redis.asyncio +""" + source_lines = code.splitlines() + tree = ast.parse(code) + + analyzer = TransportImportAnalyzer( + file_path=Path("/test.py"), + source_lines=source_lines, + ) + analyzer.visit(tree) + + assert len(analyzer.violations) == 1