Skip to content

Forward-Store Cross-Stack References Design

Current Problem

The system scans all 514,000 values recursively to find ~1% that might be cross-stack references, taking 3.6 seconds.

Proposed Solution: Forward-Store Pattern

1. Track Active Stack Context

# In Stack class
class Stack:
    _active_stack = None  # Thread-local or context variable

    def __enter__(self):
        self._previous_stack = Stack._active_stack
        Stack._active_stack = self
        return self

    def __exit__(self, *args):
        Stack._active_stack = self._previous_stack

2. Register References at Creation

class ResourceOutputWithContext:
    def __init__(self, resource, attribute, expected_type):
        super().__init__()
        self.resource = resource
        self.attribute = attribute
        self.expected_type = expected_type

        # NEW: Register cross-stack reference immediately
        source_stack = resource._find_stack()
        target_stack = Stack._active_stack

        if source_stack and target_stack and source_stack != target_stack:
            # Forward-store the reference!
            source_stack._register_outgoing_reference(resource, attribute, target_stack)
            target_stack._register_incoming_reference(resource, attribute, source_stack)

3. Stack Reference Registry

class Stack:
    def _init_cross_stack_tracking(self):
        self._outgoing_refs = []  # References TO other stacks
        self._incoming_refs = []  # References FROM other stacks

    def _register_outgoing_reference(self, resource, attribute, target_stack):
        ref = {"resource": resource, "attribute": attribute, "target_stack": target_stack}
        self._outgoing_refs.append(ref)
        # Immediately create export if needed
        self._ensure_export_for_reference(ref)

4. Eliminate Scanning Phase

def _synthesize_regular(self, stack_dir: Path, output_format: str = "json") -> None:
    # REMOVED: self._pre_scan_cross_stack_references()

    # Build config - cross-stack refs already registered!
    config = self._to_config()

    # Setup exports/imports from registered refs
    self._setup_registered_cross_stack_references()

    # Continue with resolution...

Implementation Steps

Phase 1: Add Stack Context Tracking

  1. Implement context manager for Stack
  2. Use context vars or thread-local for active stack
  3. Ensure all resource creation happens within stack context

Phase 2: Forward Registration

  1. Modify ResourceOutputWithContext.init
  2. Add reference registries to Stack
  3. Create exports/imports immediately when refs are registered

Phase 3: Remove Scanning

  1. Delete _scan_value_for_cross_refs (saves 3.6s!)
  2. Delete _pre_scan_cross_stack_references
  3. Use registered references instead

Expected Performance Impact

  • Eliminate 514,000 recursive scans
  • Save 3.6 seconds (74% of synthesis time)
  • Expected new performance: ~15,000-20,000 resources/sec

Alternative: Resource Creation Hook

class Resource:
    def __setattr__(self, name, value):
        super().__setattr__(name, value)

        # If value is a ResourceOutputWithContext from another stack
        if isinstance(value, ResourceOutputWithContext):
            source_stack = value.resource._find_stack()
            my_stack = self._find_stack()

            if source_stack != my_stack:
                # Register cross-stack reference
                my_stack._register_cross_stack_usage(self, name, value)

This catches cross-stack refs when they're assigned to resource attributes.

Benefits

  1. O(n) instead of O(n²) - Only process actual cross-stack refs
  2. Fail-fast - Know about cross-stack refs immediately
  3. Better debugging - Can track where refs are created
  4. Cleaner architecture - No scanning, just registration