Refined Token System Simplification Plan
Current State Analysis
After analyzing the codebase, I've found that the Token system is already quite sophisticated and well-integrated:
- Token Class (
libs/netherframe.core/netherframe/core/tokens.py): - Generic type support with
Token[T] - ~200 lines of defensive operator overloading (all disabled with helpful errors)
- Resolution caching with memoization
- String method interception via
__getattr__ -
Proper
__hash__and__eq__for hashability -
Integration Points:
- Resource references:
resource.ref_id,resource.ref_arn - Variable references:
variable.ref,variable.ref_as_number - Function returns: All
Fn.*methods return tokens - Lazy values:
Lazy.string(),Lazy.number(), etc. -
Phase system: Deep integration in dependency analysis
-
Key Challenges:
- The phase analyzer uses fragile introspection (
hasattrchecks on_resolvable) - Token encoding/decoding is scattered across multiple files
- Operator overloading adds significant complexity for error prevention
Refined Implementation Strategy
Phase 1: Foundation Without Breaking Changes (Week 1)
1.1 Create Protocol-Based Infrastructure
# libs/netherframe.core/netherframe/core/tokens_v2/protocols.py
from typing import Protocol, TypeVar, Generic, runtime_checkable
T = TypeVar("T")
@runtime_checkable
class DeferredValue(Protocol[T]):
"""Protocol for any value that can be resolved later"""
def resolve(self, context: "ResolutionContext") -> T: ...
def get_dependencies(self) -> list["ResourceReference"]: ...
def get_type_hint(self) -> type[T]: ...
@runtime_checkable
class ResourceReference(DeferredValue[T], Protocol):
"""Protocol for resource attribute references"""
resource: "Resource"
attribute: str
def to_terraform_reference(self) -> str: ...
1.2 Create Adapter for Existing Tokens
# libs/netherframe.core/netherframe/core/tokens_v2/adapters.py
class TokenAdapter(DeferredValue[T]):
"""Adapter to make existing Token work with new protocol"""
def __init__(self, token: Token[T]):
self._token = token
def resolve(self, context) -> T:
return self._token.resolve(context)
def get_dependencies(self) -> list[ResourceReference]:
# Extract dependencies from token's resolvable
if hasattr(self._token._resolvable, "resource"):
return [ResourceReferenceAdapter(self._token._resolvable)]
return []
Phase 2: Update Dependency Analysis (Week 2)
2.1 Protocol-Based Dependency Detection
# libs/netherframe.core/netherframe/core/phases/analyzer.py
def _analyze_value_for_dependencies(self, value: Any) -> List[DependencyEdge]:
"""Updated to use protocol-based detection"""
edges = []
# Check protocol instead of type
if isinstance(value, DeferredValue):
for dep in value.get_dependencies():
edge = self._create_edge_from_reference(dep)
if edge:
edges.append(edge)
# Fallback to Token for backward compatibility
elif isinstance(value, Token):
edge = self._token_to_edge(value, None)
if edge:
edges.append(edge)
# Continue with string pattern matching for encoded tokens
elif isinstance(value, str):
# Existing regex patterns
pass
2.2 Simplify Token Detection
Replace fragile introspection with protocol checks:
def _create_edge_from_reference(self, ref: ResourceReference) -> Optional[DependencyEdge]:
"""Create edge from resource reference protocol"""
target_stack = ref.resource._find_stack()
if target_stack:
return DependencyEdge(from_stack=self.current_stack, from_resource=self.current_resource, to_stack=target_stack.nf_id, to_resource=ref.resource.nf_id, attribute=ref.attribute, edge_type="reference")
Phase 3: Gradual Token Simplification (Week 3-4)
3.1 Create Simplified Token Class
# libs/netherframe.core/netherframe/core/tokens_v2/token.py
class SimplifiedToken(Generic[T]):
"""Simplified token without operator overloading"""
def __init__(self, resolvable: Resolvable[T]):
self._resolvable = resolvable
self._cache: dict[int, T] = {}
def resolve(self, context) -> T:
context_id = id(context)
if context_id not in self._cache:
self._cache[context_id] = self._resolvable.resolve(context)
return self._cache[context_id]
def get_dependencies(self) -> list[ResourceReference]:
# Implement based on resolvable type
return []
# NO operator overloading - let errors happen naturally
3.2 Update Resource Attribute Generation
# libs/netherframe.core/netherframe/core/constructs/resources.py
class Resource:
def ref_attribute(self, name: str) -> Token[Any]:
"""Return token that implements both old and new protocols"""
from nf.core.tokens_v2 import DualProtocolToken
return DualProtocolToken(ResourceAttribute(self, name))
Phase 4: Migration Support (Week 5)
4.1 Dual Protocol Support
Create tokens that work with both old and new systems:
class DualProtocolToken(Token[T], DeferredValue[T]):
"""Token that supports both old Token API and new DeferredValue protocol"""
def __init__(self, resolvable: Resolvable[T]):
super().__init__(resolvable)
def get_dependencies(self) -> list[ResourceReference]:
# Implement protocol method
if isinstance(self._resolvable, ResourceAttribute):
return [ResourceReferenceImpl(self._resolvable.resource, self._resolvable.attribute)]
return []
4.2 Feature Flag for New Behavior
# libs/netherframe.core/netherframe/core/config.py (settings: a flag, else [tool.nf.config])
class TokenConfig:
USE_SIMPLIFIED_TOKENS = bool(get_config_value("simplified_tokens", default=False))
DISABLE_OPERATOR_OVERLOADING = bool(get_config_value("disable_token_operators", default=False))
Phase 5: Operator Overloading Removal (Week 6)
5.1 Conditional Operator Overloading
class Token(Generic[T]):
if not TokenConfig.DISABLE_OPERATOR_OVERLOADING:
# Include all operator overloading methods
def __add__(self, other): ...
# etc.
5.2 Migration Guide
Create comprehensive documentation showing: - How to replace token operations with functions - Common patterns and their replacements - Performance implications
Implementation Order
- Week 1: Create protocol infrastructure and adapters
- Week 2: Update dependency analyzer to use protocols
- Week 3: Implement simplified token class with dual protocol
- Week 4: Update resource/variable reference generation
- Week 5: Add feature flags and migration support
- Week 6: Create migration tooling and documentation
Risk Mitigation
Backward Compatibility
- All changes maintain existing Token API
- Protocol-based approach allows gradual migration
- Feature flags enable testing without breaking users
Performance
- Maintain resolution caching
- Protocol checks are fast (use
@runtime_checkable) - Benchmark each phase against baseline
User Experience
- No breaking changes in initial phases
- Clear migration path with tooling support
- Comprehensive documentation and examples
Success Metrics
- Code Quality:
- Remove 200+ lines of operator overloading (eventually)
- Cleaner dependency detection without introspection
-
Better separation of concerns
-
Maintainability:
- Protocol-based design easier to extend
- Simpler mental model for developers
-
Reduced coupling between components
-
Performance:
- No regression in token resolution time
- Faster dependency analysis (no introspection)
- Maintained caching effectiveness
Next Steps
- Create feature branch:
token-simplification-v2 - Implement Phase 1 protocols and adapters
- Write comprehensive tests for dual protocol support
- Begin incremental migration of dependency analyzer