Token System Simplification Implementation Plan
Overview
This plan outlines a phased approach to simplifying the Token system in netherframe while maintaining backward compatibility and ensuring system stability.
Goals
- Reduce Complexity: Eliminate 200+ lines of defensive operator overloading
- Improve Maintainability: Separate concerns into focused components
- Preserve Core Functionality: Keep lazy evaluation, type safety, and dependency tracking
Phase 1: Foundation (Week 1-2)
1.1 Create New Protocol-Based Design
Files to Create:
- libs/netherframe.core/netherframe/core/tokens_v2/__init__.py
- libs/netherframe.core/netherframe/core/tokens_v2/protocols.py
- libs/netherframe.core/netherframe/core/tokens_v2/deferred.py
- libs/netherframe.core/netherframe/core/tokens_v2/references.py
Core Protocols:
# protocols.py
from typing import Protocol, TypeVar, Generic
from abc import abstractmethod
T = TypeVar("T")
R = TypeVar("R")
class Resolvable(Protocol[T]):
"""Protocol for any value that can be resolved later"""
@abstractmethod
def resolve(self, context: "ResolutionContext") -> T: ...
@abstractmethod
def get_dependencies(self) -> list["ResourceReference"]: ...
class DeferredValue(Generic[T]):
"""Simple lazy evaluation without operator complexity"""
def __init__(self, resolvable: Resolvable[T]):
self._resolvable = resolvable
self._cached_value: Optional[T] = None
def map(self, func: Callable[[T], R]) -> "DeferredValue[R]":
"""Transform the eventual value"""
return DeferredValue(MappedResolvable(self._resolvable, func))
def flat_map(self, func: Callable[[T], "DeferredValue[R]"]) -> "DeferredValue[R]":
"""Chain deferred computations"""
return DeferredValue(FlatMappedResolvable(self._resolvable, func))
def combine(self, other: "DeferredValue[U]", func: Callable[[T, U], R]) -> "DeferredValue[R]":
"""Combine two deferred values"""
return DeferredValue(CombinedResolvable(self._resolvable, other._resolvable, func))
1.2 Implement Resource Reference Specialization
# references.py
class ResourceReference(DeferredValue[T]):
"""Specialized deferred value for resource attributes"""
def __init__(self, resource: "Resource", attribute: str, expected_type: Type[T]):
self.resource = resource
self.attribute = attribute
self.expected_type = expected_type
super().__init__(ResourceAttributeResolvable(resource, attribute))
def to_terraform_reference(self) -> str:
"""Generate Terraform reference syntax"""
return f"${{{self.resource._type}.{self.resource._id}.{self.attribute}}}"
def get_cross_stack_reference(self) -> Optional["CrossStackReference"]:
"""Handle cross-stack references if needed"""
# Implementation for cross-stack logic
Phase 2: Core Integration (Week 3-4)
2.1 Update Dependency Analysis
Files to Modify:
- libs/netherframe.core/netherframe/core/phases/analyzer.py
Changes:
class DependencyAnalyzer:
def _analyze_value_for_dependencies(self, value: Any) -> list[ResourceReference]:
"""Updated to work with new token types"""
if isinstance(value, DeferredValue):
return value.get_dependencies()
elif isinstance(value, ResourceReference):
return [value]
elif isinstance(value, dict):
# Recursive analysis
pass
elif isinstance(value, list):
# Recursive analysis
pass
return []
2.2 Update Resource Attribute Generation
Files to Modify:
- libs/netherframe.core/netherframe/core/constructs/resources.py
- libs/netherframe.core/netherframe/core/constructs/attributes.py
Changes:
class Resource:
def __getattr__(self, name: str) -> ResourceReference:
"""Return new ResourceReference instead of Token"""
if name in self._schema:
attr_type = self._schema[name].type
return ResourceReference(self, name, attr_type)
2.3 Update Function Handling
Files to Modify:
- libs/netherframe.core/netherframe/core/functions.py
Changes:
class Fn:
@staticmethod
def join(delimiter: Union[str, DeferredValue[str]], values: Union[list, DeferredValue[list]]) -> DeferredValue[str]:
"""Updated to work with DeferredValue"""
# Convert inputs to DeferredValue if needed
# Return combined DeferredValue
Phase 3: Phase System Updates (Week 5-6)
3.1 Simplify Token Handling in Phases
Files to Modify:
- libs/netherframe.core/netherframe/core/phases/utils.py
- libs/netherframe.core/netherframe/core/phases/planner.py
Changes: - Remove complex token detection logic - Use protocol-based approach for dependency detection - Simplify serialization using explicit methods
3.2 Update Serialization
class DeferredValueSerializer:
"""Explicit serialization for deferred values"""
def serialize(self, value: DeferredValue) -> Dict[str, Any]:
if isinstance(value, ResourceReference):
return {"type": "resource_ref", "resource_id": value.resource._id, "attribute": value.attribute}
# Other cases
def deserialize(self, data: Dict[str, Any]) -> DeferredValue:
# Reconstruction logic
pass
4.2 Update Test Suite
Test Categories: 1. Compatibility Tests: Ensure old Token API still works 2. New API Tests: Test new DeferredValue functionality 3. Migration Tests: Test migration scenarios 4. Performance Tests: Ensure no performance regression
4.3 Update Examples and Documentation
- Update all examples to use new simplified API
- Update architecture documentation
Risk Mitigation
1. Performance Impact
- Benchmark all changes against current implementation
- Profile phase execution with new design
- Optimize hot paths identified in profiling
2. User Experience
- Clear migration documentation
- Extensive examples of new patterns
Success Metrics
- Code Reduction: Remove 200+ lines of operator overloading
- Test Coverage: Maintain 100% coverage of token functionality
- Performance: No regression in synthesis or execution time
- Developer Experience: Positive feedback on new API clarity
- Migration Success: 90%+ of code migrated automatically
Next Steps
- Review and approve implementation plan
- Create feature branch for development
- Begin Phase 1 implementation