Skip to content

feat(runtime): implement HandlerBootstrapSource for centralized handler wiring [OMN-1087] - #176

Merged
jonahgabriel merged 20 commits into
mainfrom
jonah/omn-1087-implement-handlerbootstrapsource-descriptor-based
Jan 21, 2026
Merged

jonahgabriel merged 20 commits into
mainfrom
jonah/omn-1087-implement-handlerbootstrapsource-descriptor-based

Conversation

@jonahgabriel

@jonahgabriel jonahgabriel commented Jan 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Implement HandlerBootstrapSource class that centralizes all hardcoded handler registration per OMN-1087.

Key Changes:

  • Add HandlerBootstrapSource implementing ProtocolContractSource protocol
  • Register 4 core infrastructure handlers as ModelHandlerDescriptor instances
  • Add pattern validation exemption for HandlerBootstrapSource class name

Handlers Registered

Handler ID Name Kind Description
bootstrap.consul Consul Handler effect HashiCorp Consul service discovery
bootstrap.db Database Handler effect PostgreSQL database handler
bootstrap.http HTTP Handler effect HTTP REST protocol handler
bootstrap.vault Vault Handler effect HashiCorp Vault secret management

Test Plan

  • 41 unit tests covering protocol compliance, handler discovery, descriptor validation
  • All tests pass (pytest tests/unit/runtime/test_handler_bootstrap_source.py)
  • Pattern validation passes with exemption
  • Type checking passes (mypy)

Files Changed

  • src/omnibase_infra/runtime/handler_bootstrap_source.py - New implementation
  • src/omnibase_infra/runtime/__init__.py - Added exports
  • src/omnibase_infra/validation/validation_exemptions.yaml - Added exemption
  • tests/unit/runtime/test_handler_bootstrap_source.py - Comprehensive tests

Linear Ticket

OMN-1087

Summary by CodeRabbit

  • New Features

    • Adds a bootstrap handler source that registers four core infrastructure handlers at startup (bootstrapped handlers load before contract-based handlers) and exposes handler_class (FQCN) for dynamic imports.
    • Adds a bootstrap-specific handler descriptor with validated handler_class and conversion to the base descriptor.
  • Tests

    • Large unit and integration suites covering discovery, descriptor validation, idempotency, thread-safety, error handling, and performance.
  • Style

    • Widespread typing/cast annotation updates and removal of a Ruff lint ignore.
  • Chores

    • Added validation exemption for the bootstrap source and removed two CI workflows; updated runtime wiring to register bootstrap handlers first.

✏️ Tip: You can customize this high-level summary in your review settings.

…er wiring [OMN-1087]

Add HandlerBootstrapSource class that implements ProtocolContractSource protocol
to centralize all hardcoded handler registration. This replaces scattered handler
wiring with a single source of truth for bootstrap handlers.

Handlers registered:
- bootstrap.consul: HashiCorp Consul service discovery
- bootstrap.db: PostgreSQL database handler
- bootstrap.http: HTTP REST protocol handler
- bootstrap.vault: HashiCorp Vault secret management

All handlers are registered as ModelHandlerDescriptor instances with:
- handler_kind="effect" (all are effect-type handlers)
- version="1.0.0" (stable bootstrap version)
- contract_path=None (no YAML contract, bootstrap-defined)

Includes 41 comprehensive unit tests covering:
- Protocol compliance with ProtocolContractSource
- Handler discovery and descriptor validation
- Graceful mode API consistency
- Idempotency and performance characteristics
@linear

linear Bot commented Jan 19, 2026

Copy link
Copy Markdown

OMN-1087

@coderabbitai

coderabbitai Bot commented Jan 19, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@jonahgabriel has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 9 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 020e3ca and 32be7be.

📒 Files selected for processing (2)
  • src/omnibase_infra/runtime/handler_bootstrap_source.py
  • src/omnibase_infra/runtime/service_runtime_host_process.py
📝 Walkthrough

Walkthrough

Added a bootstrap handler source that provides four hardcoded bootstrap handler descriptors (consul, db, http, vault) with fully-qualified handler class paths; ModelHandlerDescriptor gained an optional handler_class field and runtime startup now registers bootstrap handlers before contract-based discovery.

Changes

Cohort / File(s) Summary
Model descriptors
src/omnibase_infra/models/handlers/model_handler_descriptor.py, src/omnibase_infra/models/handlers/model_bootstrap_handler_descriptor.py, src/omnibase_infra/models/handlers/__init__.py
Added optional `handler_class: str
Bootstrap source & exports
src/omnibase_infra/runtime/handler_bootstrap_source.py, src/omnibase_infra/runtime/__init__.py
New HandlerBootstrapSource and SOURCE_TYPE_BOOTSTRAP implementing hardcoded bootstrap descriptors; exported from runtime package.
Runtime wiring / bootstrap registration
src/omnibase_infra/runtime/service_runtime_host_process.py
Added async _register_bootstrap_handlers() and invoked it before contract discovery; dynamically imports handler_class, registers handlers into registry, logs per-descriptor outcomes; importlib usage added.
Contract parsing propagation
src/omnibase_infra/runtime/handler_contract_source.py
_parse_contract_file() now extracts handler_class from raw YAML and passes it into constructed ModelHandlerDescriptor.
Tests — unit & integration
tests/unit/runtime/test_handler_bootstrap_source.py, tests/integration/runtime/test_bootstrap_source_integration.py, tests/unit/models/handlers/test_model_bootstrap_handler_descriptor.py, tests/unit/runtime/test_handler_discovery.py, tests/unit/runtime/test_runtime_host_process.py, ...
Added extensive unit/integration tests for bootstrap source, bootstrap descriptors, runtime integration, idempotency, concurrency; updated many tests to reflect bootstrap-first startup and graceful contract failures.
Validation exemptions
src/omnibase_infra/validation/validation_exemptions.yaml
Added exemption block for handler_bootstrap_source.py (OMN-1087) documenting rationale for hardcoded bootstrap registrations (duplicate insertion present in diff).
Typing-only adjustments
multiple files under src/omnibase_infra/... (mixins, handlers, runtime, plugins, validation, utils, node wiring)
Numerous small edits replacing typing.cast targets with string-literal forward refs; no runtime behavior changes.
Tooling
pyproject.toml
Removed Ruff ignore entry TC006.
CI workflows removed
.github/workflows/claude-code-review.yml, .github/workflows/claude.yml
Removed two Claude-related GitHub Actions workflows.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Host as RuntimeHostProcess
    participant Bootstrap as HandlerBootstrapSource
    participant Importer as importlib
    participant Registry as HandlerRegistry

    Host->>Bootstrap: discover_handlers()
    activate Bootstrap
    Bootstrap->>Bootstrap: build descriptors for\nconsul, db, http, vault
    Bootstrap-->>Host: ModelContractDiscoveryResult(descriptors)
    deactivate Bootstrap

    Host->>Host: _register_bootstrap_handlers()
    loop per descriptor
        Host->>Importer: import descriptor.handler_class
        alt import succeeds
            Importer-->>Host: HandlerClass
            Host->>Registry: register HandlerClass by protocol
        else import fails
            Importer-->>Host: ImportError
            Host->>Host: log warning, continue
        end
    end
    Host->>Host: proceed with contract-based discovery/wiring
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐇 I hopped in with names to seed,
Consul, DB, HTTP, Vault indeed.
Class paths tucked in tidy lines,
Bootstrapped handlers, wired in time.
Registry hums — my work’s complete!


Comment @coderabbitai help to get the list of available commands and usage tips.

@claude

claude Bot commented Jan 19, 2026

Copy link
Copy Markdown

PR Review: HandlerBootstrapSource Implementation [OMN-1087]

Overall Assessment: ✅ APPROVE

This is a well-implemented, thoroughly tested PR that centralizes bootstrap handler registration. The code follows ONEX patterns correctly and includes excellent test coverage.


Strengths

1. Excellent Code Quality

  • Clean architecture: Proper protocol implementation with ProtocolContractSource
  • Strong typing: No Any types, proper use of Pydantic models
  • Good documentation: Clear docstrings with usage examples and performance characteristics
  • ONEX compliance: Follows naming conventions, file patterns, and architectural principles

2. Comprehensive Test Coverage (813 lines)

The test suite is exemplary with 41 tests covering:

  • Protocol compliance verification
  • Handler discovery and descriptor validation
  • Graceful mode behavior
  • Idempotency guarantees
  • Edge cases and performance characteristics

Test organization into logical classes makes the suite maintainable and easy to understand.

3. Smart Forward Reference Handling

The _ensure_model_rebuilt() pattern cleverly avoids circular imports by deferring Pydantic model rebuild:

_model_rebuild_state: list[bool] = [False]  # Avoids global statement (PLW0603)

This is a clean solution to a common Pydantic issue.


Issues Found

🔴 CRITICAL: Missing Handler Module Paths

Location: handler_bootstrap_source.py:99-132

The _BOOTSTRAP_HANDLER_DEFINITIONS list is missing handler_module and handler_class fields. Looking at the HandlerPluginLoader pattern docs (referenced in CLAUDE.md), handler descriptors need these fields for runtime loading.

Current definition:

_BOOTSTRAP_HANDLER_DEFINITIONS: list[dict[str, str]] = [
    {
        "handler_id": "bootstrap.consul",
        "name": "Consul Handler",
        "description": "HashiCorp Consul service discovery handler",
        "handler_kind": "effect",
        "input_model": "omnibase_core.types.JsonDict",
        "output_model": "omnibase_core.models.dispatch.ModelHandlerOutput",
        # MISSING: handler_module and handler_class
    },
    # ... other handlers
]

Expected fields (based on CLAUDE.md handler_contract.yaml pattern):

"handler_module": "omnibase_infra.handlers.handler_consul",
"handler_class": "HandlerConsul",

Impact: If ModelHandlerDescriptor requires these fields, runtime handler instantiation will fail. If they're optional, this may be acceptable for bootstrap-only descriptors.

Recommendation:

  1. Check if ModelHandlerDescriptor requires handler_module/handler_class fields
  2. If required, add them to all 4 handler definitions
  3. If optional, add a comment explaining why bootstrap handlers omit them

⚠️ MODERATE: Graceful Mode Parameter Unused

Location: handler_bootstrap_source.py:195, 234

The graceful_mode parameter is stored but never actually used in the logic:

self._graceful_mode = graceful_mode  # Stored in __init__
# ... only used in logging (lines 234, 298), never in control flow

Issue: While the docstring correctly states this is "for API consistency", having an unused parameter can be confusing.

Options:

  1. Keep as-is (acceptable): Document this as intentional API consistency with HandlerContractSource
  2. Add assertion: assert not self._graceful_mode or True, "graceful_mode has no effect for bootstrap handlers"
  3. Remove parameter: If API consistency isn't critical at this stage

I lean toward option 1 (keep as-is) since API consistency is valuable, but consider adding a more prominent note in the docstring.


ℹ️ MINOR: Type Ignore Comment Could Be More Specific

Location: handler_bootstrap_source.py:245

handler_kind=handler_def["handler_kind"],  # type: ignore[arg-type]  # NOTE: Literal type checked by Pydantic

Issue: The comment says "Literal type checked by Pydantic" but the actual issue is that dict[str, str] doesn't narrow to Literal["effect"] at type-check time.

Better comment:

# type: ignore[arg-type]  # NOTE: handler_kind is Literal["effect"] but dict lookup returns str

This is cosmetic but improves clarity.


ℹ️ MINOR: Validation Exemption Pattern Could Be More Specific

Location: validation_exemptions.yaml:356

class_pattern: "Class name 'HandlerBootstrapSource'"

Issue: This pattern matches the error message text rather than being a precise regex. While functional, it's less maintainable if the validator's error message format changes.

Recommendation: Verify if the validator accepts regex patterns and use:

class_pattern: "HandlerBootstrapSource"

This is very minor and current approach is acceptable.


Security Considerations

✅ No security concerns:

  • No user input processing
  • No file I/O operations
  • No network calls
  • Hardcoded, validated data only
  • Immutable descriptors (frozen Pydantic models)

Performance Considerations

✅ Excellent performance characteristics:

  • O(1) time complexity: No I/O, just hardcoded data
  • Minimal memory: ~2KB total for 4 descriptors
  • Fast initialization: <1ms for discovery (validated by tests)
  • Idempotent: Multiple calls have identical results

The performance tests (lines 1129-1177) validate these guarantees.


Test Coverage Analysis

The test suite is comprehensive and well-structured:

Test Class Test Count Coverage
Protocol Compliance 5 ✅ Excellent
Handler Discovery 10 ✅ Excellent
Descriptor Validation 11 ✅ Excellent
Graceful Mode 6 ✅ Excellent
Idempotency 4 ✅ Excellent
Edge Cases 4 ✅ Excellent
Performance 2 ✅ Excellent

Notable test strengths:

  • Tests verify protocol compliance via isinstance(source, ProtocolContractSource)
  • Validates all 4 handler descriptors individually
  • Checks immutability (frozen models)
  • Performance bounds testing (100 rapid calls)

No significant gaps identified.


CLAUDE.md Compliance

✅ Fully compliant with ONEX patterns:

Requirement Status Evidence
No Any types ✅ No Any usage detected
File naming ✅ Not a handler, handler_bootstrap_source.py is correct for handler infrastructure
Strong typing ✅ Proper Pydantic models, list[dict[str, str]]
Protocol implementation ✅ Extends ProtocolContractSource, runtime checkable
Naming exemption ✅ Properly documented in validation_exemptions.yaml
No backwards compatibility ✅ New code, no legacy support

The inline comment # naming-ok (line 140) properly documents the exemption.


Recommendations Summary

Must Fix (Blocking)

  1. ❗ Verify handler_module/handler_class fields - Check if ModelHandlerDescriptor requires these and add if needed

Should Fix (Non-blocking)

  1. ⚠️ Document graceful_mode behavior - Add note that parameter is unused but kept for API consistency

Nice to Have

  1. ℹ️ Improve type: ignore comment clarity
  2. ℹ️ Consider more specific validation exemption pattern

Conclusion

This is high-quality code that demonstrates strong engineering discipline:

  • Clean architecture with proper protocol usage
  • Exceptional test coverage (41 tests, 813 lines)
  • Good performance characteristics
  • Excellent documentation

The only blocking concern is verifying whether handler_module/handler_class fields are required in the handler descriptors. Once confirmed, this PR is ready to merge.

Recommendation: ✅ APPROVE (pending verification of handler descriptor fields)


Review conducted following CLAUDE.md guidelines for ONEX infrastructure.

…rce [OMN-1087]

- Add handler_class field to ModelHandlerDescriptor for dynamic handler import
- Add handler_class to all bootstrap handler definitions (Consul, DB, HTTP, Vault)
- Extract handler_class in HandlerContractSource with TODO for omnibase_core update
- Document graceful_mode as unused but kept for API consistency
- Improve type: ignore comment clarity with safety rationale
- Add pattern specificity documentation to validation exemption
@claude

claude Bot commented Jan 19, 2026

Copy link
Copy Markdown

Pull Request Review: HandlerBootstrapSource Implementation [OMN-1087]

Summary

This PR implements HandlerBootstrapSource to centralize hardcoded handler registration for 4 core infrastructure handlers (Consul, Database, HTTP, Vault). The implementation follows the ProtocolContractSource protocol and provides a clean alternative to filesystem-based handler discovery.


✅ Strengths

Architecture & Design

  • Protocol compliance: Properly implements ProtocolContractSource with both source_type property and async discover_handlers() method
  • Separation of concerns: Cleanly separates bootstrap handlers from filesystem-based contract discovery
  • Idempotent design: Discovery method is safely callable multiple times
  • Performance: No I/O overhead - handlers are hardcoded definitions

Code Quality

  • Strong typing: No Any types, proper use of list[dict[str, str]] for handler definitions
  • Documentation: Comprehensive docstrings with examples, performance characteristics, and version history
  • Error handling: Graceful mode parameter for API consistency (though unused, as documented)
  • Logging: Structured logging with correlation IDs and performance metrics

Testing

  • Comprehensive coverage: 41 unit tests covering protocol compliance, discovery, validation, graceful mode, idempotency, edge cases, and performance
  • Test organization: Well-structured test classes with clear naming conventions
  • Test documentation: Each test has a clear docstring explaining the expected behavior

⚠️ Issues Found

1. CRITICAL: Potential Type Safety Issue (Line 265)

handler_kind=handler_def["handler_kind"],  # type: ignore[arg-type]

Issue: Using type: ignore to bypass type checking when passing string to Literal["compute", "effect", "reducer", "orchestrator"].

Risk: If someone modifies _BOOTSTRAP_HANDLER_DEFINITIONS and mistypes a handler_kind, the error won't be caught until runtime (Pydantic validation).

Recommendation: Use typed constants instead:

from typing import Literal

LiteralHandlerKind = Literal["compute", "effect", "reducer", "orchestrator"]

_BOOTSTRAP_HANDLER_DEFINITIONS: list[dict[str, str | LiteralHandlerKind]] = [
    {
        "handler_id": f"bootstrap.{_HANDLER_TYPE_CONSUL}",
        "handler_kind": "effect",  # No type: ignore needed
        # ...
    },
]

2. MEDIUM: TODO Comment in handler_contract_source.py (Lines 480-495)

# TODO [OMN-XXXX]: Extract handler_class from raw_data

Issue: The TODO references an unassigned ticket number (OMN-XXXX).

Impact: Technical debt tracking is incomplete. This workaround extracts handler_class from raw YAML because ModelHandlerContract doesn't have this field yet.

Recommendation:

  • Create a Linear ticket for updating ModelHandlerContract in omnibase_core
  • Update the TODO comment with the actual ticket number
  • Consider whether this should block the current PR

3. MINOR: Inconsistent Naming Convention (Line 82)

_HANDLER_TYPE_DATABASE = "db"

Issue: Constant name uses DATABASE but value is "db". Other constants match their values (consul, http, vault).

Recommendation: Either:

  • Change constant to _HANDLER_TYPE_DB to match the value
  • Change value to `"database"" to match the constant
  • Add a comment explaining the intentional mismatch

4. MINOR: Unused graceful_mode Parameter

The graceful_mode parameter is stored in _graceful_mode but never used in the implementation. While the docstring clearly documents this is for API consistency, it could confuse future maintainers.

Recommendation: Add a brief inline comment at line 211:

self._graceful_mode = graceful_mode  # Stored for API consistency only - bootstrap handlers cannot fail

🔍 ONEX Infrastructure Compliance Review

✅ Compliant Patterns

  • No Any types - All types properly specified
  • PEP 604 unions - Uses str | None correctly
  • Naming conventions - HandlerBootstrapSource follows Handler* pattern with validation exemption
  • Protocol compliance - Implements ProtocolContractSource properly
  • Correlation IDs - Logging includes structured context
  • Strong typing - All models use proper Pydantic types
  • Error handling - Returns ModelContractDiscoveryResult with validation_errors field
  • No backwards compatibility - Clean implementation without deprecated code

Pattern Validation

  • Validation exemption: Properly added to validation_exemptions.yaml (lines 1432-1452)
  • Export consistency: Correctly exported from runtime/__init__.py
  • Model usage: Uses ModelHandlerDescriptor and ModelContractDiscoveryResult from omnibase_infra.models.handlers

🧪 Test Coverage Analysis

Coverage by Category

Category Test Count Coverage
Protocol Compliance 5 ✅ Excellent
Handler Discovery 8 ✅ Excellent
Descriptor Validation 11 ✅ Excellent
Graceful Mode 6 ✅ Excellent
Idempotency 4 ✅ Excellent
Edge Cases 5 ✅ Excellent
Performance 2 ✅ Good

Test Quality Observations

  • Positive: Tests are well-organized with descriptive names
  • Positive: Each test class focuses on a specific aspect
  • Positive: Good coverage of both happy paths and edge cases
  • Suggestion: Consider adding integration tests that verify the handlers can actually be imported dynamically using the handler_class paths

🔒 Security Considerations

✅ No Security Risks Identified

  • Bootstrap handlers are hardcoded - no dynamic code execution
  • No user input processing
  • No filesystem access or network I/O
  • Handler class paths are hardcoded constants, not user-provided

