Skip to content

fix(upstream): use ctx.Err() instead of select-default for context checks - #129

Merged
Dumbris merged 1 commit into
mainfrom
fix/docker-recovery-ctx-err
Nov 4, 2025
Merged

Dumbris merged 1 commit into
mainfrom
fix/docker-recovery-ctx-err

Conversation

@Dumbris

@Dumbris Dumbris commented Nov 4, 2025

Copy link
Copy Markdown
Member

Summary

Replace select-default pattern with ctx.Err() checks to eliminate TOCTOU (Time-Of-Check-Time-Of-Use) race condition in Docker recovery monitoring goroutines.

Root Cause

The select-default pattern used in PR #126 and PR #127 creates a race window:

  1. Check: select { case <-ctx.Done(): return; default: } executes
  2. Context is not cancelled yet, so execution continues to default case
  3. Time gap: Goroutine scheduler can context-switch here
  4. Context cancelled: Test completes, context gets cancelled
  5. Use: Logging statement executes AFTER context is already cancelled
  6. Panic: "Log in goroutine after test has completed"

This is a classic TOCTOU race condition where state changes between check and use.

Solution

Use ctx.Err() which provides atomic context cancellation checking:

// Before (PR #126, #127): Race condition
select {
case <-ctx.Done():
    return
default:
}
m.logger.Info("message")  // Can execute after ctx is cancelled

// After (this PR): No race condition
if ctx.Err() != nil {
    return
}
m.logger.Info("message")  // Safe - context checked atomically

Changes

handleDockerUnavailable:

  • Line 1845: select{} → ctx.Err() after timer fires
  • Line 1854: Added ctx.Err() check before "Docker recovery successful" log
  • Line 1876: select{} → ctx.Err() in reconnection goroutine
  • Line 1883: select{} → ctx.Err() before reconnection logging
  • Line 1902: select{} → ctx.Err() before "Docker recovery retry" log

startDockerRecoveryMonitor:

  • Line 1724: select{} → ctx.Err() in initial Docker check
  • Line 1745: select{} → ctx.Err() in periodic monitoring

Test Results

Ran TestUpdateListenAddressValidation 5 times locally - all passed without panic.

Why This Fix Works

ctx.Err() returns:

  • nil if context is active
  • context.Canceled if cancelled
  • context.DeadlineExceeded if deadline passed

This is an atomic operation - no goroutine scheduling can occur between the check and the logging statement, eliminating the race condition.

Impact

Fixes persistent test failures on macOS in workflow runs:

Generated with Claude Code

…ecks

Replace select-default pattern with ctx.Err() checks to eliminate TOCTOU
race condition in Docker recovery monitoring goroutines.

The select-default pattern creates a race window where context can be
cancelled AFTER the check passes but BEFORE logging happens, causing
"Log in goroutine after test has completed" panics.

Using ctx.Err() provides atomic context cancellation checking without
the race condition.

Changes:
- handleDockerUnavailable: Use ctx.Err() for all context checks before logging
- startDockerRecoveryMonitor: Use ctx.Err() in initial check and periodic monitoring
- Added ctx.Err() check before "Docker recovery successful" logging

Fixes the persistent test failure in TestUpdateListenAddressValidation
that survived PR #126 and PR #127.

Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@github-actions

github-actions Bot commented Nov 4, 2025

Copy link
Copy Markdown
Contributor

📦 Build Artifacts for PR #129

Version: v0.9.24-dev-e5607a5-pr129
Latest tag: v0.9.24

Available Artifacts

  • frontend-dist-pr (177 KB)
  • archive-linux-amd64 (9.7 MB)
  • archive-linux-arm64 (8.8 MB)
  • archive-darwin-arm64 (16 MB)
  • installer-dmg-darwin-arm64 (18 MB)
  • archive-darwin-amd64 (18 MB)
  • installer-dmg-darwin-amd64 (20 MB)
  • archive-windows-arm64 (16 MB)
  • archive-windows-amd64 (18 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 19060967009 --repo smart-mcp-proxy/mcpproxy-go

# Or download a specific artifact:
gh run download 19060967009 --name dmg-darwin-arm64

Note: Artifacts expire in 14 days.

@Dumbris
Dumbris merged commit 284dfb1 into main Nov 4, 2025
@Dumbris
Dumbris deleted the fix/docker-recovery-ctx-err branch November 4, 2025 07:58
Dumbris added a commit that referenced this pull request Nov 4, 2025
…utdown

## Problem
After PR #129, tests were still failing with "panic: Log in goroutine after
test completed" on macOS. The `ctx.Err()` checks prevented the race between
checking context and logging, but goroutines could still be running when tests
completed because there was no synchronization mechanism.

## Root Cause
The Manager struct had `shutdownCtx` and `shutdownCancel` for signaling
shutdown, but **no `sync.WaitGroup` to track background goroutines**. When
`ShutdownAll()` or `DisconnectAll()` was called:
1. Context was cancelled
2. Function returned immediately
3. Background goroutines (OAuth monitor, Docker recovery) were still running
4. Test completed and marked `testing.T` as done
5. Goroutines tried to log → panic

## Solution
Added proper goroutine lifecycle management:

1. **Manager.shutdownWg** field - Tracks all background goroutines
2. **Goroutine launches** - Call `shutdownWg.Add(1)` before spawning:
   - `startOAuthEventMonitor` (in NewManager)
   - `startDockerRecoveryMonitor` (in NewManager and dynamic restart)
3. **Goroutine exits** - Call `defer shutdownWg.Done()` in both monitor functions
4. **Shutdown waiting** - Call `shutdownWg.Wait()` in:
   - `ShutdownAll()` - with 3-second timeout
   - `DisconnectAll()` - blocking wait

## Changes
- `Manager` struct: Added `shutdownWg sync.WaitGroup`
- `NewManager()`: Added `Add(1)` before launching monitors
- `startOAuthEventMonitor()`: Added `defer Done()` at start
- `startDockerRecoveryMonitor()`: Added `defer Done()` at start
- Dynamic recovery restart: Added `Add(1)` before `go startDockerRecoveryMonitor()`
- `ShutdownAll()`: Cancel context, wait for goroutines with timeout
- `DisconnectAll()`: Cancel context, wait for goroutines

## Testing
```bash
go test ./internal/runtime -run TestUpdateListenAddressValidation -v -race -count=5
# Result: 5/5 passed, no race conditions

go test ./internal/upstream ./internal/runtime -v -race -count=2
# Result: All tests passed
```

## Related
- Fixes persistent issue from PR #122, #126, #127, #129
- Complements the `ctx.Err()` checks added in PR #129

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant