Skip to content

Double Binding Analysis: A Critical Discovery

The Question

What happens if we create a not-yet-bound resource for deduplication and bind it twice under an @autoscope decorator?

The Surprising Answer

It does NOT fail! But there's a catch - the resource never gets bound at all!

The Discovery

Expected Behavior

We expected that assigning the same deferred resource to multiple stacks would either: 1. Fail with an error (resource already bound) 2. Succeed but cause the resource to be bound twice (error)

Actual Behavior

The resource remains permanently not yet bound because: 1. It was created outside any stack's context 2. Parent adoption only works for resources created inside the parent's context 3. Simple assignment (self.bucket = resource) doesn't trigger adoption

How Parent Adoption Actually Works

✅ Resources Created IN Context (Works)

@autoscope
class MyStack(Stack):
    def __init__(self):
        super().__init__()
        # Resource created WITH stack as context
        self.vpc = Resource(type="aws_vpc")  # ← Registered in the deferred-children list
        # When stack is bound, vpc gets adopted and bound

The resource's __init__ detects the stack template in context and registers itself:

# In Construct.__init__
if context_scope := self._current_scope():
    if not context_scope._bound:
        context_scope._pending_children.append(self)  # ← Registration!

❌ Resources Created OUTSIDE Context (Doesn't Work)

# Resource created with NO context
shared_resource = Resource(type="aws_s3_bucket")


@autoscope
class Stack1(Stack):
    def __init__(self):
        super().__init__()
        self.bucket = shared_resource  # ← NOT in the deferred-children list!
        # This resource will NEVER be adopted


@autoscope
class Stack2(Stack):
    def __init__(self):
        super().__init__()
        self.bucket = shared_resource  # ← Same resource, still not adopted

The Double Assignment Scenario

# Create resource outside any context
shared = Resource(type="aws_s3_bucket", bucket="shared")


class Stack1(Stack):
    def __init__(self):
        self.bucket = shared  # Assignment only


class Stack2(Stack):
    def __init__(self):
        self.bucket = shared  # Same resource!


s1 = Stack1()("s1", scope=app)
s2 = Stack2()("s2", scope=app)

# Result:
# s1.bucket._bound = False  ← Never bound!
# s2.bucket._bound = False  ← Never bound!
# s1.bucket is s2.bucket = True  ← Same object!

No error occurs because: 1. The resource is never in either stack's deferred-children list 2. Parent adoption never tries to bind it 3. Both stacks just hold a reference to the same deferred resource

Implications

The Good

  • No double-binding error (because no binding happens at all)
  • Multiple stacks can reference the same deferred resource
  • No conflicts or crashes

The Bad

  • The resource is never bound and can't be synthesized properly
  • It has no nf_id or nf_path
  • It's essentially broken for infrastructure purposes

The Ugly

  • This is a silent failure - no error, just broken behavior
  • Users might not realize their resources aren't being included
  • Synthesis might produce incomplete or invalid output

Design Solutions

Solution 1: Detect and Error

def __call__(self, nf_id, scope):
    # In Stack binding, check for external deferred resources
    for attr_name, attr_value in self.__dict__.items():
        if isinstance(attr_value, Resource) and not attr_value._bound:
            if attr_value not in self._pending_children:
                raise ValidationError(f"External deferred resource '{attr_name}' cannot be adopted. Resources must be created within the Stack's context.")

Solution 2: Force Registration

class Stack:
    def __setattr__(self, name, value):
        super().__setattr__(name, value)
        # If assigning a deferred resource, register it
        if isinstance(value, Resource) and not value._bound:
            if value not in self._pending_children:
                self._pending_children.append(value)

Solution 3: Document the Pattern

Make it clear that resources must be created within the stack context:

# WRONG - Resource created outside
shared = Resource(...)


class Stack1(Stack):
    def __init__(self):
        self.r = shared  # Won't be adopted!


# RIGHT - Resource created inside
class Stack1(Stack):
    def __init__(self):
        self.r = Resource(...)  # Will be adopted!

Correct Patterns for Shared Resources

Pattern 1: Factory Functions

def create_bucket():
    return Resource(type="aws_s3_bucket", bucket="config")


class Stack1(Stack):
    def __init__(self):
        self.bucket = create_bucket()  # New instance


class Stack2(Stack):
    def __init__(self):
        self.bucket = create_bucket()  # Different instance

Pattern 2: Shared Stack

class SharedStack(Stack):
    def __init__(self):
        self.bucket = Resource(...)  # Bound once


class ConsumerStack(Stack):
    def __init__(self, shared_stack):
        self.shared = shared_stack  # Reference only
        # Use self.shared.bucket.output

Conclusion

The deferred binding pattern has a subtle limitation: parent adoption only works for resources created within the parent's context. External deferred resources:

  1. Can be assigned to multiple parents without error
  2. Are never adopted or bound
  3. Create silent failures in synthesis

This should either be: - Fixed (detect external resources and handle them) - Documented (warn users about this limitation) - Prevented (error on external deferred resource assignment)