Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions OrchestratorIDE.Daemon/HiveService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,23 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)

// Wire election/heartbeat logs after Start (services auto-created inside Start).
if (_nodeServer.ElectionService is { } election)
{
election.OnLog += msg => _log.LogInformation("[Election] {Msg}", msg);

// Discovered live (2026-07-29) verifying the new /hive/roles/degrade and
// /hive/tasks/cancel endpoints: HiveElectionService.WarchiefNodeId is ONLY ever set
// via live election-protocol messages (SetWarchief's own doc comment: "Must be
// called by the app when a HIVE session starts... we've received a session context
// identifying who is"). Nothing here ever called it for a statically-configured
// worker, even though _cfg.WarchiefNodeId is already known from config -- so every
// Warchief-only mutation gate (this one, /hive/roles/degrade, /hive/tasks/cancel, and
// the PRE-EXISTING /hive/update/deploy) rejected the fleet's real, correctly-signed
// Warchief with a 403 on every one of them, on every worker in this deployment shape.
// A worker that already knows its Warchief via config doesn't need to wait for
// election traffic to learn what it was already told.
if (!string.IsNullOrWhiteSpace(_cfg.WarchiefNodeId))
election.SetWarchief(_cfg.WarchiefNodeId);
}
if (_nodeServer.MeshHeartbeat is { } hb)
hb.OnLog += msg => _log.LogInformation("[Heartbeat] {Msg}", msg);

Expand Down Expand Up @@ -257,6 +273,13 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
}).ToList(),
};
};

// HV-3 item 3 (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md): MarkRoleDegraded was
// previously reachable only from the runtime's own internal NoKvSlot handling —
// this wires the long-deferred remote trigger (POST /hive/roles/degrade) to the
// same NativeRoleRuntime instance NativeTelemetryProvider above already closes
// over.
_nodeServer.MarkRoleDegradedHandler = role => nativeRuntime.MarkRoleDegraded(role);
}

_worker = new HiveWorkerAgent
Expand All @@ -270,6 +293,11 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
WarchiefNodeId = _cfg.WarchiefNodeId,
ModelStore = _taskQueue.ModelStore,
};
// HV-4 item 1: a campaign cancel previously only marked the task cancelled on the
// Warchief while the worker kept generating to completion — no remote trigger existed
// to actually interrupt it. POST /hive/tasks/cancel now reaches this worker's
// per-task cancellation registry directly.
_nodeServer.CancelTaskHandler = taskId => _worker.TryCancelTask(taskId);
_worker.OnLog += msg => _log.LogInformation("[Worker] {Msg}", msg);
var installedPacks = CampaignPackCatalog.ResolveInstalled(_cfg.AlienSearchImage);
_worker.Capabilities = await WorkerCapabilityDetector.DetectAsync(
Expand Down
28 changes: 28 additions & 0 deletions OrchestratorIDE.UnitTests/HiveNodeServerAuthorizationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (C) 2025-present hardcoreerik / TheOrc contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
using NUnit.Framework;
using OrchestratorIDE.Services.Hive;

namespace OrchestratorIDE.UnitTests;

/// <summary>
/// HiveNodeServer.IsWarchief is the shared authority gate for the Warchief-only mutation
/// endpoints (remote deploy, /hive/roles/degrade, /hive/tasks/cancel — HV-3 item 3 / HV-4
/// item 1). It reads ElectionService.WarchiefNodeId, which requires a real HiveElectionService
/// (itself requiring a real HiveIdentity, private-constructor-only) to test the "configured and
/// matches" branch — too heavy for what should be a cheap authorization check. This covers the
/// safe-default branch instead: no ElectionService configured must mean nobody is authorized
/// (fail-closed), not "any caller passes."
/// </summary>
[TestFixture]
public sealed class HiveNodeServerAuthorizationTests
{
[TestCase("")]
[TestCase("some-node-id")]
public void IsWarchief_ReturnsFalse_WhenElectionServiceNotConfigured(string nodeId)
{
using var server = new HiveNodeServer();
Assert.That(server.ElectionService, Is.Null, "test assumes the default-constructed state");
Assert.That(server.IsWarchief(nodeId), Is.False);
}
}
16 changes: 16 additions & 0 deletions OrchestratorIDE.UnitTests/HiveWorkerAgentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,20 @@ public async Task RunLoop_Survives_A_Timed_Out_Lease_Poll()
foreach (var client in stalled) client.Dispose();
}
}

/// <summary>
/// HV-4 item 1's remote cancel endpoint (HiveNodeServer.CancelTaskHandler) reports "not
/// found" (404) rather than an error for a taskId this worker isn't currently tracking —
/// covers the empty-registry case (never claimed anything) and an id that simply doesn't
/// match. The "found and actually cancels" path needs a real claimed task in flight
/// (a heavier integration scenario); this locks down the safe, cheap half: an unknown id
/// never throws and never reports a false positive.
/// </summary>
[TestCase("")]
[TestCase("never-claimed-task-id")]
public void TryCancelTask_ReturnsFalse_ForUnknownTaskId(string taskId)
{
var agent = new HiveWorkerAgent();
Assert.That(agent.TryCancelTask(taskId), Is.False);
}
}
14 changes: 14 additions & 0 deletions OrchestratorIDE/Core/Runtime/IRoleRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,20 @@ public IReadOnlyList<AdapterRoleResidency> GetResidencySnapshot()
return _orchestrator.GetResidencySnapshot();
}

/// <summary>
/// Forwards to <see cref="_orchestrator"/>. Public entry point for
/// <see cref="OrchestratorIDE.Services.Hive.HiveNodeServer"/>'s remote
/// <c>POST /hive/roles/degrade</c> endpoint (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md
/// HV-3 item 3) — previously this method was reachable only from the internal NoKvSlot/
/// generation-failure paths inside this same class (<see cref="StreamRoleCompletionCoreAsync"/>,
/// <see cref="InferUntilReadyAsync"/>).
/// </summary>
public Task MarkRoleDegraded(RuntimeRole role)
{
ThrowIfDisposed();
return _orchestrator.MarkRoleDegraded(role);
}

public Task<int?> GetContextLengthAsync(string model, CancellationToken ct = default) =>
Task.FromResult<int?>(_options.ContextLength);

Expand Down
133 changes: 133 additions & 0 deletions OrchestratorIDE/Services/Hive/HiveNodeServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using OrchestratorIDE.Core.Runtime;

namespace OrchestratorIDE.Services.Hive;

Expand All @@ -23,6 +24,8 @@ namespace OrchestratorIDE.Services.Hive;
/// POST /hive/mesh/election/stepdown — authenticated election: temp Warchief stepping down
/// GET /hive/update/version — this node's installed version (unauthenticated)
/// POST /hive/update/deploy — Warchief-authenticated remote update trigger
/// POST /hive/roles/degrade — Warchief-authenticated forced role recycle
/// POST /hive/tasks/cancel — Warchief-authenticated single in-flight task cancel
///
/// Auth: all /hive/mesh/* endpoints validate HMAC headers via HiveAuthMiddleware.
/// /hive/tasks/* endpoints (port 7079, HiveTaskQueue) are wired separately and
Expand Down Expand Up @@ -80,6 +83,26 @@ public sealed class HiveNodeServer : IDisposable
/// </summary>
public Func<object?>? NativeTelemetryProvider { get; set; }

/// <summary>
/// Injected by the app (Daemon: HiveService, alongside NativeTelemetryProvider) so
/// POST /hive/roles/degrade can force a role's native executor to recycle on its next mint
/// (<see cref="OrchestratorIDE.Core.Runtime.RuntimeOrchestrator.MarkRoleDegraded"/> via
/// <c>NativeRoleRuntime</c>'s public forwarder). Previously reachable ONLY from the runtime's
/// own NoKvSlot/generation-failure handling (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md,
/// HV-3 item 3 / HV-4 item 1) — this is that long-deferred remote trigger. Null when native
/// execution isn't configured on this node, same convention as NativeTelemetryProvider.
/// </summary>
public Func<RuntimeRole, Task>? MarkRoleDegradedHandler { get; set; }

/// <summary>
/// Injected by the app (Daemon: HiveService, after constructing HiveWorkerAgent) so
/// POST /hive/tasks/cancel can interrupt ONE in-flight task
/// (<see cref="HiveWorkerAgent.TryCancelTask"/>) without stopping the worker or any other
/// concurrently-running task. Returns false (surfaced as 404) for an id this worker isn't
/// currently tracking. Null on a node with no worker agent (e.g. Warchief-only).
/// </summary>
public Func<string, bool>? CancelTaskHandler { get; set; }

// Pending pairing sessions: sessionId → (request, expiry, initiator-remote-ip)
private readonly Dictionary<string, (HivePairingRequest Req, DateTime Expiry, string RemoteIp)> _pendingPairings = [];
// Completed results: sessionId → (response, stored-at). Pruned after 10 min.
Expand Down Expand Up @@ -549,6 +572,35 @@ private async Task HandleAsync(HttpListenerContext ctx, CancellationToken ct)
return;
}

// Forced role recycle — Warchief-only, same authority tier as remote deploy: this is
// a fleet-operator diagnostic action (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md
// HV-3 item 3), not something any authenticated-but-unprivileged peer should trigger.
if (method == "POST" && path == "/hive/roles/degrade")
{
if (!IsWarchief(authResult.NodeId))
{
resp.StatusCode = 403;
Error(resp, "only the Warchief may force a role recycle");
return;
}
HandleMarkRoleDegraded(body, resp);
return;
}

// Single in-flight task cancel — Warchief-only, same reasoning as above: this
// interrupts a real running generation on the worker (HV-4 item 1), not a read.
if (method == "POST" && path == "/hive/tasks/cancel")
{
if (!IsWarchief(authResult.NodeId))
{
resp.StatusCode = 403;
Error(resp, "only the Warchief may cancel a task");
return;
}
HandleCancelTask(body, resp);
return;
}

resp.StatusCode = 404;
Error(resp, "not found");
}
Expand Down Expand Up @@ -934,6 +986,87 @@ private void HandleMeshHeartbeat(byte[] body, HttpListenerRequest req,
catch { resp.StatusCode = 400; Error(resp, "bad request"); }
}

/// <summary>
/// Shared authority check for the Warchief-only mutation endpoints (remote deploy, forced
/// role recycle, task cancel). Mirrors the inline check already used by
/// /hive/update/deploy — factored out here rather than duplicated a third time. Peer-local
/// and non-transitive: being a Founder elsewhere does not make a node the Warchief FROM this
/// node's own perspective (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md:90-99), so this checks
/// ElectionService's own live view, the same source /hive/update/deploy already trusts.
/// </summary>
internal bool IsWarchief(string nodeId)
{
var wc = ElectionService?.WarchiefNodeId;
return !string.IsNullOrEmpty(wc) && wc == nodeId;
}

// ── /hive/roles/degrade ───────────────────────────────────────────────────

private sealed record MarkRoleDegradedRequest(string Role);

private void HandleMarkRoleDegraded(byte[] body, HttpListenerResponse resp)
{
if (MarkRoleDegradedHandler is null)
{
resp.StatusCode = 503;
Error(resp, "native execution is not configured on this node");
return;
}
MarkRoleDegradedRequest? payload;
try { payload = JsonSerializer.Deserialize<MarkRoleDegradedRequest>(body, _jsonIn); }
catch { resp.StatusCode = 400; Error(resp, "bad request"); return; }

if (payload is null || !Enum.TryParse<RuntimeRole>(payload.Role, ignoreCase: true, out var role))
{
resp.StatusCode = 400;
Error(resp, $"invalid or missing role (expected one of: {string.Join(", ", Enum.GetNames<RuntimeRole>())})");
return;
}
Comment on lines +1014 to +1027

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Repository files containing HiveNodeServer.cs:"
git ls-files | grep -F 'HiveNodeServer.cs' || true

echo
echo "Relevant source excerpt:"
if [ -f "OrchestratorIDE/Services/Hive/HiveNodeServer.cs" ]; then
  sed -n '980,1080p' "OrchestratorIDE/Services/Hive/HiveNodeServer.cs" | nl -ba -v980
fi

echo
echo "Search RuntimeRole and MarkRoleDegradedHandler:"
rg -n "enum RuntimeRole|RuntimeRole|MarkRoleDegradedHandler|MarkRoleDegradedRequest" -S .
echo
echo ".NET Enum.TryParse behavior probe:"
python3 - <<'PY'
# Python enum TryParse has different behavior; this block exists only to satisfy framework if present.
PY

Repository: hardcoreerik/TheOrc

Length of output: 319


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Behavioral probe outside repository code: compile and run a small .cs file if dotnet is available.
cat > /tmp/EnumTryParseProbe.cs <<'CS'
using System;
using System.Reflection;

enum RuntimeRole { None = 0, Leader = 1, Follower = 2 }

class Program
{
    static int Main()
    {
        string[] testCases = new[] { "Leader", "999", "leader", "1", "0", "abc" };
        foreach (var role in testCases)
        {
            if (Enum.TryParse<RuntimeRole>(role, ignoreCase: true, out var parsed))
                Console.WriteLine($"{role,-6} -> parsed={parsed} (undefined={(!Enum.IsDefined<RuntimeRole>(parsed)).ToString().ToLower()})");
            else
                Console.WriteLine($"{role,-6} -> parsed_null");
        }
        return 0;
    }
}
CS

if command -v dotnet >/dev/null 2>&1; then
  tmpdir="$(mktemp -d)"
  cp /tmp/EnumTryParseProbe.cs "$tmpdir/Program.cs"
  (
    cd "$tmpdir"
    dotnet new console --force --no-restore >/dev/null 2>&1 || true
    dotnet build >/dev/null 2>&1 || exit 1
    dotnet run
  )
else
  echo "dotnet not available; cannot run behavioral probe"
fi

rm -f /tmp/EnumTryParseProbe.cs
rm -rf "${tmpdir:-}"

Repository: hardcoreerik/TheOrc

Length of output: 207


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Behavioral probe outside repository code: compile and run a small .cs file if dotnet is available.
cat > /tmp/EnumTryParseProbe.cs <<'CS'
using System;
using System.Reflection;

enum RuntimeRole { None = 0, Leader = 1, Follower = 2 }

class Program
{
    static int Main()
    {
        string[] testCases = new[] { "Leader", "999", "leader", "1", "0", "abc" };
        foreach (var role in testCases)
        {
            if (Enum.TryParse<RuntimeRole>(role, ignoreCase: true, out var parsed))
                Console.WriteLine($"{role,-6} -> parsed={parsed} (undefined={(!Enum.IsDefined<RuntimeRole>(parsed)).ToString().ToLower()})");
            else
                Console.WriteLine($"{role,-6} -> parsed_null");
        }
        return 0;
    }
}
CS

if command -v dotnet >/dev/null 2>&1; then
  tmpdir="$(mktemp -d)"
  cp /tmp/EnumTryParseProbe.cs "$tmpdir/Program.cs"
  (
    cd "$tmpdir"
    dotnet new console --force --no-restore >/dev/null 2>&1 || true
    dotnet build >/dev/null 2>&1 || exit 1
    dotnet run
  )
else
  echo "dotnet not available; cannot run behavioral probe"
fi

2> /tmp/enum_probe_err.txt; true
rm -f /tmp/EnumTryParseProbe.cs /tmp/enum_probe_err.txt
rm -rf "${tmpdir:-}"

Repository: hardcoreerik/TheOrc

Length of output: 207


🌐 Web query:

Microsoft .NET Enum.TryParse numeric string undefined enum value IsDefined behavior

💡 Result:

In.NET, the Enum.TryParse method is designed to parse both the names and the underlying numeric values of an enumeration [1][2][3]. When a numeric string is provided, Enum.TryParse will successfully parse it into the target enum type even if that numeric value is not explicitly defined in the enumeration [1][4][5]. This behavior occurs because Enum.TryParse treats any string representation of an integer as a valid attempt to convert to the enum's underlying integral type [1][2][5]. Consequently, the method will return true and output the corresponding enum value, regardless of whether that value corresponds to a named member [4][6]. If this behavior is undesirable and you need to ensure that the parsed value is a valid, defined member of the enumeration, you must explicitly call Enum.IsDefined after a successful parse [1][2][5]. Example of the safe usage pattern: string input = "99"; // An undefined value if (Enum.TryParse(input, out MyEnum result) && Enum.IsDefined(typeof(MyEnum), result)) { // Result is a valid, defined member of the enum } else { // Handle invalid or undefined value } Note that Enum.IsDefined evaluates whether the specific value (or name) exists within the enumeration [7][5]. In cases where you are dealing with enumerations marked with the [Flags] attribute, keep in mind that Enum.IsDefined may return false for composite values (e.g., bitwise combinations) even if they are logically valid for your use case, and you should use Enum.HasFlag instead [7].

Citations:


🌐 Web query:

Microsoft .NET Enum.TryParse numeric string undefined enum value IsDefined behavior

💡 Result:

In.NET, the Enum.TryParse method is designed to succeed even when the input numeric string does not correspond to a defined constant within the enumeration [1][2][3]. If the input string is a valid representation of the underlying integral type of the enum, Enum.TryParse will parse it and return true, assigning the resulting value to the output parameter [1][4]. This behavior is intentional, as it allows the method to support the parsing of underlying integral values that may not be explicitly named constants [1][5]. Because Enum.TryParse returns true for these undefined values, it does not implicitly validate that the result is a defined member of the enumeration [6][3]. To ensure that a parsed value is an actual defined member of the enum, you must explicitly call Enum.IsDefined [1][6]. When using Enum.IsDefined for this purpose, it is critical to pass the enum value itself, not the original string [6][7]. Enum.IsDefined(typeof(TEnum), "some_string") looks for a member named "some_string" and will return false if the string is numeric, even if that number corresponds to a valid enum constant [7]. Instead, you should perform the following sequence [6][8][7]: 1. Use Enum.TryParse to convert the string to the enum type [1][8]. 2. Pass the resulting enum value to Enum.IsDefined to verify it is a defined constant [6][8]. Example: string input = "99"; // Undefined value if (Enum.TryParse(input, out MyEnum result)) { if (Enum.IsDefined(typeof(MyEnum), result)) { // Value is defined } else { // Value is parsed but not defined in the enum } }

Citations:


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Relevant HiveNodeServer excerpt:"
sed -n '980,1090p' "OrchestratorIDE/Services/Hive/HiveNodeServer.cs" | awk '{printf "%6d\t%s\n", NR+979, $0}'

echo
echo "RuntimeRole definition and handler usages:"
rg -n "enum RuntimeRole|RuntimeRole|MarkRoleDegradedHandler|MarkRoleDegradedRequest|IsDefined" -S "OrchestratorIDE/Services/Hive"

Repository: hardcoreerik/TheOrc

Length of output: 7935


Reject undefined RuntimeRole values before invoking the handler.

.NET enum parsing accepts valid integer strings for undefined values, so {"role":"999"} currently returns success and calls MarkRoleDegradedHandler(999) instead of returning the documented 400 role validation error.

🛡️ Proposed fix
-        if (payload is null || !Enum.TryParse<RuntimeRole>(payload.Role, ignoreCase: true, out var role))
+        if (payload is null
+            || !Enum.TryParse<RuntimeRole>(payload.Role, ignoreCase: true, out var role)
+            || !Enum.IsDefined(role))
         {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
MarkRoleDegradedRequest? payload;
try { payload = JsonSerializer.Deserialize<MarkRoleDegradedRequest>(body, _jsonIn); }
catch { resp.StatusCode = 400; Error(resp, "bad request"); return; }
if (payload is null || !Enum.TryParse<RuntimeRole>(payload.Role, ignoreCase: true, out var role))
{
resp.StatusCode = 400;
Error(resp, $"invalid or missing role (expected one of: {string.Join(", ", Enum.GetNames<RuntimeRole>())})");
return;
}
MarkRoleDegradedRequest? payload;
try { payload = JsonSerializer.Deserialize<MarkRoleDegradedRequest>(body, _jsonIn); }
catch { resp.StatusCode = 400; Error(resp, "bad request"); return; }
if (payload is null
|| !Enum.TryParse<RuntimeRole>(payload.Role, ignoreCase: true, out var role)
|| !Enum.IsDefined(role))
{
resp.StatusCode = 400;
Error(resp, $"invalid or missing role (expected one of: {string.Join(", ", Enum.GetNames<RuntimeRole>())})");
return;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@OrchestratorIDE/Services/Hive/HiveNodeServer.cs` around lines 1015 - 1024,
Update the role validation in the MarkRoleDegraded request handling before
invoking MarkRoleDegradedHandler to reject parsed RuntimeRole values that are
not defined enum members. Preserve the existing case-insensitive name parsing
and documented 400 response, including the expected-role message, for undefined
numeric or other invalid values.


// Fire the recycle, respond immediately — MarkRoleDegraded itself is a fast, in-memory
// flag set (AdapterManager.cs:317-334), but the actual recycle only happens lazily on the
// role's next mint, so there's nothing further to await before answering the caller.
Ok(resp, Json(new { status = "ok", role = role.ToString() }));
var handler = MarkRoleDegradedHandler;
_ = Task.Run(async () =>
{
try { await handler(role).ConfigureAwait(false); }
catch (Exception ex) { /* best-effort: the next mint will still recycle on its own detection paths */ Console.Error.WriteLine($"[HiveNodeServer] MarkRoleDegraded({role}) failed: {ex.Message}"); }
});
}

// ── /hive/tasks/cancel ────────────────────────────────────────────────────

private sealed record CancelTaskRequest(string TaskId);

private void HandleCancelTask(byte[] body, HttpListenerResponse resp)
{
if (CancelTaskHandler is null)
{
resp.StatusCode = 503;
Error(resp, "no worker agent is running on this node");
return;
}
CancelTaskRequest? payload;
try { payload = JsonSerializer.Deserialize<CancelTaskRequest>(body, _jsonIn); }
catch { resp.StatusCode = 400; Error(resp, "bad request"); return; }

if (payload is null || string.IsNullOrWhiteSpace(payload.TaskId))
{
resp.StatusCode = 400;
Error(resp, "missing taskId");
return;
}

if (!CancelTaskHandler(payload.TaskId))
{
resp.StatusCode = 404;
Error(resp, "no in-flight task with this id on this worker");
return;
}
Ok(resp, Json(new { status = "ok", taskId = payload.TaskId }));
}

// ── /hive/mesh/election/* ─────────────────────────────────────────────────

private void HandleElection(string path, byte[] body, string authenticatedNodeId,
Expand Down
37 changes: 35 additions & 2 deletions OrchestratorIDE/Services/Hive/HiveWorkerAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ public sealed class HiveWorkerAgent : IDisposable, IAsyncDisposable
{
private static readonly TimeSpan DefaultDisposeWaitTimeout = TimeSpan.FromSeconds(5);
private CancellationTokenSource? _cts;
// Per-task cancellation, separate from _cts (the worker's whole-process lifetime token).
// Registered in ClaimAndExecuteAsync while a task is in flight, removed in its `finally` —
// lets a remote /hive/tasks/cancel request (see HiveNodeServer.CancelTaskHandler) interrupt
// ONE task's generation without stopping the worker or any other concurrently-running task.
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, CancellationTokenSource>
_activeTaskCancellations = new();
private Task? _runLoopTask;
private Task? _shutdownTask;
private int _disposeState;
Expand Down Expand Up @@ -127,6 +133,21 @@ public void Stop()
_cts = null;
}

/// <summary>
/// Cancels ONE in-flight task by id, surfacing as <see cref="OperationCanceledException"/>
/// inside that task's generation loop (via the per-task token created in
/// <see cref="ClaimAndExecuteAsync"/>) without affecting the worker's poll loop or any other
/// concurrently-running task. Returns false if no task with this id is currently tracked
/// (already finished, never claimed by this worker, or a stale/unknown id) — the caller
/// (<see cref="HiveNodeServer"/>'s cancel endpoint) reports that as "not found", not an error.
/// </summary>
public bool TryCancelTask(string taskId)
{
if (!_activeTaskCancellations.TryGetValue(taskId, out var cts)) return false;
try { cts.Cancel(); } catch (ObjectDisposedException) { return false; }
return true;
}

// ── Main polling loop ─────────────────────────────────────────────────────

private async Task RunLoopAsync(CancellationToken ct)
Expand Down Expand Up @@ -429,13 +450,24 @@ private async Task ClaimAndExecuteAsync(HiveTaskBundle bundle, CancellationToken
using var heartbeatCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var heartbeatTask = HeartbeatLoopAsync(bundle, claimToken ?? "", heartbeatCts.Token);

// Separate linked token for the task ITSELF, distinct from heartbeatCts above (that one
// stops HEARTBEATING once execution ends; this one, cancelled independently by
// TryCancelTask via a remote /hive/tasks/cancel request, interrupts the GENERATION).
// Registered here rather than earlier because a task without a claim token was never
// really "this worker's" to cancel.
using var taskCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_activeTaskCancellations[bundle.TaskId] = taskCts;

try
{
result = await ExecuteTaskAsync(bundle, ct).ConfigureAwait(false);
result = await ExecuteTaskAsync(bundle, taskCts.Token).ConfigureAwait(false);
}
// Same distinction as RunLoopAsync: an HTTP-timeout TaskCanceledException is a task
// failure to report back to the Warchief, not a worker shutdown — rethrowing it would
// orphan the lease with no fail result posted.
// orphan the lease with no fail result posted. A remote per-task cancel (taskCts tripped,
// ct itself still live) falls through to the generic handler below instead, exactly like
// any other execution failure — the plan's own "cancellation surfaces mid-generation as
// an OperationCanceledException, task fails visibly" requirement, not a worker shutdown.
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception ex)
{
Expand All @@ -457,6 +489,7 @@ private async Task ClaimAndExecuteAsync(HiveTaskBundle bundle, CancellationToken
{
heartbeatCts.Cancel();
try { await heartbeatTask.ConfigureAwait(false); } catch { }
_activeTaskCancellations.TryRemove(bundle.TaskId, out _);
}

var taskResult = new HiveTaskResult
Expand Down
Loading
Loading