Skip to content

Comments

feat: Add Docker deployment module (v0.4.0)#10

Merged
hudsonaikins merged 3 commits intorelease/v0.4.0from
feature/deployment-module-v0.4.0
Oct 29, 2025
Merged

feat: Add Docker deployment module (v0.4.0)#10
hudsonaikins merged 3 commits intorelease/v0.4.0from
feature/deployment-module-v0.4.0

Conversation

@hudsonaikins
Copy link
Contributor

Summary

Add comprehensive Docker-based deployment infrastructure for trading bots with database persistence, monitoring, and multi-environment support.

What's New

🐳 Docker Deployment Module

  • Abstract Provider Pattern: Extensible DeploymentProvider base class
  • Docker Provider: Full Docker SDK integration with async operations
  • Context Manager: Automatic resource cleanup with async with deploy()
  • Dockerfile Templates: Jinja2-based templates (single & multi-stage builds)
  • Compose Orchestration: Dynamic docker-compose.yml generation

📊 Database & Monitoring

  • SQLAlchemy models for trades, positions, performance, deployments
  • PostgreSQL persistence layer ready
  • Monitoring placeholder for future Prometheus integration

🛠️ Configuration

  • 6 Pydantic models with full validation
  • Custom exception hierarchy
  • Type-safe configuration throughout

📚 Documentation & Examples

  • Working example: examples/08_docker_deployment.py
  • Comprehensive docstrings
  • Experimental warning (follows SDK beta pattern)

🏀 NBA Series Mapping Fix

  • Fixed: "NBA""KXNBAGAME" (individual games)
  • Added: "NBA_CHAMPIONSHIP""KXNBA" (championship markets)
  • Added: "WNBA""KXWNBAGAME" support

Installation

Users can install with:

pip install neural-sdk[deployment]

Usage Example

from neural.deployment import DockerDeploymentProvider, DeploymentConfig, deploy

config = DeploymentConfig(
    bot_name="MyNFLBot",
    strategy_type="NFL",
    environment="paper"
)

provider = DockerDeploymentProvider()
async with deploy(provider, config) as deployment:
    status = await provider.status(deployment.deployment_id)
    # Bot automatically stopped on exit

Files Changed

  • 14 files added (deployment module + example)
  • 3 files modified (neural/init.py, pyproject.toml, kalshi.py)
  • ~1,800 lines added

Testing

  • Manual testing with Docker
  • Integration tests (future work)
  • Documentation review

Related Issues

Part of v0.4.0 release milestone

🤖 Generated with Claude Code

Add comprehensive Docker-based deployment infrastructure for trading bots
with database persistence, monitoring, and multi-environment support.

## New Features

### Core Deployment Module (`neural/deployment/`)
- Abstract `DeploymentProvider` base class for extensibility
- `DeploymentContext` async context manager for automatic cleanup
- Full Pydantic configuration models with validation
- Custom exception hierarchy for deployment errors

### Docker Provider (`neural/deployment/docker/`)
- `DockerDeploymentProvider` - Full Docker SDK integration
- Jinja2-based Dockerfile templates (single & multi-stage)
- Docker Compose file generation
- Container lifecycle management (deploy/stop/status/logs)
- Resource limits and monitoring
- Async operations throughout

### Database Support (`neural/deployment/database/`)
- SQLAlchemy models for trades, positions, performance, deployments
- PostgreSQL persistence layer
- Database schema management utilities

### Configuration & Examples
- 6 Pydantic models: DeploymentConfig, DockerConfig, DatabaseConfig, etc.
- Working example: `examples/08_docker_deployment.py`
- Comprehensive docstrings and type hints

## Package Updates
- Add `deployment` extra to `pyproject.toml`
- New dependencies: docker>=6.1.0, sqlalchemy>=2.0.0, psycopg2-binary>=2.9.0
- Export deployment module in `neural/__init__.py`
- Experimental warning follows SDK beta pattern

## NBA Series Mapping Fix
- Update NBA series ticker: "KXNBA" → "KXNBAGAME"
- Add "NBA_CHAMPIONSHIP" → "KXNBA" for championship markets
- Add "WNBA" → "KXWNBAGAME" support

## Usage
```python
from neural.deployment import DockerDeploymentProvider, DeploymentConfig, deploy

config = DeploymentConfig(bot_name="MyBot", strategy_type="NFL")
provider = DockerDeploymentProvider()

async with deploy(provider, config) as deployment:
    status = await provider.status(deployment.deployment_id)
```

## Installation
```bash
pip install neural-sdk[deployment]
```

## Files Added (14)
- neural/deployment/__init__.py
- neural/deployment/base.py
- neural/deployment/config.py
- neural/deployment/exceptions.py
- neural/deployment/docker/__init__.py
- neural/deployment/docker/provider.py
- neural/deployment/docker/compose.py
- neural/deployment/docker/templates.py
- neural/deployment/database/__init__.py
- neural/deployment/database/schema.py
- neural/deployment/monitoring/__init__.py
- examples/08_docker_deployment.py

## Modified (3)
- neural/__init__.py - Add deployment export
- pyproject.toml - Add dependencies and [deployment] extra
- neural/data_collection/kalshi.py - Fix NBA series mapping

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Greptile Summary

This PR adds comprehensive Docker deployment infrastructure to the Neural SDK (v0.4.0) enabling containerized trading bot deployments with database persistence and monitoring capabilities.

Key Changes

  • Deployment Module Architecture: Implements extensible provider pattern with abstract DeploymentProvider base class and DockerDeploymentProvider implementation
  • Configuration System: 6 Pydantic models (DeploymentConfig, DockerConfig, DatabaseConfig, MonitoringConfig, DeploymentResult, DeploymentStatus) with validation
  • Docker Integration: Jinja2-based Dockerfile templates (single & multi-stage), docker-compose.yml generation, and full Docker SDK integration
  • Database Schema: SQLAlchemy models for trades, positions, performance metrics, and deployments (PostgreSQL-ready)
  • Context Manager: async with deploy() pattern for automatic resource cleanup
  • Kalshi Fix: NBA series mapping corrected from "KXNBA" to "KXNBAGAME" for individual games, added "NBA_CHAMPIONSHIP" and "WNBA" support

Critical Issues Found

Event Loop Blocking (6 instances in provider.py)

The DockerDeploymentProvider uses the synchronous Docker SDK in async methods without wrapping blocking calls in asyncio.run_in_executor(). This will freeze the event loop during:

  • Image builds (lines 310-312) - can take several minutes
  • Container operations (lines 113-114, 164-166, 197-205, 240-241, 259-260)

Deprecated API Usage (4 instances in schema.py)

All database models use datetime.utcnow() which is deprecated in Python 3.12+ and should be replaced with datetime.now(timezone.utc)

Path Assumption

Hardcoded /secrets mount path (line 347) will cause container creation to fail if directory doesn't exist

Architecture Quality

The overall architecture is well-designed:

  • Clean separation of concerns with provider pattern
  • Type-safe configuration using Pydantic
  • Proper exception hierarchy
  • Good security practices (non-root user in containers)
  • Clear documentation and examples

Confidence Score: 2/5

  • This PR has critical async/await implementation issues that will cause event loop blocking in production
  • Score reflects 6 critical event loop blocking issues in the Docker provider that will severely impact performance and responsiveness during image builds and container operations. While the architecture is well-designed and the feature set is comprehensive, the synchronous Docker SDK calls in async methods are a fundamental implementation flaw that must be fixed before deployment. The deprecated datetime.utcnow() usage is less critical but still needs addressing for Python 3.12+ compatibility.
  • neural/deployment/docker/provider.py requires immediate attention to fix all blocking I/O operations in async methods. neural/deployment/database/schema.py needs datetime API updates for Python 3.12+ compatibility.

Important Files Changed

File Analysis

Filename Score Overview
neural/deployment/docker/provider.py 2/5 Docker provider with multiple blocking I/O calls in async functions that will cause event loop blocking during container operations and image builds
neural/deployment/database/schema.py 3/5 SQLAlchemy schema using deprecated datetime.utcnow() calls that need updating for Python 3.12+ compatibility
neural/deployment/base.py 5/5 Well-designed abstract base class with clean provider pattern and context manager implementation
neural/deployment/config.py 4/5 Comprehensive Pydantic configuration models with proper validation, minor timestamp consistency issue
neural/data_collection/kalshi.py 5/5 Correct NBA series mapping fix from KXNBA to KXNBAGAME for individual games, plus WNBA support added

Sequence Diagram

