diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md
index 263cd36..e3caf7c 100644
--- a/skills/mdns-camera-discovery/SKILL.md
+++ b/skills/mdns-camera-discovery/SKILL.md
@@ -24,8 +24,12 @@ Read `AGENTS.md`, the focused mDNS Gitea issue, `skills/heimdall-dotnet/SKILL.md
- The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists.
- The PostgreSQL integration scenario `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` exercises confirmation from discovery metadata through persisted camera fields, including an ONVIF service port distinct from UDP 3702. Preserve that relational coverage when changing confirmation mapping.
+## UDP receive lifetime at shutdown
+
+`MdnsClient` owns each `UdpClient` for one probe/discovery call. When a receive window expires, cancel the receive with a linked token and await its task before leaving the socket scope; this observes the expected cancellation and prevents a pending receive task from surfacing later as `UnobservedTaskException`. Do not swallow unrelated `SocketException` failures: keep them observable (or log a sanitized exception type at the discovery boundary). The focused regression test `ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures` covers expected cancellation and an unexpected socket failure. Run the focused and full `Heimdall.Agent.Tests` suites after changes to this lifecycle.
+
## Disposable Compose
-Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN.
+Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its recursively referenced source projects, plus root build props/targets and `global.json`, into a temporary archive outside the repository. Mount the archive read-only, extract it inside the SDK container with `tar --no-same-owner` into `/tmp` (the container filesystem there is writable), and restore with `--locked-mode`. For mDNS lifecycle changes, run `HomeKitMdnsProbeTests` and the focused receive-cancellation regression test; otherwise run the relevant focused Agent tests. Use a unique Compose project, project-scoped NuGet package volume, and isolated bridge; publish no ports and never use host networking. The container is read-only except for `/tmp`, `/root/.local/share/NuGet` (NuGet HTTP cache), and the project-scoped package volume. Do not mark the bridge `internal`: locked restore may need NuGet network access; the bridge remains isolated from host/production networks. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the archive and Compose file, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN.
This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`.
diff --git a/src/Heimdall.Mdns/Heimdall.Mdns.csproj b/src/Heimdall.Mdns/Heimdall.Mdns.csproj
index 05ecbf0..ee33f4d 100644
--- a/src/Heimdall.Mdns/Heimdall.Mdns.csproj
+++ b/src/Heimdall.Mdns/Heimdall.Mdns.csproj
@@ -10,4 +10,8 @@
-
\ No newline at end of file
+
+
+
+
+
diff --git a/src/Heimdall.Mdns/MdnsClient.cs b/src/Heimdall.Mdns/MdnsClient.cs
index 07f743d..525fda5 100644
--- a/src/Heimdall.Mdns/MdnsClient.cs
+++ b/src/Heimdall.Mdns/MdnsClient.cs
@@ -52,44 +52,46 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
await udpClient.SendAsync(query, ct).ConfigureAwait(false);
// Try to receive within timeout
- var receiveTask = udpClient.ReceiveAsync(ct).AsTask();
- var completedTask = await Task.WhenAny(receiveTask, Task.Delay(options.Timeout, ct)).ConfigureAwait(false);
-
- if (completedTask != receiveTask)
+ using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ receiveCts.CancelAfter(options.Timeout);
+ var receiveTask = udpClient.ReceiveAsync(receiveCts.Token).AsTask();
+ try
{
- if (retry < options.MaxRetries)
- continue; // retry
- break; // timeout, try next service type
- }
+ var result = await receiveTask.ConfigureAwait(false);
+ var response = MdnsResponse.Parse(result.Buffer);
- var result = await receiveTask.ConfigureAwait(false);
- var response = MdnsResponse.Parse(result.Buffer);
-
- if (response is not null)
- {
- // If it's a HomeKit device, parse HomeKit-specific info
- if (response.Type == MdnsConstants.TypePtr &&
- response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true)
+ if (response is not null)
{
+ // If it's a HomeKit device, parse HomeKit-specific info
+ if (response.Type == MdnsConstants.TypePtr &&
+ response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true)
+ {
+ return new MdnsProbeResult
+ {
+ Target = target,
+ ServiceType = response.Name,
+ InstanceName = response.PtrName,
+ HostName = response.Address?.ToString(),
+ ResolvedAddress = response.Address,
+ HomeKitInfo = ParseHomeKitInfo(target, response)
+ };
+ }
+
return new MdnsProbeResult
{
Target = target,
ServiceType = response.Name,
InstanceName = response.PtrName,
HostName = response.Address?.ToString(),
- ResolvedAddress = response.Address,
- HomeKitInfo = ParseHomeKitInfo(target, response)
+ ResolvedAddress = response.Address
};
}
-
- return new MdnsProbeResult
- {
- Target = target,
- ServiceType = response.Name,
- InstanceName = response.PtrName,
- HostName = response.Address?.ToString(),
- ResolvedAddress = response.Address
- };
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ if (retry < options.MaxRetries)
+ continue; // timeout, retry
+ break; // timeout, try next service type
}
}
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
@@ -167,17 +169,29 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil)
{
- var receiveTask = udp.ReceiveAsync(ct).AsTask();
- var completed = await Task.WhenAny(receiveTask, Task.Delay(options.ListenWindow, ct)).ConfigureAwait(false);
+ using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ var remaining = listenUntil - DateTime.UtcNow;
+ if (remaining <= TimeSpan.Zero)
+ break;
+ receiveCts.CancelAfter(remaining);
+ var receiveTask = udp.ReceiveAsync(receiveCts.Token).AsTask();
+ try
+ {
+ var result = await receiveTask.ConfigureAwait(false);
+ var replies = ParsePacket(result.Buffer);
- if (completed != receiveTask)
- break; // no more replies expected
-
- var result = await receiveTask.ConfigureAwait(false);
- var replies = ParsePacket(result.Buffer);
-
- if (replies.Count > 0)
- collected.AddRange(replies);
+ if (replies.Count > 0)
+ collected.AddRange(replies);
+ }
+ catch (SocketException ex)
+ {
+ _logger.LogWarning("mDNS multicast receive failed (error type {ErrorType})", ex.GetType().Name);
+ break;
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ break; // listen window elapsed; receive cancellation is observed here
+ }
}
// Build devices from collected replies
@@ -201,6 +215,18 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
}
}
+ internal static async Task ObserveCanceledReceiveAsync(Task receiveTask, CancellationToken operationToken)
+ {
+ try
+ {
+ await receiveTask.ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!operationToken.IsCancellationRequested)
+ {
+ // The receive was canceled because its individual timeout elapsed.
+ }
+ }
+
// ─── DNS packet parsing (with compression pointers) ──────────────
private sealed record MdnsReply(
diff --git a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs
index 1834f3d..14b9264 100644
--- a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs
+++ b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs
@@ -1,5 +1,6 @@
using System.Text;
using System.Net;
+using System.Net.Sockets;
using Heimdall.Agent.Services;
using Heimdall.Application.DTOs;
using Heimdall.Mdns;
@@ -12,6 +13,18 @@ namespace Heimdall.Agent.Tests;
public class HomeKitMdnsProbeTests
{
+ [Fact]
+ public async Task ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures()
+ {
+ var canceledReceive = Task.FromCanceled(new CancellationToken(canceled: true));
+
+ await Should.NotThrowAsync(() => MdnsClient.ObserveCanceledReceiveAsync(canceledReceive, CancellationToken.None));
+
+ var socketFailure = Task.FromException(new SocketException((int)SocketError.NetworkDown));
+ await Should.ThrowAsync(
+ () => MdnsClient.ObserveCanceledReceiveAsync(socketFailure, CancellationToken.None));
+ }
+
[Fact]
public async Task DiscoverAsync_NoDevices_ReturnsEmptyWithoutThrow()
{