Skip to content

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:

  1. Token Class (libs/netherframe.core/netherframe/core/tokens.py):
  2. Generic type support with Token[T]
  3. ~200 lines of defensive operator overloading (all disabled with helpful errors)
  4. Resolution caching with memoization
  5. String method interception via __getattr__
  6. Proper __hash__ and __eq__ for hashability

  7. Integration Points:

  8. Resource references: resource.ref_id, resource.ref_arn
  9. Variable references: variable.ref, variable.ref_as_number
  10. Function returns: All Fn.* methods return tokens
  11. Lazy values: Lazy.string(), Lazy.number(), etc.
  12. Phase system: Deep integration in dependency analysis

  13. Key Challenges:

  14. The phase analyzer uses fragile introspection (hasattr checks on _resolvable)
  15. Token encoding/decoding is scattered across multiple files
  16. 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

  1. Week 1: Create protocol infrastructure and adapters
  2. Week 2: Update dependency analyzer to use protocols
  3. Week 3: Implement simplified token class with dual protocol
  4. Week 4: Update resource/variable reference generation
  5. Week 5: Add feature flags and migration support
  6. 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

  1. Code Quality:
  2. Remove 200+ lines of operator overloading (eventually)
  3. Cleaner dependency detection without introspection
  4. Better separation of concerns

  5. Maintainability:

  6. Protocol-based design easier to extend
  7. Simpler mental model for developers
  8. Reduced coupling between components

  9. Performance:

  10. No regression in token resolution time
  11. Faster dependency analysis (no introspection)
  12. Maintained caching effectiveness

Next Steps

  1. Create feature branch: token-simplification-v2
  2. Implement Phase 1 protocols and adapters
  3. Write comprehensive tests for dual protocol support
  4. Begin incremental migration of dependency analyzer