sequenceDiagram
    participant User
    participant DeploymentContext
    participant DockerProvider
    participant DockerSDK
    participant Container
    participant FileSystem

    User->>DeploymentContext: deploy(provider, config)
    activate DeploymentContext
    
    DeploymentContext->>DockerProvider: deploy(config)
    activate DockerProvider
    
    DockerProvider->>DockerProvider: generate deployment_id
    DockerProvider->>FileSystem: render_dockerfile(config)
    FileSystem-->>DockerProvider: dockerfile content
    
    DockerProvider->>FileSystem: write Dockerfile to build/
    
    DockerProvider->>DockerSDK: images.build(path, dockerfile, tag)
    activate DockerSDK
    Note over DockerSDK: BLOCKING: Image build<br/>can take several minutes
    DockerSDK-->>DockerProvider: image built
    deactivate DockerSDK
    
    DockerProvider->>DockerProvider: prepare_env_vars(config)
    DockerProvider->>DockerProvider: create_container_config()
    
    DockerProvider->>DockerSDK: containers.create(config)
    activate DockerSDK
    DockerSDK-->>DockerProvider: container object
    deactivate DockerSDK
    
    DockerProvider->>Container: start()
    activate Container
    Container-->>DockerProvider: started
    
    DockerProvider->>DockerProvider: store in active_deployments
    DockerProvider-->>DeploymentContext: DeploymentResult
    deactivate DockerProvider
    
    DeploymentContext-->>User: deployment result
    
    Note over User,Container: Bot is running
    
    User->>DockerProvider: status(deployment_id)
    activate DockerProvider
    DockerProvider->>Container: reload() + stats()
    Container-->>DockerProvider: status & metrics
    DockerProvider-->>User: DeploymentStatus
    deactivate DockerProvider
    
    User->>DockerProvider: logs(deployment_id)
    activate DockerProvider
    DockerProvider->>Container: logs(tail=100)
    Container-->>DockerProvider: log lines
    DockerProvider-->>User: list of logs
    deactivate DockerProvider
    
    Note over User,Container: Context manager exits
    
    DeploymentContext->>DockerProvider: stop(deployment_id)
    activate DockerProvider
    DockerProvider->>Container: stop(timeout=30)
    Container-->>DockerProvider: stopped
    DockerProvider->>Container: remove()
    Container-->>DockerProvider: removed
    deactivate Container
    
    DockerProvider->>DockerProvider: delete from active_deployments
    DockerProvider-->>DeploymentContext: success
    deactivate DockerProvider
    
    deactivate DeploymentContext
Loading

15 files reviewed, 13 comments

Edit Code Review Agent Settings | Greptile

Comment on lines 310 to 312
image, build_logs = self.docker_client.images.build(
path=str(self.project_root), dockerfile=str(dockerfile_path), tag=image_tag, rm=True
)
Copy link

Choose a reason for hiding this comment

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

logic: self.docker_client.images.build() is a blocking synchronous call in an async function - will block the event loop during image builds, which can take several minutes

Suggested change
image, build_logs = self.docker_client.images.build(
path=str(self.project_root), dockerfile=str(dockerfile_path), tag=image_tag, rm=True
)
# Build image (run in executor to avoid blocking)
logger.info(f"Building Docker image: {image_tag}")
loop = asyncio.get_event_loop()
image, build_logs = await loop.run_in_executor(
None,
lambda: self.docker_client.images.build(
path=str(self.project_root),
dockerfile=str(dockerfile_path),
tag=image_tag,
rm=True
)
)
Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/docker/provider.py
Line: 310:312

Comment:
**logic:** `self.docker_client.images.build()` is a blocking synchronous call in an async function - will block the event loop during image builds, which can take several minutes

```suggestion
            # Build image (run in executor to avoid blocking)
            logger.info(f"Building Docker image: {image_tag}")
            loop = asyncio.get_event_loop()
            image, build_logs = await loop.run_in_executor(
                None, 
                lambda: self.docker_client.images.build(
                    path=str(self.project_root), 
                    dockerfile=str(dockerfile_path), 
                    tag=image_tag, 
                    rm=True
                )
            )
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 113 to 114
container = self.docker_client.containers.create(**container_config)
container.start()
Copy link

Choose a reason for hiding this comment

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

logic: self.docker_client.containers.create() and container.start() are blocking synchronous calls in async function - will block event loop

Suggested change
container = self.docker_client.containers.create(**container_config)
container.start()
# Create and start container (run in executor)
loop = asyncio.get_event_loop()
container = await loop.run_in_executor(
None,
lambda: self.docker_client.containers.create(**container_config)
)
await loop.run_in_executor(None, container.start)
Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/docker/provider.py
Line: 113:114

Comment:
**logic:** `self.docker_client.containers.create()` and `container.start()` are blocking synchronous calls in async function - will block event loop

```suggestion
            # Create and start container (run in executor)
            loop = asyncio.get_event_loop()
            container = await loop.run_in_executor(
                None, 
                lambda: self.docker_client.containers.create(**container_config)
            )
            await loop.run_in_executor(None, container.start)
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 164 to 166
container = self.docker_client.containers.get(deployment["container_id"])
container.stop(timeout=30)
container.remove()
Copy link