📝 Documentation Quality

✅ Excellent Documentation

  • Module docstring clearly explains purpose and lists all registered handlers
  • Class docstring includes protocol compliance notes, API consistency explanation, examples, and performance characteristics
  • Method docstrings explain parameters, return values, and behavior
  • TODO comments explain workarounds (though ticket number needs updating)

Suggestion

Add a brief mention in CLAUDE.md about the bootstrap handler pattern to help future developers understand when to use HandlerBootstrapSource vs HandlerContractSource.


🎯 Recommendations

Must Fix Before Merge

  1. Resolve TODO ticket number - Either create the ticket or document why it's deferred
  2. Consider type safety improvement - Remove type: ignore by using proper typing

Should Fix (Non-Blocking)

  1. Clarify _HANDLER_TYPE_DATABASE vs `"db"" naming inconsistency
  2. Add inline comment for unused graceful_mode storage

Nice to Have

  1. Add integration test for dynamic handler class loading
  2. Update CLAUDE.md with bootstrap handler pattern guidance

✅ Final Verdict

APPROVED with minor suggestions

This is a well-designed, thoroughly tested implementation that follows ONEX infrastructure patterns correctly. The identified issues are minor and mostly relate to documentation/type safety improvements rather than functional problems.

The PR successfully:

  • Centralizes hardcoded handler registration per OMN-1087
  • Implements the ProtocolContractSource protocol properly
  • Provides comprehensive test coverage (41 tests)
  • Follows ONEX naming conventions and validation patterns
  • Maintains clean separation from filesystem-based contract discovery

Recommendation: Merge after addressing the TODO ticket number (item #1). Other suggestions can be addressed in follow-up PRs if preferred.


Great work on this implementation! The code quality, testing, and documentation are all excellent. 🎉

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/omnibase_infra/runtime/handler_bootstrap_source.py`:
- Around line 100-137: _BOOTSTRAP_HANDLER_DEFINITIONS contains four handler
dicts whose "input_model" wrongly points to "omnibase_core.types.JsonDict"
(which doesn't exist); update each handler dict's "input_model" to the correct
type path — either "omnibase_core.types.JsonType" (preferred canonical type) or
"omnibase_infra.models.types.JsonDict" if you want the local alias — so change
the "input_model" value for the entries with handler_class
"omnibase_infra.handlers.handler_consul.HandlerConsul",
"omnibase_infra.handlers.handler_db.HandlerDb",
"omnibase_infra.handlers.handler_http.HandlerHttpRest", and
"omnibase_infra.handlers.handler_vault.HandlerVault".
🧹 Nitpick comments (2)
tests/unit/runtime/test_handler_bootstrap_source.py (1)

687-700: Consider using a more specific exception type for frozen model test.

The pytest.raises(Exception) is broad. For Pydantic frozen models, the specific exception is pydantic_core._pydantic_core.ValidationError (or the wrapper pydantic.ValidationError). Using a more specific type would make the test more precise.

💡 Suggested refinement
 `@pytest.mark.asyncio`
 async def test_descriptors_are_frozen(self) -> None:
     """ModelHandlerDescriptor instances should be frozen (immutable).

     The ModelHandlerDescriptor model config has frozen=True.
     """
+    from pydantic import ValidationError
+
     source = HandlerBootstrapSource()

     result = await source.discover_handlers()

     for descriptor in result.descriptors:
         # Attempting to modify a frozen model should raise an error
-        with pytest.raises(Exception):  # ValidationError for frozen models
+        with pytest.raises(ValidationError):
             descriptor.handler_id = "modified"  # type: ignore[misc]
src/omnibase_infra/runtime/handler_contract_source.py (1)

480-495: Placeholder ticket number should be replaced with actual ticket.

The TODO comment references OMN-XXXX which is a placeholder. This should be replaced with an actual ticket number to track the work of adding handler_class to ModelHandlerContract in omnibase_core.

📋 Suggested fix

Create a ticket in your issue tracker for updating ModelHandlerContract to include handler_class, then replace the placeholder:

-        # TODO [OMN-XXXX]: Extract handler_class from raw_data
+        # TODO [OMN-1234]: Extract handler_class from ModelHandlerContract

Where OMN-1234 is the actual ticket number.

Comment thread src/omnibase_infra/runtime/handler_bootstrap_source.py Outdated
- Fix incorrect input_model path: omnibase_core.types.JsonDict →
  omnibase_infra.models.types.JsonDict (CRITICAL)
- Add BootstrapEffectDefinition TypedDict to eliminate type: ignore comment
- Add design note explaining handler_class vs handler_module decision
- Use pydantic.ValidationError instead of generic Exception in test
- Replace placeholder OMN-XXXX with OMN-1087 in handler_contract_source
- Export LiteralHandlerKind from models/handlers for TypedDict usage
@claude

claude Bot commented Jan 19, 2026

Copy link
Copy Markdown

Pull Request Review: HandlerBootstrapSource Implementation

I've reviewed PR #176 implementing HandlerBootstrapSource for centralized handler registration. Overall, this is a well-designed and well-tested implementation that follows ONEX conventions. Here's my detailed feedback:


✅ Strengths

1. Excellent Code Quality

  • Clean separation of concerns: Bootstrap source cleanly separates hardcoded handler registration from filesystem-based discovery
  • Strong type safety: Uses TypedDict (BootstrapEffectDefinition) to ensure compile-time type safety for handler definitions
  • Proper protocol compliance: Correctly implements ProtocolContractSource with all required methods
  • ONEX conventions: Follows all repository patterns (naming, structure, documentation)

2. Outstanding Test Coverage

  • 41 comprehensive unit tests covering all scenarios:
    • Protocol compliance verification
    • Handler discovery functionality
    • Descriptor validation
    • Edge cases (frozen models, no duplicates, idempotency)
    • Performance characteristics
  • Excellent test organization: Clear test class separation by concern
  • Thorough assertions: Tests validate both positive and negative cases

3. Documentation Excellence

  • Comprehensive docstrings: Module, class, and method documentation is detailed and accurate
  • Design notes: Inline comments explain architectural decisions (e.g., handler_class vs handler_module)
  • Performance guarantees documented: States expected performance characteristics with measurable assertions in tests

4. Proper Error Handling

  • Uses _ensure_model_rebuilt() to defer Pydantic forward reference resolution, avoiding circular imports
  • Gracefully handles the unused graceful_mode parameter with clear documentation about why it exists (API consistency)

🔍 Code Quality Observations

Architectural Decisions ✅

  1. Explicit protocol inheritance (line 175-177):

    class HandlerBootstrapSource(ProtocolContractSource):

    This is correct for ONEX - explicit inheritance ensures runtime isinstance() checks work correctly.

  2. Forward reference resolution pattern (lines 72-94):
    The deferred model_rebuild() approach is a good solution to circular import issues. The state tracking via list avoids global variable warnings.

  3. TypedDict for type safety (lines 49-64):
    Excellent use of TypedDict to ensure LiteralHandlerKind type compliance without needing type: ignore comments.

Potential Improvements 🔧

1. Thread Safety Consideration (Minor)

Location: _ensure_model_rebuilt() function (lines 72-94)

Issue: The current implementation has a potential race condition in multi-threaded contexts:

if _model_rebuild_state[0]:  # Thread A checks: False
    return
# Thread B could execute here and also pass the check
ModelContractDiscoveryResult.model_rebuild()  # Both threads call rebuild
_model_rebuild_state[0] = True

Impact: Low - model_rebuild() is likely idempotent, but in a concurrent runtime startup scenario, this could cause redundant work or potential race conditions.

Suggestion: Use threading.Lock for thread-safe initialization:

import threading

_model_rebuild_lock = threading.Lock()
_model_rebuild_state: list[bool] = [False]

def _ensure_model_rebuilt() -> None:
    if _model_rebuild_state[0]:
        return
    
    with _model_rebuild_lock:
        # Double-check pattern
        if _model_rebuild_state[0]:
            return
        
        from omnibase_infra.models.errors import ModelHandlerValidationError
        ModelContractDiscoveryResult.model_rebuild()
        _ = ModelHandlerValidationError
        _model_rebuild_state[0] = True

Priority: Optional - only relevant if bootstrap source is called concurrently during startup.

2. Handler Class Path Validation (Minor Enhancement)

Location: _BOOTSTRAP_HANDLER_DEFINITIONS (lines 132-169)

Observation: The handler_class paths are hardcoded strings that could become stale if handlers are renamed or moved.

Current risk: Low - changes to handler locations would be caught at import time by the plugin loader.

Suggestion (optional): Consider adding a validation test that attempts to import each handler class to catch stale paths early:

@pytest.mark.asyncio
async def test_all_handler_classes_are_importable() -> None:
    """Verify all bootstrap handler classes can be imported."""
    import importlib
    
    source = HandlerBootstrapSource()
    result = await source.discover_handlers()
    
    for descriptor in result.descriptors:
        if descriptor.handler_class:
            module_path, class_name = descriptor.handler_class.rsplit('.', 1)
            module = importlib.import_module(module_path)
            handler_cls = getattr(module, class_name)
            assert handler_cls is not None

Priority: Low - this is a nice-to-have that would catch refactoring issues earlier.

3. Consistency with HandlerContractSource (Documentation)

Location: handler_contract_source.py TODO comment (lines 444-460)

Observation: The TODO comment in handler_contract_source.py references extracting handler_class from raw_data because ModelHandlerContract doesn't have this field yet.

Note: This PR correctly adds handler_class to ModelHandlerDescriptor, and HandlerContractSource extracts it from raw YAML. This is consistent and correct.

Suggestion: Track the TODO [OMN-1087] mentioned in the comment to update ModelHandlerContract in omnibase_core to include handler_class as a first-class field.


🔒 Security Review

No Security Concerns ✅

  • No dynamic code execution: All handler definitions are hardcoded at development time
  • No external input: Source doesn't parse user-provided data
  • Pattern exemption properly documented: Validation exemption for "Handler" prefix is correctly added with proper justification
  • Aligns with security documentation: Bootstrap source is the trusted foundation for the plugin loader's security model

📋 ONEX Convention Compliance

Convention Status Notes
Strong typing (no Any) ✅ PASS No Any types used
PEP 604 unions (X | None) ✅ PASS Consistent use throughout
Protocol compliance ✅ PASS Implements ProtocolContractSource correctly
Container injection ⚠️ N/A Not applicable - source is stateless
File naming (handler_*.py) ✅ PASS Follows convention
Model naming ✅ PASS ModelHandlerDescriptor, ModelContractDiscoveryResult
Test coverage ✅ PASS Comprehensive unit tests
Documentation ✅ PASS Excellent docstrings and comments

🧪 Testing Recommendations

Additional Test Scenarios (Optional)

  1. Concurrent discovery test: Verify thread-safe behavior if discover_handlers() is called from multiple threads simultaneously
  2. Handler class import validation: Test that all handler_class paths are valid and importable (mentioned above)
  3. Integration test: Verify bootstrap source integrates correctly with the handler plugin loader in a full runtime scenario

📊 Performance Characteristics

The implementation correctly documents and tests performance guarantees:

  • No I/O operations ✅
  • Constant time O(1) ✅
  • Sub-millisecond performance ✅ (test validates < 100ms with generous CI variance tolerance)
  • Memory efficient ✅ (~500 bytes per descriptor estimate is reasonable)

The performance tests (lines 1265-1313) are well-designed with appropriate tolerances for CI variability.


✨ Best Practices Highlights

  1. Idempotency testing: Excellent coverage of repeated calls returning consistent results
  2. Frozen model validation: Tests verify ModelHandlerDescriptor immutability
  3. Structured logging: Uses proper extra dict for structured log fields
  4. Constants at module level: All magic strings extracted to named constants
  5. Export control: Proper __all__ declarations in both implementation and tests

🎯 Final Recommendation

APPROVE ✅ with optional minor improvements

This PR is production-ready and demonstrates excellent software engineering practices. The suggested improvements are minor and optional - they don't block merging.

Required Before Merge

  • ✅ All tests pass
  • ✅ CI validators pass (Any type checks, pattern validation)
  • ✅ Documentation complete

Optional Follow-ups

  • Consider adding thread safety to _ensure_model_rebuilt() if concurrent startup is a concern
  • Add handler class import validation test for early detection of refactoring issues
  • Track the ModelHandlerContract.handler_class field addition in omnibase_core

📝 Summary

This is a high-quality implementation that successfully centralizes hardcoded handler registration. The code is clean, well-tested, properly documented, and follows all ONEX conventions. The architectural design is sound and provides a clean foundation for the handler plugin system.

Great work on this PR! 🚀

…strapSource [OMN-1087]

- Add thread-safe initialization for _ensure_model_rebuilt() using
  double-checked locking pattern to prevent race conditions
- Add test_all_handler_classes_are_importable() test to verify handler
  class paths are valid and can be dynamically imported
@claude

claude Bot commented Jan 19, 2026

Copy link
Copy Markdown

Pull Request Review: HandlerBootstrapSource Implementation

This PR implements HandlerBootstrapSource to centralize hardcoded handler registration. The code is high-quality, well-tested, and follows all ONEX patterns.

Strengths

  1. Excellent Code Quality - Clean architecture with ProtocolContractSource, strong type safety with BootstrapEffectDefinition TypedDict, correct thread-safe double-checked locking
  2. Comprehensive Test Coverage - 41 unit tests covering protocol compliance, discovery, validation, idempotency, and performance
  3. Excellent Documentation - Detailed docstrings, design notes, thread safety explanations

Code Review Findings

CRITICAL: Potential Division by Zero (Low Impact)

  • Location: handler_bootstrap_source.py:348-349
  • Issue: handlers_per_sec returns 0.0 when duration_seconds == 0, should be infinity or large value
  • Recommendation: Use float('inf') or max(duration_seconds, 1e-9)
  • Impact: Low - logging/observability issue only

MINOR: Unused graceful_mode Parameter

  • The _graceful_mode attribute is stored but never used (documented as intentional)
  • Current approach acceptable given clear documentation

Test Coverage Analysis

Excellent coverage: protocol compliance, all 4 handlers discovered correctly, idempotency, descriptor immutability, dynamic import validation, performance.

Potential gaps: No concurrent access test for _ensure_model_rebuilt() thread safety, no error injection tests.

Security Review

No concerns - hardcoded definitions, no user input, handler class validation via regex, all classes verified importable.

ONEX Architecture Compliance

Fully compliant with CLAUDE.md: No Any types, PEP 604 unions, strong typing with LiteralHandlerKind, protocol-based design, proper exports, pattern validation exemption documented.

Recommendations Summary

Must Fix: None - code is production-ready

Should Consider (low priority): Division by zero edge case, optional concurrent access test

Nice to Have: Add warning when graceful_mode=True, stricter regex validation

Final Verdict: APPROVED

High-quality, well-tested, properly documented code following all ONEX patterns. Thread-safe, type-safe, comprehensive test coverage (41 tests). Minor issues are cosmetic and do not block merging.

Reviewed against: CLAUDE.md (ONEX Infrastructure patterns)
Linear Ticket: OMN-1087

…Source [OMN-1087]

- Add inline comment explaining graceful_mode parameter storage
  (stored for API consistency only - bootstrap handlers cannot fail)
- Fix division by zero edge case in handlers_per_sec calculation
  (returns inf when duration_seconds == 0 and handlers discovered)
@claude

claude Bot commented Jan 20, 2026

Copy link
Copy Markdown

PR Review: HandlerBootstrapSource Implementation [OMN-1087]

This PR implements a clean, well-designed solution for centralizing hardcoded handler registration.

Strengths

1. Excellent Code Quality

  • Clean ProtocolContractSource implementation with TypedDict for type safety
  • Thread-safe double-checked locking in _ensure_model_rebuilt()
  • Comprehensive docstrings with examples and cross-references

2. Strong ONEX Compliance

  • No Any types, proper PEP 604 unions (str | None)
  • Protocol-based design, correct naming conventions
  • Validation exemption documented in validation_exemptions.yaml

3. Comprehensive Test Coverage

  • 856 lines covering 41 tests across 7 test classes
  • Tests protocol compliance, descriptors, edge cases, performance, idempotency
  • Excellent: test_all_handler_classes_are_importable() catches refactoring issues

4. Security

  • Frozen models prevent tampering
  • Regex validation for handler_class, input_model, output_model
  • No path traversal or injection vulnerabilities

Code Review Findings

Critical Issues

None - PR is ready to merge ✅

Design Considerations

  1. graceful_mode parameter: Accepted but unused - this is fine for API consistency with HandlerContractSource

  2. Model rebuild pattern: Necessary workaround for Pydantic forward references - implementation is correct

  3. Performance discrepancy: Docstring claims "<1ms" but test allows 100ms - minor documentation inconsistency

Test Quality: 5/5

All categories excellent:

  • Protocol compliance: 5 tests
  • Handler discovery: 10 tests
  • Descriptor validation: 14 tests
  • Graceful mode: 6 tests
  • Idempotency: 4 tests
  • Edge cases: 6 tests
  • Performance: 2 tests

Architecture: 5/5

Correct ONEX patterns:

  • Protocol-based design
  • Descriptor pattern for metadata
  • Source abstraction for multiple handler sources
  • Graceful error handling

Recommendations

Must Have (Before Merge)

None - ready to merge ✅

Should Have (Low Priority)

  1. Clarify performance claims: Update docstring or test threshold for consistency
  2. Track omnibase_core TODO: Create follow-up ticket for ModelHandlerContract.handler_class

Nice to Have

  1. Adopt importability test pattern in other handler sources
  2. Consider centralizing model rebuild logic

Summary Score

Category Score
Code Quality 5/5
ONEX Compliance 5/5
Test Coverage 5/5
Security 5/5
Documentation 5/5
Performance 5/5
Overall 5/5

Final Verdict

APPROVED ✅

This PR is exceptionally well-implemented with:

  • Clean architecture following ONEX patterns
  • Comprehensive test coverage (41 tests)
  • Excellent documentation
  • No security concerns
  • Thread-safe implementation
  • Zero critical issues

Recommendation: Merge after optionally addressing documentation note about performance claims.

Great work! The TypedDict for type safety and comprehensive test suite set a high bar for future implementations.


Review by Claude Code following ONEX standards in CLAUDE.md

…urce [OMN-1087]

- Clarify performance claims: docstring now distinguishes typical (<1ms local)
  from test threshold (100ms for CI variance)
- Update TODO comment to reference OMN-1420 (follow-up for ModelHandlerContract
  handler_class field in omnibase_core)
- Fix pyproject.toml: remove invalid TC006 rule (doesn't exist in ruff)
@claude

claude Bot commented Jan 20, 2026

Copy link
Copy Markdown

Code Review - PR #176: HandlerBootstrapSource Implementation

This PR implements a centralized bootstrap handler source for hardcoded handler registration. The implementation is high quality with excellent test coverage and follows ONEX architectural patterns.

Strengths

1. Excellent Architecture and Design

  • Protocol compliance: Properly implements ProtocolContractSource protocol
  • Clean separation: Centralizes hardcoded handler wiring
  • Type safety: Uses BootstrapEffectDefinition TypedDict for compile-time safety
  • Thread-safe initialization: Double-checked locking pattern for _ensure_model_rebuilt()

2. Outstanding Test Coverage (856 lines!)

  • 41 comprehensive unit tests across 7 test classes
  • Tests cover: protocol compliance, discovery, descriptor validation, graceful mode, idempotency, edge cases, performance
  • Particularly strong: test_all_handler_classes_are_importable catches refactoring issues early

3. Clear Documentation

  • Module docstring explains purpose, registered handlers, relationships
  • Inline comments explain design decisions
  • Docstrings include examples and performance characteristics

Potential Issues

CRITICAL: handler_class Field Validation

Location: model_handler_descriptor.py:49-54

The regex pattern is too permissive and allows minimal paths like a.b.c or evil.module.DeleteDatabase.

Recommendation: Ensure namespace allowlisting is ENABLED in production configurations per CLAUDE.md security patterns.

Minor: TODO Comment Tracking

Location: handler_contract_source.py:478-494

TODO OMN-1420 references extracting handler_class from ModelHandlerContract. Verify this ticket exists and is tracked.

Performance

Excellent performance characteristics:

  • No I/O operations
  • Constant time O(1) discovery
  • Memory efficient: 500 bytes per handler
  • Performance tests enforce under 100ms total, under 10ms avg

Security

Built-in protections include YAML safe loading, protocol validation, and namespace allowlisting.

Ensure deployment checklist items from CLAUDE.md are followed especially namespace allowlisting ENABLED in production.

Test Coverage

Exceptional test quality with 41 tests across 7 test classes covering all aspects.

Overall Assessment

Verdict: APPROVE with minor recommendations

This is excellent work demonstrating strong architectural design, outstanding test coverage, clear documentation, and proper ONEX conventions. The implementation is production-ready.

Action Items for follow-up:

  • Track OMN-1420 for ModelHandlerContract.handler_class field
  • Verify namespace allowlisting in production configs
  • Consider simplifying nested ternary for readability

Great job!

… [OMN-1087]

Ruff 0.14.x introduced TC006 lint rule requiring quoted type expressions
in typing.cast() calls to prevent runtime type evaluation issues with
TYPE_CHECKING-only imports.

Changes:
- Add quotes to 26 cast() type expressions across 13 files
- Auto-fixed via `ruff check --fix`

Affected modules:
- handlers/mixins/mixin_consul_kv.py
- handlers/service_discovery/handler_service_discovery_consul.py
- mixins/mixin_node_introspection.py
- mixins/mixin_retry_execution.py
- nodes/node_registration_orchestrator/wiring.py
- plugins/examples/plugin_json_normalizer.py
- plugins/examples/plugin_json_normalizer_error_handling.py
- runtime/service_message_dispatch_engine.py
- utils/util_dsn_validation.py
- validation/validator_chain_propagation.py
- validation/validator_runtime_shape.py
- tests/chaos/test_recovery_dlq.py
- tests/integration/registration/e2e/performance_utils.py
@claude

claude Bot commented Jan 20, 2026

Copy link
Copy Markdown

PR Review: HandlerBootstrapSource Implementation

Overview

This PR implements HandlerBootstrapSource to centralize hardcoded handler registration for core infrastructure handlers. Implements ProtocolContractSource protocol and provides 4 bootstrap handlers as ModelHandlerDescriptor instances.


Strengths

1. Excellent Architecture

  • Proper ProtocolContractSource implementation
  • TypedDict usage for compile-time type safety
  • Thread-safe model rebuild with double-checked locking
  • 41 comprehensive unit tests

2. Type Safety

  • Zero Any types (CLAUDE.md compliant)
  • PEP 604 unions
  • Strong Pydantic typing
  • LiteralHandlerKind properly exported

3. Documentation

  • Clear module docstrings
  • Inline design notes
  • Proper versionadded markers

Potential Issues

CRITICAL: Input Model Path Verification

Bootstrap handlers specify: input_model: omnibase_core.types.JsonDict

Action Required: Verify this path is correct vs omnibase_infra.models.types.JsonDict

Recommendation: Add test to verify input_model and output_model paths are importable

Test Coverage Gaps

Missing:

  • Input/output model importability tests
  • Concurrent discovery thread safety tests

Minor: Validation Exemption Documentation

Needs clearer explanation in validation_exemptions.yaml


Test Coverage: 41 Tests

  • Protocol Compliance: 5 tests
  • Handler Discovery: 9 tests
  • Descriptor Validation: 11 tests
  • Graceful Mode: 6 tests
  • Idempotency: 4 tests
  • Edge Cases: 5 tests
  • Performance: 2 tests

Approval Recommendation

APPROVE with minor fixes

Excellent implementation following ONEX patterns. Only blocking issue is verifying input_model import path.

Risk: LOW
Test coverage: EXCELLENT
Documentation: EXCELLENT
Code quality: HIGH


Highlights

  1. TypedDict pattern for type safety
  2. Correct double-checked locking
  3. Comprehensive test suite
  4. Design documentation
  5. Protocol-driven design

Review conducted per CLAUDE.md guidelines

…087]

Address PR #176 review recommendations:

1. Input/output model importability tests (TestHandlerBootstrapSourceModelImportability):
   - test_all_input_models_are_importable: Verifies input_model paths resolve
   - test_all_output_models_are_importable: Verifies output_model paths resolve
   - test_input_model_jsondict_is_correct_type: Confirms omnibase_infra path
   - test_output_model_handler_output_is_pydantic_model: Validates BaseModel

2. Concurrent discovery thread safety tests (TestHandlerBootstrapSourceThreadSafety):
   - test_concurrent_discovery_returns_consistent_results: Asyncio concurrency
   - test_concurrent_discovery_with_multiple_sources: Multiple source instances
   - test_model_rebuild_lock_is_thread_safe: Thread-based concurrency
   - test_rapid_concurrent_discovery_stress: High-concurrency stress test

The input_model paths were already fixed in prior commit (4f12625) to use
omnibase_infra.models.types.JsonDict instead of the incorrect
omnibase_core.types.JsonDict path. These tests ensure the fix stays correct.
@claude

claude Bot commented Jan 20, 2026

Copy link
Copy Markdown

PR Review: HandlerBootstrapSource Implementation (OMN-1087)

Summary

This PR implements a well-designed bootstrap handler source that centralizes hardcoded handler registration. The implementation is solid with excellent test coverage (41 comprehensive unit tests) and follows ONEX patterns consistently.


✅ Strengths

1. Architecture & Design

  • Clean separation of concerns: Bootstrap source correctly implements ProtocolContractSource protocol
  • Consistent pattern: Mirrors HandlerContractSource design for API consistency
  • Well-documented rationale: Clear explanation of why hardcoded handlers are needed vs. filesystem discovery

2. Code Quality

  • Strong type safety: Uses LiteralHandlerKind and BootstrapEffectDefinition TypedDict to ensure compile-time correctness
  • Thread-safe initialization: Double-checked locking pattern for _ensure_model_rebuilt() is correctly implemented
  • Immutability: ModelHandlerDescriptor properly uses frozen=True config
  • Zero Any types: Fully compliant with ONEX strict typing rules

3. Test Coverage ⭐

Exceptionally thorough test suite covering:

  • Protocol compliance verification
  • All 4 bootstrap handlers (consul, db, http, vault)
  • Descriptor field validation and importability
  • Graceful mode API consistency
  • Idempotency guarantees
  • Thread safety with concurrent discovery tests (excellent!)
  • Performance characteristics verification
  • Edge cases (frozen models, no duplicates, valid handler kinds)

4. Documentation

  • Clear module docstring with handler registry table
  • Version history tracking (versionadded directives)
  • Inline comments explaining design decisions (e.g., handler_class vs handler_module)
  • Test docstrings explain expected behavior

5. Adherence to ONEX Patterns

  • ✅ No backwards compatibility (breaking changes allowed)
  • ✅ Strong typing with Pydantic models
  • ✅ PEP 604 union syntax (X | None)
  • ✅ Proper file/class naming (handler_bootstrap_source.py → HandlerBootstrapSource)
  • ✅ Contract-driven architecture

🔍 Code Review Findings

Minor Issues

1. Type Checker Suppression Comment (Low Priority)

File: handler_bootstrap_source.py:109

# Suppress unused variable warning - the import is needed for model_rebuild()
_ = ModelHandlerValidationError

Issue: The comment mentions "unused variable warning" but the actual suppression is for model_rebuild() side effects.

Suggestion: Clarify comment to better reflect intent:

# Import needed in scope for Pydantic model_rebuild() to resolve forward references
_ = ModelHandlerValidationError  # Keep import in scope for rebuild

2. Graceful Mode Documentation Clarity

File: handler_bootstrap_source.py:208-213

Observation: The docstring notes that graceful_mode is "currently unused" which is correct, but could add a forward-looking note about when it might be used.

Suggestion: Add note about future extensibility:

Note: This parameter is currently unused. Bootstrap handlers are hardcoded
definitions that cannot fail validation. If future bootstrap handlers involve
dynamic discovery or validation, this mode would enable error collection.

3. Error Handling for Model Rebuild

File: handler_bootstrap_source.py:77-110

Observation: The _ensure_model_rebuilt() function doesn't catch potential exceptions from ModelContractDiscoveryResult.model_rebuild().

Question: Should we wrap the rebuild in a try-except to handle potential circular import or validation errors more gracefully? This would prevent obscure errors during bootstrap.

Potential Enhancement:

try:
    ModelContractDiscoveryResult.model_rebuild()
    _model_rebuild_state[0] = True
except Exception as e:
    logger.error("Failed to rebuild ModelContractDiscoveryResult: %s", e)
    raise RuntimeError(
        f"Model rebuild failed during bootstrap initialization: {e}"
    ) from e

🎯 Verification Items

✅ Completed

  • Protocol compliance (implements ProtocolContractSource)
  • All handler classes are importable (verified by tests)
  • Input/output model paths are valid (verified by tests)
  • Thread safety with concurrent access
  • Idempotency guarantees
  • Performance characteristics (<100ms for discovery)
  • Proper exports in runtime/__init__.py
  • Validation exemption added for class naming pattern
  • No Any types used

⚠️ To Verify

  • Integration Test: Verify bootstrap source integrates correctly with runtime handler loading
  • Runtime Verification: Confirm handlers are actually registered and callable in runtime context
  • CI Pipeline: Ensure all validators pass (pattern validation, Any type check)

🔒 Security Review

✅ No Security Concerns

  • Hardcoded handler definitions (no dynamic imports in bootstrap source itself)
  • No user input or untrusted data
  • No secrets or sensitive data handling
  • Thread-safe initialization prevents race conditions

Note: The actual handler classes (Consul, DB, HTTP, Vault) would need separate security review, but this bootstrap source is just metadata registration.


📊 Performance Considerations

✅ Excellent Performance Design

  • Constant time O(1) discovery (no filesystem I/O)
  • Memory efficient: ~500 bytes per descriptor
  • Fast initialization: <1ms typical, <100ms test threshold
  • Test suite verifies 100 rapid calls complete in <10ms average

Benchmark Results (from test suite):

  • Single discovery: <100ms
  • 100 rapid calls: <1 second total (<10ms average per call)

🧪 Test Quality Assessment

⭐ Exceptional Test Coverage

Test Categories:

  1. Protocol Compliance (5 tests) - Verify interface implementation
  2. Handler Discovery (10 tests) - Core discovery functionality
  3. Descriptor Validation (15 tests) - Field validation and content checks
  4. Graceful Mode (5 tests) - API consistency verification
  5. Idempotency (4 tests) - Repeated call consistency
  6. Thread Safety (4 tests) - Concurrent access verification
  7. Model Importability (4 tests) - Dynamic import validation
  8. Performance (2 tests) - Speed characteristics

Test Strengths:

  • ✅ Comprehensive edge case coverage
  • ✅ Clear test names describing expected behavior
  • ✅ Proper use of pytest fixtures and markers
  • ✅ Verification of both positive and negative cases
  • ✅ Performance regression tests

📝 Documentation Review

✅ Well-Documented

  • Module docstring: Clear purpose and handler registry
  • Class docstring: Usage examples with expected output
  • Method docstrings: Parameter descriptions and return types
  • Inline comments: Design decisions explained (e.g., handler_class field design)
  • Version tracking: versionadded directives for traceability

Suggestions

  1. Add ADR (Architecture Decision Record) for why bootstrap handlers are needed vs. pure contract-based discovery
  2. Consider adding sequence diagram showing how bootstrap source fits into handler loading flow

🎨 Code Style & Conventions

✅ Excellent Adherence to ONEX Standards

  • File naming: ✅ handler_bootstrap_source.py
  • Class naming: ✅ HandlerBootstrapSource
  • Type annotations: ✅ PEP 604 unions (str | None)
  • Imports: ✅ Proper from __future__ import annotations
  • Constants: ✅ SCREAMING_SNAKE_CASE (SOURCE_TYPE_BOOTSTRAP)
  • Docstrings: ✅ Google-style with proper formatting

Minor Style Notes

  1. Line length: All lines within 100 character limit ✅
  2. Import ordering: Follows isort configuration ✅
  3. Type hints: Comprehensive and accurate ✅

🔄 Changes to Other Files

✅ Proper Propagation

1. Runtime __init__.py (src/omnibase_infra/runtime/__init__.py)

  • ✅ Correctly exports HandlerBootstrapSource and SOURCE_TYPE_BOOTSTRAP
  • ✅ Added to __all__ list
  • ✅ Documented with comments

2. Validation Exemptions (validation_exemptions.yaml)

  • ✅ Added exemption for HandlerBootstrapSource class name pattern
  • ✅ Proper rationale provided (ONEX handler infrastructure)
  • ✅ References OMN-1087 ticket
  • ✅ Consistent with HandlerContractSource exemption pattern

3. Model Exports (models/handlers/__init__.py)

  • ✅ Exports LiteralHandlerKind type alias
  • ✅ Already exported ModelHandlerDescriptor

4. TC006 Ruff Rule Removed (pyproject.toml)

  • ✅ Removed TC006 ignore (quotes in type expressions)
  • ⚠️ Verify: Ensure this doesn't cause issues in other parts of codebase
  • Files affected: Multiple files updated with quoted cast() calls

⚠️ Potential Risks & Considerations

Low Risk Items

  1. Model Rebuild Dependency

    • Risk: model_rebuild() depends on import side effects
    • Mitigation: Double-checked locking prevents race conditions
    • Severity: LOW (well-tested pattern)
  2. Hardcoded Handler List

    • Risk: Forgetting to update when handlers are added/renamed
    • Mitigation: Tests verify all handlers are importable
    • Severity: LOW (caught by tests)
    • Suggestion: Consider CI job that compares bootstrap list to actual handler implementations
  3. API Consistency Parameter

    • Risk: graceful_mode parameter is unused but present
    • Mitigation: Documented as API consistency parameter
    • Severity: LOW (intentional design choice)

🚀 Recommendations

Before Merge (Optional Improvements)

  1. Add integration test showing bootstrap source working with handler registry
  2. Add comment clarifying model rebuild import side effect
  3. Consider error handling around model_rebuild() call

Post-Merge (Future Work)

  1. Create ADR documenting bootstrap vs. contract-based discovery design decision
  2. Add CI check that verifies bootstrap handler list matches actual implementations
  3. Monitor performance in production to validate <1ms typical performance claim

📋 Final Verdict

✅ APPROVED - Excellent Implementation

Summary: This PR is well-designed, thoroughly tested, and follows ONEX patterns consistently. The code quality is high with strong type safety, proper thread safety, and comprehensive test coverage.

Minor suggestions above are optional improvements that don't block merging. The implementation is production-ready.

Key Metrics:

  • Test Coverage: 41 comprehensive unit tests ⭐⭐⭐⭐⭐
  • Type Safety: 100% (no Any types) ⭐⭐⭐⭐⭐
  • Documentation: Excellent with examples ⭐⭐⭐⭐⭐
  • Performance: <1ms typical discovery ⭐⭐⭐⭐⭐
  • Thread Safety: Verified with concurrent tests ⭐⭐⭐⭐⭐

Confidence Level: HIGH - Ready to merge


🙏 Nice Work!

Particularly impressed by:

  1. Thread safety tests with concurrent discovery
  2. Model importability verification tests
  3. Performance regression tests
  4. Clear documentation with usage examples
  5. Consistent API design matching HandlerContractSource

This sets a great standard for future handler source implementations.


Reviewer: Claude (Sonnet 4.5)
Review Date: 2026-01-20
PR: #176 (OMN-1087)

…y [OMN-1087]

Address code review feedback:

1. Clarified comment explaining why ModelHandlerValidationError import
   must be in scope for Pydantic's forward reference resolution

2. Added try-except around model_rebuild() to provide clear error message
   instead of obscure Pydantic errors when circular imports or missing
   type definitions occur

3. Renamed comment from "suppress unused variable warning" to better
   reflect the intent: "keep import reference in scope for forward refs"
@claude

claude Bot commented Jan 20, 2026

Copy link
Copy Markdown

PR Review: HandlerBootstrapSource Implementation [OMN-1087]

This PR implements a well-structured HandlerBootstrapSource class that centralizes hardcoded handler registration for core infrastructure handlers. The implementation follows ONEX patterns and includes comprehensive test coverage (41 unit tests, 1145 lines).

Strengths

1. Excellent Code Quality

  • Clean architecture with proper ProtocolContractSource implementation
  • Thread-safe initialization using double-checked locking pattern (lines 69-119)
  • Type safety via BootstrapEffectDefinition TypedDict with LiteralHandlerKind
  • Comprehensive documentation with examples and rationale

2. Strong Test Coverage (1145 lines)

  • Protocol compliance tests
  • Descriptor validation (all fields)
  • Thread safety tests (concurrent discovery)
  • Performance tests (< 100ms threshold)
  • Edge cases (frozen models, no duplicates)
  • Model importability tests

3. Proper ONEX Patterns

  • Container-based DI patterns
  • Proper error handling with structured logging
  • Consistent with HandlerContractSource API
  • Validation exemption properly documented
  • Exports added to runtime/init.py

4. Security

  • Hardcoded definitions prevent runtime tampering
  • No filesystem/network I/O reduces attack surface
  • Constant-time O(1) discovery

Issues & Recommendations

CRITICAL: Unused graceful_mode Parameter

Location: handler_bootstrap_source.py:250-270

Issue: The graceful_mode parameter is accepted but never used. While the docstring explains this is for API consistency, this creates a misleading interface.

Why this matters:

  1. Violates Principle of Least Surprise - users may expect different behavior
  2. Maintenance burden - future maintainers may assume this has an effect
  3. Test pollution - tests verify both modes behave identically (lines 549-601)

Recommendation (PREFERRED): Remove the parameter entirely

  • Per CLAUDE.md No Backwards Compatibility policy - breaking changes are acceptable
  • Simpler API surface
  • Removes misleading interface
  • Protocol does not require this parameter
  • Can add back later if truly needed

Alternative: Keep for protocol compatibility but add warning when used

MINOR: Ruff TC006 Rule

The PR removes the TC006 ignore, requiring cast expressions to use string literals. This is a minor style consistency improvement. No action needed.

Files affected: mixin_consul_kv.py, handler_service_discovery_consul.py, test files

OBSERVATION: Model Rebuild Pattern

The model rebuild pattern (lines 77-120) is identical to handler_contract_source.py. Consider extracting to shared utility if more sources are added (NOT for this PR).

Performance

Excellent performance characteristics validated by tests:

  • Discovery completes in < 100ms
  • No filesystem/network I/O
  • Constant time O(1) complexity
  • Thread-safe concurrent access (50 concurrent calls tested)
  • Average call time < 10ms (100 iterations)

Security

No security concerns identified:

  • Hardcoded definitions prevent injection attacks
  • No dynamic code execution
  • No filesystem traversal
  • Thread-safe initialization
  • All handler class paths validated as importable

ONEX Compliance

Checked against CLAUDE.md:

  • No Any types used
  • Proper file/class naming
  • Pydantic models with strong typing
  • Container-based DI pattern compatible
  • Protocol-driven architecture
  • Validation exemption properly documented

Verdict

APPROVE with recommendation to remove graceful_mode parameter

This is a high-quality implementation with exceptional test coverage. The only significant issue is the unused graceful_mode parameter.

Action Items:

  1. RECOMMENDED: Remove graceful_mode parameter or add warning
  2. OPTIONAL: Document model rebuild pattern duplication for future refactoring

Merge Readiness:

  • Can merge as-is if graceful_mode consistency is valued over API simplicity
  • Better to address graceful_mode parameter before merge per No Backwards Compatibility policy

Great work on the comprehensive test coverage and clean implementation!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/omnibase_infra/runtime/handler_bootstrap_source.py`:
- Around line 37-46: Replace uses of RuntimeError raised for rebuild failures
with ModelOnexError (or the project's OnexError subclass for model errors) and
include an appropriate error code and descriptive message; update imports to
bring ModelOnexError into scope and change every raise RuntimeError(...) in this
module (including the occurrences around the rebuild logic at the earlier and
later blocks referenced) to raise ModelOnexError(code="MODEL_REBUILD_FAILED",
message="...") or the project's canonical code/message pattern. Ensure the new
error preserves the original failure message and any chained exception info when
available (e.g., raise ModelOnexError(...) from err).
♻️ Duplicate comments (1)
src/omnibase_infra/runtime/handler_bootstrap_source.py (1)

157-193: Prefer canonical JsonType for bootstrap input_model.
Align the hardcoded input_model with the canonical JSON alias. As per coding guidelines, use JsonType from omnibase_core.types for JSON-compatible values.

♻️ Suggested update
-        "input_model": "omnibase_infra.models.types.JsonDict",
+        "input_model": "omnibase_core.types.JsonType",
@@
-        "input_model": "omnibase_infra.models.types.JsonDict",
+        "input_model": "omnibase_core.types.JsonType",
@@
-        "input_model": "omnibase_infra.models.types.JsonDict",
+        "input_model": "omnibase_core.types.JsonType",
@@
-        "input_model": "omnibase_infra.models.types.JsonDict",
+        "input_model": "omnibase_core.types.JsonType",
🧹 Nitpick comments (1)
tests/unit/runtime/test_handler_bootstrap_source.py (1)

1094-1132: Consider de‑flaking timing-based performance assertions.

The <100ms and <10ms thresholds can be noisy under CI contention. Consider marking these as @pytest.mark.slow or relaxing bounds / making them configurable to avoid intermittent failures.

Also applies to: 1114-1132

Comment on lines +37 to +46
import logging
import threading
import time
from typing import TypedDict

from omnibase_infra.models.handlers import (
LiteralHandlerKind,
ModelContractDiscoveryResult,
ModelHandlerDescriptor,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Use ModelOnexError instead of RuntimeError for rebuild failures.
Project error-handling conventions require OnexError types with error codes. As per coding guidelines, use OnexError for error handling.

🔧 Proposed fix
-from omnibase_infra.models.handlers import (
+from omnibase_core.enums import EnumCoreErrorCode
+from omnibase_core.models.errors import ModelOnexError
+from omnibase_infra.models.handlers import (
@@
-        except Exception as e:
-            raise RuntimeError(
-                f"Failed to rebuild ModelContractDiscoveryResult during bootstrap "
-                f"initialization. This typically indicates a circular import or missing "
-                f"type definition: {e}"
-            ) from e
+        except Exception as e:
+            raise ModelOnexError(
+                message=(
+                    "Failed to rebuild ModelContractDiscoveryResult during bootstrap "
+                    "initialization. This typically indicates a circular import or missing "
+                    f"type definition: {e}"
+                ),
+                error_code=EnumCoreErrorCode.INTERNAL_ERROR,
+            ) from e

Also applies to: 101-115

🤖 Prompt for AI Agents
In `@src/omnibase_infra/runtime/handler_bootstrap_source.py` around lines 37 - 46,
Replace uses of RuntimeError raised for rebuild failures with ModelOnexError (or
the project's OnexError subclass for model errors) and include an appropriate
error code and descriptive message; update imports to bring ModelOnexError into
scope and change every raise RuntimeError(...) in this module (including the
occurrences around the rebuild logic at the earlier and later blocks referenced)
to raise ModelOnexError(code="MODEL_REBUILD_FAILED", message="...") or the
project's canonical code/message pattern. Ensure the new error preserves the
original failure message and any chained exception info when available (e.g.,
raise ModelOnexError(...) from err).

Address PR review recommendation to remove misleading graceful_mode parameter.

**Why removed:**
- Protocol (ProtocolContractSource) doesn't require constructor params
- Bootstrap handlers are hardcoded and CANNOT fail validation
- graceful_mode was semantically meaningless for this source
- Per CLAUDE.md: "NO backwards compatibility is maintained"
- Tests were verifying "both modes behave identically" (testing nothing)

**Changes:**
- Remove __init__ graceful_mode parameter from HandlerBootstrapSource
- Remove self._graceful_mode from logging extra fields
- Remove "API Consistency Note" from class docstring
- Delete TestHandlerBootstrapSourceGracefulMode test class (6 tests)

Test count: 50 → 44 (removed pointless tests)
@claude

claude Bot commented Jan 20, 2026

Copy link
Copy Markdown

PR Review: HandlerBootstrapSource Implementation (OMN-1087)

This PR implements a centralized bootstrap handler source for core infrastructure handlers. Overall, this is high-quality code with excellent test coverage and clean architecture.

Strengths

  1. Excellent Architecture - Properly implements ProtocolContractSource with clear separation of concerns
  2. Outstanding Test Coverage - 44 comprehensive tests covering protocol compliance, thread safety, concurrency, and performance
  3. Thread Safety - Double-checked locking pattern in _ensure_model_rebuilt() is correctly implemented
  4. Type Safety - BootstrapEffectDefinition TypedDict eliminates type: ignore comments
  5. Clean Error Handling - Good error messages and edge case handling
  6. Documentation - Excellent inline comments explaining design decisions

Critical Issue: Missing Runtime Integration

The HandlerBootstrapSource is implemented but there is no visible integration point in the runtime. Expected to see it used by HandlerPluginLoader or ContractHandlerDiscovery during bootstrap.

Questions:

  • How does the runtime discover these bootstrap handlers?
  • Is there a follow-up PR that wires this into the runtime?
  • Should wire_default_handlers() be updated to use this source?

Recommendation: Either add integration in this PR OR document this as part 1 of multi-PR implementation.

Minor Issues

  1. handler_class Field Optionality - Bootstrap handlers require handler_class but field is optional (str | None). Consider making required or adding validation.
  2. Performance Test Threshold - 100ms seems generous for 4 hardcoded handlers with no I/O. Consider tightening to 50ms.
  3. Model Rebuild Pattern - Pattern duplicated between HandlerBootstrapSource and HandlerContractSource with variations. Consider shared utility or add comments explaining differences.

Security Review

  • Validation exemption properly documented
  • Thread safety verified with comprehensive tests
  • No Any types used

Final Verdict

APPROVE with clarification needed on runtime integration.

This is high-quality code that follows ONEX patterns consistently. The only blocking concern is understanding how this integrates with the runtime. Once clarified, this is ready to merge.

Great work on the comprehensive test coverage! 🎉

…N-1087]

Integrate HandlerBootstrapSource into RuntimeHostProcess to ensure core
infrastructure handlers (consul, db, http, vault) are always available
during bootstrap, regardless of user contract discovery errors.

Changes:
- Add _register_bootstrap_handlers() to service_runtime_host_process.py
  that loads bootstrap handlers FIRST before contract discovery
- Create ModelBootstrapHandlerDescriptor with required handler_class field
- Add thread-safe model_rebuild pattern to handler_bootstrap_source.py
- Update tests to verify graceful degradation behavior (handlers registered
  even when contracts fail)
- Fix macOS symlink path resolution in test fixtures

Test coverage:
- 12 new integration tests for bootstrap source runtime integration
- 24 new unit tests for ModelBootstrapHandlerDescriptor
- Updated 9 handler discovery tests for graceful degradation
- All 2339 tests passing
@claude

claude Bot commented Jan 20, 2026

Copy link
Copy Markdown

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

Bootstrap handlers now provide core infrastructure (Consul, DB, HTTP, Vault),
making the wire_handlers() fallback redundant.

Changes:
- Remove wire_handlers() fallback from _discover_or_wire_handlers()
- Update docstring to reflect bootstrap-first architecture
- Update test_start_wires_handlers → test_start_registers_bootstrap_handlers
- Fix outdated comments referencing fallback behavior in tests
…ptor

Remove unused _VersionField and LiteralHandlerKind imports that were
inadvertently included during initial implementation. These type aliases
are not used in the bootstrap descriptor module.

[OMN-1087]
Replace manual field-by-field copy with Pydantic's model_dump() pattern.
This is more concise and automatically captures any new fields added
to the parent class in future versions.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@tests/integration/runtime/test_bootstrap_source_integration.py`:
- Around line 229-263: The test mocks HandlerBootstrapSource to return empty
descriptors which can cause RuntimeHostProcess.start() to raise
ProtocolConfigurationError when the global registry has no handlers; modify the
test (test_bootstrap_source_called_during_start and the similar case at 358-391)
to ensure a non-empty registry before calling process.start() by seeding a stub
handler or creating/injecting a fresh RegistryProtocolBinding containing a dummy
handler (so that RuntimeHostProcess sees at least one registered handler) or by
passing a test-specific RegistryProtocolBinding into RuntimeHostProcess for
isolation; reference HandlerBootstrapSource, RuntimeHostProcess.start, and
RegistryProtocolBinding when making the change.

In `@tests/unit/runtime/test_runtime_host_process.py`:
- Around line 650-675: The test currently reads global state via
get_handler_registry(), which couples it to a singleton registry; instead
construct and inject a fresh RegistryProtocolBinding (or test double) into
RuntimeHostProcess before calling start(), call process.start(), then assert the
fresh registry instance has HANDLER_TYPE_CONSUL, HANDLER_TYPE_DATABASE,
HANDLER_TYPE_HTTP, and HANDLER_TYPE_VAULT registered (use the same constants)
and finally call process.stop(); update the test to avoid calling
get_handler_registry() and to pass the new registry into RuntimeHostProcess (or
its constructor/initializer) so assertions target that injected instance.
🧹 Nitpick comments (2)
src/omnibase_infra/runtime/service_runtime_host_process.py (1)

1134-1188: Skip already-registered bootstrap handlers to avoid noisy re-registration.

When multiple RuntimeHostProcess instances share the singleton registry (or start/stop cycles happen), repeated registration can emit errors or overwrite existing entries. A quick guard keeps logs clean and avoids unnecessary imports.

♻️ Suggested guard
                 handler_id = descriptor.handler_id
                 if handler_id.startswith("bootstrap."):
                     protocol_type = handler_id[len("bootstrap.") :]
                 else:
                     # Fallback: use full handler_id as protocol type
                     protocol_type = handler_id
+
+                if handler_registry.is_registered(protocol_type):
+                    logger.debug(
+                        "Bootstrap handler already registered, skipping",
+                        extra={
+                            "handler_id": handler_id,
+                            "protocol_type": protocol_type,
+                            "source_type": SOURCE_TYPE_BOOTSTRAP,
+                        },
+                    )
+                    continue
tests/integration/runtime/test_bootstrap_source_integration.py (1)

175-223: Ordering assertion doesn’t match the docstring intent.

This test says it verifies bootstrap handlers are registered before contract-based handlers, but it only checks presence. Consider either asserting ordering (e.g., dummy contract registration index is after bootstrap) or renaming the test to reflect the actual assertion.

Comment on lines +229 to +263
async def test_bootstrap_source_called_during_start(self) -> None:
"""HandlerBootstrapSource.discover_handlers() is called during start.

Verifies that RuntimeHostProcess actually calls the bootstrap source
discover_handlers() method during startup.
"""
event_bus = EventBusInmemory()

# Patch at the source module where it's imported from
with patch(
"omnibase_infra.runtime.handler_bootstrap_source.HandlerBootstrapSource"
) as MockBootstrapSource:
# Create a mock that returns proper discovery result
mock_source = MagicMock()
mock_discovery_result = MagicMock()
mock_discovery_result.descriptors = [] # Empty for simplicity
mock_source.discover_handlers = AsyncMock(
return_value=mock_discovery_result
)
MockBootstrapSource.return_value = mock_source

process = RuntimeHostProcess(
event_bus=event_bus,
input_topic="test.input",
)

try:
await process.start()

# Verify HandlerBootstrapSource was instantiated and called
MockBootstrapSource.assert_called_once()
mock_source.discover_handlers.assert_called_once()

finally:
await process.stop()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Potential flakiness: start() can fail if registry is empty in these mocked cases.

When HandlerBootstrapSource is mocked to return empty descriptors, start() will raise ProtocolConfigurationError if no handlers are registered. These tests currently rely on singleton state from prior tests. Consider seeding a stub handler or injecting a fresh RegistryProtocolBinding with a dummy handler to keep them order-independent.

🔧 Example seeding approach
+        from omnibase_infra.runtime.handler_registry import RegistryProtocolBinding
+
+        class DummyHandler:
+            async def execute(self, envelope: dict[str, object]) -> dict[str, object]:
+                return {"status": "ok"}
+
+            async def shutdown(self) -> None:
+                return None
+
+            async def health_check(self) -> dict[str, object]:
+                return {"healthy": True}
+
+        registry = RegistryProtocolBinding()
+        registry.register("dummy", DummyHandler)
 
             process = RuntimeHostProcess(
                 event_bus=event_bus,
                 input_topic="test.input",
+                handler_registry=registry,
             )

Also applies to: 358-391

🤖 Prompt for AI Agents
In `@tests/integration/runtime/test_bootstrap_source_integration.py` around lines
229 - 263, The test mocks HandlerBootstrapSource to return empty descriptors
which can cause RuntimeHostProcess.start() to raise ProtocolConfigurationError
when the global registry has no handlers; modify the test
(test_bootstrap_source_called_during_start and the similar case at 358-391) to
ensure a non-empty registry before calling process.start() by seeding a stub
handler or creating/injecting a fresh RegistryProtocolBinding containing a dummy
handler (so that RuntimeHostProcess sees at least one registered handler) or by
passing a test-specific RegistryProtocolBinding into RuntimeHostProcess for
isolation; reference HandlerBootstrapSource, RuntimeHostProcess.start, and
RegistryProtocolBinding when making the change.

Comment on lines +650 to +675
async def test_start_registers_bootstrap_handlers(self) -> None:
"""Test that start() registers bootstrap handlers.

The RuntimeHostProcess should use the wiring module to register
all configured handlers when started.
The RuntimeHostProcess should register bootstrap handlers (consul, db,
http, vault) via HandlerBootstrapSource when started.
"""
from omnibase_infra.runtime.handler_registry import (
HANDLER_TYPE_CONSUL,
HANDLER_TYPE_DATABASE,
HANDLER_TYPE_HTTP,
HANDLER_TYPE_VAULT,
get_handler_registry,
)

process = RuntimeHostProcess()
await process.start()

with patch(
"omnibase_infra.runtime.service_runtime_host_process.wire_handlers"
) as mock_wire:
mock_wire.return_value = {}
await process.start()

try:
mock_wire.assert_called_once()
finally:
await process.stop()
try:
# Verify bootstrap handlers are registered
registry = get_handler_registry()
assert registry.is_registered(HANDLER_TYPE_CONSUL)
assert registry.is_registered(HANDLER_TYPE_DATABASE)
assert registry.is_registered(HANDLER_TYPE_HTTP)
assert registry.is_registered(HANDLER_TYPE_VAULT)
finally:
await process.stop()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Avoid singleton registry coupling in this bootstrap test.

This test relies on get_handler_registry() (global state), which can leak across tests and make results order-dependent. Prefer injecting a fresh RegistryProtocolBinding into RuntimeHostProcess and asserting against that instance.

🔧 Example isolation tweak
 from omnibase_infra.runtime.handler_registry import (
     HANDLER_TYPE_CONSUL,
     HANDLER_TYPE_DATABASE,
     HANDLER_TYPE_HTTP,
     HANDLER_TYPE_VAULT,
+    RegistryProtocolBinding,
     get_handler_registry,
 )
 
-        process = RuntimeHostProcess()
+        registry = RegistryProtocolBinding()
+        process = RuntimeHostProcess(handler_registry=registry)
         await process.start()
 
         try:
             # Verify bootstrap handlers are registered
-            registry = get_handler_registry()
             assert registry.is_registered(HANDLER_TYPE_CONSUL)
             assert registry.is_registered(HANDLER_TYPE_DATABASE)
             assert registry.is_registered(HANDLER_TYPE_HTTP)
             assert registry.is_registered(HANDLER_TYPE_VAULT)
🤖 Prompt for AI Agents
In `@tests/unit/runtime/test_runtime_host_process.py` around lines 650 - 675, The
test currently reads global state via get_handler_registry(), which couples it
to a singleton registry; instead construct and inject a fresh
RegistryProtocolBinding (or test double) into RuntimeHostProcess before calling
start(), call process.start(), then assert the fresh registry instance has
HANDLER_TYPE_CONSUL, HANDLER_TYPE_DATABASE, HANDLER_TYPE_HTTP, and
HANDLER_TYPE_VAULT registered (use the same constants) and finally call
process.stop(); update the test to avoid calling get_handler_registry() and to
pass the new registry into RuntimeHostProcess (or its constructor/initializer)
so assertions target that injected instance.

- Add @Final decorator to HandlerBootstrapSource to prevent subclassing
- Replace float("inf") with 1_000_000.0 cap in handlers_per_sec calculation
  to avoid issues with downstream logging/monitoring systems
- Add comprehensive docstring to to_base_descriptor() explaining why
  model_dump() without exclude_unset is safe (field parity with parent)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/omnibase_infra/runtime/handler_bootstrap_source.py`:
- Around line 158-165: Replace the RuntimeError raised in the
ModelContractDiscoveryResult.model_rebuild() exception handler with the
project's OnexError: catch Exception as e around
ModelContractDiscoveryResult.model_rebuild(), then raise OnexError(...) from e
using the same message text; also ensure OnexError is imported into the module
so the new exception class is available for use.
🧹 Nitpick comments (1)
src/omnibase_infra/models/handlers/model_bootstrap_handler_descriptor.py (1)

96-100: Consider removing redundant model_config redefinition.

The parent ModelHandlerDescriptor already defines identical model_config settings. In Pydantic v2, child classes inherit the parent's model configuration automatically. This redefinition is not harmful but adds maintenance overhead if the parent config changes.

♻️ Optional removal
 class ModelBootstrapHandlerDescriptor(ModelHandlerDescriptor):
     # ... docstring ...
 
-    model_config = ConfigDict(
-        frozen=True,
-        extra="forbid",
-        strict=True,
-    )
-
     # Override handler_class to be required (no default, not optional)

Comment on lines +158 to +165
try:
ModelContractDiscoveryResult.model_rebuild()
except Exception as e:
raise RuntimeError(
f"Failed to rebuild ModelContractDiscoveryResult during bootstrap "
f"initialization. This typically indicates a circular import or missing "
f"type definition: {e}"
) from e

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Use OnexError instead of RuntimeError for error handling.

Per coding guidelines: "Use raise OnexError(...) from e for error handling - never raise other exception types." The current RuntimeError should be replaced with OnexError from the project's error handling framework.

🔧 Proposed fix
+from omnibase_core.errors import OnexError
+
 # ... in _ensure_model_rebuilt() ...
         try:
             ModelContractDiscoveryResult.model_rebuild()
         except Exception as e:
-            raise RuntimeError(
-                f"Failed to rebuild ModelContractDiscoveryResult during bootstrap "
-                f"initialization. This typically indicates a circular import or missing "
-                f"type definition: {e}"
+            raise OnexError(
+                message=(
+                    "Failed to rebuild ModelContractDiscoveryResult during bootstrap "
+                    "initialization. This typically indicates a circular import or missing "
+                    f"type definition: {e}"
+                ),
             ) from e
🤖 Prompt for AI Agents
In `@src/omnibase_infra/runtime/handler_bootstrap_source.py` around lines 158 -
165, Replace the RuntimeError raised in the
ModelContractDiscoveryResult.model_rebuild() exception handler with the
project's OnexError: catch Exception as e around
ModelContractDiscoveryResult.model_rebuild(), then raise OnexError(...) from e
using the same message text; also ensure OnexError is imported into the module
so the new exception class is available for use.

Add rationale explaining there are no external users yet, making this
the optimal time for aggressive breaking changes. Strengthen language
to make deletion of deprecated code mandatory, not optional.
- Replace nested ternary with if/elif/else in handlers_per_sec calculation
- Use str.removeprefix() for cleaner protocol type extraction
@jonahgabriel
jonahgabriel merged commit 941d35a into main Jan 21, 2026
19 checks passed
@jonahgabriel
jonahgabriel deleted the jonah/omn-1087-implement-handlerbootstrapsource-descriptor-based branch January 21, 2026 10:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant