Phase System Implementation Plan
Historical note: This page is preserved as an archival planning document. It may mention older subsystem names or assumptions that no longer match the current codebase. Start with Historical Internal Docs, Hybrid Execution Overview, and Migration Guide for current guidance.
Overview
This document provides a concrete implementation plan for simplifying the netherframe phase system, including new module organization, API design, and step-by-step migration path.
New Module Organization
Proposed Directory Structure
libs/netherframe.core/netherframe/core/phases/
├── __init__.py # Public API exports
├── models.py # Unified data models
├── analyzer.py # Dependency analysis and cycle detection
├── planner.py # Phase planning core logic
├── strategies/ # Planning strategies
│ ├── __init__.py
│ ├── base.py # Base strategy class
│ ├── minimal.py # Minimal modification strategy
│ └── level_based.py # Level-based grouping strategy
├── executor.py # Unified execution engine
├── parallel.py # Parallel execution support
├── utils.py # Shared utilities and helpers
└── compat.py # Backward compatibility layer
Detailed Module Specifications
1. models.py - Unified Data Models
"""Unified phase system data models."""
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Set, Optional, Any
from pathlib import Path
class ExecutionMode(Enum):
"""Execution modes for phases."""
TERRAFORM = "terraform"
NATIVE = "native"
HYBRID = "hybrid"
@dataclass
class ResourcePhaseConfig:
"""Configuration for a resource in a specific phase."""
resource_id: str
resource_type: str
base_config: Dict[str, Any]
modifications: Dict[str, Any] = field(default_factory=dict)
omit_attributes: Set[str] = field(default_factory=set)
dependencies: Set[str] = field(default_factory=set)
can_parallel: bool = True
def get_config(self) -> Dict[str, Any]:
"""Get the final configuration for this phase."""
config = self.base_config.copy()
for attr in self.omit_attributes:
config.pop(attr, None)
config.update(self.modifications)
return config
@dataclass
class PhaseExecutionConfig:
"""Configuration for phase execution."""
parallel_enabled: bool = True
max_concurrent: int = 10
timeout_seconds: Optional[int] = None
retry_count: int = 0
continue_on_error: bool = False
@dataclass
class Phase:
"""Represents a single execution phase."""
number: int
description: str
stack_id: str
resources: Dict[str, ResourcePhaseConfig] = field(default_factory=dict)
execution_config: PhaseExecutionConfig = field(default_factory=PhaseExecutionConfig)
def add_resource(self, resource_config: ResourcePhaseConfig) -> None:
"""Add a resource to this phase."""
self.resources[resource_config.resource_id] = resource_config
@dataclass
class CircularDependency:
"""Information about a circular dependency."""
cycle: List[Tuple[str, str, str, str]] # [(src_stack, src_res, tgt_res, tgt_stack)]
participating_stacks: Set[str] = field(init=False)
participating_resources: Dict[str, Set[str]] = field(init=False)
def __post_init__(self):
self.participating_stacks = set()
self.participating_resources = {}
for src_stack, src_res, tgt_res, tgt_stack in self.cycle:
self.participating_stacks.update([src_stack, tgt_stack])
self.participating_resources.setdefault(src_stack, set()).add(src_res)
self.participating_resources.setdefault(tgt_stack, set()).add(tgt_res)
@dataclass
class PlanMetadata:
"""Metadata for a phase plan."""
created_at: str
strategy_used: str
circular_dependencies: List[CircularDependency] = field(default_factory=list)
optimization_hints: Dict[str, Any] = field(default_factory=dict)
@dataclass
class PhasePlan:
"""Unified execution plan for phased deployment."""
plan_id: str
app_id: str
phases: List[Phase] = field(default_factory=list)
metadata: PlanMetadata = field(default_factory=lambda: PlanMetadata(created_at="", strategy_used="auto"))
def get_phase(self, number: int) -> Optional[Phase]:
"""Get a phase by number."""
for phase in self.phases:
if phase.number == number:
return phase
return None
def to_terraform_json(self) -> Dict[str, Any]:
"""Convert to Terraform-compatible JSON format."""
# Implementation here
def to_native_plan(self) -> Dict[str, Any]:
"""Convert to native execution format."""
# Implementation here
2. analyzer.py - Centralized Dependency Analysis
"""Centralized dependency analysis for phase planning."""
from typing import Dict, List, Set, Tuple, Optional
from dataclasses import dataclass
import re
from nf.core.tokens import Token, TokenEncoding
from .models import CircularDependency
@dataclass
class DependencyEdge:
"""Represents a dependency between resources."""
from_stack: str
from_resource: str
to_stack: str
to_resource: str
attribute: Optional[str] = None
class DependencyAnalyzer:
"""Unified dependency analyzer with caching."""
def __init__(self, cache_enabled: bool = True):
self._cache_enabled = cache_enabled
self._dependency_cache: Dict[str, List[DependencyEdge]] = {}
self._cycle_cache: Dict[str, List[CircularDependency]] = {}
def analyze_stack(self, stack: "Stack") -> List[DependencyEdge]:
"""Analyze dependencies in a stack."""
if self._cache_enabled and stack.nf_id in self._dependency_cache:
return self._dependency_cache[stack.nf_id]
edges = []
for resource in stack.resources:
edges.extend(self._analyze_resource(resource, stack))
if self._cache_enabled:
self._dependency_cache[stack.nf_id] = edges
return edges
def find_cycles(self, edges: List[DependencyEdge]) -> List[CircularDependency]:
"""Find circular dependencies using Tarjan's algorithm."""
# Convert edges to adjacency list
graph = self._build_graph(edges)
# Run Tarjan's algorithm
cycles = self._tarjan_scc(graph)
# Convert to CircularDependency objects
return [self._cycle_to_dependency(cycle, edges) for cycle in cycles]
def _analyze_resource(self, resource: "Resource", stack: "Stack") -> List[DependencyEdge]:
"""Extract dependencies from a resource."""
edges = []
config = resource._to_config()
# Analyze all attributes
for attr_name, attr_value in config.items():
deps = self._extract_dependencies(attr_value, resource, stack)
edges.extend(deps)
return edges
def _extract_dependencies(self, value: Any, source_resource: "Resource", source_stack: "Stack") -> List[DependencyEdge]:
"""Extract dependencies from a value (recursive)."""
edges = []
if isinstance(value, Token):
# Handle token references
edge = self._token_to_edge(value, source_resource, source_stack)
if edge:
edges.append(edge)
elif isinstance(value, str) and self._is_reference(value):
# Handle string references
edge = self._string_ref_to_edge(value, source_resource, source_stack)
if edge:
edges.append(edge)
elif isinstance(value, dict):
for v in value.values():
edges.extend(self._extract_dependencies(v, source_resource, source_stack))
elif isinstance(value, list):
for item in value:
edges.extend(self._extract_dependencies(item, source_resource, source_stack))
return edges
def _is_reference(self, value: str) -> bool:
"""Check if a string contains a reference."""
patterns = [
r"\$\{[^}]+\}", # ${...} references
r"data\.terraform_remote_state\.", # Remote state references
r"\$\{TOKEN:", # Token placeholders
]
return any(re.search(pattern, value) for pattern in patterns)
# Additional helper methods...
3. planner.py - Simplified Phase Planner
"""Simplified phase planner with pluggable strategies."""
from typing import Optional, Type
from .models import PhasePlan, PlanMetadata
from .analyzer import DependencyAnalyzer
from .strategies.base import PhaseStrategy
from .strategies import get_strategy
class PhasePlanner:
"""Unified phase planner for all scenarios."""
def __init__(self, analyzer: Optional[DependencyAnalyzer] = None):
self.analyzer = analyzer or DependencyAnalyzer()
def create_plan(self, app: "App", strategy: str = "auto", **options) -> PhasePlan:
"""Create a phase plan for an application.
Args:
app: The application to analyze
strategy: Strategy name ("auto", "minimal", "level_based")
**options: Additional options for the strategy
Returns:
A complete phase plan
"""
# Analyze dependencies
all_edges = []
for stack in app._stacks.values():
edges = self.analyzer.analyze_stack(stack)
all_edges.extend(edges)
# Find circular dependencies
circular_deps = self.analyzer.find_cycles(all_edges)
# No cycles? Simple single-phase plan
if not circular_deps:
return self._create_simple_plan(app)
# Get strategy
strategy_impl = get_strategy(strategy, circular_deps, app)
# Create plan using strategy
plan = strategy_impl.create_plan(app, circular_deps, **options)
# Add metadata
plan.metadata = PlanMetadata(created_at=self._get_timestamp(), strategy_used=strategy, circular_dependencies=circular_deps)
return plan
def _create_simple_plan(self, app: "App") -> PhasePlan:
"""Create a simple single-phase plan when no cycles exist."""
plan = PhasePlan(plan_id=self._generate_plan_id(), app_id=app.nf_id)
# Single phase for each stack
for stack in app._stacks.values():
phase = Phase(number=1, description=f"Deploy {stack.nf_id}", stack_id=stack.nf_id)
# Add all resources
for resource in stack.resources:
config = ResourcePhaseConfig(resource_id=resource.nf_id, resource_type=resource._resource_type, base_config=resource.config)
phase.add_resource(config)
plan.phases.append(phase)
return plan
4. Simplified Public API
# nf/core/phases/__init__.py
"""Simplified phase system API."""
from .planner import PhasePlanner
from .executor import PhaseExecutor
from .models import PhasePlan, ExecutionMode
__all__ = ["analyze", "execute", "PhasePlan", "ExecutionMode"]
# Global instances
_planner = PhasePlanner()
_executor = PhaseExecutor()
def analyze(app: "App", strategy: str = "auto", **options) -> PhasePlan:
"""Analyze an application and create a phase plan.
Args:
app: The application to analyze
strategy: Planning strategy ("auto", "minimal", "level_based")
**options: Additional strategy options
Returns:
A phase execution plan
Example:
>>> plan = phases.analyze(app)
>>> print(f"Created {len(plan.phases)} phases")
"""
return _planner.create_plan(app, strategy, **options)
def execute(plan: PhasePlan, mode: ExecutionMode = ExecutionMode.TERRAFORM, parallel: bool = True, **options) -> "ExecutionResult":
"""Execute a phase plan.
Args:
plan: The phase plan to execute
mode: Execution mode (terraform, native, hybrid)
parallel: Enable parallel execution within phases
**options: Additional execution options
Returns:
Execution result with status and details
Example:
>>> result = phases.execute(plan, mode=ExecutionMode.NATIVE)
>>> if result.success:
... print("Deployment successful!")
"""
return _executor.execute(plan, mode=mode, parallel=parallel, **options)
Migration Strategy
Phase 1: Foundation (Week 1)
-
Create new module structure
mkdir -p libs/netherframe.core/netherframe/core/phases/strategies touch libs/netherframe.core/netherframe/core/phases/{__init__,models,analyzer,planner,executor,utils,compat}.py -
Implement unified models
- Port best parts from
phase_models.pyandphased_execution.py -
Add backward compatibility type aliases
-
Centralize dependency analysis
- Extract common patterns from phase planners
- Implement caching layer
Phase 2: Core Logic (Week 2)
- Implement unified planner
- Combine best of v1 and v2 planners
-
Add strategy plugin system
-
Port strategies
- Extract common base class
-
Simplify to two main strategies
-
Create compatibility layer
# compat.py - Maintain old APIs from .models import PhasePlan as NewPhasePlan class PhaseExecutionPlan: """Compatibility wrapper for old API.""" def __init__(self, stack_id: str): self._wrapped = NewPhasePlan(...)
Phase 3: Execution (Week 3)
- Unify executors
- Merge terraform and native execution paths
-
Integrate parallel execution
-
Update CLI integration
- Modify
phase_executor.pyto use new API - Update command implementations
Phase 4: Cleanup (Week 4)
-
Add deprecation warnings
import warnings warnings.warn("phase_planner.py is deprecated, use nf.core.phases instead", DeprecationWarning) -
Update all imports
- Use automated script to update imports
-
Run full test suite
-
Remove old code (after grace period)
Testing Plan
Unit Tests
# tests/unit/phases/test_analyzer.py
def test_cycle_detection():
analyzer = DependencyAnalyzer()
edges = [...]
cycles = analyzer.find_cycles(edges)
assert len(cycles) == 1
# tests/unit/phases/test_planner.py
def test_strategy_selection():
planner = PhasePlanner()
plan = planner.create_plan(app, strategy="minimal")
assert plan.metadata.strategy_used == "minimal"
Integration Tests
- Test backward compatibility
- Test all execution modes
- Test parallel execution
- Test error recovery
Performance Tests
- Benchmark against current implementation
- Ensure no performance regression
- Test with large dependency graphs
Success Metrics
- Code Reduction: 35-45% reduction in phase-related code
- API Simplicity: 3 main functions vs 15+ entry points
- Performance: <10% overhead vs current implementation
- Test Coverage: >90% coverage of new modules
- Migration Success: All existing code works with compatibility layer
Risk Mitigation
- Backward Compatibility: Extensive compatibility layer
- Performance: Benchmark at each step
- Feature Parity: Comprehensive test suite
- User Impact: Feature flag for gradual rollout
Timeline
- Week 1: Foundation and models
- Week 2: Core logic and strategies
- Week 3: Execution and integration
- Week 4: Testing and cleanup
- Week 5: Documentation and rollout
Total: 5 weeks from start to production-ready