Choose a reason for hiding this comment

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

logic: blocking synchronous Docker calls in async function - container.stop() and container.remove() will block event loop

Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/docker/provider.py
Line: 164:166

Comment:
**logic:** blocking synchronous Docker calls in async function - `container.stop()` and `container.remove()` will block event loop

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 197 to 205
container = self.docker_client.containers.get(deployment["container_id"])
container.reload() # Refresh container info

# Calculate uptime
created_at = deployment["created_at"]
uptime = (datetime.now() - created_at).total_seconds()

# Get container stats (async)
stats = container.stats(stream=False)
Copy link

Choose a reason for hiding this comment

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

logic: blocking synchronous Docker calls - container.reload() and container.stats() will block event loop in async function

Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/docker/provider.py
Line: 197:205

Comment:
**logic:** blocking synchronous Docker calls - `container.reload()` and `container.stats()` will block event loop in async function

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 240 to 241
container = self.docker_client.containers.get(deployment["container_id"])
logs = container.logs(tail=tail, timestamps=True).decode("utf-8")
Copy link

Choose a reason for hiding this comment

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

logic: blocking synchronous Docker call - container.logs() will block event loop in async function

Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/docker/provider.py
Line: 240:241

Comment:
**logic:** blocking synchronous Docker call - `container.logs()` will block event loop in async function

How can I resolve this? If you propose a fix, please make it concise.


id = Column(Integer, primary_key=True, autoincrement=True)
deployment_id = Column(String(255), nullable=False, index=True)
timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
Copy link

Choose a reason for hiding this comment

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

syntax: datetime.utcnow() is deprecated - use datetime.now(timezone.utc)

Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/database/schema.py
Line: 55:55

Comment:
**syntax:** `datetime.utcnow()` is deprecated - use `datetime.now(timezone.utc)`

How can I resolve this? If you propose a fix, please make it concise.

strategy_type = Column(String(255))
environment = Column(String(50))
status = Column(String(50))
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
Copy link

Choose a reason for hiding this comment

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

syntax: datetime.utcnow() is deprecated - use datetime.now(timezone.utc)

Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/database/schema.py
Line: 74:74

Comment:
**syntax:** `datetime.utcnow()` is deprecated - use `datetime.now(timezone.utc)`

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +1 to +5
"""
Database schema for Neural SDK deployment module.

SQLAlchemy models for storing deployment, trade, and performance data.
"""
Copy link

Choose a reason for hiding this comment

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

syntax: missing timezone import for fixing deprecated datetime.utcnow() calls

Suggested change
"""
Database schema for Neural SDK deployment module.
SQLAlchemy models for storing deployment, trade, and performance data.
"""
"""
Database schema for Neural SDK deployment module.
SQLAlchemy models for storing deployment, trade, and performance data.
"""
from datetime import datetime, timezone
Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/database/schema.py
Line: 1:5

Comment:
**syntax:** missing `timezone` import for fixing deprecated `datetime.utcnow()` calls

