Skip to content

Token System Complete Replacement Checklist

Phase 1: Delete Old System (Day 1-2)

Files to DELETE Entirely

  • [ ] libs/netherframe.core/netherframe/core/tokens.py
  • [ ] libs/netherframe.core/tests/test_tokens.py
  • [ ] libs/netherframe.core/tests/test_coverage_tokens.py
  • [ ] libs/netherframe.core/tests/test_token_identity.py
  • [ ] libs/netherframe.core/tests/test_token_guardrails.py
  • [ ] libs/netherframe.core/tests/test_token_dependency_detection.py
  • [ ] libs/netherframe.core/tests/performance/test_optimization_6_memoized_tokens.py
  • [ ] libs/netherframe.core/tests/performance/test_optimization_8_batch_tokens.py

Imports to REMOVE from Files

  • [ ] Remove from nf.core.tokens import Token, TokenEncoding, TokenResolver from:
  • libs/netherframe.core/netherframe/core/__init__.py
  • libs/netherframe.core/netherframe/core/constructs/attributes.py
  • libs/netherframe.core/netherframe/core/constructs/base_construct.py
  • libs/netherframe.core/netherframe/core/constructs/resources.py
  • libs/netherframe.core/netherframe/core/functions.py
  • libs/netherframe.core/netherframe/core/function_base.py
  • libs/netherframe.core/netherframe/core/orchestrator.py
  • libs/netherframe.core/netherframe/core/state_engine.py
  • libs/netherframe.core/netherframe/core/dependency_analyzer.py
  • libs/netherframe.core/netherframe/core/phases/analyzer.py
  • libs/netherframe.core/netherframe/core/phases/utils.py

Phase 2: Create New System (Day 3-5)

New Files to CREATE

# libs/netherframe.core/netherframe/core/deferred.py
"""Clean deferred value system without any Token legacy"""

from typing import Protocol, TypeVar, Generic, Callable, Any
from abc import abstractmethod

T = TypeVar("T")
R = TypeVar("R")


class DeferredValue(Protocol[T]):
    """Protocol for any value resolved at synthesis/runtime"""

    @abstractmethod
    def resolve(self, context: "ResolutionContext") -> T:
        """Resolve to concrete value"""
        ...

    @abstractmethod
    def get_dependencies(self) -> list["DeferredValue"]:
        """Get all deferred values this depends on"""
        ...

    @abstractmethod
    def map(self, fn: Callable[[T], R]) -> "DeferredValue[R]":
        """Transform the eventual value"""
        ...


class ResolutionContext(Protocol):
    """Context providing values for resolution"""

    @abstractmethod
    def get_resource_output(self, resource_id: str, attribute: str) -> Any: ...

    @abstractmethod
    def get_variable_value(self, name: str) -> Any: ...

    @abstractmethod
    def get_local_value(self, name: str) -> Any: ...
# libs/netherframe.core/netherframe/core/deferred_impl.py
"""Concrete implementations of deferred values"""

from dataclasses import dataclass
from typing import Any, Callable, TypeVar, Generic

T = TypeVar("T")
R = TypeVar("R")


@dataclass(frozen=True)
class ResourceOutput(Generic[T]):
    """Reference to a resource output attribute"""

    resource_id: str
    attribute: str
    expected_type: type[T]

    def resolve(self, context: ResolutionContext) -> T:
        value = context.get_resource_output(self.resource_id, self.attribute)
        # Type checking could go here if needed
        return value

    def get_dependencies(self) -> list[DeferredValue]:
        return []  # Leaf node

    def map(self, fn: Callable[[T], R]) -> DeferredValue[R]:
        return MappedValue(self, fn)

    def __str__(self) -> str:
        # For debugging
        return f"${{{self.resource_id}.{self.attribute}}}"


@dataclass(frozen=True)
class VariableReference(Generic[T]):
    """Reference to a variable"""

    name: str
    expected_type: type[T]

    def resolve(self, context: ResolutionContext) -> T:
        return context.get_variable_value(self.name)

    def get_dependencies(self) -> list[DeferredValue]:
        return []

    def map(self, fn: Callable[[T], R]) -> DeferredValue[R]:
        return MappedValue(self, fn)


@dataclass(frozen=True)
class MappedValue(Generic[R]):
    """A transformed deferred value"""

    source: DeferredValue
    transform: Callable[[Any], R]

    def resolve(self, context: ResolutionContext) -> R:
        source_value = self.source.resolve(context)
        return self.transform(source_value)

    def get_dependencies(self) -> list[DeferredValue]:
        return [self.source]

    def map(self, fn: Callable[[R], S]) -> DeferredValue[S]:
        # Function composition
        return MappedValue(self.source, lambda x: fn(self.transform(x)))


@dataclass(frozen=True)
class ConstantValue(Generic[T]):
    """A concrete value wrapped as deferred"""

    value: T

    def resolve(self, context: ResolutionContext) -> T:
        return self.value

    def get_dependencies(self) -> list[DeferredValue]:
        return []

    def map(self, fn: Callable[[T], R]) -> DeferredValue[R]:
        # Could optimize by pre-computing
        return ConstantValue(fn(self.value))

Phase 3: Update Resources (Day 6-7)

Changes to libs/netherframe.core/netherframe/core/constructs/resources.py

REMOVE:

def ref_id(self) -> Token[str]:
    return Token(ResourceAttribute(self, "id"))


def ref_arn(self) -> Token[str]:
    return Token(ResourceAttribute(self, "arn"))


def ref_attribute(self, name: str) -> Token[Any]:
    return Token(ResourceAttribute(self, name))

