Radical Token System Simplification - No Compatibility Constraints
Historical note: This page is preserved as an archival design exercise. It may mention older subsystem names or assumptions that no longer match the current codebase. Start with Historical Internal Docs, Hybrid Execution Overview, and Migration Guide for current guidance.
Executive Summary
With no compatibility constraints, we can completely reimagine the Token system as a clean, protocol-based deferred value system. This eliminates ~500+ lines of defensive code and creates a more maintainable, performant system.
Core Design Principles
- No Operator Overloading: Let Python's natural type errors guide users
- Protocol-First: Everything is a protocol, implementations are minimal
- Explicit Over Implicit: No magic, no hidden behavior
- Type Safety: Leverage Python's type system fully
- Zero Global State: No token registries or encoding tricks
New Architecture
1. Core Protocols (Total: ~50 lines)
# libs/netherframe.core/netherframe/core/deferred.py
from typing import Protocol, TypeVar, Generic, runtime_checkable
from abc import abstractmethod
T = TypeVar("T")
R = TypeVar("R")
@runtime_checkable
class DeferredValue(Protocol[T]):
"""Any value that will be resolved later"""
@abstractmethod
def resolve(self, context: "ResolutionContext") -> T: ...
@abstractmethod
def get_dependencies(self) -> list["DeferredValue"]: ...
@abstractmethod
def map(self, fn: Callable[[T], R]) -> "DeferredValue[R]": ...
@runtime_checkable
class ResolutionContext(Protocol):
"""Context for resolving deferred values"""
@abstractmethod
def get_resource_output(self, resource_id: str, attribute: str) -> Any: ...
@abstractmethod
def get_variable_value(self, name: str) -> Any: ...
2. Simple Implementations (Total: ~100 lines)
# libs/netherframe.core/netherframe/core/deferred_impl.py
from dataclasses import dataclass
from typing import Callable, Optional
@dataclass(frozen=True)
class ResourceOutput(DeferredValue[T]):
"""Reference to a resource output"""
resource_id: str
attribute: str
expected_type: type[T]
def resolve(self, context: ResolutionContext) -> T:
return context.get_resource_output(self.resource_id, self.attribute)
def get_dependencies(self) -> list[DeferredValue]:
return [] # Leaf node
def map(self, fn: Callable[[T], R]) -> DeferredValue[R]:
return MappedValue(self, fn)
@dataclass(frozen=True)
class MappedValue(DeferredValue[R]):
"""A transformed deferred value"""
source: DeferredValue[T]
transform: Callable[[T], R]
def resolve(self, context: ResolutionContext) -> R:
return self.transform(self.source.resolve(context))
def get_dependencies(self) -> list[DeferredValue]:
return [self.source]
def map(self, fn: Callable[[R], S]) -> DeferredValue[S]:
# Compose transformations
return MappedValue(self.source, lambda x: fn(self.transform(x)))
@dataclass(frozen=True)
class CombinedValue(DeferredValue[R]):
"""Combination of multiple deferred values"""
values: list[DeferredValue]
combiner: Callable[..., R]
def resolve(self, context: ResolutionContext) -> R:
resolved = [v.resolve(context) for v in self.values]
return self.combiner(*resolved)
def get_dependencies(self) -> list[DeferredValue]:
return self.values
3. Replace Token Usage Throughout Codebase
Resources (Before):
# Old: Complex token generation with operator overloading protection
class Resource:
def __getattr__(self, name: str) -> Token[Any]:
attr = ResourceAttribute(self, name)
return Token(attr)
# Usage that we prevented:
# instance.id + "suffix" # Raises TypeError
Resources (After):
# New: Simple deferred value generation
class Resource:
def output(self, name: str, expected_type: type[T] = Any) -> DeferredValue[T]:
return ResourceOutput(self.nf_id, name, expected_type)
# Natural Python errors:
# instance.output("id") + "suffix" # TypeError: unsupported operand type(s)
4. Simplified Dependency Analysis
# libs/netherframe.core/netherframe/core/analysis.py
class DependencyAnalyzer:
def analyze_value(self, value: Any) -> set[str]:
"""Extract resource dependencies from any value"""
deps = set()
if isinstance(value, DeferredValue):
# Direct protocol check - no introspection needed!
for dep in value.get_dependencies():
if isinstance(dep, ResourceOutput):
deps.add(dep.resource_id)
deps.update(self.analyze_value(dep))
elif isinstance(value, dict):
for v in value.values():
deps.update(self.analyze_value(v))
elif isinstance(value, (list, tuple)):
for v in value:
deps.update(self.analyze_value(v))
return deps
5. Clean Resolution System
# libs/netherframe.core/netherframe/core/resolver.py
@dataclass
class SimpleResolutionContext:
"""Concrete resolution context"""
resource_outputs: dict[tuple[str, str], Any]
variables: dict[str, Any]
def get_resource_output(self, resource_id: str, attribute: str) -> Any:
return self.resource_outputs[(resource_id, attribute)]
def get_variable_value(self, name: str) -> Any:
return self.variables[name]
def resolve_value(value: Any, context: ResolutionContext) -> Any:
"""Recursively resolve all deferred values"""
if isinstance(value, DeferredValue):
return value.resolve(context)
elif isinstance(value, dict):
return {k: resolve_value(v, context) for k, v in value.items()}
elif isinstance(value, list):
return [resolve_value(v, context) for v in value]
else:
return value
Implementation Strategy
Phase 1: Rip Out Old System (Day 1-2)
- Delete:
libs/netherframe.core/netherframe/core/tokens.py(400+ lines)- All Token-related utilities and encodings
-
All operator overloading code
-
Remove:
- Token imports from all files
- TokenEncoding usage
- TokenResolver implementations
Phase 2: Implement New System (Day 3-5)
- Create:
libs/netherframe.core/netherframe/core/deferred.py- Protocolslibs/netherframe.core/netherframe/core/deferred_impl.py- Implementations-
libs/netherframe.core/netherframe/core/resolver.py- Resolution logic -
Core implementations:
- ResourceOutput, VariableReference
- MappedValue, CombinedValue
- ConstantValue for literals
Phase 3: Update Core Constructs (Day 6-8)
- Resources:
- Replace
ref_*methods withoutput()method - Remove ResourceAttribute Token generation
-
Update all resource types
-
Variables:
- Replace
refproperty withvalue()method -
Return DeferredValue instead of Token
-
Outputs:
- Update to use DeferredValue
Phase 4: Update Functions (Day 9-10)
- Core Functions:
- Rewrite to accept and return DeferredValue
- Remove Token type annotations
-
Simplify implementation
-
Generated Functions:
- Update generator to produce DeferredValue code
- Regenerate all function bindings
Phase 5: Update Analysis & Phase System (Day 11-13)
- Dependency Analysis:
- Use protocol-based detection
- Remove regex token parsing
-
Simplify circular dependency detection
-
Phase Planning:
- Update to work with DeferredValue
- Remove token encoding/decoding
- Simplify value serialization
Phase 6: Update Native Execution (Day 14-15)
- State Engine:
- Update resolution to use new system
-
Remove token-specific handling
-
Orchestrator:
- Update to resolve DeferredValue
- Simplify execution logic
Phase 7: Rewrite Tests (Day 16-18)
- Delete:
- All token-specific tests
- Operator overloading tests
-
Token encoding tests
-
Create:
- DeferredValue protocol tests
- Resolution tests
- Integration tests
Benefits of Radical Simplification
Code Reduction
- Delete: ~500 lines of Token defensive code
- Delete: ~200 lines of TokenEncoding
- Delete: ~100 lines of regex token parsing
- Net reduction: ~800 lines
Performance Improvements
- No string encoding/decoding overhead
- Direct protocol checks (no introspection)
- Better JIT optimization opportunities
- Simpler resolution path
Developer Experience
- Natural Python errors guide correct usage
- Simple mental model (just deferred values)
- Better IDE support with protocols
- Easier debugging (no magic)
Maintainability
- Clear separation of concerns
- Protocol-based extensibility
- No global state to manage
- Straightforward testing
Example: Before and After
Before (Complex)
# User tries this
bucket = Resource("aws_s3_bucket", "my_bucket")
name = bucket.ref_id + "-logs" # TypeError with custom message
# Has to do this
name = Fn.concat("", [bucket.ref_id, "-logs"])
# Dependency detection needs introspection
if hasattr(value._resolvable, "__class__"):
if value._resolvable.__class__.__name__ == "ResourceAttribute":
# Extract dependency
pass
After (Simple)
# User tries this
bucket = Resource("aws_s3_bucket", "my_bucket")
name = bucket.output("id") + "-logs" # Natural TypeError
# Clear alternative
name = Fn.concat("-", bucket.output("id"), "logs")
# Clean dependency detection
if isinstance(value, DeferredValue):
deps = value.get_dependencies()
Risks and Mitigations
- Learning Curve:
- Mitigation: Clear examples and documentation
-
Natural Python errors are actually more helpful
-
Large Changeset:
- Mitigation: Can be done in 2-3 weeks
-
Each phase is independently testable
-
Missing Edge Cases:
- Mitigation: Comprehensive test suite
- Simpler system has fewer edge cases
Conclusion
By removing compatibility constraints, we can create a dramatically simpler, more maintainable Token system. The new design: - Reduces code by ~800 lines - Eliminates all defensive programming - Uses clean protocols and types - Provides better performance - Offers superior developer experience
This is the system we would design from scratch knowing what we know now.