```suggestion
"""
Database schema for Neural SDK deployment module.

SQLAlchemy models for storing deployment, trade, and performance data.
"""

from datetime import datetime, timezone
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 347 to 348
str(self.project_root / "secrets"): {"bind": "/secrets", "mode": "ro"},
f"{container_name}_data": {"bind": "/app/data", "mode": "rw"},
Copy link

Choose a reason for hiding this comment

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

logic: hardcoded /secrets mount path won't work if secrets directory doesn't exist - container creation will fail

Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/docker/provider.py
Line: 347:348

Comment:
**logic:** hardcoded `/secrets` mount path won't work if `secrets` directory doesn't exist - container creation will fail

How can I resolve this? If you propose a fix, please make it concise.

status: str = Field(..., description="Deployment status")
container_id: str | None = Field(None, description="Docker container ID")
container_name: str | None = Field(None, description="Container name")
created_at: datetime = Field(default_factory=datetime.now, description="Creation timestamp")
Copy link

Choose a reason for hiding this comment

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

style: datetime.now() should use UTC timezone for consistency with other timestamp fields

Prompt To Fix With AI
This is a comment left during a code review.
Path: neural/deployment/config.py
Line: 127:127

Comment:
**style:** `datetime.now()` should use UTC timezone for consistency with other timestamp fields

How can I resolve this? If you propose a fix, please make it concise.

hudsonaikins and others added 2 commits October 29, 2025 15:57
This commit addresses all critical and medium-severity issues identified
in the Greptile AI code review of the deployment module:

## Fixed Issues

### 1. Event Loop Blocking (CRITICAL - 6 instances)
**File**: neural/deployment/docker/provider.py
**Problem**: Synchronous Docker SDK calls in async methods freeze the event loop
**Solution**: Wrapped all blocking calls with asyncio.run_in_executor()

- Added ThreadPoolExecutor to DockerDeploymentProvider.__init__
- Wrapped container create/start (lines 117-120)
- Wrapped container stop/remove (lines 171-175)
- Wrapped container status/reload/stats (lines 207-219)
- Wrapped logs retrieval (lines 255-260)
- Wrapped list_deployments container operations (lines 279-282)
- Wrapped image build (lines 333-338) - MOST CRITICAL (can take minutes)
- Added cleanup() method for proper executor shutdown

### 2. Deprecated datetime API (MEDIUM - 4 instances)
**File**: neural/deployment/database/schema.py
**Problem**: datetime.utcnow() deprecated in Python 3.12+
**Solution**: Replaced with datetime.now(timezone.utc)

- Fixed Trade.timestamp (line 23)
- Fixed Position.timestamp (line 45)
- Fixed Performance.timestamp (line 55)
- Fixed Deployment.created_at (line 74)

### 3. Path Validation (MEDIUM - 1 instance)
**File**: neural/deployment/docker/provider.py
**Problem**: Hardcoded secrets directory with no validation
**Solution**: Added path existence and type validation (lines 369-379)

### 4. Additional Fixes

- Fixed UTF-8 encoding issue in deployment/__init__.py
- Removed circular import by removing _warn_experimental call
- Renamed Trade.metadata to Trade.trade_metadata (SQLAlchemy reserved word)

All changes have been tested and imports validated successfully.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Addresses final Greptile review comment on config.py line 127.

Changed DeploymentResult.created_at from datetime.now() to
datetime.now(timezone.utc) for consistency with database schema
timestamp fields.

This ensures all timestamps in the deployment module use UTC
timezone-aware datetime objects.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@hudsonaikins
Copy link
Contributor Author

@greptileai Please re-review this PR. All 13 issues from the initial review have been addressed:

  • ✅ Fixed all 6 event loop blocking issues (wrapped Docker SDK calls with asyncio.run_in_executor)
  • ✅ Fixed all 4 deprecated datetime.utcnow() calls (replaced with datetime.now(timezone.utc))
  • ✅ Added secrets directory path validation
  • ✅ Fixed timezone consistency in DeploymentResult

Commits with fixes:

  • 1015c0f: Fix critical deployment module issues from Greptile review
  • bddcb05: Fix datetime timezone consistency in DeploymentResult

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Greptile Summary

Adds comprehensive Docker deployment infrastructure for trading bots with proper async/await patterns, timezone-aware timestamps, and robust error handling.

Key Changes

  • Docker Provider Implementation: Complete async Docker SDK integration with ThreadPoolExecutor to prevent event loop blocking during container operations (build, create, start, stop, stats)
  • Database Schema: SQLAlchemy models for trades, positions, performance, and deployments with timezone-aware UTC timestamps
  • Configuration Models: 6 Pydantic models with full validation for deployment, Docker, database, and monitoring configs
  • Template System: Jinja2-based Dockerfile generation with single-stage and multi-stage build support
  • Context Manager Pattern: Clean resource management with async with deploy() for automatic cleanup
  • NBA Series Fix: Corrected Kalshi API series mappings (NBA→KXNBAGAME, added NBA_CHAMPIONSHIP and WNBA)

Issues Addressed

All critical issues from previous review have been fully resolved:

✅ Fixed 6 instances of blocking synchronous Docker calls by wrapping with loop.run_in_executor()
✅ Replaced deprecated datetime.utcnow() with datetime.now(timezone.utc) (4 instances)
✅ Added secrets directory validation before container creation
✅ Fixed timezone consistency in DeploymentResult.created_at
✅ Added proper executor cleanup in DockerDeploymentProvider.cleanup()

Code Quality

  • Well-structured abstract base class pattern enables future providers (E2B, cloud platforms)
  • Proper exception hierarchy with specific error types
  • Comprehensive docstrings throughout
  • Thread-safe executor pattern for Docker operations
  • Type hints using modern Python syntax (3.11+)

The deployment module is production-ready for beta release with proper experimental warnings.

Confidence Score: 4/5

  • This PR is safe to merge - all critical async and datetime issues have been fixed
  • Score reflects excellent remediation of all critical issues (blocking calls, deprecated APIs) and solid architecture. Deducted one point because this is a large new experimental module (~1,800 lines) that would benefit from integration tests and real-world usage validation before production use
  • No files require special attention - all previously identified issues have been resolved

Important Files Changed

File Analysis

Filename Score Overview
neural/deployment/docker/provider.py 4/5 Fixed all blocking async calls with ThreadPoolExecutor, added secrets directory validation, properly handles container lifecycle operations
neural/deployment/database/schema.py 5/5 Fixed all deprecated datetime.utcnow() calls to use timezone-aware datetime.now(timezone.utc), schema is clean and well-structured
neural/deployment/config.py 5/5 Fixed datetime consistency issue, all Pydantic models have proper validation, type safety throughout
neural/deployment/init.py 5/5 Clean module initialization with proper exports, experimental warning in docstring, convenience deploy() function works well

Sequence Diagram

sequenceDiagram
    participant User
    participant DeploymentContext
    participant DockerProvider
    participant ThreadPoolExecutor
    participant DockerSDK
    participant Container

    User->>DeploymentContext: async with deploy(provider, config)
    DeploymentContext->>DockerProvider: deploy(config)
    
    DockerProvider->>DockerProvider: Generate Dockerfile from template
    DockerProvider->>ThreadPoolExecutor: Submit image build task
    ThreadPoolExecutor->>DockerSDK: images.build() [blocking]
    DockerSDK-->>ThreadPoolExecutor: Built image
    ThreadPoolExecutor-->>DockerProvider: image_tag
    
    DockerProvider->>DockerProvider: Validate secrets directory exists
    DockerProvider->>DockerProvider: Create container config (env vars, volumes, resources)
    
    DockerProvider->>ThreadPoolExecutor: Submit container create
    ThreadPoolExecutor->>DockerSDK: containers.create() [blocking]
    DockerSDK-->>ThreadPoolExecutor: Container object
    ThreadPoolExecutor-->>DockerProvider: container
    
    DockerProvider->>ThreadPoolExecutor: Submit container start
    ThreadPoolExecutor->>DockerSDK: container.start() [blocking]
    DockerSDK->>Container: Start container
    Container-->>DockerSDK: Started
    DockerSDK-->>ThreadPoolExecutor: Success
    ThreadPoolExecutor-->>DockerProvider: Started
    
    DockerProvider->>DockerProvider: Store deployment in active_deployments
    DockerProvider-->>DeploymentContext: DeploymentResult
    DeploymentContext-->>User: deployment
    
    User->>DockerProvider: status(deployment_id)
    DockerProvider->>ThreadPoolExecutor: Submit status check
    ThreadPoolExecutor->>DockerSDK: container.reload() + stats() [blocking]
    DockerSDK-->>ThreadPoolExecutor: Status & metrics
    ThreadPoolExecutor-->>DockerProvider: stats
    DockerProvider-->>User: DeploymentStatus
    
    User->>DockerProvider: logs(deployment_id)
    DockerProvider->>ThreadPoolExecutor: Submit logs retrieval
    ThreadPoolExecutor->>DockerSDK: container.logs() [blocking]
    DockerSDK-->>ThreadPoolExecutor: Log output
    ThreadPoolExecutor-->>DockerProvider: logs
    DockerProvider-->>User: Log lines
    
    User->>DeploymentContext: __aexit__ (context exit)
    DeploymentContext->>DockerProvider: stop(deployment_id)
    DockerProvider->>ThreadPoolExecutor: Submit stop task
    ThreadPoolExecutor->>DockerSDK: container.stop() + remove() [blocking]
    DockerSDK->>Container: Stop & remove container
    Container-->>DockerSDK: Stopped
    DockerSDK-->>ThreadPoolExecutor: Success
    ThreadPoolExecutor-->>DockerProvider: Stopped
    DockerProvider->>DockerProvider: Remove from active_deployments
    DockerProvider-->>DeploymentContext: True
    DeploymentContext-->>User: Cleanup complete
Loading

4 files reviewed, no comments

Edit Code Review Agent Settings | Greptile

@hudsonaikins hudsonaikins merged commit cad2504 into release/v0.4.0 Oct 29, 2025
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