Skip to content

feat: add circuit breaker for cascading failure protection#20

Open
bnusunny wants to merge 32 commits into
developfrom
test/microvm-logs-verify
Open

feat: add circuit breaker for cascading failure protection#20
bnusunny wants to merge 32 commits into
developfrom
test/microvm-logs-verify

Conversation

@bnusunny

Copy link
Copy Markdown
Owner

Adds a thread-safe circuit breaker implementation to protect against cascading failures in external service calls.

bnusunny and others added 30 commits February 11, 2026 17:07
Add a manually-triggered GitHub Actions workflow that runs
test_download_two_layers 5 times with debug instrumentation
to diagnose why layers sometimes return 'Layer1' instead of
'Layer2' on Docker (but not Finch).

Instrumentation logs:
- Layer ordering in download_all() input/output
- Generated Dockerfile ADD command sequence
- Tarball construction order
- Image build vs reuse decisions
Instead of running isolated iterations, run the exact same pytest
command as the CI local-invoke suite with added debug logging.
This reproduces the real test ordering and cross-test interactions.

Enhanced instrumentation now also captures:
- Per-layer download decisions (cached vs fresh)
- Extracted layer file contents after download
- Docker build stream output (cache hits show as CACHED)
Run just the TestLayerVersion class instead of the full local-invoke
suite. This covers the failing test_download_two_layers plus the
other tests in the class that may cause cross-test contamination.
debug: add workflow to investigate flaky layer ordering tests
debug: remove repo guard for fork
…rm container tests

