Skip to content

Commit b645e6f

Browse files
authored
Improve backchannel reliability with PID-based socket naming (#14080)
* Improve backchannel reliability with PID-based socket naming - Add PID to socket filename: auxi.sock.{hash}.{pid} - Create shared BackchannelConstants.cs for consistent socket helpers - AppHost cleans up orphaned sockets on startup - CLI uses PID-based orphan detection before connecting - Add FindMatchingSockets helper for socket discovery - Fully backward compatible with old CLI/AppHost versions - Add 11 new unit tests (783 total CLI tests pass) * Fix aspire ps to show all running instances Changed Connections dictionary from hash-keyed (one per AppHost) to prefix-keyed with nested socket-keyed dict (one-to-many). This allows aspire ps to show all running instances of the same AppHost. - Changed _connections to _connectionsByHash with nested dictionaries - Added GetConnectionsByHash() for efficient lookup by hash - Updated Connections property to flatten all connections - Updated callers to use new interface * Parallelize socket stop and disconnect operations
1 parent 4599550 commit b645e6f

20 files changed

Lines changed: 856 additions & 162 deletions

‎src/Aspire.Cli/Aspire.Cli.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
<Compile Include="$(RepoRoot)src\Aspire.Hosting\Ats\RuntimeSpec.cs" Link="Ats\RuntimeSpec.cs" />
6060
<Compile Include="$(SharedDir)PackageUpdateHelpers.cs" Link="Utils\PackageUpdateHelpers.cs" />
6161
<Compile Include="$(SharedDir)PathLookupHelper.cs" Link="Utils\PathLookupHelper.cs" />
62+
<Compile Include="$(SharedDir)BackchannelConstants.cs" Link="Backchannel\BackchannelConstants.cs" />
6263
<Compile Include="$(SharedDir)Mcp\McpIconHelper.cs" Link="Mcp\McpIconHelper.cs" />
6364
<Compile Include="$(RepoRoot)src\Aspire.Hosting\Utils\X509Certificate2Extensions.cs" Link="Utils\X509Certificate2Extensions.cs" />
6465
</ItemGroup>

‎src/Aspire.Cli/Backchannel/AuxiliaryBackchannelMonitor.cs‎

Lines changed: 79 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ internal sealed class AuxiliaryBackchannelMonitor(
2525
{
2626
private static readonly TimeSpan s_maxRetryElapsed = TimeSpan.FromSeconds(3);
2727
private static readonly TimeSpan s_maxRetryDelay = TimeSpan.FromSeconds(1);
28-
private readonly ConcurrentDictionary<string, AppHostAuxiliaryBackchannel> _connections = new();
28+
29+
// Outer key: hash (prefix), Inner key: socketPath, Value: connection
30+
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, AppHostAuxiliaryBackchannel>> _connectionsByHash = new();
2931
private readonly string _backchannelsDirectory = GetBackchannelsDirectory();
3032

3133
// Track known socket files to detect additions and removals
@@ -34,9 +36,18 @@ internal sealed class AuxiliaryBackchannelMonitor(
3436
private readonly TimeProvider _timeProvider = timeProvider;
3537

3638
/// <summary>
37-
/// Gets the collection of active AppHost connections.
39+
/// Gets all active AppHost connections, flattened from all hashes.
3840
/// </summary>
39-
public IReadOnlyDictionary<string, AppHostAuxiliaryBackchannel> Connections => _connections;
41+
public IEnumerable<AppHostAuxiliaryBackchannel> Connections =>
42+
_connectionsByHash.Values.SelectMany(d => d.Values);
43+
44+
/// <summary>
45+
/// Gets connections for a specific AppHost hash (prefix).
46+
/// </summary>
47+
/// <param name="hash">The AppHost hash.</param>
48+
/// <returns>All connections for the given hash, or empty if none.</returns>
49+
public IEnumerable<AppHostAuxiliaryBackchannel> GetConnectionsByHash(string hash) =>
50+
_connectionsByHash.TryGetValue(hash, out var connections) ? connections.Values : [];
4051

4152
/// <summary>
4253
/// Gets or sets the path to the selected AppHost. When set, this AppHost will be used for MCP operations.
@@ -50,7 +61,7 @@ public AppHostAuxiliaryBackchannel? SelectedConnection
5061
{
5162
get
5263
{
53-
var connections = _connections.Values.ToList();
64+
var connections = Connections.ToList();
5465

5566
if (connections.Count == 0)
5667
{
@@ -91,7 +102,7 @@ public AppHostAuxiliaryBackchannel? SelectedConnection
91102
/// </summary>
92103
public IReadOnlyList<AppHostAuxiliaryBackchannel> GetConnectionsForWorkingDirectory(DirectoryInfo workingDirectory)
93104
{
94-
return _connections.Values
105+
return Connections
95106
.Where(c => IsAppHostInScopeOfDirectory(c.AppHostInfo?.AppHostPath, workingDirectory.FullName))
96107
.ToList();
97108
}
@@ -174,12 +185,10 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
174185
}
175186
finally
176187
{
177-
// Clean up all connections
178-
foreach (var connection in _connections.Values)
179-
{
180-
await DisconnectAsync(connection).ConfigureAwait(false);
181-
}
182-
_connections.Clear();
188+
// Clean up all connections in parallel
189+
var disconnectTasks = Connections.Select(DisconnectAsync);
190+
await Task.WhenAll(disconnectTasks).ConfigureAwait(false);
191+
_connectionsByHash.Clear();
183192
}
184193
}
185194

@@ -221,9 +230,17 @@ private async Task<IReadOnlyList<Task>> ProcessDirectoryChangesAsync(Cancellatio
221230
{
222231
logger.LogDebug("Socket deleted: {SocketPath}", removedFile);
223232
var hash = AppHostHelper.ExtractHashFromSocketPath(removedFile);
224-
if (!string.IsNullOrEmpty(hash) && _connections.TryRemove(hash, out var connection))
233+
if (!string.IsNullOrEmpty(hash) &&
234+
_connectionsByHash.TryGetValue(hash, out var connectionsForHash) &&
235+
connectionsForHash.TryRemove(removedFile, out var connection))
225236
{
226237
_ = Task.Run(async () => await DisconnectAsync(connection).ConfigureAwait(false), CancellationToken.None);
238+
239+
// Clean up empty hash entries
240+
if (connectionsForHash.IsEmpty)
241+
{
242+
_connectionsByHash.TryRemove(hash, out _);
243+
}
227244
}
228245
}
229246

@@ -271,10 +288,34 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
271288
return;
272289
}
273290

274-
// Check if we're already connected
275-
if (_connections.ContainsKey(hash))
291+
// Check if we're already connected to this specific socket
292+
if (_connectionsByHash.TryGetValue(hash, out var existingConnections) &&
293+
existingConnections.ContainsKey(socketPath))
276294
{
277-
logger.LogDebug("Already connected to AppHost with hash {Hash}", hash);
295+
logger.LogDebug("Already connected to socket: {SocketPath}", socketPath);
296+
return;
297+
}
298+
299+
// PID-based orphan detection (for new format sockets with PID in filename)
300+
var pid = AppHostHelper.ExtractPidFromSocketPath(socketPath);
301+
if (pid is { } pidValue && !AppHostHelper.ProcessExists(pidValue))
302+
{
303+
logger.LogDebug("Socket is orphaned (PID {Pid} not running), skipping: {SocketPath}", pidValue, socketPath);
304+
// Clean up the orphaned socket with double-check to minimize TOCTOU race window
305+
// (A new process could theoretically start with the same PID between our checks)
306+
try
307+
{
308+
if (!AppHostHelper.ProcessExists(pidValue))
309+
{
310+
File.Delete(socketPath);
311+
logger.LogDebug("Deleted orphaned socket: {SocketPath}", socketPath);
312+
}
313+
}
314+
catch (Exception ex)
315+
{
316+
logger.LogDebug(ex, "Failed to delete orphaned socket: {SocketPath}", socketPath);
317+
}
318+
failedSockets.Add(socketPath);
278319
return;
279320
}
280321

@@ -317,14 +358,12 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
317358
socket?.Dispose();
318359
socket = null;
319360

320-
// If connection is refused on first attempt, the socket file is likely stale
321-
// (AppHost crashed without cleaning up). However, there's a narrow race condition:
322-
// when an AppHost creates its socket file (bind) but hasn't called listen() yet,
323-
// we'd get ConnectionRefused. To avoid false positives, check if the socket file
324-
// was created very recently - if so, allow retries. If the file is older, it's
325-
// genuinely stale and we fail fast.
326-
if (isFirstAttempt)
361+
// For sockets without PID (old format from versions before 9.3), if connection is refused and file is old, it's stale.
362+
// For sockets with PID, we already checked process existence above, so this is transient.
363+
// TODO: Remove old format support after 9.3 is widely adopted (target: 10.0 release)
364+
if (isFirstAttempt && !pid.HasValue)
327365
{
366+
// Old format socket - use file age heuristic for backward compatibility
328367
var fileInfo = new FileInfo(socketPath);
329368
if (fileInfo.Exists)
330369
{
@@ -343,6 +382,7 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
343382
}
344383

345384
logger.LogDebug("Socket not ready yet, will retry: {SocketPath}", socketPath);
385+
isFirstAttempt = false;
346386
}
347387
catch (Exception ex)
348388
{
@@ -380,23 +420,35 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
380420
// Set up disconnect handler
381421
rpc.Disconnected += (sender, args) =>
382422
{
383-
logger.LogInformation("Disconnected from AppHost {Hash}: {Reason}", hash, args.Reason);
384-
if (_connections.TryRemove(hash, out var conn))
423+
logger.LogInformation("Disconnected from AppHost at {SocketPath}: {Reason}", socketPath, args.Reason);
424+
if (_connectionsByHash.TryGetValue(hash, out var connectionsForHash) &&
425+
connectionsForHash.TryRemove(socketPath, out var conn))
385426
{
386427
_ = Task.Run(async () => await DisconnectAsync(conn).ConfigureAwait(false));
428+
429+
// Clean up empty hash entries
430+
if (connectionsForHash.IsEmpty)
431+
{
432+
_connectionsByHash.TryRemove(hash, out _);
433+
}
387434
}
388435
};
389436

390-
if (_connections.TryAdd(hash, connection))
437+
// Get or create the inner dictionary for this hash
438+
var connectionsDict = _connectionsByHash.GetOrAdd(hash, _ => new ConcurrentDictionary<string, AppHostAuxiliaryBackchannel>());
439+
440+
if (connectionsDict.TryAdd(socketPath, connection))
391441
{
392442
logger.LogInformation(
393-
"Successfully connected to AppHost {Hash}. " +
443+
"Successfully connected to AppHost at {SocketPath}. " +
444+
"Hash: {Hash}, " +
394445
"AppHost Path: {AppHostPath}, " +
395446
"AppHost PID: {AppHostPid}, " +
396447
"CLI PID: {CliPid}, " +
397448
"Dashboard URL: {DashboardUrl}, " +
398449
"Dashboard Token: {DashboardToken}, " +
399450
"In Scope: {InScope}",
451+
socketPath,
400452
hash,
401453
appHostInfo?.AppHostPath ?? "N/A",
402454
appHostInfo?.ProcessId.ToString(CultureInfo.InvariantCulture) ?? "N/A",
@@ -407,7 +459,7 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
407459
}
408460
else
409461
{
410-
logger.LogWarning("Failed to add connection for AppHost {Hash}", hash);
462+
logger.LogWarning("Failed to add connection for socket {SocketPath}", socketPath);
411463
await DisconnectAsync(connection).ConfigureAwait(false);
412464
}
413465
}

‎src/Aspire.Cli/Backchannel/IAuxiliaryBackchannelMonitor.cs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,16 @@ namespace Aspire.Cli.Backchannel;
99
internal interface IAuxiliaryBackchannelMonitor
1010
{
1111
/// <summary>
12-
/// Gets the collection of active AppHost connections.
12+
/// Gets all active AppHost connections.
1313
/// </summary>
14-
IReadOnlyDictionary<string, AppHostAuxiliaryBackchannel> Connections { get; }
14+
IEnumerable<AppHostAuxiliaryBackchannel> Connections { get; }
15+
16+
/// <summary>
17+
/// Gets connections for a specific AppHost hash (prefix).
18+
/// </summary>
19+
/// <param name="hash">The AppHost hash.</param>
20+
/// <returns>All connections for the given hash, or empty if none.</returns>
21+
IEnumerable<AppHostAuxiliaryBackchannel> GetConnectionsByHash(string hash);
1522

1623
/// <summary>
1724
/// Gets or sets the path to the selected AppHost. When set, this AppHost will be used for MCP operations.

‎src/Aspire.Cli/Commands/McpStartCommand.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -368,12 +368,12 @@ private async Task<int> RefreshResourceToolMapAsync(CancellationToken cancellati
368368
/// </summary>
369369
private async Task<AppHostAuxiliaryBackchannel?> GetSelectedConnectionAsync(CancellationToken cancellationToken)
370370
{
371-
var connections = _auxiliaryBackchannelMonitor.Connections.Values.ToList();
371+
var connections = _auxiliaryBackchannelMonitor.Connections.ToList();
372372

373373
if (connections.Count == 0)
374374
{
375375
await _auxiliaryBackchannelMonitor.ScanAsync(cancellationToken).ConfigureAwait(false);
376-
connections = _auxiliaryBackchannelMonitor.Connections.Values.ToList();
376+
connections = _auxiliaryBackchannelMonitor.Connections.ToList();
377377
if (connections.Count == 0)
378378
{
379379
return null;

‎src/Aspire.Cli/Commands/PsCommand.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ protected override async Task<int> ExecuteAsync(ParseResult parseResult, Cancell
6868
if (jsonOutput)
6969
{
7070
await _backchannelMonitor.ScanAsync(cancellationToken).ConfigureAwait(false);
71-
connections = _backchannelMonitor.Connections.Values.ToList();
71+
connections = _backchannelMonitor.Connections.ToList();
7272
}
7373
else
7474
{
@@ -77,7 +77,7 @@ protected override async Task<int> ExecuteAsync(ParseResult parseResult, Cancell
7777
async () =>
7878
{
7979
await _backchannelMonitor.ScanAsync(cancellationToken).ConfigureAwait(false);
80-
return _backchannelMonitor.Connections.Values.ToList();
80+
return _backchannelMonitor.Connections.ToList();
8181
});
8282
}
8383

‎src/Aspire.Cli/Commands/RunCommand.cs‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -565,24 +565,31 @@ private async Task<int> ExecuteDetachedAsync(ParseResult parseResult, FileInfo?
565565

566566
_logger.LogDebug("Starting AppHost in background: {AppHostPath}", effectiveAppHostFile.FullName);
567567

568-
// Compute the expected auxiliary socket path hash for this AppHost
569-
// The Connections dictionary is keyed by hash, not the full path
570-
var expectedSocketPath = AppHostHelper.ComputeAuxiliarySocketPath(
568+
// Compute the expected auxiliary socket path prefix for this AppHost.
569+
// The hash identifies the AppHost (from project path), while the PID makes each instance unique.
570+
// Multiple instances of the same AppHost will have the same hash but different PIDs.
571+
var expectedSocketPrefix = AppHostHelper.ComputeAuxiliarySocketPrefix(
571572
effectiveAppHostFile.FullName,
572573
ExecutionContext.HomeDirectory.FullName);
573-
// We know the format is valid since we just computed it with ComputeAuxiliarySocketPath
574-
var expectedHash = AppHostHelper.ExtractHashFromSocketPath(expectedSocketPath)!;
574+
// We know the format is valid since we just computed it with ComputeAuxiliarySocketPrefix
575+
var expectedHash = AppHostHelper.ExtractHashFromSocketPath(expectedSocketPrefix)!;
575576

576-
_logger.LogDebug("Waiting for socket: {SocketPath}, Hash: {Hash}", expectedSocketPath, expectedHash);
577+
_logger.LogDebug("Waiting for socket with prefix: {SocketPrefix}, Hash: {Hash}", expectedSocketPrefix, expectedHash);
577578

578579
// Check for running instance and stop it if found (same behavior as regular run)
579580
var runningInstanceDetectionEnabled = _features.IsFeatureEnabled(KnownFeatures.RunningInstanceDetectionEnabled, defaultValue: true);
580-
if (runningInstanceDetectionEnabled && File.Exists(expectedSocketPath))
581+
var existingSockets = AppHostHelper.FindMatchingSockets(
582+
effectiveAppHostFile.FullName,
583+
ExecutionContext.HomeDirectory.FullName);
584+
585+
if (runningInstanceDetectionEnabled && existingSockets.Length > 0)
581586
{
582-
_logger.LogDebug("Found running instance for this AppHost, stopping it first");
587+
_logger.LogDebug("Found {Count} running instance(s) for this AppHost, stopping them first", existingSockets.Length);
583588
var manager = new RunningInstanceManager(_logger, _interactionService, _timeProvider);
584-
// Don't block on failure - just try to stop
585-
await manager.StopRunningInstanceAsync(expectedSocketPath, cancellationToken).ConfigureAwait(false);
589+
// Stop all running instances in parallel - don't block on failures
590+
var stopTasks = existingSockets.Select(socket =>
591+
manager.StopRunningInstanceAsync(socket, cancellationToken));
592+
await Task.WhenAll(stopTasks).ConfigureAwait(false);
586593
}
587594

588595
// Build the arguments for the child CLI process
@@ -720,8 +727,9 @@ private async Task<int> ExecuteDetachedAsync(ParseResult parseResult, FileInfo?
720727
// Trigger a scan and try to connect
721728
await _backchannelMonitor.ScanAsync(cancellationToken).ConfigureAwait(false);
722729

723-
// Check if we can find a connection for this AppHost (keyed by hash)
724-
if (_backchannelMonitor.Connections.TryGetValue(expectedHash, out var connection))
730+
// Check if we can find a connection for this AppHost by hash
731+
var connection = _backchannelMonitor.GetConnectionsByHash(expectedHash).FirstOrDefault();
732+
if (connection is not null)
725733
{
726734
return connection;
727735
}

‎src/Aspire.Cli/Commands/StopCommand.cs‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,20 +54,25 @@ protected override async Task<int> ExecuteAsync(ParseResult parseResult, Cancell
5454
if (passedAppHostProjectFile is not null)
5555
{
5656
var targetPath = passedAppHostProjectFile.FullName;
57-
var expectedSocketPath = AppHostHelper.ComputeAuxiliarySocketPath(
57+
var matchingSockets = AppHostHelper.FindMatchingSockets(
5858
targetPath,
5959
ExecutionContext.HomeDirectory.FullName);
6060

61-
if (File.Exists(expectedSocketPath))
61+
// Try each matching socket until we get a connection
62+
foreach (var socketPath in matchingSockets)
6263
{
6364
try
6465
{
6566
selectedConnection = await AppHostAuxiliaryBackchannel.ConnectAsync(
66-
expectedSocketPath, _logger, cancellationToken).ConfigureAwait(false);
67+
socketPath, _logger, cancellationToken).ConfigureAwait(false);
68+
if (selectedConnection is not null)
69+
{
70+
break;
71+
}
6772
}
6873
catch (Exception ex)
6974
{
70-
_logger.LogDebug(ex, "Failed to connect to socket at {SocketPath}", expectedSocketPath);
75+
_logger.LogDebug(ex, "Failed to connect to socket at {SocketPath}", socketPath);
7176
}
7277
}
7378

@@ -87,7 +92,7 @@ protected override async Task<int> ExecuteAsync(ParseResult parseResult, Cancell
8792
async () =>
8893
{
8994
await _backchannelMonitor.ScanAsync(cancellationToken).ConfigureAwait(false);
90-
return _backchannelMonitor.Connections.Values.ToList();
95+
return _backchannelMonitor.Connections.ToList();
9196
});
9297

9398
if (connections.Count == 0)

‎src/Aspire.Cli/Mcp/ListAppHostsTool.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public override async ValueTask<CallToolResult> CallToolAsync(ModelContextProtoc
4646

4747
var workingDirectory = executionContext.WorkingDirectory.FullName;
4848

49-
var connections = auxiliaryBackchannelMonitor.Connections.Values.ToList();
49+
var connections = auxiliaryBackchannelMonitor.Connections.ToList();
5050

5151
var inScopeAppHosts = connections
5252
.Where(c => c.IsInScope)

‎src/Aspire.Cli/Mcp/SelectAppHostTool.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public override ValueTask<CallToolResult> CallToolAsync(ModelContextProtocol.Cli
6969
}
7070

7171
// Check if there's a running AppHost with this path
72-
var matchingConnection = auxiliaryBackchannelMonitor.Connections.Values
72+
var matchingConnection = auxiliaryBackchannelMonitor.Connections
7373
.FirstOrDefault(c =>
7474
{
7575
if (c.AppHostInfo?.AppHostPath is null)
@@ -83,7 +83,7 @@ public override ValueTask<CallToolResult> CallToolAsync(ModelContextProtocol.Cli
8383
if (matchingConnection == null)
8484
{
8585
// List available AppHosts
86-
var availableAppHosts = auxiliaryBackchannelMonitor.Connections.Values
86+
var availableAppHosts = auxiliaryBackchannelMonitor.Connections
8787
.Where(c => c.AppHostInfo?.AppHostPath != null)
8888
.Select(c => c.AppHostInfo!.AppHostPath)
8989
.ToList();

0 commit comments

Comments
 (0)