Skip to content

Phase System Simplification Analysis

Executive Summary

The phase system in netherframe has experienced significant code sprawl with duplicate models, overlapping functionality, and complex execution paths. This analysis identifies key issues and proposes a simplified architecture that maintains functionality while improving maintainability.

Current Architecture Issues

1. Duplicate Data Models

The codebase contains duplicate definitions for core phase concepts:

  • CircularDependencyInfo is defined in both:
  • phase_models.py (lines 136-174)
  • phased_execution.py (lines 145-159)

  • Phase class exists in:

  • phase_models.py (lines 88-133) - with parallel execution support
  • phased_execution.py (lines 58-75) - simpler version

  • Execution plans have multiple representations:

  • ExecutionPlan in phase_models.py
  • PhaseExecutionPlan in phased_execution.py

2. Multiple Phase Planners

Two different phase planner implementations exist: - phase_planner.py: Original CircularDependencyPhasePlanner - phase_planner_v2.py: OptimizedPhasePlanner with caching

Both appear to be actively used, creating confusion about which to use when.

3. Complex Strategy Pattern

Three strategies with significant code overlap: - AttributeModificationStrategy: Modifies attributes to break cycles - ResourceDeferralStrategy: Defers entire resources - DynamicStrategy: Chooses approach dynamically

All strategies share similar structure and helper methods.

4. Fragmented Execution System

Phase execution is spread across multiple modules: - parallel_phase_executor.py: Concurrent execution within phases - phase_executor.py (CLI): JSON-based execution - native_circular_deps_parallel.py: Native mode execution - Various orchestrators with phase support

5. Circular Dependency Detection Duplication

Cycle detection logic appears in: - Phase planners (both v1 and v2) - ResourceDependencyAnalyzer - CachedDependencyAnalyzer - Individual orchestrators

Proposed Simplified Architecture

1. Unified Data Models

Consolidate all phase-related models into a single phase_models.py:

# phase_models.py - Single source of truth for all phase models
@dataclass
class Phase:
    """Unified phase representation"""

    number: int
    description: str
    stack_id: str
    resources: Dict[str, ResourcePhaseConfig]
    execution_config: PhaseExecutionConfig  # Parallel settings, etc.


@dataclass
class PhasePlan:
    """Unified execution plan for all modes"""

    id: str
    phases: List[Phase]
    metadata: PlanMetadata

    def to_terraform_json(self) -> Dict:
        pass

    def to_native_plan(self) -> Dict:
        pass

2. Single Phase Planner

Replace both planners with one unified implementation:

# phase_planner.py - Single planner with pluggable analyzers
class PhasePlanner:
    def __init__(self, analyzer: DependencyAnalyzer):
        self.analyzer = analyzer

    def create_plan(self, app: App, strategy: str = "auto") -> PhasePlan:
        """Single entry point for phase planning"""

3. Simplified Strategy System

Reduce to two core strategies with shared base:

# phase_strategies.py
class PhaseStrategy(ABC):
    """Base with all shared logic"""

    def apply(self, resources: List[Resource], cycles: List[Cycle]) -> PhasePlan:
        pass


class MinimalModificationStrategy(PhaseStrategy):
    """Modify only what's necessary (combines current attribute/dynamic)"""


class LevelBasedStrategy(PhaseStrategy):
    """Level-based resource grouping (enhanced deferral)"""

4. Unified Execution Interface

Single execution interface for all modes:

# phase_executor.py
class PhaseExecutor:
    """Unified executor for all execution modes"""

    def execute(self, plan: PhasePlan, mode: ExecutionMode) -> ExecutionResult:
        if mode == ExecutionMode.TERRAFORM:
            return self._execute_terraform(plan)
        elif mode == ExecutionMode.NATIVE:
            return self._execute_native(plan)

5. Centralized Dependency Analysis

Move all cycle detection to a single module:

# dependency_analyzer.py
class DependencyAnalyzer:
    """Single source for dependency analysis"""

    def find_cycles(self, graph: DependencyGraph) -> List[Cycle]:
        pass

    def analyze_impact(self, cycle: Cycle) -> CycleImpact:
        pass

Simplified API Design

User-Facing API

# Simple, intuitive API for users
from nf.core.phases import analyze_phases, execute_phases

# Analyze and get plan
plan = analyze_phases(app, strategy="auto")

# Execute with options
result = execute_phases(
    plan,
    mode="terraform",  # or "native"
    parallel=True,
    max_concurrent=10,
)

Internal API Structure

nf.core.phases/
├── __init__.py          # Public API exports
├── models.py            # All data models
├── analyzer.py          # Dependency analysis
├── planner.py           # Phase planning logic
├── strategies.py        # Planning strategies
├── executor.py          # Unified execution
└── utils.py            # Shared utilities

Migration Path

Phase 1: Consolidate Models (Week 1)

  1. Merge duplicate model definitions
  2. Create adapters for backward compatibility
  3. Update imports throughout codebase

Phase 2: Unify Planners (Week 2)

  1. Create unified planner incorporating best of both
  2. Deprecate old planners with warnings
  3. Update all usage points

Phase 3: Simplify Strategies (Week 3)

  1. Extract common logic to base class
  2. Merge overlapping strategies
  3. Simplify strategy selection logic

Phase 4: Unify Execution (Week 4)

  1. Create unified executor
  2. Integrate parallel execution capabilities
  3. Update CLI and orchestrators

Benefits of Simplification

  1. Reduced Complexity: From ~15 phase-related files to ~6
  2. Clear API: Single entry point for phase operations
  3. Better Maintainability: No duplicate code or models
  4. Improved Performance: Unified caching and optimization
  5. Easier Testing: Centralized logic easier to test
  6. Better Documentation: Single source of truth

Backward Compatibility

Maintain compatibility through: 1. Adapter layers for old APIs 2. Deprecation warnings 3. Migration guides 4. Gradual rollout with feature flags

Example: Simplified Phase Usage

# Before - Complex and unclear
from nf.core.phase_planner_v2 import OptimizedPhasePlanner
from nf.core.phase_strategies import get_strategy
from nf.cli.services.phase_executor import PhaseExecutor

planner = OptimizedPhasePlanner()
strategy = get_strategy("dynamic")
# ... complex setup ...

# After - Simple and clear
from nf.core import phases

# Analyze and execute
plan = phases.analyze(app)
result = phases.execute(plan)

Conclusion

The current phase system, while functional, has become overly complex through organic growth. The proposed simplification maintains all functionality while dramatically reducing complexity, making the system easier to understand, maintain, and extend.