ADD:

from nf.core.deferred import DeferredValue
from nf.core.deferred_impl import ResourceOutput


def output(self, attribute: str, expected_type: type[T] = Any) -> DeferredValue[T]:
    """Get a deferred reference to a resource output"""
    return ResourceOutput(self.nf_id, attribute, expected_type)


# Convenience properties using the new system
@property
def id(self) -> DeferredValue[str]:
    return self.output("id", str)


@property
def arn(self) -> DeferredValue[str]:
    return self.output("arn", str)

Changes to libs/netherframe.core/netherframe/core/constructs/base_construct.py

REMOVE: All Token imports and Token return types

UPDATE: Variable class

class Variable:
    def value(self, expected_type: type[T] = Any) -> DeferredValue[T]:
        """Get deferred reference to variable value"""
        return VariableReference(self.name, expected_type)

    # Remove old ref properties

Phase 5: Update Dependency Analysis (Day 10-11)

Changes to libs/netherframe.core/netherframe/core/phases/analyzer.py

REMOVE: - All Token-specific code - Regex patterns for token detection - Complex introspection logic

ADD:

from nf.core.deferred import DeferredValue
from nf.core.deferred_impl import ResourceOutput


def _analyze_value_for_dependencies(self, value: Any) -> List[DependencyEdge]:
    """Extract dependencies using clean protocol checks"""
    edges = []

    if isinstance(value, DeferredValue):
        # Protocol-based - no introspection!
        deps = value.get_dependencies()

        # Check for resource outputs
        if isinstance(value, ResourceOutput):
            edges.append(DependencyEdge(from_stack=self.current_stack, from_resource=self.current_resource, to_stack=self._find_resource_stack(value.resource_id), to_resource=value.resource_id, attribute=value.attribute))

        # Recursively check dependencies
        for dep in deps:
            edges.extend(self._analyze_value_for_dependencies(dep))

    elif isinstance(value, dict):
        for v in value.values():
            edges.extend(self._analyze_value_for_dependencies(v))

    elif isinstance(value, (list, tuple)):
        for v in value:
            edges.extend(self._analyze_value_for_dependencies(v))

    return edges

Phase 6: Update State Engine & Orchestrator (Day 12-13)

Changes to libs/netherframe.core/netherframe/core/state_engine.py

REMOVE: All resolve() function imports and Token handling

ADD:

from nf.core.deferred import ResolutionContext
from nf.core.resolver import resolve_value


class StateEngineResolutionContext:
    """Resolution context backed by state engine"""

    def __init__(self, state_engine: "StateEngine"):
        self.state_engine = state_engine

    def get_resource_output(self, resource_id: str, attribute: str) -> Any:
        resource_state = self.state_engine.get_resource_state(resource_id)
        return resource_state.outputs.get(attribute)

    def get_variable_value(self, name: str) -> Any:
        return self.state_engine.get_variable(name)

UPDATE resolution calls:

# Old
resolved_config = resolve(resource.config, self)

# New
context = StateEngineResolutionContext(self)
resolved_config = resolve_value(resource.config, context)

Phase 7: Update Tests (Day 14-15)

New Test Files to CREATE

# libs/netherframe.core/tests/test_deferred_values.py
"""Test new deferred value system"""


def test_resource_output():
    output = ResourceOutput("bucket-1", "id", str)
    assert output.resource_id == "bucket-1"
    assert output.attribute == "id"


def test_mapped_value():
    source = ConstantValue("hello")
    mapped = source.map(str.upper)

    context = MockResolutionContext()
    assert mapped.resolve(context) == "HELLO"


def test_dependency_extraction():
    bucket_id = ResourceOutput("bucket-1", "id", str)
    upper_id = bucket_id.map(str.upper)

    deps = upper_id.get_dependencies()
    assert len(deps) == 1
    assert deps[0] is bucket_id

Update Existing Tests

  • Replace all Token[T] with DeferredValue[T]
  • Replace token.encoded checks with protocol checks
  • Remove operator overloading error tests
  • Update resolution tests to use new context

Phase 8: Generator Updates (Day 16)

Changes to Function Generator

UPDATE libs/netherframe.generation/netherframe/generation/functions/generator.py: - Change imports from Token to DeferredValue - Update return type annotations - Modify generated code templates

Example Generated Code Change:

# Old
def base64encode(input: Union[str, Token[str]]) -> Token[str]:
    return Token(FunctionCall("base64encode", {"input": input}))


# New
def base64encode(input: str | DeferredValue[str]) -> DeferredValue[str]:
    if isinstance(input, str):
        input = ConstantValue(input)
    return FunctionCall("base64encode", {"input": input})

Phase 9: Final Cleanup (Day 17-18)

Documentation Updates

  • [ ] Update docs/core/core/GENERIC_TOKENS_GUIDE.md → Rename to DEFERRED_VALUES_GUIDE.md
  • [ ] Remove token-specific documentation
  • [ ] Create new examples showing deferred value usage

Remove Legacy Code

  • [ ] Delete any remaining Token references
  • [ ] Remove TokenEncoding class completely
  • [ ] Delete token-related regex patterns
  • [ ] Remove global token registry code

Performance Verification

  • [ ] Benchmark new deferred value creation
  • [ ] Test resolution performance
  • [ ] Verify memory usage improvements
  • [ ] Check synthesis time

Success Criteria

  • [ ] All tests pass with new system
  • [ ] No references to Token remain in codebase
  • [ ] Synthesis performance improved by 10%+
  • [ ] Code reduction of 800+ lines achieved
  • [ ] Clean protocol-based design throughout