Skip to content

Native Mode Management Refactoring

Problem Statement

Currently, native mode detection uses thread-local storage (threading.current_thread()._nf_native_mode), which causes:

  1. Testing difficulties: Tests must manually manage thread-local state
  2. Fragility: Different threads don't share the state
  3. Implicit dependencies: Code depends on global state that's not obvious
  4. Multiple entry points: Flag is set in multiple places without clear ownership

Current Implementation

Setting Native Mode

# In enable_hybrid_execution()
threading.current_thread()._nf_native_mode = True

# In HybridExecutionMode.plan() and apply()
threading.current_thread()._nf_native_mode = True

Checking Native Mode

# In is_native_mode()
def is_native_mode() -> bool:
    return getattr(threading.current_thread(), "_nf_native_mode", False)

Proposed Solution

1. Add Execution Context to App

from enum import Enum
from typing import Optional


class ExecutionMode(Enum):
    TERRAFORM = "terraform"  # Traditional synthesis
    NATIVE = "native"  # Direct provider communication


class App:
    def __init__(self, nf_id: str, outdir: Optional[str] = None, execution_mode: ExecutionMode = ExecutionMode.TERRAFORM, **kwargs):
        self.nf_id = nf_id
        self.outdir = outdir
        self.execution_mode = execution_mode
        # ... rest of init

2. Pass Context Through Construct Tree

class Construct:
    @property
    def execution_mode(self) -> ExecutionMode:
        """Get execution mode from app."""
        app = self.app
        if app and hasattr(app, "execution_mode"):
            return app.execution_mode
        return ExecutionMode.TERRAFORM

3. Replace Global Checks

Instead of:

if is_native_mode():
    # Native mode logic
    pass

Use:

if self.execution_mode == ExecutionMode.NATIVE:
    # Native mode logic
    pass

4. Update HybridExecutionMode

class HybridExecutionMode:
    def __init__(self, app: App, *args, **kwargs):
        self.app = app
        # Set execution mode on app instead of thread-local
        self.app.execution_mode = ExecutionMode.NATIVE
        # ... rest of init

5. Update Cross-Stack References

class ResourceOutputWithContext:
    def __str__(self):
        # Access execution mode from construct
        if self.resource.execution_mode == ExecutionMode.NATIVE:
            return self._native_format()
        else:
            return self._terraform_format()

Benefits

  1. Explicit context: Execution mode is clearly visible in the app configuration
  2. Better testing: Tests can easily set execution mode without thread-local manipulation
  3. Type safety: Using enums provides better IDE support and type checking
  4. Single source of truth: Mode is stored in one place (App) and propagated down
  5. Thread safety: No thread-local state to manage

Migration Strategy

  1. Phase 1: Add new execution_mode to App while keeping thread-local checks
  2. Phase 2: Update all checks to use app.execution_mode
  3. Phase 3: Remove thread-local state and is_native_mode()
  4. Phase 4: Update all tests to use the new approach

Example Test Update

Before:

def test_build_dependency_graph(self):
    # Manually manage thread-local state
    current_thread = threading.current_thread()
    old_native_mode = getattr(current_thread, "_nf_native_mode", None)
    current_thread._nf_native_mode = False
    try:
        # ... test code ...
        pass
    finally:
        # Restore state
        pass

After:

def test_build_dependency_graph(self):
    app = App(nf_id="test", execution_mode=ExecutionMode.TERRAFORM)
    # ... test code ...
    # No cleanup needed!

Implementation Checklist

  • [ ] Add ExecutionMode enum
  • [ ] Add execution_mode parameter to App.init
  • [ ] Add execution_mode property to Construct base class
  • [ ] Update ResourceOutputWithContext.str to use construct property
  • [ ] Update dependency extraction in UnifiedOrchestrator
  • [ ] Update cross-stack reference handling in attributes.py
  • [ ] Create deprecation wrapper for is_native_mode()
  • [ ] Update HybridExecutionMode to set app.execution_mode
  • [ ] Remove thread-local state usage
  • [ ] Update all tests to use new approach
  • [ ] Remove test workarounds