* Update notify-slack.yml to add sleep (aws#8646)

* fix: use tag prefix matching to clean up samcli/lambda-* images (aws#8647)

Docker's images.list(name='samcli/lambda') does exact repository matching
and won't match repositories like 'samcli/lambda-python'. This caused
stale images to persist across parameterized test classes, leading to
flaky test_download_two_layers failures where Layer2 should overwrite
Layer1 but the image was never rebuilt.

Fix by:
1. Adding _cleanup_samcli_images() that lists all images and filters by
   'samcli/lambda-' tag prefix
2. Using this method in both tearDown and tearDownClass
3. Fixing the same pattern in TestLayerVersionThatDoNotCreateCache

* fix: remove fallback in count_running_containers that causes flaky warm container tests

The count_running_containers method had a fallback that returned the count
of ALL SAM CLI containers when MODE env var filtering found no matches.
This caused AssertionError: 3 != 2 when stale containers from other tests
were present. Now it strictly counts only containers matching this test's
unique MODE UUID and uses exact string matching.

* fix: add AWS_DEFAULT_REGION and use -k pattern for parameterized tests

* fix: add BY_CANARY=true to enable Docker tests on CI

* fix: exclude RemoteLayers tests that need AWS credentials

---------

Co-authored-by: seshubaws <116689586+seshubaws@users.noreply.github.com>
When build_in_source is used with Node.js, the build directory contains
a node_modules symlink. During local invoke, SAM CLI resolves this symlink
and creates an additional bind mount. Docker tolerates creating a mountpoint
over a symlink, but Finch (containerd/runc) fails with 'not a directory'.

This fix temporarily replaces symlinks with empty directories before
container creation, then restores them afterward. This ensures:
- Finch/runc gets a valid directory mountpoint
- Docker continues to work as before
- Repeated invocations work because symlinks are restored
- Host filesystem is left unchanged even if container creation fails
fix: replace symlinks with dirs for Finch container mount compatibility
fix: restore BY_CANARY to run docker tests on CI
Containerd/Finch resolves bind mounts at start time, not create time.
Moving the symlink restore to after start() ensures the empty directory
mountpoints are still present when the container runtime sets up mounts.
fix: move symlink restore to after container start
Bind mounts must remain valid for the container's entire lifetime.
Both Docker and Finch need the empty directory mountpoint to persist
until the container is stopped and deleted. Restoring symlinks in the
delete() method's finally block ensures proper cleanup alongside
the existing host_tmp_dir cleanup.
fix: restore symlinks at container delete time
Implement a local CloudFormation Language Extensions processor supporting:
- Fn::ForEach loop expansion in Resources, Conditions, and Outputs
- Fn::Length, Fn::ToJsonString intrinsic functions
- Fn::FindInMap with DefaultValue support
- Conditional DeletionPolicy/UpdateReplacePolicy
- Nested ForEach depth validation (max 5 levels)
- Partial resolution mode preserving unresolvable references

Pipeline architecture: TemplateParsingProcessor -> ForEachProcessor ->
IntrinsicResolverProcessor -> DeletionPolicyProcessor ->
UpdateReplacePolicyProcessor

Includes comprehensive unit tests and CloudFormation compatibility suite.
Wire the language extensions library into SAM CLI with two-phase architecture:
- Phase 1: expand_language_extensions() -> LanguageExtensionResult
- Phase 2: SamTranslatorWrapper.run_plugins() (SAM transform only)

Key components:
- expand_language_extensions() canonical entry point with template-level
  cache keyed on (path, mtime, params_hash)
- SamTranslatorWrapper receives pre-expanded template (Phase 2 only)
- SamLocalStackProvider.get_stacks() calls expand_language_extensions()
- SamTemplateValidator calls expand_language_extensions()
- DynamicArtifactProperty dataclass for Mappings transformation
- Fn::ForEach guards in artifact_exporter, normalizer, cdk/utils
- clear_expansion_cache() for warm container file change events
- _get_template_for_output() preserves Fn::ForEach in build output
- _update_foreach_artifact_paths() generates Mappings for dynamic
  artifact properties with per-function build paths
- Recursive nested Fn::ForEach support
- ForEach-aware path resolution skips Docker image URIs

Test templates: static CodeUri, dynamic CodeUri, parameter collections,
nested stacks, nested ForEach, dynamic ImageUri, depth validation.
Package:
- _export() calls expand_language_extensions() for Phase 1
- Preserves Fn::ForEach in packaged template with S3 URIs
- Generates Mappings for dynamic artifact properties
- _find_artifact_uri_for_resource() handles all export formats:
  string, {S3Bucket,S3Key}, {Bucket,Key}, {ImageUri}
- Recursive nested Fn::ForEach support
- Warning for parameter-based collections

Deploy:
- Uploads original unexpanded template to CloudFormation
- Clear error for missing Mapping keys

Integration tests for CodeUri, ContentUri, DefinitionUri, ImageUri,
BodyS3Location across all packageable resource types.
- sam validate: valid ForEach, invalid syntax, cloud-dependent collections,
  dynamic CodeUri, nested depth validation (5 valid, 6 invalid)
- sam local invoke: expanded function names from ForEach
- sam local start-api: ForEach-generated API endpoints
Add make test-lang-ext and make test-all targets so the 1695
language extensions unit tests only run when needed, keeping
the default make test fast for unrelated PRs.
The expand_language_extensions() cache stored references to template dicts
that were later mutated in-place by ApplicationBuilder.update_template()
(which changes nested stack Location properties to build-output paths).
On cache hit, the mutated dict was returned, causing TemplateNotFoundException
during the second infra sync in sam sync --watch.

Remove the cache entirely since deep-copying on hit negates the performance
benefit and adds complexity. Keep clear_expansion_cache() as a no-op for
backward compatibility.

Fixes TestSyncInfraNestedStacks_0 and TestSyncInfraNestedStacks_1 integration
test failures.
fix: remove expansion cache to fix sync watch nested stack failures
fix: use OIDC credentials directly for sync test workflow

@cortex-assistant cortex-assistant Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Circuit Breaker Review

The implementation is clean and well-structured — good use of time.monotonic(), enum-based state modeling, and clear docstrings. However, there are a couple of correctness issues and missing elements that should be addressed before merging.

🔴 Critical Issues

  1. Race condition in allow_request() for HALF_OPEN stateallow_request() calls self.state (which acquires/releases the lock), then returns the result. Between the lock release inside the state property and the caller acting on the return value, another thread can also read HALF_OPEN and get True. This allows multiple threads to pass through simultaneously, violating the "one probe call" contract. Fix: allow_request() should atomically check the state and, if HALF_OPEN, set a flag to block subsequent callers until the probe completes.

  2. No tests — This is a concurrency-sensitive component where bugs are subtle. Unit tests should cover: all state transitions, threshold boundary, recovery timeout behavior, HALF_OPEN success/failure paths, and thread-safety under contention.

🟡 Medium Issues

  1. record_success() unconditionally resets to CLOSED — Calling record_success() while in OPEN state (before timeout expires) would incorrectly force the breaker closed, bypassing recovery timeout. Consider guarding so it only transitions from HALF_OPEN → CLOSED.

  2. No logging — Other utils in this project use LOG = logging.getLogger(__name__). State transitions (CLOSED→OPEN, OPEN→HALF_OPEN, HALF_OPEN→CLOSED) are critical operational events that should be logged.

  3. No integration point — The circuit breaker is added but nothing uses it. Consider adding a decorator or context-manager interface to make it practical.

🟢 Minor

  1. No input validation on failure_threshold (could be 0 or negative) and recovery_timeout (could be negative).

What's Good

  • time.monotonic() over time.time()
  • Clean enum-based state machine ✅
  • Clear class docstring describing the contract ✅
  • Proper threading.Lock usage ✅


def allow_request(self) -> bool:
current = self.state
return current in (CircuitState.CLOSED, CircuitState.HALF_OPEN)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Race condition: allow_request() reads self.state which acquires and releases the lock, but between that release and the caller acting on the result, another thread can also see HALF_OPEN and get True. This violates the "one probe call" contract.

Suggested fix — make the check-and-transition atomic:

def allow_request(self) -> bool:
    with self._lock:
        if self._state == CircuitState.OPEN:
            if time.monotonic() - self._last_failure_time >= self._recovery_timeout:
                self._state = CircuitState.HALF_OPEN
            else:
                return False
        if self._state == CircuitState.HALF_OPEN:
            # Block further callers until probe completes
            self._state = CircuitState.OPEN
            return True  # Only this caller gets through
        return self._state == CircuitState.CLOSED

def record_success(self) -> None:
with self._lock:
self._failure_count = 0
self._state = CircuitState.CLOSED

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Guard against misuse: record_success() unconditionally resets to CLOSED. If called while OPEN (before timeout), it bypasses the recovery timeout entirely. Consider:

def record_success(self) -> None:
    with self._lock:
        self._failure_count = 0
        if self._state == CircuitState.HALF_OPEN:
            self._state = CircuitState.CLOSED

"""

def __init__(self, failure_threshold: int = 5, recovery_timeout: float = 30.0):
self._failure_threshold = failure_threshold

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Minor: Add input validation to prevent nonsensical configurations:

if failure_threshold < 1:
    raise ValueError("failure_threshold must be >= 1")
if recovery_timeout <= 0:
    raise ValueError("recovery_timeout must be > 0")

@cortex-assistant

Copy link
Copy Markdown

I've completed the review of PR #20. Here's a summary of what I did:

Review submitted: REQUEST_CHANGES with 3 inline comments:

  1. 🔴 Race condition in allow_request() (line 55) — The HALF_OPEN state check is not atomic, allowing multiple threads to pass through simultaneously when only one probe call should be permitted. Provided a suggested fix that makes the check-and-transition atomic under a single lock acquisition.

  2. 🟡 record_success() guard (line 44) — Currently unconditionally resets to CLOSED, which could bypass the recovery timeout if called while OPEN. Suggested guarding the transition to only apply from HALF_OPEN.

  3. 🟢 Input validation (line 26) — No validation on constructor parameters; negative/zero values would cause nonsensical behavior.

The review body also calls out the missing tests (critical for a concurrency primitive), missing logging for state transitions, and the lack of any integration point or decorator/context-manager API.

Label added: size:S (1 file, +55 lines)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant