Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
332 changes: 296 additions & 36 deletions src/Octopus.App/Collab/CollabCoordinator.cs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/Octopus.App/Collab/Ledger/CollabBatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ public sealed class CollabBatchRecord
public string? TriggeredReason { get; set; }
/// <summary>The one aggregate wake delivery id; recorded so a retry, reseal or restart never sends a second one.</summary>
public string? WakeDeliveryId { get; set; }
/// <summary>The last recorded aggregate wake outcome: delivered, queued_for_idle, failed, skipped, ambiguous when acceptance is unconfirmed, or null while unknown.</summary>
public string? WakeDeliveryState { get; set; }

/// <summary>The caller's idempotency keys, scoped to the opening session and the tool that used them.</summary>
public string? OpenKey { get; init; }
Expand Down
169 changes: 135 additions & 34 deletions src/Octopus.App/Collab/Ledger/CollabLedger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ internal sealed class CollabLedger : IDisposable
private readonly Dictionary<(string Caller, string Tool, string Key), string> _idempotency = new();
/// <summary>Delivery id → the durable report event that reserved it. Held from reservation through projection.</summary>
private readonly Dictionary<string, string> _deliveryClaimByEvent = new(StringComparer.Ordinal);
private HashSet<string> _persistedBatchIds = new(StringComparer.Ordinal);

/// <summary>
/// Raised under <see cref="Gate"/> when a task enters a terminal state. Handlers must not re-enter the ledger; the
Expand Down Expand Up @@ -2145,15 +2146,89 @@ public void SchedulePersist()
}

/// <summary>Writes dirty state synchronously. Returns false when the store rejected the write.</summary>
public bool Flush() => FlushCore(isDisposing: false);
public bool Flush() => FlushCore(isDisposing: false, requiredBatchId: null);

private bool FlushCore(bool isDisposing)
/// <summary>
/// Writes dirty state synchronously only if <paramref name="batchId"/> is included in the candidate snapshot.
/// Returns false without overwriting the previously persisted store document if retention would omit it or the store rejects the write.
/// </summary>
public bool FlushBatch(string batchId) => FlushCore(isDisposing: false, requiredBatchId: batchId);

/// <summary>
/// Atomically stages a batch transition under <see cref="Gate"/> while holding <see cref="_persistGate"/> so no
/// concurrent or background flush can observe or persist the staged transition (or a coupled keyed-report dispatch
/// marker) before it either saves with <paramref name="batchId"/> included in the snapshot or rolls back under
/// <see cref="Gate"/>. Slow JSON serialization and store I/O run outside <see cref="Gate"/>.
/// </summary>
public bool TryCommitBatchTransition(
string batchId,
Func<bool> stageLocked,
Action rollbackLocked,
Action? onCommittedLocked,
out bool staged)
{
staged = false;
lock (_persistGate)
{
CollabLedgerDocument doc;
long snapshotVersion;
HashSet<string> snapshotBatchIds;
lock (Gate)
{
if (!stageLocked()) return true;
staged = true;

if (_store is null)
{
onCommittedLocked?.Invoke();
return true;
}
if (_disposed || _preserveStoreDocument)
{
rollbackLocked();
return false;
}

snapshotVersion = _dirtyVersion;
PruneInMemoryIfOversizedLocked();
doc = ToDocument();
snapshotBatchIds = doc.Batches.Select(b => b.BatchId).ToHashSet(StringComparer.Ordinal);
if (!snapshotBatchIds.Contains(batchId))
{
rollbackLocked();
return false;
}
}

// Serialize and save outside Gate so concurrent collab operations never stall behind I/O,
// while _persistGate prevents any other flush from capturing the staged transition before commit or rollback.
var json = JsonSerializer.Serialize(doc, Json.CollabLedgerDocument);
var saved = _store.Save(json);

lock (Gate)
{
if (saved)
{
RecordPersistSuccessLocked(snapshotVersion, snapshotBatchIds);
onCommittedLocked?.Invoke();
return true;
}

rollbackLocked();
RecordPersistFailureLocked(snapshotVersion, isDisposing: false);
return false;
}
}
}

private bool FlushCore(bool isDisposing, string? requiredBatchId = null)
{
if (_store is null) return true;
lock (_persistGate)
{
CollabLedgerDocument doc;
long snapshotVersion;
HashSet<string> snapshotBatchIds;
lock (Gate)
{
if (_disposed && !isDisposing) return false;
Expand All @@ -2163,11 +2238,16 @@ private bool FlushCore(bool isDisposing)
_consecutivePersistFailures = 0;
_failedRetryVersion = 0;
if (!_disposed) _persistTimer?.Change(Timeout.Infinite, Timeout.Infinite);
return true;
return requiredBatchId is null || _persistedBatchIds.Contains(requiredBatchId);
}
snapshotVersion = _dirtyVersion;
PruneInMemoryIfOversizedLocked();
doc = ToDocument();
snapshotBatchIds = doc.Batches.Select(b => b.BatchId).ToHashSet(StringComparer.Ordinal);
if (requiredBatchId is not null && !snapshotBatchIds.Contains(requiredBatchId))
{
return false;
}
}

// Serialize outside Gate so concurrent collab operations never stall behind multi-megabyte JSON formatting.
Expand All @@ -2178,45 +2258,56 @@ private bool FlushCore(bool isDisposing)
{
if (saved)
{
if (snapshotVersion > _persistedVersion) _persistedVersion = snapshotVersion;
_consecutivePersistFailures = 0;
_failedRetryVersion = 0;
if (!_disposed && _dirtyVersion <= _persistedVersion)
{
_persistTimer?.Change(Timeout.Infinite, Timeout.Infinite);
}
RecordPersistSuccessLocked(snapshotVersion, snapshotBatchIds);
}
else
{
if (_dirtyVersion > snapshotVersion)
{
_consecutivePersistFailures = 0;
_failedRetryVersion = snapshotVersion;
if (!_disposed && !isDisposing) ArmTimerLocked(PersistDebounceMs);
}
else
{
if (snapshotVersion > _failedRetryVersion)
{
_consecutivePersistFailures = 1;
_failedRetryVersion = snapshotVersion;
}
else
{
_consecutivePersistFailures++;
}
if (!_disposed && !isDisposing && _consecutivePersistFailures <= MaxPersistRetries)
{
ArmTimerLocked(ComputeRetryDelayMs(_consecutivePersistFailures));
}
}
RecordPersistFailureLocked(snapshotVersion, isDisposing);
}
}

return saved;
}
}

private void RecordPersistSuccessLocked(long snapshotVersion, HashSet<string> snapshotBatchIds)
{
if (snapshotVersion > _persistedVersion) _persistedVersion = snapshotVersion;
_persistedBatchIds = snapshotBatchIds;
_consecutivePersistFailures = 0;
_failedRetryVersion = 0;
if (!_disposed && _dirtyVersion <= _persistedVersion)
{
_persistTimer?.Change(Timeout.Infinite, Timeout.Infinite);
}
}

private void RecordPersistFailureLocked(long snapshotVersion, bool isDisposing)
{
if (_dirtyVersion > snapshotVersion)
{
_consecutivePersistFailures = 0;
_failedRetryVersion = snapshotVersion;
if (!_disposed && !isDisposing) ArmTimerLocked(PersistDebounceMs);
}
else
{
if (snapshotVersion > _failedRetryVersion)
{
_consecutivePersistFailures = 1;
_failedRetryVersion = snapshotVersion;
}
else
{
_consecutivePersistFailures++;
}
if (!_disposed && !isDisposing && _consecutivePersistFailures <= MaxPersistRetries)
{
ArmTimerLocked(ComputeRetryDelayMs(_consecutivePersistFailures));
}
}
}

private void ArmTimerLocked(int dueTimeMs)
{
_persistTimer ??= new Timer(_ => FlushCore(isDisposing: false), null, Timeout.Infinite, Timeout.Infinite);
Expand Down Expand Up @@ -2301,6 +2392,7 @@ public void Restore()
try
{
FromDocument(doc, maxEventSeq);
_persistedBatchIds = Batches.Keys.ToHashSet(StringComparer.Ordinal);
}
finally
{
Expand Down Expand Up @@ -2460,6 +2552,7 @@ private static bool HasSafeBatchValues(JsonElement batches)
|| !IsOptionalBoolean(batch, "triggered")
|| !IsOptionalString(batch, "triggered_reason", allowNull: true)
|| !IsOptionalString(batch, "wake_delivery_id", allowNull: true)
|| !IsOptionalEnumValue(batch, "wake_delivery_state", BatchWakeDeliveryStateKeys)
|| !IsOptionalString(batch, "open_key", allowNull: true)
|| !IsOptionalString(batch, "seal_key", allowNull: true)
|| !IsOptionalStringArray(batch, "notified_exceptions")
Expand Down Expand Up @@ -2660,7 +2753,7 @@ private static bool HasOnly(JsonElement value, HashSet<string> known)
"batch_id", "caller", "title", "join_policy", "wake_policy", "state", "milestone_count",
"milestone_ratio", "milestone_tasks", "milestone_stage", "exceptional_rules", "members",
"expected_member_count", "created", "sealed", "settled", "triggered", "triggered_reason",
"wake_delivery_id", "open_key", "seal_key", "notified_exceptions", "seq",
"wake_delivery_id", "wake_delivery_state", "open_key", "seal_key", "notified_exceptions", "seq",
];

private static readonly HashSet<string> BatchMemberFields =
Expand All @@ -2676,6 +2769,7 @@ private static bool HasOnly(JsonElement value, HashSet<string> known)

private static readonly HashSet<string> BatchJoinPolicyKeys = ["all", "any", "milestone", "manual"];
private static readonly HashSet<string> BatchWakePolicyKeys = ["idle_only", "immediate", "none"];
private static readonly HashSet<string> BatchWakeDeliveryStateKeys = ["delivered", "queued_for_idle", "failed", "skipped", "ambiguous"];
private static readonly HashSet<string> BatchStateKeys = ["open", "sealed", "paused", "settled", "cancelled"];
private static readonly HashSet<string> BatchExceptionKindKeys =
["error", "timeout", "process_exit", "approval_required", "disconnect", "retries_exhausted"];
Expand Down Expand Up @@ -2890,9 +2984,14 @@ private CollabLedgerDocument ToDocument()
})],
Batches = [.. Batches.Values.Where(b => !b.IsFinished)
.Concat(Batches.Values.Where(b => b.IsFinished)
.OrderByDescending(b => b.CreatedAt)
.OrderByDescending(b => b.UpdatedSeq)
.ThenByDescending(b => b.SettledAt ?? b.CreatedAt)
.ThenByDescending(b => b.CreatedAt)
.ThenByDescending(b => b.BatchId, StringComparer.Ordinal)
.Take(MaxPersistedFinishedBatches))
.OrderBy(b => b.CreatedAt)
.ThenBy(b => b.UpdatedSeq)
.ThenBy(b => b.BatchId, StringComparer.Ordinal)
.Select(b => new CollabBatchDocument
{
BatchId = b.BatchId,
Expand Down Expand Up @@ -2929,6 +3028,7 @@ private CollabLedgerDocument ToDocument()
Triggered = b.Triggered,
TriggeredReason = b.TriggeredReason,
WakeDeliveryId = b.WakeDeliveryId,
WakeDeliveryState = b.WakeDeliveryState,
OpenKey = b.OpenKey,
SealKey = b.SealKey,
NotifiedExceptions = [.. b.NotifiedExceptions],
Expand Down Expand Up @@ -3147,6 +3247,7 @@ private void FromDocument(CollabLedgerDocument doc, long maxEventSeq)
Triggered = b.Triggered,
TriggeredReason = b.TriggeredReason,
WakeDeliveryId = b.WakeDeliveryId,
WakeDeliveryState = b.WakeDeliveryState,
OpenKey = b.OpenKey,
SealKey = b.SealKey,
NotifiedExceptions = [.. b.NotifiedExceptions ?? []],
Expand Down
2 changes: 2 additions & 0 deletions src/Octopus.App/Collab/Ledger/CollabLedgerDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ internal sealed class CollabBatchDocument
[JsonPropertyName("triggered")] public bool Triggered { get; set; }
[JsonPropertyName("triggered_reason")] public string? TriggeredReason { get; set; }
[JsonPropertyName("wake_delivery_id")] public string? WakeDeliveryId { get; set; }
/// <summary><c>delivered</c>, <c>queued_for_idle</c>, <c>failed</c>, <c>skipped</c>, or <c>ambiguous</c>; omitted by older documents.</summary>
[JsonPropertyName("wake_delivery_state")] public string? WakeDeliveryState { get; set; }
[JsonPropertyName("open_key")] public string? OpenKey { get; set; }
[JsonPropertyName("seal_key")] public string? SealKey { get; set; }
[JsonPropertyName("notified_exceptions")] public List<string> NotifiedExceptions { get; set; } = [];
Expand Down
50 changes: 47 additions & 3 deletions src/Octopus.App/Collab/Tools/BatchTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ public sealed class BatchOpenTool : ICollabTool

public string Description =>
"Open an opt-in batch owned by you before delegating several tasks. Tasks join it with delegate_task(batch_id=...), and "
+ "batch_seal freezes the membership. With wake_policy 'idle_only' (the only supported policy in this build) your delegates' "
+ "batch_seal freezes the membership. Join policies: 'all' settles when every member is terminal; 'any' settles on the first "
+ "valid explicit report; 'milestone' settles at a configured count, ratio, member or stage; 'manual' never wakes you itself, "
+ "and batch_resume collects it. With wake_policy 'idle_only' (the only supported policy in this build) your delegates' "
+ "explicit reports are recorded without waking you while the batch is open or below its threshold; when it settles you get "
+ "exactly one aggregate wake, queued until your current turn ends. This batch only affects its own members; legacy "
+ "delegate_task calls keep their behavior.";
Expand All @@ -23,9 +25,10 @@ public sealed class BatchOpenTool : ICollabTool
["join_policy"] = new JsonObject
{
["type"] = "string",
["enum"] = new JsonArray("all", "any", "milestone"),
["enum"] = new JsonArray("all", "any", "milestone", "manual"),
["description"] = "'all': settle once every member reaches a terminal state. 'any': settle on the first explicit report. "
+ "'milestone': settle when any configured count, ratio, named member or stage criterion is reached.",
+ "'milestone': settle when any configured count, ratio, named member or stage criterion is reached. "
+ "'manual': stay silent until batch_resume.",
},
["milestone_count"] = new JsonObject
{
Expand Down Expand Up @@ -113,6 +116,47 @@ public Task<JsonObject> CallAsync(ICollabOperations ops, string callerItemId, Co
}
}

/// <summary>MCP tool <c>batch_resume</c>: collects a manual batch, or resumes one paused for human action.</summary>
public sealed class BatchResumeTool : ICollabTool
{
public string Name => "batch_resume";

public string Description =>
"Collect a sealed batch you own that is waiting for a human ('manual'), or resume one paused by an exceptional rule. "
+ "A manual batch never wakes you on its own reports, failures, aborts or cancellations; this call sends its single "
+ "aggregate wake with the results collected so far. Resuming an already settled manual batch returns the original result "
+ "with deduplicated: true and never sends a second wake; batches that settle automatically refuse this call unless currently paused.";

public JsonObject InputSchema => new()
{
["type"] = "object",
["required"] = new JsonArray("batch_id"),
["properties"] = new JsonObject
{
["batch_id"] = new JsonObject { ["type"] = "string", ["description"] = "The batch id returned by batch_open." },
["note"] = new JsonObject
{
["type"] = "string",
["description"] = "Optional note included in the aggregate wake, for example what the human decided.",
},
},
};

public Task<JsonObject> CallAsync(ICollabOperations ops, string callerItemId, CollabToolArgs args, CancellationToken ct)
{
var batchId = args.PresentString("batch_id", out _, out var batchIdMalformed);
if (batchIdMalformed)
{
return Task.FromResult(CollabToolResult.Error("'batch_id' must be a string when present."));
}
if (!BatchToolArgs.TryOptionalString(args, "note", out var note, out var noteError))
{
return Task.FromResult(CollabToolResult.Error(noteError!));
}
return ops.BatchResumeAsync(callerItemId, batchId ?? "", note, ct);
}
}

/// <summary>MCP tool <c>batch_seal</c>: freezes an open batch and reports whether it settled.</summary>
public sealed class BatchSealTool : ICollabTool
{
Expand Down
5 changes: 4 additions & 1 deletion src/Octopus.App/Collab/Tools/CollabToolContracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ public interface ICollabOperations
Task<JsonObject> BatchOpenAsync(string callerItemId, CollabBatchOpenRequest request, CancellationToken ct);
/// <summary>Freezes an open batch's membership, persists the seal, and sends its one settlement wake if already met.</summary>
Task<JsonObject> BatchSealAsync(string callerItemId, string batchId, int? expectedCount, string? idempotencyKey, CancellationToken ct);
/// <summary>Collects a sealed manual batch, or resumes one paused for human action, with one settle wake.</summary>
Task<JsonObject> BatchResumeAsync(string callerItemId, string batchId, string? note, CancellationToken ct);
/// <summary>Read-only report of the orchestration guarantees this bus provides (one boolean, pinned by tests).</summary>
JsonObject DescribeCapabilities();
}
Expand All @@ -51,7 +53,7 @@ public interface ICollabOperations
public sealed record CollabBatchOpenRequest
{
public string? Title { get; init; }
/// <summary><c>all</c>, <c>any</c> or <c>milestone</c>; <c>manual</c> is reserved and rejected by this build.</summary>
/// <summary><c>all</c>, <c>any</c>, <c>milestone</c> or <c>manual</c>.</summary>
public string JoinPolicy { get; init; } = "all";
/// <summary>Only <c>idle_only</c> is accepted by this build; other policies are rejected.</summary>
public string WakePolicy { get; init; } = "idle_only";
Expand Down Expand Up @@ -346,6 +348,7 @@ public CollabToolRegistry(IEnumerable<ICollabTool> tools)
new CancelTaskTool(),
new BatchOpenTool(),
new BatchSealTool(),
new BatchResumeTool(),
new OrchestratorCapabilitiesTool(),
];

Expand Down
Loading
Loading