From a84ae6e199f1755d28e52425dc08c9de20ecfa97 Mon Sep 17 00:00:00 2001 From: SHI ZHENWEI Date: Tue, 1 Dec 2026 19:17:24 +0900 Subject: [PATCH 1/2] feat(collab): add manual batch policy and batch_resume Compose the corrected third manual/resume slice by replaying c2915e2fd59c1787ef467f09ef5e18452d8f0886..5871c8e78d84db1968f3b8cec5a12078d2056e7f (a9d627f59ca1b2e26c70f2a6115af730ff2634d9 plus manual HOLD fixes 5871c8e78d84db1968f3b8cec5a12078d2056e7f) onto accepted threshold base 8e4c75fce8fedf80b8a43efb08423b98813a85df. Includes: - join_policy "manual" and MCP tool batch_resume (with optional note) - Truthful overlapped resume receipts and in-flight wake ownership tracking - Consumed deferred-wake outcome preservation and ambiguous wake classification - Durable batch wake delivery state/error ledger persistence and validation - Automatic all/any/milestone refusal of batch_resume even after settlement (unless currently paused), with aligned BatchResumeTool contract wording - Finished-batch retention ordered by UpdatedSeq then SettledAt/CreatedAt within the 200-batch cap, plus truthful FlushBatch verification on settlement - Manual/resume, wake, ledger, and tool-registry regression coverage Preserves the threshold retained-report fix (8e4c75fc), ordinary batch same-key/receipt fixes (9bb6059d), #153 cursor and structured replies, and #156 GUI peer status. Excludes later exception policies, immediate/none wake policies, deadline, lease, quota, dependency, and launch permission work. --- src/Octopus.App/Collab/CollabCoordinator.cs | 276 +++++- src/Octopus.App/Collab/Ledger/CollabBatch.cs | 2 + src/Octopus.App/Collab/Ledger/CollabLedger.cs | 32 +- .../Collab/Ledger/CollabLedgerDocument.cs | 2 + src/Octopus.App/Collab/Tools/BatchTools.cs | 50 +- .../Collab/Tools/CollabToolContracts.cs | 5 +- src/Octopus.Remote/Protocol/CollabEnvelope.cs | 4 +- .../CollabBatchLedgerTests.cs | 211 +++++ .../CollabBatchManualTests.cs | 806 ++++++++++++++++++ .../Octopus.App.Tests/CollabBatchWakeTests.cs | 208 ++++- tests/Octopus.App.Tests/CollabTests.cs | 2 +- 11 files changed, 1561 insertions(+), 37 deletions(-) create mode 100644 tests/Octopus.App.Tests/CollabBatchManualTests.cs diff --git a/src/Octopus.App/Collab/CollabCoordinator.cs b/src/Octopus.App/Collab/CollabCoordinator.cs index d2c83adb..45af4a15 100644 --- a/src/Octopus.App/Collab/CollabCoordinator.cs +++ b/src/Octopus.App/Collab/CollabCoordinator.cs @@ -4059,6 +4059,7 @@ private void CancelStaleWakeupsForPeer(string callerItemId, string peerItemId) null or "" or "all" => CollabBatchJoinPolicy.All, "any" => CollabBatchJoinPolicy.Any, "milestone" => CollabBatchJoinPolicy.Milestone, + "manual" => CollabBatchJoinPolicy.Manual, _ => null, }; @@ -4082,7 +4083,7 @@ public async Task BatchOpenAsync(string callerItemId, CollabBatchOpe var joinPolicy = ParseBatchJoinPolicy(request.JoinPolicy); if (joinPolicy is null) { - return ToolError("join_policy must be \"all\", \"any\" or \"milestone\"; \"manual\" is not implemented in this build."); + return ToolError("join_policy must be \"all\", \"any\", \"milestone\", or \"manual\"."); } var milestoneTasks = request.MilestoneTasks.Select(t => t.Trim()).Where(t => t.Length > 0).Distinct(StringComparer.Ordinal).ToList(); var milestoneStage = string.IsNullOrWhiteSpace(request.MilestoneStage) ? null : request.MilestoneStage.Trim(); @@ -4283,6 +4284,140 @@ public async Task BatchSealAsync( return ToolOk(payload); } + public async Task BatchResumeAsync(string callerItemId, string batchId, string? note, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(batchId)) + { + return ToolError("batch_id is required."); + } + + CollabBatchRecord batch; + var resumedPause = false; + using (await AcquireBatchOperationGateAsync(callerItemId, batchId, ct).ConfigureAwait(false)) + { + lock (_ledger.Gate) + { + if (_ledger.FindBatch(batchId) is not { } found + || !string.Equals(found.CallerItemId, callerItemId, StringComparison.Ordinal)) + { + return ToolError($"Unknown batch '{batchId}'."); + } + batch = found; + + if (batch.State == CollabBatchState.Paused && !batch.Triggered) + { + _ledger.SetBatchState(batch, CollabBatchState.Sealed); + resumedPause = true; + } + else if (batch.JoinPolicy != CollabBatchJoinPolicy.Manual) + { + return ToolError( + $"Batch '{batchId}' settles automatically under join_policy '{batch.JoinPolicy.ToKey()}'; batch_resume is for manual or paused batches."); + } + else if (batch.Triggered || batch.State == CollabBatchState.Settled) + { + var evaluation = _ledger.EvaluateBatch(batch); + var settledReceipt = CaptureBatchWakeReceipt(batch); + var existingWakeState = settledReceipt.WakeDeliveryState; + var existingWakeInFlight = existingWakeState is null && settledReceipt.WakeAttemptInFlight; + var already = BatchResumePayload(batch.BatchId, settledReceipt, evaluation, deduplicated: true, delivered: existingWakeState == "delivered"); + already["delivery"] = existingWakeState ?? (existingWakeInFlight ? "in_flight" : "unknown"); + already["note"] = BatchSettledWakeNote(existingWakeState, existingWakeInFlight); + return ToolOk(already); + } + else if (batch.State == CollabBatchState.Open) + { + return ToolError($"Batch '{batchId}' is still open; seal it before resuming."); + } + else if (batch.State != CollabBatchState.Sealed) + { + return ToolError($"Batch '{batchId}' is {batch.State.ToKey()}; only a sealed manual batch or a paused batch can be resumed."); + } + } + + if (resumedPause && !_ledger.Flush()) + { + lock (_ledger.Gate) { _ledger.SetBatchState(batch, CollabBatchState.Paused); } + return ToolError($"Could not save the resume of batch '{batchId}'; it is still paused."); + } + } + + var settlement = await TrySettleBatchAsync( + batch, + durableReportEventId: null, + ct: ct, + force: batch.JoinPolicy == CollabBatchJoinPolicy.Manual, + forcedReason: "manual_resume", + wakeNote: note).ConfigureAwait(false); + if (settlement.SaveFailed) + { + var retryTool = batch.JoinPolicy == CollabBatchJoinPolicy.Manual ? "batch_resume" : "batch_seal"; + return ToolError( + $"The settlement of batch '{batchId}' could not be saved; no wake was sent. Retry {retryTool} after storage recovers."); + } + var nonOwningOverlap = settlement.Triggered && !settlement.WakeAttemptedByThisCall; + var receipt = CaptureBatchWakeReceipt(batch); + var wakeState = receipt.WakeDeliveryState; + var wakeInFlight = wakeState is null && receipt.WakeAttemptInFlight; + var payload = BatchResumePayload( + batch.BatchId, + receipt, + settlement.Evaluation, + deduplicated: nonOwningOverlap, + delivered: nonOwningOverlap ? wakeState == "delivered" : settlement.Delivered); + payload["delivery"] = !settlement.Triggered ? "still_running" + : nonOwningOverlap ? wakeState ?? (wakeInFlight ? "in_flight" : "unknown") + : settlement.Delivered ? "delivered" + : settlement.Deferred ? "queued_for_idle" + : batch.WakePolicy == CollabBatchWakePolicy.IdleOnly ? "failed" + : "skipped"; + if (nonOwningOverlap) + { + payload["note"] = BatchSettledWakeNote(wakeState, wakeInFlight); + } + else if (settlement.Deferred) + { + payload["note"] = "The single aggregate wake is queued and will be sent when the owner's terminal is idle."; + } + return ToolOk(payload); + } + + private static string BatchSettledWakeNote(string? wakeState, bool wakeInFlight) => wakeState switch + { + "delivered" => "This batch already settled and its one wake was delivered; no new wake was sent.", + "failed" => "This batch already settled but its one wake was not accepted; it was not resent. Read the member threads or use await_events.", + "queued_for_idle" => "This batch already settled and its one wake was recorded as queued for the owner's idle turn; no new wake was sent.", + "skipped" => "This batch already settled without a wake by policy; no new wake was sent.", + "ambiguous" => "This batch already settled, but its one wake outcome is unconfirmed; it was not resent. Read the member threads or use await_events.", + _ => wakeInFlight + ? "The single aggregate wake is still in flight under another overlapping batch operation; no new wake was sent." + : "This batch already settled; its wake outcome is unknown and it was not resent.", + }; + + private static JsonObject BatchResumePayload( + string batchId, + BatchWakeReceipt receipt, + BatchEvaluation evaluation, + bool deduplicated, + bool delivered) + { + return new JsonObject + { + ["batch_id"] = batchId, + ["state"] = receipt.Triggered ? "settled" : receipt.State.ToKey(), + ["expected_count"] = evaluation.Expected, + ["settled_count"] = evaluation.Settled, + ["failed_count"] = evaluation.Failed, + ["running_count"] = evaluation.Running, + ["queued_count"] = evaluation.Queued, + ["triggered"] = receipt.Triggered, + ["wake_delivery"] = receipt.Triggered ? receipt.WakeDeliveryId : null, + ["wake_delivery_state"] = receipt.WakeDeliveryState, + ["wake_delivered"] = delivered, + ["deduplicated"] = deduplicated, + }; + } + private static JsonObject BatchSealPayload(CollabBatchRecord batch, BatchEvaluation evaluation, bool deduplicated) { var payload = new JsonObject @@ -4296,6 +4431,7 @@ private static JsonObject BatchSealPayload(CollabBatchRecord batch, BatchEvaluat ["queued_count"] = evaluation.Queued, ["triggered"] = batch.Triggered, ["wake_delivery"] = batch.WakeDeliveryId, + ["wake_delivery_state"] = batch.WakeDeliveryState, ["deduplicated"] = deduplicated, }; if (deduplicated) @@ -4305,6 +4441,13 @@ private static JsonObject BatchSealPayload(CollabBatchRecord batch, BatchEvaluat return payload; } + private sealed record BatchWakeReceipt( + CollabBatchState State, + bool Triggered, + string? WakeDeliveryId, + string? WakeDeliveryState, + bool WakeAttemptInFlight); + private sealed record BatchSettlementResult( bool Triggered, bool Delivered, @@ -4325,6 +4468,7 @@ private sealed record DeferredBatchWake( private readonly object _deferredBatchWakeGate = new(); private readonly Dictionary _deferredBatchWakes = new(StringComparer.Ordinal); + private readonly HashSet _batchWakeAttemptsInFlight = new(StringComparer.Ordinal); /// /// Evaluates a batch and, when its policy is met for the first time, persists the one-shot latch and sends the single @@ -4336,18 +4480,23 @@ private sealed record DeferredBatchWake( private async Task TrySettleBatchAsync( CollabBatchRecord batch, string? durableReportEventId, - CancellationToken ct) + CancellationToken ct, + bool force = false, + string? forcedReason = null, + string? wakeNote = null) { BatchEvaluation evaluation; string? wakeDeliveryId = null; string? reportEventStateBeforeDispatch = null; var reportEventMarkedDispatching = false; + var sendWake = false; + var wakeAttemptInFlight = false; using (await AcquireBatchOperationGateAsync(batch.CallerItemId, batch.BatchId, ct).ConfigureAwait(false)) { lock (_ledger.Gate) { evaluation = _ledger.EvaluateBatch(batch); - if (batch.Triggered || !evaluation.ShouldTrigger) + if (batch.Triggered || (!force && !evaluation.ShouldTrigger)) { return new BatchSettlementResult(batch.Triggered, false, false, false, batch.WakeDeliveryId, evaluation, false); } @@ -4360,12 +4509,15 @@ private async Task TrySettleBatchAsync( { return new BatchSettlementResult(false, false, false, true, null, evaluation with { ShouldTrigger = true }, false); } - wakeDeliveryId = _ledger.NextId("bwake"); + var reason = force ? forcedReason ?? "manual_resume" : evaluation.Reason; + evaluation = evaluation with { ShouldTrigger = true, Reason = reason }; + sendWake = batch.WakePolicy == CollabBatchWakePolicy.IdleOnly; + wakeDeliveryId = sendWake ? _ledger.NextId("bwake") : null; batch.WakeDeliveryId = wakeDeliveryId; - _ledger.MarkBatchTriggered(batch, evaluation.Reason); + _ledger.MarkBatchTriggered(batch, reason); } - if (!_ledger.Flush()) + if (!_ledger.FlushBatch(batch.BatchId)) { lock (_ledger.Gate) { @@ -4382,18 +4534,81 @@ private async Task TrySettleBatchAsync( } return new BatchSettlementResult(false, false, false, true, null, evaluation with { ShouldTrigger = true }, false); } + if (sendWake) + { + lock (_ledger.Gate) _batchWakeAttemptsInFlight.Add(batch.BatchId); + wakeAttemptInFlight = true; + } + } + + try + { + RaiseChangedForItems(CollabChangeKind.Topology, batch.CallerItemId); + if (!sendWake) + { + SetBatchWakeState(batch, "skipped"); + return new BatchSettlementResult(true, false, false, false, null, evaluation, true); + } + var delivery = await DeliverBatchSettlementAsync(batch, evaluation, wakeDeliveryId!, ct, wakeNote).ConfigureAwait(false); + SetBatchWakeState(batch, delivery.Delivered ? "delivered" : delivery.Deferred ? "queued_for_idle" : "failed"); + return new BatchSettlementResult(true, delivery.Delivered, delivery.Deferred, false, wakeDeliveryId, evaluation, true); + } + finally + { + if (wakeAttemptInFlight) + { + lock (_ledger.Gate) _batchWakeAttemptsInFlight.Remove(batch.BatchId); + } + } + } + + private BatchWakeReceipt CaptureBatchWakeReceipt(CollabBatchRecord batch) + { + lock (_ledger.Gate) + { + return new BatchWakeReceipt( + batch.State, + batch.Triggered, + batch.WakeDeliveryId, + batch.WakeDeliveryState, + _batchWakeAttemptsInFlight.Contains(batch.BatchId)); + } + } + + private static bool IsTerminalBatchWakeState(string? state) => + state is "delivered" or "failed" or "skipped" or "ambiguous"; + + /// Remembers what became of the one aggregate wake, so a later resume or reseal reports it truthfully. + private void SetBatchWakeState(CollabBatchRecord batch, string state) + { + lock (_ledger.Gate) + { + if (state == "queued_for_idle" && IsTerminalBatchWakeState(batch.WakeDeliveryState)) return; + batch.WakeDeliveryState = state; + _ledger.Touch(batch); } + _ledger.Flush(); + } - RaiseChangedForItems(CollabChangeKind.Topology, batch.CallerItemId); - var delivery = await DeliverBatchSettlementAsync(batch, evaluation, wakeDeliveryId, ct).ConfigureAwait(false); - return new BatchSettlementResult(true, delivery.Delivered, delivery.Deferred, false, wakeDeliveryId, evaluation, true); + /// Updates the owning batch when a deferred aggregate is finally accepted, declined or requeued. + private void UpdateBatchWakeState(string wakeDeliveryId, string state) + { + if (string.IsNullOrWhiteSpace(wakeDeliveryId)) return; + CollabBatchRecord? owner; + lock (_ledger.Gate) + { + owner = _ledger.Batches.Values.FirstOrDefault(b => + string.Equals(b.WakeDeliveryId, wakeDeliveryId, StringComparison.Ordinal)); + } + if (owner is not null) SetBatchWakeState(owner, state); } private async Task DeliverBatchSettlementAsync( CollabBatchRecord batch, BatchEvaluation evaluation, string wakeDeliveryId, - CancellationToken ct) + CancellationToken ct, + string? note = null) { string title; string joinPolicy; @@ -4429,7 +4644,8 @@ task is not null m.SessionId, m.Status, m.Tentative, - m.Result))]); + m.Result))], + note); if (TryDeferBatchWake(batch.CallerItemId, wakeDeliveryId, envelope)) { return new BatchDeliveryResult(false, true); @@ -7106,6 +7322,7 @@ private async Task DeliverDeferredBatchWakeAsync(DeferredBatchWake wake) || current.Generation != wake.Generation || !current.IsRunning) { + UpdateBatchWakeState(wake.WakeDeliveryId, "failed"); return; } if (_activity?.Of(wake.TargetItemId) is ItemActivity.Working or ItemActivity.Waiting) @@ -7113,18 +7330,27 @@ private async Task DeliverDeferredBatchWakeAsync(DeferredBatchWake wake) RequeueDeferredBatchWake(wake); return; } - var delivered = await DeliverEnvelopeCoreAsync( - wake.TargetItemId, - wake.Envelope, - threadId: null, - taskId: null, - expectReply: false, - callerItemId: "", - wakeup: null, - reopenCompletedTask: false, - ct: CancellationToken.None, - reservedDeliveryId: wake.WakeDeliveryId, - requireIdle: true).ConfigureAwait(false); + bool delivered; + try + { + delivered = await DeliverEnvelopeCoreAsync( + wake.TargetItemId, + wake.Envelope, + threadId: null, + taskId: null, + expectReply: false, + callerItemId: "", + wakeup: null, + reopenCompletedTask: false, + ct: CancellationToken.None, + reservedDeliveryId: wake.WakeDeliveryId, + requireIdle: true).ConfigureAwait(false); + } + catch + { + UpdateBatchWakeState(wake.WakeDeliveryId, "ambiguous"); + return; + } if (!delivered) { var after = _terminalSessions?.Find(wake.TargetItemId); @@ -7135,8 +7361,12 @@ private async Task DeliverDeferredBatchWakeAsync(DeferredBatchWake wake) && _activity?.Of(wake.TargetItemId) is ItemActivity.Working or ItemActivity.Waiting) { RequeueDeferredBatchWake(wake); + return; } + UpdateBatchWakeState(wake.WakeDeliveryId, "failed"); + return; } + UpdateBatchWakeState(wake.WakeDeliveryId, "delivered"); } private void RequeueDeferredBatchWake(DeferredBatchWake wake) diff --git a/src/Octopus.App/Collab/Ledger/CollabBatch.cs b/src/Octopus.App/Collab/Ledger/CollabBatch.cs index 1a991862..b259052a 100644 --- a/src/Octopus.App/Collab/Ledger/CollabBatch.cs +++ b/src/Octopus.App/Collab/Ledger/CollabBatch.cs @@ -213,6 +213,8 @@ public sealed class CollabBatchRecord public string? TriggeredReason { get; set; } /// The one aggregate wake delivery id; recorded so a retry, reseal or restart never sends a second one. public string? WakeDeliveryId { get; set; } + /// The last recorded aggregate wake outcome: delivered, queued_for_idle, failed, skipped, ambiguous when acceptance is unconfirmed, or null while unknown. + public string? WakeDeliveryState { get; set; } /// The caller's idempotency keys, scoped to the opening session and the tool that used them. public string? OpenKey { get; init; } diff --git a/src/Octopus.App/Collab/Ledger/CollabLedger.cs b/src/Octopus.App/Collab/Ledger/CollabLedger.cs index 3035f472..74d38ab8 100644 --- a/src/Octopus.App/Collab/Ledger/CollabLedger.cs +++ b/src/Octopus.App/Collab/Ledger/CollabLedger.cs @@ -186,6 +186,7 @@ internal sealed class CollabLedger : IDisposable private readonly Dictionary<(string Caller, string Tool, string Key), string> _idempotency = new(); /// Delivery id → the durable report event that reserved it. Held from reservation through projection. private readonly Dictionary _deliveryClaimByEvent = new(StringComparer.Ordinal); + private HashSet _persistedBatchIds = new(StringComparer.Ordinal); /// /// Raised under when a task enters a terminal state. Handlers must not re-enter the ledger; the @@ -2145,15 +2146,22 @@ public void SchedulePersist() } /// Writes dirty state synchronously. Returns false when the store rejected the write. - public bool Flush() => FlushCore(isDisposing: false); + public bool Flush() => FlushCore(isDisposing: false, requiredBatchId: null); - private bool FlushCore(bool isDisposing) + /// + /// Writes dirty state synchronously and verifies that was included in the + /// persisted snapshot rather than evicted by finished-batch retention. + /// + public bool FlushBatch(string batchId) => FlushCore(isDisposing: false, requiredBatchId: batchId); + + private bool FlushCore(bool isDisposing, string? requiredBatchId = null) { if (_store is null) return true; lock (_persistGate) { CollabLedgerDocument doc; long snapshotVersion; + HashSet snapshotBatchIds; lock (Gate) { if (_disposed && !isDisposing) return false; @@ -2163,11 +2171,12 @@ 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); } // Serialize outside Gate so concurrent collab operations never stall behind multi-megabyte JSON formatting. @@ -2179,6 +2188,7 @@ private bool FlushCore(bool isDisposing) if (saved) { if (snapshotVersion > _persistedVersion) _persistedVersion = snapshotVersion; + _persistedBatchIds = snapshotBatchIds; _consecutivePersistFailures = 0; _failedRetryVersion = 0; if (!_disposed && _dirtyVersion <= _persistedVersion) @@ -2213,7 +2223,7 @@ private bool FlushCore(bool isDisposing) } } - return saved; + return saved && (requiredBatchId is null || snapshotBatchIds.Contains(requiredBatchId)); } } @@ -2301,6 +2311,7 @@ public void Restore() try { FromDocument(doc, maxEventSeq); + _persistedBatchIds = Batches.Keys.ToHashSet(StringComparer.Ordinal); } finally { @@ -2460,6 +2471,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") @@ -2660,7 +2672,7 @@ private static bool HasOnly(JsonElement value, HashSet 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 BatchMemberFields = @@ -2676,6 +2688,7 @@ private static bool HasOnly(JsonElement value, HashSet known) private static readonly HashSet BatchJoinPolicyKeys = ["all", "any", "milestone", "manual"]; private static readonly HashSet BatchWakePolicyKeys = ["idle_only", "immediate", "none"]; + private static readonly HashSet BatchWakeDeliveryStateKeys = ["delivered", "queued_for_idle", "failed", "skipped", "ambiguous"]; private static readonly HashSet BatchStateKeys = ["open", "sealed", "paused", "settled", "cancelled"]; private static readonly HashSet BatchExceptionKindKeys = ["error", "timeout", "process_exit", "approval_required", "disconnect", "retries_exhausted"]; @@ -2890,9 +2903,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, @@ -2929,6 +2947,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], @@ -3147,6 +3166,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 ?? []], diff --git a/src/Octopus.App/Collab/Ledger/CollabLedgerDocument.cs b/src/Octopus.App/Collab/Ledger/CollabLedgerDocument.cs index 2242ae56..e2d1a127 100644 --- a/src/Octopus.App/Collab/Ledger/CollabLedgerDocument.cs +++ b/src/Octopus.App/Collab/Ledger/CollabLedgerDocument.cs @@ -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; } + /// delivered, queued_for_idle, failed, skipped, or ambiguous; omitted by older documents. + [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 NotifiedExceptions { get; set; } = []; diff --git a/src/Octopus.App/Collab/Tools/BatchTools.cs b/src/Octopus.App/Collab/Tools/BatchTools.cs index 60166518..a2d460e7 100644 --- a/src/Octopus.App/Collab/Tools/BatchTools.cs +++ b/src/Octopus.App/Collab/Tools/BatchTools.cs @@ -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."; @@ -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 { @@ -113,6 +116,47 @@ public Task CallAsync(ICollabOperations ops, string callerItemId, Co } } +/// MCP tool batch_resume: collects a manual batch, or resumes one paused for human action. +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 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); + } +} + /// MCP tool batch_seal: freezes an open batch and reports whether it settled. public sealed class BatchSealTool : ICollabTool { diff --git a/src/Octopus.App/Collab/Tools/CollabToolContracts.cs b/src/Octopus.App/Collab/Tools/CollabToolContracts.cs index 53c287c7..d59b27ef 100644 --- a/src/Octopus.App/Collab/Tools/CollabToolContracts.cs +++ b/src/Octopus.App/Collab/Tools/CollabToolContracts.cs @@ -43,6 +43,8 @@ public interface ICollabOperations Task BatchOpenAsync(string callerItemId, CollabBatchOpenRequest request, CancellationToken ct); /// Freezes an open batch's membership, persists the seal, and sends its one settlement wake if already met. Task BatchSealAsync(string callerItemId, string batchId, int? expectedCount, string? idempotencyKey, CancellationToken ct); + /// Collects a sealed manual batch, or resumes one paused for human action, with one settle wake. + Task BatchResumeAsync(string callerItemId, string batchId, string? note, CancellationToken ct); /// Read-only report of the orchestration guarantees this bus provides (one boolean, pinned by tests). JsonObject DescribeCapabilities(); } @@ -51,7 +53,7 @@ public interface ICollabOperations public sealed record CollabBatchOpenRequest { public string? Title { get; init; } - /// all, any or milestone; manual is reserved and rejected by this build. + /// all, any, milestone or manual. public string JoinPolicy { get; init; } = "all"; /// Only idle_only is accepted by this build; other policies are rejected. public string WakePolicy { get; init; } = "idle_only"; @@ -346,6 +348,7 @@ public CollabToolRegistry(IEnumerable tools) new CancelTaskTool(), new BatchOpenTool(), new BatchSealTool(), + new BatchResumeTool(), new OrchestratorCapabilitiesTool(), ]; diff --git a/src/Octopus.Remote/Protocol/CollabEnvelope.cs b/src/Octopus.Remote/Protocol/CollabEnvelope.cs index 70644600..77de359b 100644 --- a/src/Octopus.Remote/Protocol/CollabEnvelope.cs +++ b/src/Octopus.Remote/Protocol/CollabEnvelope.cs @@ -152,7 +152,8 @@ public static string BatchSettlement( int expected, int settled, int failed, - IReadOnlyList members) + IReadOnlyList members, + string? note = null) { var sb = new StringBuilder(); sb.Append("[Octopus Collab Batch · ").Append(title) @@ -161,6 +162,7 @@ public static string BatchSettlement( sb.Append(settled).Append('/').Append(expected).Append(" tasks settled"); if (failed > 0) sb.Append(" (").Append(failed).Append(" failed or stopped)"); sb.AppendLine("."); + if (!string.IsNullOrWhiteSpace(note)) sb.Append("Note: ").AppendLine(note.Trim()); sb.AppendLine(); foreach (var member in members) { diff --git a/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs b/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs index 3dd0a8ca..ccc278e8 100644 --- a/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs +++ b/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs @@ -282,6 +282,77 @@ public void A_batch_and_its_members_round_trip_with_stable_ids_and_report_facts( } } + [Fact] + public void An_ambiguous_wake_state_round_trips_and_an_omitted_state_remains_valid() + { + using var paths = NewPaths(); + var store = new CollabStateStore(paths); + WriteDocument(store, """ + { + "version": 2, + "id_seq": 8, + "event_seq": 21, + "tasks": [], + "threads": [], + "seen": {}, + "inbox": [], + "idempotency": [], + "batches": [ + { + "batch_id": "batch-ambiguous", + "caller": "owner-item", + "title": "Uncertain wave", + "join_policy": "manual", + "wake_policy": "idle_only", + "state": "settled", + "members": [], + "expected_member_count": 1, + "triggered": true, + "wake_delivery_id": "wake-ambiguous", + "wake_delivery_state": "ambiguous", + "seq": 20 + }, + { + "batch_id": "batch-legacy", + "caller": "owner-item", + "title": "Legacy wave", + "join_policy": "manual", + "wake_policy": "idle_only", + "state": "settled", + "members": [], + "expected_member_count": 1, + "triggered": true, + "wake_delivery_id": "wake-legacy", + "seq": 21 + } + ] + } + """); + + using (var ledger = new CollabLedger(store)) + { + ledger.Restore(); + Assert.False(ledger.IsStorePreserved); + Assert.Equal(2, ledger.Batches.Count); + Assert.Equal("ambiguous", ledger.FindBatch("batch-ambiguous")?.WakeDeliveryState); + Assert.Null(ledger.FindBatch("batch-legacy")?.WakeDeliveryState); + Assert.True(ledger.Flush()); + } + + var json = JsonNode.Parse(File.ReadAllText(store.FilePath))!.AsObject(); + var rows = json["batches"]!.AsArray(); + var ambiguous = Assert.Single(rows, row => row!["batch_id"]!.GetValue() == "batch-ambiguous"); + var legacy = Assert.Single(rows, row => row!["batch_id"]!.GetValue() == "batch-legacy"); + Assert.Equal("ambiguous", ambiguous!["wake_delivery_state"]!.GetValue()); + Assert.Null(legacy!["wake_delivery_state"]); + + using var reopened = new CollabLedger(store); + reopened.Restore(); + Assert.False(reopened.IsStorePreserved); + Assert.Equal("ambiguous", reopened.FindBatch("batch-ambiguous")?.WakeDeliveryState); + Assert.Null(reopened.FindBatch("batch-legacy")?.WakeDeliveryState); + } + [Fact] public void Open_batches_accept_unique_members_and_a_task_has_at_most_one_batch() { @@ -420,6 +491,145 @@ public void Open_and_sealed_batches_survive_retention_of_newer_finished_batches( Assert.Equal(202, restored.Batches.Count); } + [Fact] + public void Finished_batch_retention_keeps_recently_settled_older_batches_and_supports_legacy_records_within_cap() + { + using var paths = NewPaths(); + var store = new CollabStateStore(paths); + var baseTime = new DateTimeOffset(2026, 11, 29, 10, 0, 0, TimeSpan.Zero); + + using (var ledger = new CollabLedger(store)) + { + var longLived = new CollabBatchRecord + { + BatchId = "batch-long-lived", + CallerItemId = "owner", + Title = "Long-lived manual", + JoinPolicy = CollabBatchJoinPolicy.Manual, + WakePolicy = CollabBatchWakePolicy.IdleOnly, + CreatedAt = baseTime, + }; + ledger.AddBatch(longLived); + ledger.SealBatch(longLived, 1); + + for (var i = 0; i < 200; i++) + { + var created = baseTime.AddMinutes(i + 1); + var newer = new CollabBatchRecord + { + BatchId = $"batch-newer-{i:D3}", + CallerItemId = "owner", + Title = $"Newer {i}", + JoinPolicy = CollabBatchJoinPolicy.All, + WakePolicy = CollabBatchWakePolicy.IdleOnly, + CreatedAt = created, + }; + ledger.AddBatch(newer); + ledger.SealBatch(newer, 1); + ledger.MarkBatchTriggered(newer, "all_members_settled"); + newer.SettledAt = created; + } + + longLived.WakeDeliveryId = "bwake-long-lived"; + ledger.MarkBatchTriggered(longLived, "manual_resume"); + Assert.True(ledger.Flush()); + } + + using (var restored = new CollabLedger(store)) + { + restored.Restore(); + Assert.Equal(200, restored.Batches.Values.Count(b => b.IsFinished)); + var kept = restored.FindBatch("batch-long-lived"); + Assert.NotNull(kept); + Assert.Equal("bwake-long-lived", kept.WakeDeliveryId); + Assert.Null(restored.FindBatch("batch-newer-000")); + Assert.NotNull(restored.FindBatch("batch-newer-199")); + } + + // Compatibility for older documents where seq is omitted (0): order by settled timestamp, falling back to created. + using var legacyPaths = NewPaths(); + var legacyStore = new CollabStateStore(legacyPaths); + var legacyRows = new List + { + $$"""{"batch_id":"legacy-old-settled-latest","caller":"owner","title":"Old","join_policy":"manual","wake_policy":"idle_only","state":"settled","created":"{{baseTime:O}}","settled":"{{baseTime.AddHours(10):O}}","triggered":true,"wake_delivery_id":"bwake-legacy"}""", + }; + for (var i = 0; i < 200; i++) + { + var t = baseTime.AddMinutes(i + 1); + legacyRows.Add( + $$"""{"batch_id":"legacy-newer-{{i:D3}}","caller":"owner","title":"N{{i}}","join_policy":"all","wake_policy":"idle_only","state":"settled","created":"{{t:O}}","settled":"{{t:O}}","triggered":true}"""); + } + WriteDocument(legacyStore, $$"""{"version":1,"batches":[{{string.Join(",", legacyRows)}}]}"""); + + using (var legacy = new CollabLedger(legacyStore)) + { + legacy.Restore(); + // Trigger one unrelated dirty write so Flush writes the retained 200 finished batches. + lock (legacy.Gate) + { + legacy.Add(NewTask("task-trigger-flush", "owner", "worker")); + } + Assert.True(legacy.Flush()); + } + + using (var legacyRestored = new CollabLedger(legacyStore)) + { + legacyRestored.Restore(); + Assert.Equal(200, legacyRestored.Batches.Values.Count(b => b.IsFinished)); + Assert.NotNull(legacyRestored.FindBatch("legacy-old-settled-latest")); + Assert.Equal("bwake-legacy", legacyRestored.FindBatch("legacy-old-settled-latest")!.WakeDeliveryId); + Assert.Null(legacyRestored.FindBatch("legacy-newer-000")); + } + + // Legacy records without seq or settled timestamp still fall back deterministically to created timestamp. + using var createdOnlyPaths = NewPaths(); + var createdOnlyStore = new CollabStateStore(createdOnlyPaths); + var createdOnlyRows = new List(); + for (var i = 0; i < 201; i++) + { + var t = baseTime.AddMinutes(i); + createdOnlyRows.Add( + $$"""{"batch_id":"legacy-created-{{i:D3}}","caller":"owner","title":"C{{i}}","join_policy":"all","wake_policy":"idle_only","state":"cancelled","created":"{{t:O}}"}"""); + } + WriteDocument(createdOnlyStore, $$"""{"version":1,"batches":[{{string.Join(",", createdOnlyRows)}}]}"""); + + using (var createdOnly = new CollabLedger(createdOnlyStore)) + { + createdOnly.Restore(); + lock (createdOnly.Gate) + { + createdOnly.Add(NewTask("task-trigger-created-flush", "owner", "worker")); + } + Assert.True(createdOnly.Flush()); + } + + using (var createdOnlyRestored = new CollabLedger(createdOnlyStore)) + { + createdOnlyRestored.Restore(); + Assert.Equal(200, createdOnlyRestored.Batches.Values.Count(b => b.IsFinished)); + Assert.Null(createdOnlyRestored.FindBatch("legacy-created-000")); + Assert.NotNull(createdOnlyRestored.FindBatch("legacy-created-200")); + } + + // FlushBatch truthfully reports false when a finished batch is evicted by 200 newer finished batches (cap stays 200). + using var evictedPaths = NewPaths(); + var evictedStore = new CollabStateStore(evictedPaths); + using (var evicted = new CollabLedger(evictedStore)) + { + var displaced = NewBatch("batch-displaced"); + evicted.AddBatch(displaced); + evicted.MarkBatchTriggered(displaced, "manual_resume"); + for (var i = 0; i < 200; i++) + { + var newer = NewBatch($"batch-after-{i:D3}"); + evicted.AddBatch(newer); + evicted.MarkBatchTriggered(newer, "all_members_settled"); + } + Assert.False(evicted.FlushBatch("batch-displaced")); + Assert.True(evicted.FlushBatch("batch-after-199")); + } + } + [Fact] public void Existing_c1_records_and_batch_one_shot_state_survive_restart_together() { @@ -557,6 +767,7 @@ public void Malformed_or_unknown_batch_shapes_are_preserved_without_partial_impo SupportedDocumentWithBatches("""[{"batch_id":null,"caller":"owner"}]"""), SupportedDocumentWithBatches("""[{"batch_id":"a","caller":"owner","members":[{"task_id":"shared","session_id":"worker-a"}]},{"batch_id":"b","caller":"owner","members":[{"task_id":"shared","session_id":"worker-b"}]}]"""), SupportedDocumentWithBatches("""[{"batch_id":"bad","caller":"owner","join_policy":"future"}]"""), + SupportedDocumentWithBatches("""[{"batch_id":"bad","caller":"owner","wake_delivery_state":"future"}]"""), SupportedDocumentWithBatches("""[{"batch_id":"bad","caller":"owner","exceptional_rules":[{"on":"error","policy":"record_only"},{"on":"error","policy":"wake_immediately"}]}]"""), SupportedDocumentWithBatches("""[{"batch_id":"bad","caller":"owner","members":[{"task_id":"task","session_id":null}]}]"""), }; diff --git a/tests/Octopus.App.Tests/CollabBatchManualTests.cs b/tests/Octopus.App.Tests/CollabBatchManualTests.cs new file mode 100644 index 00000000..fd4994b8 --- /dev/null +++ b/tests/Octopus.App.Tests/CollabBatchManualTests.cs @@ -0,0 +1,806 @@ +using System.Reflection; +using System.Text.Json.Nodes; +using Avalonia.Headless.XUnit; +using Octopus.Agents; +using Octopus.App.Collab; +using Octopus.App.Collab.Ledger; +using Octopus.App.Composition; +using Octopus.App.Services; +using Octopus.Core.Agents; +using Octopus.Core.Projects; +using Octopus.Platform; +using Octopus.Storage; +using Xunit; + +namespace Octopus.App.Tests; + +/// +/// The manual join policy and batch_resume: reports, failures and aborts stay silent, and the owner collects +/// the batch with one explicit resume. A resume is owner-scoped, needs a sealed batch, refuses batches that settle on +/// their own, and never sends a second wake after the batch has settled. +/// +public sealed class CollabBatchManualTests +{ + private sealed class RecordingBridge(string itemId, string agentId, string title, string cwd) : ICollabSessionBridge + { + private readonly object _gate = new(); + + public string ItemId => itemId; + public string AgentId => agentId; + public string DisplayTitle => title; + public string WorkingDirectory => cwd; + public bool IsBusy { get; set; } + public bool IsConnected { get; set; } = true; + public string? CurrentStatusDetail { get; set; } + public bool Accept { get; set; } = true; + public List DeliveredPrompts { get; } = []; + public TaskCompletionSource DeliveryStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource? DeliveryGate { get; set; } + + public async Task DeliverCollabPromptAsync(CollabDeliveryRequest request, CancellationToken cancellationToken = default) + { + if (Accept) + { + DeliveryStarted.TrySetResult(true); + if (DeliveryGate is { } gate) + { + await gate.Task.WaitAsync(cancellationToken); + } + lock (_gate) DeliveredPrompts.Add(request.PromptText); + } + return Accept; + } + + public Task DeliverCollabPromptAsync(string promptText, string? threadId = null, string? taskId = null, CancellationToken cancellationToken = default) => + DeliverCollabPromptAsync(new CollabDeliveryRequest(promptText, threadId, taskId), cancellationToken); + + public int CancelQueuedCollabPrompts(string? threadId = null, string? taskId = null) => 0; + public string ReadRecentSummary(int maxTurns = 5) => "Summary"; + } + + private sealed class TempPaths(string root) : IAppPaths, IDisposable + { + public string DataDirectory { get; set; } = Path.Combine(root, "data"); + public string CacheDirectory => Path.Combine(root, "cache"); + + public void Dispose() + { + try { Directory.Delete(root, true); } catch (IOException) { } + } + } + + private static JsonObject Body(JsonObject toolResult) + { + var text = toolResult["content"]![0]!["text"]!.GetValue(); + try + { + return JsonNode.Parse(text)!.AsObject(); + } + catch (Exception ex) + { + throw new InvalidDataException($"Tool result is not a JSON object: {text}", ex); + } + } + + private static string Message(JsonObject result) => result["content"]![0]!["text"]!.GetValue(); + + private sealed record Fixture( + Project Project, + ProjectItem Parent, + RecordingBridge ParentBridge, + ProjectItem[] Workers, + RecordingBridge[] WorkerBridges, + CollabCoordinator Coordinator, + CollabStateStore Store); + + private static async Task CreateAsync(int workerCount, CollabStateStore? store = null) + { + await Task.Yield(); + var dir = Directory.CreateTempSubdirectory("octopus-0c-batch-manual-").FullName; + var projects = AppHost.Get(); + var project = projects.AddProject(dir); + var parent = new ProjectItem { Kind = ProjectItemKind.Agent, AgentId = "claude", Title = "Parent", Surface = AgentSurface.Gui }; + projects.AddItem(project, parent); + var workers = new ProjectItem[workerCount]; + var bridges = new RecordingBridge[workerCount]; + for (var i = 0; i < workerCount; i++) + { + workers[i] = new ProjectItem { Kind = ProjectItemKind.Agent, AgentId = "codex", Title = $"Worker {i + 1}", Surface = AgentSurface.Gui }; + projects.AddItem(project, workers[i], activate: false); + bridges[i] = new RecordingBridge(workers[i].Id, "codex", workers[i].Title, dir); + } + var effectiveStore = store ?? AppHost.Get(); + var coordinator = store is null + ? (CollabCoordinator)AppHost.Get() + : new CollabCoordinator( + projects, + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + new CollabMcpServer(), + store: store); + coordinator.Server.Start(); + var parentBridge = new RecordingBridge(parent.Id, "claude", parent.Title, dir); + coordinator.RegisterGuiSession(parentBridge); + foreach (var bridge in bridges) coordinator.RegisterGuiSession(bridge); + return new Fixture(project, parent, parentBridge, workers, bridges, coordinator, effectiveStore); + } + + private static async Task OpenManualAsync(CollabCoordinator coordinator, ProjectItem parent, CancellationToken ct) + { + var opened = Body(await coordinator.CallToolAsync( + parent.Id, + "batch_open", + new JsonObject { ["title"] = "Manual wave", ["join_policy"] = "manual", ["wake_policy"] = "idle_only" }, + ct)); + return opened["batch_id"]!.GetValue(); + } + + private static async Task DelegateAsync( + CollabCoordinator coordinator, ProjectItem parent, ProjectItem worker, string goal, string batchId, CancellationToken ct) => + Body(await coordinator.CallToolAsync( + parent.Id, + "delegate_task", + new JsonObject { ["target"] = worker.Id, ["goal"] = goal, ["batch_id"] = batchId }, + ct)); + + private static async Task ReportAsync( + CollabCoordinator coordinator, ProjectItem worker, string threadId, string message, string status, CancellationToken ct) => + Body(await coordinator.CallToolAsync( + worker.Id, + "reply_thread", + new JsonObject { ["thread_id"] = threadId, ["message"] = message, ["status"] = status }, + ct)); + + private static Task ResumeAsync(CollabCoordinator coordinator, ProjectItem parent, string batchId, CancellationToken ct) => + coordinator.CallToolAsync(parent.Id, "batch_resume", new JsonObject { ["batch_id"] = batchId, ["note"] = "Collect the wave." }, ct); + + private static void SetBatchState(CollabCoordinator coordinator, string batchId, CollabBatchState state) + { + var ledger = (CollabLedger)typeof(CollabCoordinator) + .GetField("_ledger", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(coordinator)!; + lock (ledger.Gate) + { + ledger.SetBatchState(ledger.FindBatch(batchId)!, state); + } + Assert.True(ledger.Flush()); + } + + private static string BatchOperationGateKeyForTests(string callerItemId, string batchId) => + $"batch:{callerItemId.Length}:{callerItemId}{batchId.Length}:{batchId}"; + + private static object BatchOperationGates(CollabCoordinator coordinator) => + typeof(CollabCoordinator) + .GetField("_batchOperationGates", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(coordinator)!; + + private static async Task AcquireBatchOperationGateForTests( + CollabCoordinator coordinator, + string callerItemId, + string batchId, + CancellationToken ct) + { + var gates = BatchOperationGates(coordinator); + var key = BatchOperationGateKeyForTests(callerItemId, batchId); + var acquire = gates.GetType().GetMethod("AcquireAsync", BindingFlags.Instance | BindingFlags.Public)!; + return await ((Task)acquire.Invoke(gates, [key, ct])!).WaitAsync(ct); + } + + private static int BatchOperationGateReferenceCount(CollabCoordinator coordinator, string callerItemId, string batchId) + { + var gates = BatchOperationGates(coordinator); + var entries = (System.Collections.IDictionary)gates + .GetType() + .GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(gates)!; + var key = BatchOperationGateKeyForTests(callerItemId, batchId); + if (!entries.Contains(key)) return 0; + var entry = entries[key]!; + return (int)entry.GetType().GetField("References", BindingFlags.Instance | BindingFlags.Public)!.GetValue(entry)!; + } + + private static async Task WaitUntilAsync(Func condition, CancellationToken ct, int timeoutMs = 4000) + { + var deadline = Environment.TickCount64 + timeoutMs; + while (!condition()) + { + if (Environment.TickCount64 > deadline) throw new TimeoutException("Condition was not met in time."); + await Task.Delay(10, ct); + } + } + + [AvaloniaFact, FreshApp] + public async Task A_manual_batch_stays_silent_until_one_resume_collects_it() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(3); + using var _ = f.Coordinator; + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var tasks = new List(); + foreach (var worker in f.Workers) + { + tasks.Add(await DelegateAsync(f.Coordinator, f.Parent, worker, "Manual part.", batchId, ct)); + } + var sealedResult = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct)); + Assert.Equal("sealed", sealedResult["state"]!.GetValue()); + Assert.False(sealedResult["triggered"]!.GetValue()); + + await ReportAsync(f.Coordinator, f.Workers[0], tasks[0]["thread_id"]!.GetValue(), "One.", "agreed", ct); + await ReportAsync(f.Coordinator, f.Workers[1], tasks[1]["thread_id"]!.GetValue(), "Two.", "continue", ct); + await ReportAsync(f.Coordinator, f.Workers[2], tasks[2]["thread_id"]!.GetValue(), "Three.", "agreed", ct); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + var resumed = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(resumed["triggered"]!.GetValue()); + Assert.Equal("settled", resumed["state"]!.GetValue()); + Assert.Equal("delivered", resumed["delivery"]!.GetValue()); + Assert.Equal("delivered", resumed["wake_delivery_state"]!.GetValue()); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains("Note: Collect the wave.", prompt, StringComparison.Ordinal); + Assert.Contains("One.", prompt, StringComparison.Ordinal); + Assert.Contains("Two.", prompt, StringComparison.Ordinal); + Assert.Contains("Three.", prompt, StringComparison.Ordinal); + + var again = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(again["deduplicated"]!.GetValue()); + Assert.Equal("delivered", again["delivery"]!.GetValue()); + Assert.Single(f.ParentBridge.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task A_manual_batch_collects_failed_members_without_an_earlier_wake() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(2); + using var _ = f.Coordinator; + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var first = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Will fail.", batchId, ct); + await DelegateAsync(f.Coordinator, f.Parent, f.Workers[1], "Will finish.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + f.Coordinator.NotifyTurnAborted(f.Workers[0].Id, "Process exited unexpectedly.", failed: true); + await Task.Delay(120, ct); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + var resumed = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(resumed["triggered"]!.GetValue()); + Assert.Equal(1, resumed["failed_count"]!.GetValue()); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains("failed", prompt, StringComparison.Ordinal); + Assert.Contains("Process exited unexpectedly.", prompt, StringComparison.Ordinal); + Assert.NotNull(first["thread_id"]); + } + + [AvaloniaFact, FreshApp] + public async Task A_manual_batch_collects_cancelled_members_without_an_earlier_wake() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(2); + using var _ = f.Coordinator; + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var first = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Finish normally.", batchId, ct); + var second = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[1], "Be cancelled.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + await ReportAsync(f.Coordinator, f.Workers[0], first["thread_id"]!.GetValue(), "Finished.", "agreed", ct); + var cancelled = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, + "cancel_task", + new JsonObject { ["task_id"] = second["task_id"]!.GetValue(), ["reason"] = "No longer needed." }, + ct)); + Assert.Equal("cancelled", cancelled["status"]!.GetValue()); + await Task.Delay(120, ct); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + var resumed = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(resumed["triggered"]!.GetValue()); + Assert.Equal(1, resumed["failed_count"]!.GetValue()); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains("Finished.", prompt, StringComparison.Ordinal); + Assert.Contains("cancelled", prompt, StringComparison.Ordinal); + Assert.Contains("No longer needed.", prompt, StringComparison.Ordinal); + } + + [AvaloniaFact, FreshApp] + public async Task Overlapping_manual_resumes_do_not_report_the_non_owner_as_a_fresh_failure() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Concurrent resume member.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + var parentDeliveryGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.ParentBridge.DeliveryGate = parentDeliveryGate; + var blocker = await AcquireBatchOperationGateForTests(f.Coordinator, f.Parent.Id, batchId, ct); + var firstResume = ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + var secondResume = ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + Task? nonOwningTask = null; + try + { + await WaitUntilAsync( + () => BatchOperationGateReferenceCount(f.Coordinator, f.Parent.Id, batchId) >= 3, + ct); + blocker.Dispose(); + + nonOwningTask = await Task.WhenAny(firstResume, secondResume); + await f.ParentBridge.DeliveryStarted.Task.WaitAsync(TimeSpan.FromSeconds(2), ct); + var nonOwningRaw = await nonOwningTask; + var nonOwning = Body(nonOwningRaw); + Assert.True(nonOwning["deduplicated"]!.GetValue(), Message(nonOwningRaw)); + Assert.Equal("in_flight", nonOwning["delivery"]!.GetValue()); + Assert.Null(nonOwning["wake_delivery_state"]); + Assert.False(nonOwning["wake_delivered"]!.GetValue()); + } + finally + { + blocker.Dispose(); + parentDeliveryGate.TrySetResult(true); + } + + var owningTask = ReferenceEquals(nonOwningTask, firstResume) ? secondResume : firstResume; + var owning = Body(await owningTask); + Assert.False(owning["deduplicated"]!.GetValue()); + Assert.Equal("delivered", owning["delivery"]!.GetValue()); + Assert.Equal("delivered", owning["wake_delivery_state"]!.GetValue()); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains(batchId, prompt, StringComparison.Ordinal); + + var after = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(after["deduplicated"]!.GetValue()); + Assert.Equal("delivered", after["delivery"]!.GetValue()); + Assert.Equal("delivered", after["wake_delivery_state"]!.GetValue()); + Assert.Single(f.ParentBridge.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task A_denied_manual_wake_is_reported_as_failed_on_retry() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var task = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Only member.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + f.ParentBridge.Accept = false; + var first = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.Equal("failed", first["delivery"]!.GetValue()); + Assert.False(first["wake_delivered"]!.GetValue()); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + f.ParentBridge.Accept = true; + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "Finished after the denial.", "agreed", ct); + var retry = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(retry["deduplicated"]!.GetValue()); + Assert.Equal("failed", retry["delivery"]!.GetValue()); + Assert.False(retry["wake_delivered"]!.GetValue()); + Assert.Equal(1, retry["settled_count"]!.GetValue()); + Assert.DoesNotContain("sent earlier", retry["note"]!.GetValue(), StringComparison.OrdinalIgnoreCase); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task Resume_requires_ownership_valid_input_and_a_sealed_batch() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var stranger = new ProjectItem { Kind = ProjectItemKind.Agent, AgentId = "claude", Title = "Stranger", Surface = AgentSurface.Gui }; + AppHost.Get().AddItem(f.Project, stranger, activate: false); + f.Coordinator.RegisterGuiSession(new RecordingBridge(stranger.Id, "claude", stranger.Title, f.Project.Path)); + + var foreign = await f.Coordinator.CallToolAsync(stranger.Id, "batch_resume", new JsonObject { ["batch_id"] = batchId }, ct); + var unknown = await f.Coordinator.CallToolAsync(stranger.Id, "batch_resume", new JsonObject { ["batch_id"] = "batch_999_none" }, ct); + Assert.True(foreign["isError"]!.GetValue()); + Assert.Equal( + Message(foreign).Replace(batchId, "", StringComparison.Ordinal), + Message(unknown).Replace("batch_999_none", "", StringComparison.Ordinal)); + + var malformedId = await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_resume", new JsonObject { ["batch_id"] = 7 }, ct); + Assert.True(malformedId["isError"]!.GetValue()); + Assert.Contains("batch_id", Message(malformedId), StringComparison.Ordinal); + var malformedNote = await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_resume", new JsonObject { ["batch_id"] = batchId, ["note"] = 7 }, ct); + Assert.True(malformedNote["isError"]!.GetValue()); + Assert.Contains("note", Message(malformedNote), StringComparison.Ordinal); + + var open = await ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + Assert.True(open["isError"]!.GetValue()); + Assert.Contains("seal", Message(open), StringComparison.OrdinalIgnoreCase); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Only member.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + var owned = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(owned["triggered"]!.GetValue()); + } + + [AvaloniaFact, FreshApp] + public async Task Resume_refuses_a_batch_that_settles_on_its_own() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var opened = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, + "batch_open", + new JsonObject { ["join_policy"] = "all", ["wake_policy"] = "idle_only" }, + ct)); + var batchId = opened["batch_id"]!.GetValue(); + await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Automatic.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + var resumed = await ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + Assert.True(resumed["isError"]!.GetValue()); + Assert.Contains("automatically", Message(resumed), StringComparison.OrdinalIgnoreCase); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + } + + [AvaloniaTheory, FreshApp] + [InlineData("all")] + [InlineData("any")] + [InlineData("milestone")] + public async Task Resume_refuses_an_automatically_settled_batch_after_settlement_without_extra_wake(string joinPolicy) + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var openArgs = new JsonObject { ["join_policy"] = joinPolicy, ["wake_policy"] = "idle_only" }; + if (joinPolicy == "milestone") openArgs["milestone_count"] = 1; + var opened = Body(await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_open", openArgs, ct)); + var batchId = opened["batch_id"]!.GetValue(); + var task = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Auto settle.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "Done automatically.", "agreed", ct); + Assert.Single(f.ParentBridge.DeliveredPrompts); + + var resumed = await ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + Assert.True(resumed["isError"]?.GetValue() ?? false, Message(resumed)); + Assert.Contains("automatically", Message(resumed), StringComparison.OrdinalIgnoreCase); + Assert.Contains(joinPolicy, Message(resumed), StringComparison.Ordinal); + Assert.Single(f.ParentBridge.DeliveredPrompts); + + var stranger = new ProjectItem { Kind = ProjectItemKind.Agent, AgentId = "claude", Title = "Stranger", Surface = AgentSurface.Gui }; + AppHost.Get().AddItem(f.Project, stranger, activate: false); + f.Coordinator.RegisterGuiSession(new RecordingBridge(stranger.Id, "claude", stranger.Title, f.Project.Path)); + var foreign = await f.Coordinator.CallToolAsync(stranger.Id, "batch_resume", new JsonObject { ["batch_id"] = batchId }, ct); + Assert.True(foreign["isError"]?.GetValue() ?? false, Message(foreign)); + Assert.Contains("Unknown batch", Message(foreign), StringComparison.Ordinal); + Assert.Single(f.ParentBridge.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task A_formerly_paused_automatic_batch_refuses_resume_retry_once_unpaused_or_settled() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(2); + using var _ = f.Coordinator; + + // Case 1: unpaused while still running, then settles later. + var openedRunning = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, + "batch_open", + new JsonObject { ["join_policy"] = "all", ["wake_policy"] = "idle_only" }, + ct)); + var runningBatchId = openedRunning["batch_id"]!.GetValue(); + var member = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Paused then resumed.", runningBatchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = runningBatchId }, ct); + SetBatchState(f.Coordinator, runningBatchId, CollabBatchState.Paused); + + var unpaused = Body(await ResumeAsync(f.Coordinator, f.Parent, runningBatchId, ct)); + Assert.Equal("sealed", unpaused["state"]!.GetValue()); + Assert.Equal("still_running", unpaused["delivery"]!.GetValue()); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + var retryWhileSealed = await ResumeAsync(f.Coordinator, f.Parent, runningBatchId, ct); + Assert.True(retryWhileSealed["isError"]?.GetValue() ?? false, Message(retryWhileSealed)); + Assert.Contains("automatically", Message(retryWhileSealed), StringComparison.OrdinalIgnoreCase); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + await ReportAsync(f.Coordinator, f.Workers[0], member["thread_id"]!.GetValue(), "Finished after unpause.", "agreed", ct); + Assert.Single(f.ParentBridge.DeliveredPrompts); + + var retryAfterSettled = await ResumeAsync(f.Coordinator, f.Parent, runningBatchId, ct); + Assert.True(retryAfterSettled["isError"]?.GetValue() ?? false, Message(retryAfterSettled)); + Assert.Contains("automatically", Message(retryAfterSettled), StringComparison.OrdinalIgnoreCase); + Assert.Single(f.ParentBridge.DeliveredPrompts); + + // Case 2: member already finished while paused; first resume unpauses and settles once, retry refuses with no extra wake. + var openedReady = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, + "batch_open", + new JsonObject { ["join_policy"] = "all", ["wake_policy"] = "idle_only" }, + ct)); + var readyBatchId = openedReady["batch_id"]!.GetValue(); + var readyMember = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[1], "Finish while paused.", readyBatchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = readyBatchId }, ct); + SetBatchState(f.Coordinator, readyBatchId, CollabBatchState.Paused); + await ReportAsync(f.Coordinator, f.Workers[1], readyMember["thread_id"]!.GetValue(), "Done while paused.", "agreed", ct); + Assert.Single(f.ParentBridge.DeliveredPrompts); + + var settledByResume = Body(await ResumeAsync(f.Coordinator, f.Parent, readyBatchId, ct)); + Assert.True(settledByResume["triggered"]!.GetValue()); + Assert.Equal("settled", settledByResume["state"]!.GetValue()); + Assert.Equal("delivered", settledByResume["delivery"]!.GetValue()); + Assert.False(settledByResume["deduplicated"]!.GetValue()); + Assert.Equal(2, f.ParentBridge.DeliveredPrompts.Count); + + var retryReady = await ResumeAsync(f.Coordinator, f.Parent, readyBatchId, ct); + Assert.True(retryReady["isError"]?.GetValue() ?? false, Message(retryReady)); + Assert.Contains("automatically", Message(retryReady), StringComparison.OrdinalIgnoreCase); + Assert.Equal(2, f.ParentBridge.DeliveredPrompts.Count); + } + + [AvaloniaFact, FreshApp] + public async Task A_paused_automatic_batch_resume_reevaluates_without_forcing_it() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(2); + using var _ = f.Coordinator; + var opened = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, + "batch_open", + new JsonObject { ["join_policy"] = "all", ["wake_policy"] = "idle_only" }, + ct)); + var batchId = opened["batch_id"]!.GetValue(); + var first = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "First paused member.", batchId, ct); + var second = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[1], "Second paused member.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + SetBatchState(f.Coordinator, batchId, CollabBatchState.Paused); + + var resumed = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.False(resumed["triggered"]!.GetValue()); + Assert.Equal("sealed", resumed["state"]!.GetValue()); + Assert.Equal("still_running", resumed["delivery"]!.GetValue()); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + await ReportAsync(f.Coordinator, f.Workers[0], first["thread_id"]!.GetValue(), "First done.", "agreed", ct); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + await ReportAsync(f.Coordinator, f.Workers[1], second["thread_id"]!.GetValue(), "Second done.", "agreed", ct); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains("First done.", prompt, StringComparison.Ordinal); + Assert.Contains("Second done.", prompt, StringComparison.Ordinal); + } + + [AvaloniaFact, FreshApp] + public async Task A_manual_resume_that_cannot_save_is_honest_and_retries_once() + { + var ct = TestContext.Current.CancellationToken; + using var paths = new TempPaths(Directory.CreateTempSubdirectory("octopus-0c-batch-manual-outage-").FullName); + var store = new CollabStateStore(paths); + var f = await CreateAsync(1, store); + using var _ = f.Coordinator; + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Survive storage.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + var realData = paths.DataDirectory; + var blocked = Path.Combine(realData, "blocked"); + Directory.CreateDirectory(blocked); + File.WriteAllText(Path.Combine(blocked, "collab"), "not a directory"); + paths.DataDirectory = blocked; + + var failed = await ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + Assert.True(failed["isError"]!.GetValue()); + Assert.Contains("could not be saved", Message(failed), StringComparison.OrdinalIgnoreCase); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + paths.DataDirectory = realData; + var retried = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(retried["triggered"]!.GetValue()); + Assert.Equal("delivered", retried["delivery"]!.GetValue()); + Assert.Single(f.ParentBridge.DeliveredPrompts); + + var again = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(again["deduplicated"]!.GetValue()); + Assert.Single(f.ParentBridge.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task A_manual_batch_resumed_after_restart_sends_one_wake_and_no_replay() + { + var ct = TestContext.Current.CancellationToken; + using var paths = new TempPaths(Directory.CreateTempSubdirectory("octopus-0c-batch-manual-restart-").FullName); + var store = new CollabStateStore(paths); + var f = await CreateAsync(1, store); + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var task = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Survive.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "Before restart.", "agreed", ct); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + f.Coordinator.Dispose(); + + var reopened = new CollabCoordinator( + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + new CollabMcpServer(), + store: store); + reopened.Server.Start(); + using var _ = reopened; + var fresh = new RecordingBridge(f.Parent.Id, "claude", f.Parent.Title, f.Project.Path); + reopened.RegisterGuiSession(fresh); + + var resumed = Body(await ResumeAsync(reopened, f.Parent, batchId, ct)); + Assert.True(resumed["triggered"]!.GetValue()); + Assert.Equal("delivered", resumed["delivery"]!.GetValue()); + var prompt = Assert.Single(fresh.DeliveredPrompts); + Assert.Contains("Before restart.", prompt, StringComparison.Ordinal); + + var again = Body(await ResumeAsync(reopened, f.Parent, batchId, ct)); + Assert.True(again["deduplicated"]!.GetValue()); + Assert.Equal("delivered", again["delivery"]!.GetValue()); + Assert.Single(fresh.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task A_long_lived_manual_batch_retains_its_first_wake_receipt_past_200_newer_finished_batches_and_restart() + { + var ct = TestContext.Current.CancellationToken; + using var paths = new TempPaths(Directory.CreateTempSubdirectory("octopus-0c-batch-manual-retention-").FullName); + var store = new CollabStateStore(paths); + var f = await CreateAsync(1, store); + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var task = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Long-lived manual work.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "Long-lived result.", "agreed", ct); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + var ledger = (CollabLedger)typeof(CollabCoordinator) + .GetField("_ledger", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(f.Coordinator)!; + lock (ledger.Gate) + { + var oldCreatedAt = ledger.FindBatch(batchId)!.CreatedAt; + for (var i = 0; i < 200; i++) + { + var createdAt = oldCreatedAt.AddTicks((i + 1) * 10); + var newer = new CollabBatchRecord + { + BatchId = $"batch_newer_{i:D3}", + CallerItemId = f.Parent.Id, + Title = $"Newer finished {i}", + JoinPolicy = CollabBatchJoinPolicy.All, + WakePolicy = CollabBatchWakePolicy.IdleOnly, + CreatedAt = createdAt, + }; + ledger.AddBatch(newer); + ledger.SealBatch(newer, 1); + ledger.MarkBatchTriggered(newer, "all_members_settled"); + newer.SettledAt = createdAt; + newer.WakeDeliveryId = $"bwake_newer_{i:D3}"; + newer.WakeDeliveryState = "delivered"; + } + } + Assert.True(ledger.Flush()); + await Task.Delay(15, ct); + + var resumed = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(resumed["triggered"]!.GetValue()); + Assert.Equal("settled", resumed["state"]!.GetValue()); + Assert.Equal("delivered", resumed["delivery"]!.GetValue()); + Assert.Equal("delivered", resumed["wake_delivery_state"]!.GetValue()); + var wakeDeliveryId = resumed["wake_delivery"]!.GetValue(); + Assert.StartsWith("bwake_", wakeDeliveryId, StringComparison.Ordinal); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains("Long-lived result.", prompt, StringComparison.Ordinal); + f.Coordinator.Dispose(); + + using (var restoredLedger = new CollabLedger(store)) + { + restoredLedger.Restore(); + Assert.Equal(200, restoredLedger.Batches.Values.Count(b => b.IsFinished)); + var saved = restoredLedger.FindBatch(batchId); + Assert.NotNull(saved); + Assert.True(saved.Triggered); + Assert.Equal(CollabBatchState.Settled, saved.State); + Assert.Equal(wakeDeliveryId, saved.WakeDeliveryId); + Assert.Equal("delivered", saved.WakeDeliveryState); + Assert.Null(restoredLedger.FindBatch("batch_newer_000")); + } + + var reopened = new CollabCoordinator( + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + new CollabMcpServer(), + store: store); + reopened.Server.Start(); + using var _ = reopened; + var fresh = new RecordingBridge(f.Parent.Id, "claude", f.Parent.Title, f.Project.Path); + reopened.RegisterGuiSession(fresh); + + var replayRaw = await ResumeAsync(reopened, f.Parent, batchId, ct); + Assert.False(replayRaw["isError"]?.GetValue() ?? false, Message(replayRaw)); + var replay = Body(replayRaw); + Assert.True(replay["deduplicated"]!.GetValue()); + Assert.Equal("settled", replay["state"]!.GetValue()); + Assert.Equal(wakeDeliveryId, replay["wake_delivery"]!.GetValue()); + Assert.Equal("delivered", replay["wake_delivery_state"]!.GetValue()); + Assert.Equal("delivered", replay["delivery"]!.GetValue()); + Assert.Empty(fresh.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task A_long_lived_manual_batch_handles_flush_failure_truthfully_with_200_newer_finished_batches() + { + var ct = TestContext.Current.CancellationToken; + using var paths = new TempPaths(Directory.CreateTempSubdirectory("octopus-0c-batch-manual-retention-outage-").FullName); + var store = new CollabStateStore(paths); + var f = await CreateAsync(1, store); + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var task = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Outage retention work.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "Outage result.", "agreed", ct); + + var ledger = (CollabLedger)typeof(CollabCoordinator) + .GetField("_ledger", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(f.Coordinator)!; + lock (ledger.Gate) + { + var oldCreatedAt = ledger.FindBatch(batchId)!.CreatedAt; + for (var i = 0; i < 200; i++) + { + var createdAt = oldCreatedAt.AddTicks((i + 1) * 10); + var newer = new CollabBatchRecord + { + BatchId = $"batch_outage_newer_{i:D3}", + CallerItemId = f.Parent.Id, + Title = $"Newer {i}", + JoinPolicy = CollabBatchJoinPolicy.All, + WakePolicy = CollabBatchWakePolicy.IdleOnly, + CreatedAt = createdAt, + }; + ledger.AddBatch(newer); + ledger.SealBatch(newer, 1); + ledger.MarkBatchTriggered(newer, "all_members_settled"); + newer.SettledAt = createdAt; + } + } + Assert.True(ledger.Flush()); + + var realData = paths.DataDirectory; + var blocked = Path.Combine(realData, "blocked"); + Directory.CreateDirectory(blocked); + File.WriteAllText(Path.Combine(blocked, "collab"), "not a directory"); + paths.DataDirectory = blocked; + + var failed = await ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + Assert.True(failed["isError"]?.GetValue() ?? false, Message(failed)); + Assert.Contains("could not be saved", Message(failed), StringComparison.OrdinalIgnoreCase); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + paths.DataDirectory = realData; + var retried = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(retried["triggered"]!.GetValue()); + Assert.Equal("delivered", retried["delivery"]!.GetValue()); + var wakeDeliveryId = retried["wake_delivery"]!.GetValue(); + Assert.Single(f.ParentBridge.DeliveredPrompts); + f.Coordinator.Dispose(); + + var reopened = new CollabCoordinator( + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + new CollabMcpServer(), + store: store); + reopened.Server.Start(); + using var _ = reopened; + var fresh = new RecordingBridge(f.Parent.Id, "claude", f.Parent.Title, f.Project.Path); + reopened.RegisterGuiSession(fresh); + + var replay = Body(await ResumeAsync(reopened, f.Parent, batchId, ct)); + Assert.True(replay["deduplicated"]!.GetValue()); + Assert.Equal(wakeDeliveryId, replay["wake_delivery"]!.GetValue()); + Assert.Equal("delivered", replay["wake_delivery_state"]!.GetValue()); + Assert.Empty(fresh.DeliveredPrompts); + } +} diff --git a/tests/Octopus.App.Tests/CollabBatchWakeTests.cs b/tests/Octopus.App.Tests/CollabBatchWakeTests.cs index a2f604dd..43848019 100644 --- a/tests/Octopus.App.Tests/CollabBatchWakeTests.cs +++ b/tests/Octopus.App.Tests/CollabBatchWakeTests.cs @@ -1,3 +1,4 @@ +using System.Reflection; using System.Text.Json.Nodes; using Avalonia.Headless.XUnit; using Octopus.Agents; @@ -27,6 +28,7 @@ private sealed class RecordingBridge(string itemId, string agentId, string title { private readonly object _gate = new(); private readonly List _queuedWhileBusy = []; + private int _deliveryAttempts; public string ItemId => itemId; public string AgentId => agentId; @@ -35,11 +37,17 @@ private sealed class RecordingBridge(string itemId, string agentId, string title public bool IsBusy { get; set; } public bool IsConnected { get; set; } = true; public string? CurrentStatusDetail { get; set; } + public bool Accept { get; set; } = true; + public bool ThrowOnDelivery { get; set; } public List DeliveredPrompts { get; } = []; public List QueuedPrompts { get; } = []; + public int DeliveryAttempts => Volatile.Read(ref _deliveryAttempts); public Task DeliverCollabPromptAsync(CollabDeliveryRequest request, CancellationToken cancellationToken = default) { + Interlocked.Increment(ref _deliveryAttempts); + if (ThrowOnDelivery) throw new IOException("fixture bridge failed"); + if (!Accept) return Task.FromResult(false); lock (_gate) { if (IsBusy) @@ -191,6 +199,17 @@ private static async Task WaitUntilAsync(Func condition, CancellationToken } } + private static async Task PollUntilAsync(Func condition, CancellationToken ct, int timeoutMs) + { + var deadline = Environment.TickCount64 + timeoutMs; + while (!condition()) + { + if (Environment.TickCount64 > deadline) return false; + await Task.Delay(20, ct); + } + return true; + } + private static async Task OpenBatchAsync(CollabCoordinator coordinator, ProjectItem parent, CancellationToken ct, string? key = null) { var opened = Body(await coordinator.CallToolAsync( @@ -233,6 +252,39 @@ private static Task ReportAsync( return coordinator.CallToolAsync(worker.Id, "reply_thread", args, ct); } + private static async Task ArrangeDeferredTerminalWakeAsync( + Fixture f, + ProjectItem parent, + string message, + CancellationToken ct) + { + var batchId = await OpenBatchAsync(f.Coordinator, parent, ct); + var task = Body(await DelegateAsync(f.Coordinator, parent, f.Workers[0], "Work.", batchId, ct)); + await f.Coordinator.CallToolAsync(parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + var reported = Body(await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), message, ct)); + Assert.Equal("queued_for_idle", reported["delivery"]!.GetValue()); + Assert.Equal("queued_for_idle", ReadBatch(f.Store, batchId)?.WakeDeliveryState); + return batchId; + } + + private static void WriteBatchWakeStateForTests(CollabCoordinator coordinator, string batchId, string state) + { + var ledger = (CollabLedger)typeof(CollabCoordinator) + .GetField("_ledger", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(coordinator)!; + CollabBatchRecord batch; + lock (ledger.Gate) + { + batch = ledger.FindBatch(batchId)!; + } + typeof(CollabCoordinator) + .GetMethod("SetBatchWakeState", BindingFlags.NonPublic | BindingFlags.Instance)! + .Invoke(coordinator, [batch, state]); + } + + private static void ReplayInitialQueuedWakeWrite(CollabCoordinator coordinator, string batchId) => + WriteBatchWakeStateForTests(coordinator, batchId, "queued_for_idle"); + [AvaloniaFact, FreshApp] public async Task Three_workers_reporting_out_of_order_wake_the_parent_exactly_once_at_the_threshold() { @@ -700,6 +752,158 @@ public async Task A_busy_terminal_owner_gets_the_aggregate_only_after_it_is_idle Assert.Contains("1/1", TerminalText(pty), StringComparison.Ordinal); Assert.Contains("terminal result", TerminalText(pty), StringComparison.Ordinal); Assert.EndsWith("\r", TerminalText(pty), StringComparison.Ordinal); + await WaitUntilAsync(() => ReadBatch(f.Store, batchId)?.WakeDeliveryState == "delivered", ct); + } + + [AvaloniaFact, FreshApp] + public async Task A_rejected_deferred_terminal_wake_is_recorded_as_failed_and_not_retried() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var parent = AddTerminalParent(f.Project, "CLI Parent"); + StartTerminal(f.Project, parent); + var activity = AppHost.Get(); + activity.ReportStatus(parent.Id, ItemActivity.Working); + var batchId = await ArrangeDeferredTerminalWakeAsync(f, parent, "deferred rejection", ct); + + var rejecting = new RecordingBridge(parent.Id, "claude", parent.Title, f.Project.Path) { Accept = false }; + f.Coordinator.RegisterGuiSession(rejecting); + activity.ReportStatus(parent.Id, ItemActivity.Idle); + + await WaitUntilAsync(() => ReadBatch(f.Store, batchId)?.WakeDeliveryState == "failed", ct); + Assert.Equal(1, rejecting.DeliveryAttempts); + Assert.Empty(rejecting.DeliveredPrompts); + + activity.ReportStatus(parent.Id, ItemActivity.Working); + activity.ReportStatus(parent.Id, ItemActivity.Idle); + await Task.Delay(120, ct); + Assert.Equal(1, rejecting.DeliveryAttempts); + Assert.Equal("failed", ReadBatch(f.Store, batchId)?.WakeDeliveryState); + } + + [AvaloniaFact, FreshApp] + public async Task A_throwing_deferred_terminal_wake_is_recorded_as_uncertain_and_not_retried() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var parent = AddTerminalParent(f.Project, "CLI Parent"); + StartTerminal(f.Project, parent); + var activity = AppHost.Get(); + activity.ReportStatus(parent.Id, ItemActivity.Working); + var batchId = await ArrangeDeferredTerminalWakeAsync(f, parent, "deferred throw", ct); + + var throwing = new RecordingBridge(parent.Id, "claude", parent.Title, f.Project.Path) { ThrowOnDelivery = true }; + f.Coordinator.RegisterGuiSession(throwing); + activity.ReportStatus(parent.Id, ItemActivity.Idle); + + await WaitUntilAsync(() => throwing.DeliveryAttempts > 0, ct); + await PollUntilAsync(() => ReadBatch(f.Store, batchId)?.WakeDeliveryState == "ambiguous", ct, timeoutMs: 1000); + Assert.Equal("ambiguous", ReadBatch(f.Store, batchId)?.WakeDeliveryState); + Assert.Equal(1, throwing.DeliveryAttempts); + Assert.Empty(throwing.DeliveredPrompts); + + activity.ReportStatus(parent.Id, ItemActivity.Working); + activity.ReportStatus(parent.Id, ItemActivity.Idle); + await Task.Delay(120, ct); + Assert.Equal(1, throwing.DeliveryAttempts); + Assert.Equal("ambiguous", ReadBatch(f.Store, batchId)?.WakeDeliveryState); + } + + [AvaloniaFact, FreshApp] + public async Task A_stale_initial_queue_write_cannot_rewind_a_consumed_deferred_wake() + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + var store = f.Store; + var parent = AddTerminalParent(f.Project, "CLI Parent"); + StartTerminal(f.Project, parent); + var activity = AppHost.Get(); + activity.ReportStatus(parent.Id, ItemActivity.Working); + + var opened = Body(await f.Coordinator.CallToolAsync( + parent.Id, + "batch_open", + new JsonObject { ["title"] = "Manual terminal wave", ["join_policy"] = "manual", ["wake_policy"] = "idle_only" }, + ct)); + var batchId = opened["batch_id"]!.GetValue(); + var task = Body(await DelegateAsync(f.Coordinator, parent, f.Workers[0], "Work.", batchId, ct)); + await f.Coordinator.CallToolAsync(parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "consumed deferred overwrite", ct); + + var initial = Body(await f.Coordinator.CallToolAsync( + parent.Id, + "batch_resume", + new JsonObject { ["batch_id"] = batchId }, + ct)); + Assert.Equal("queued_for_idle", initial["delivery"]!.GetValue()); + Assert.Equal("queued_for_idle", ReadBatch(store, batchId)?.WakeDeliveryState); + + var throwing = new RecordingBridge(parent.Id, "claude", parent.Title, f.Project.Path) { ThrowOnDelivery = true }; + f.Coordinator.RegisterGuiSession(throwing); + activity.ReportStatus(parent.Id, ItemActivity.Idle); + await WaitUntilAsync(() => ReadBatch(store, batchId)?.WakeDeliveryState == "ambiguous", ct); + Assert.Equal(1, throwing.DeliveryAttempts); + + ReplayInitialQueuedWakeWrite(f.Coordinator, batchId); + + Assert.Equal("ambiguous", ReadBatch(store, batchId)?.WakeDeliveryState); + var receipt = Body(await f.Coordinator.CallToolAsync( + parent.Id, + "batch_resume", + new JsonObject { ["batch_id"] = batchId }, + ct)); + Assert.True(receipt["deduplicated"]!.GetValue()); + Assert.Equal("ambiguous", receipt["delivery"]!.GetValue()); + Assert.Equal("ambiguous", receipt["wake_delivery_state"]!.GetValue()); + + f.Coordinator.Dispose(); + Assert.Equal("ambiguous", ReadBatch(store, batchId)?.WakeDeliveryState); + var reopened = new CollabCoordinator( + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + new CollabMcpServer(), + store: store); + reopened.Server.Start(); + using var _ = reopened; + var restoredReceipt = Body(await reopened.CallToolAsync( + parent.Id, + "batch_resume", + new JsonObject { ["batch_id"] = batchId }, + ct)); + Assert.True(restoredReceipt["deduplicated"]!.GetValue()); + Assert.Equal("ambiguous", restoredReceipt["delivery"]!.GetValue()); + Assert.Equal("ambiguous", restoredReceipt["wake_delivery_state"]!.GetValue()); + Assert.Equal(1, throwing.DeliveryAttempts); + } + + [AvaloniaTheory, FreshApp] + [InlineData("delivered")] + [InlineData("failed")] + [InlineData("ambiguous")] + public async Task A_stale_initial_queue_write_cannot_rewind_a_terminal_wake_state(string terminalState) + { + var ct = TestContext.Current.CancellationToken; + var f = await CreateAsync(1); + using var _ = f.Coordinator; + var batchId = await OpenBatchAsync(f.Coordinator, f.Parent, ct); + var task = Body(await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Work.", batchId, ct)); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "terminal overwrite control", ct); + var wakeDeliveryId = ReadBatch(f.Store, batchId)?.WakeDeliveryId; + Assert.NotNull(wakeDeliveryId); + Assert.Equal("delivered", ReadBatch(f.Store, batchId)?.WakeDeliveryState); + + WriteBatchWakeStateForTests(f.Coordinator, batchId, terminalState); + Assert.Equal(terminalState, ReadBatch(f.Store, batchId)?.WakeDeliveryState); + ReplayInitialQueuedWakeWrite(f.Coordinator, batchId); + + var batch = ReadBatch(f.Store, batchId); + Assert.Equal(wakeDeliveryId, batch?.WakeDeliveryId); + Assert.Equal(terminalState, batch?.WakeDeliveryState); } [AvaloniaFact, FreshApp] @@ -978,7 +1182,7 @@ public async Task The_public_first_slice_rejects_wake_and_join_policies_it_does_ Assert.Contains("idle_only", Message(result), StringComparison.Ordinal); } - foreach (var policy in new[] { "all", "any", "milestone" }) + foreach (var policy in new[] { "all", "any", "milestone", "manual" }) { var extra = new JsonObject { ["join_policy"] = policy }; if (policy == "milestone") extra["milestone_count"] = 1; @@ -990,7 +1194,7 @@ public async Task The_public_first_slice_rejects_wake_and_join_policies_it_does_ var unsupportedJoin = await f.Coordinator.CallToolAsync( f.Parent.Id, "batch_open", - new JsonObject { ["join_policy"] = "manual" }, + new JsonObject { ["join_policy"] = "bogus" }, ct); Assert.True(unsupportedJoin["isError"]?.GetValue()); Assert.Contains("manual", Message(unsupportedJoin), StringComparison.Ordinal); diff --git a/tests/Octopus.App.Tests/CollabTests.cs b/tests/Octopus.App.Tests/CollabTests.cs index 44ec75dd..6d36c7b8 100644 --- a/tests/Octopus.App.Tests/CollabTests.cs +++ b/tests/Octopus.App.Tests/CollabTests.cs @@ -2370,7 +2370,7 @@ public async Task A_new_tool_is_one_class_it_is_listed_called_and_can_replace_a_ tools: [.. Octopus.App.Collab.Tools.CollabToolRegistry.BuiltIn, new EchoTool(), new EchoTool("read_session")]); var names = coordinator.ListTools().Select(t => t!["name"]!.GetValue()).ToList(); - Assert.Equal(11, names.Count); + Assert.Equal(12, names.Count); Assert.Contains("echo", names); Assert.Single(names, n => n == "read_session"); From 914777ad7a9b947cb29a8c9657f3fbbab5812929 Mon Sep 17 00:00:00 2001 From: SHI ZHENWEI Date: Tue, 1 Dec 2026 19:41:13 +0900 Subject: [PATCH 2/2] fix(collab): check batch snapshot inclusion before save and commit settlement atomically Fix the cap-miss persistence HOLD on d8bdb47a5d8524bf200b3ccd1f032d0a9bfb1b2c: 1. Check requiredBatchId inclusion in CollabLedger.FlushCore before serializing or calling _store.Save so a cap-miss candidate snapshot never overwrites the previously persisted sealed batch or advances _persistedVersion/_persistedBatchIds. 2. Add CollabLedger.TryCommitBatchTransition and use it in CollabCoordinator.TrySettleBatchAsync to hold _persistGate across staging (under Gate), pre-save snapshot inclusion check, off-Gate JSON serialization/store save, and commit or rollback (under Gate). No concurrent or background flush can observe or persist a staged settlement or coupled keyed-report dispatching marker before commit or rollback completes. 3. Add deterministic 200-finished cap-collision regressions with actual persisted snapshot reloads for direct FlushBatch, manual batch_resume (with healthy retry and restart replay), keyed automatic report settlement (preserving sealed batch and recorded event state before batch_seal retry), and atomic TryCommitBatchTransition rollback. --- src/Octopus.App/Collab/CollabCoordinator.cs | 76 ++++-- src/Octopus.App/Collab/Ledger/CollabLedger.cs | 147 +++++++--- .../CollabBatchLedgerTests.cs | 224 ++++++++++++++++ .../CollabBatchManualTests.cs | 251 ++++++++++++++++++ 4 files changed, 642 insertions(+), 56 deletions(-) diff --git a/src/Octopus.App/Collab/CollabCoordinator.cs b/src/Octopus.App/Collab/CollabCoordinator.cs index 45af4a15..7b32ac60 100644 --- a/src/Octopus.App/Collab/CollabCoordinator.cs +++ b/src/Octopus.App/Collab/CollabCoordinator.cs @@ -4485,10 +4485,13 @@ private async Task TrySettleBatchAsync( string? forcedReason = null, string? wakeNote = null) { - BatchEvaluation evaluation; + BatchEvaluation evaluation = null!; string? wakeDeliveryId = null; string? reportEventStateBeforeDispatch = null; var reportEventMarkedDispatching = false; + var missingDurableReportEvent = false; + var alreadyTriggered = false; + string? existingWakeDeliveryId = null; var sendWake = false; var wakeAttemptInFlight = false; using (await AcquireBatchOperationGateAsync(batch.CallerItemId, batch.BatchId, ct).ConfigureAwait(false)) @@ -4500,26 +4503,38 @@ private async Task TrySettleBatchAsync( { return new BatchSettlementResult(batch.Triggered, false, false, false, batch.WakeDeliveryId, evaluation, false); } - if (durableReportEventId is not null && _ledger.FindEvent(durableReportEventId) is { } reportEvent) - { - reportEventStateBeforeDispatch = reportEvent.State; - reportEventMarkedDispatching = _ledger.TrySetEventState(durableReportEventId, "dispatching"); - } - if (durableReportEventId is not null && !reportEventMarkedDispatching) - { - return new BatchSettlementResult(false, false, false, true, null, evaluation with { ShouldTrigger = true }, false); - } - var reason = force ? forcedReason ?? "manual_resume" : evaluation.Reason; - evaluation = evaluation with { ShouldTrigger = true, Reason = reason }; - sendWake = batch.WakePolicy == CollabBatchWakePolicy.IdleOnly; - wakeDeliveryId = sendWake ? _ledger.NextId("bwake") : null; - batch.WakeDeliveryId = wakeDeliveryId; - _ledger.MarkBatchTriggered(batch, reason); } - if (!_ledger.FlushBatch(batch.BatchId)) - { - lock (_ledger.Gate) + var committed = _ledger.TryCommitBatchTransition( + batch.BatchId, + stageLocked: () => + { + evaluation = _ledger.EvaluateBatch(batch); + if (batch.Triggered || (!force && !evaluation.ShouldTrigger)) + { + alreadyTriggered = batch.Triggered; + existingWakeDeliveryId = batch.WakeDeliveryId; + return false; + } + if (durableReportEventId is not null && _ledger.FindEvent(durableReportEventId) is { } reportEvent) + { + reportEventStateBeforeDispatch = reportEvent.State; + reportEventMarkedDispatching = _ledger.TrySetEventState(durableReportEventId, "dispatching"); + } + if (durableReportEventId is not null && !reportEventMarkedDispatching) + { + missingDurableReportEvent = true; + return false; + } + var reason = force ? forcedReason ?? "manual_resume" : evaluation.Reason; + evaluation = evaluation with { ShouldTrigger = true, Reason = reason }; + sendWake = batch.WakePolicy == CollabBatchWakePolicy.IdleOnly; + wakeDeliveryId = sendWake ? _ledger.NextId("bwake") : null; + batch.WakeDeliveryId = wakeDeliveryId; + _ledger.MarkBatchTriggered(batch, reason); + return true; + }, + rollbackLocked: () => { if (reportEventMarkedDispatching) { @@ -4531,13 +4546,28 @@ private async Task TrySettleBatchAsync( batch.SettledAt = null; batch.WakeDeliveryId = null; _ledger.Touch(batch); + }, + onCommittedLocked: () => + { + if (sendWake) + { + _batchWakeAttemptsInFlight.Add(batch.BatchId); + wakeAttemptInFlight = true; + } + }, + out var staged); + + if (!staged) + { + if (missingDurableReportEvent) + { + return new BatchSettlementResult(false, false, false, true, null, evaluation with { ShouldTrigger = true }, false); } - return new BatchSettlementResult(false, false, false, true, null, evaluation with { ShouldTrigger = true }, false); + return new BatchSettlementResult(alreadyTriggered, false, false, false, existingWakeDeliveryId, evaluation, false); } - if (sendWake) + if (!committed) { - lock (_ledger.Gate) _batchWakeAttemptsInFlight.Add(batch.BatchId); - wakeAttemptInFlight = true; + return new BatchSettlementResult(false, false, false, true, null, evaluation with { ShouldTrigger = true }, false); } } diff --git a/src/Octopus.App/Collab/Ledger/CollabLedger.cs b/src/Octopus.App/Collab/Ledger/CollabLedger.cs index 74d38ab8..68e8cb77 100644 --- a/src/Octopus.App/Collab/Ledger/CollabLedger.cs +++ b/src/Octopus.App/Collab/Ledger/CollabLedger.cs @@ -2149,11 +2149,78 @@ public void SchedulePersist() public bool Flush() => FlushCore(isDisposing: false, requiredBatchId: null); /// - /// Writes dirty state synchronously and verifies that was included in the - /// persisted snapshot rather than evicted by finished-batch retention. + /// Writes dirty state synchronously only if 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. /// public bool FlushBatch(string batchId) => FlushCore(isDisposing: false, requiredBatchId: batchId); + /// + /// Atomically stages a batch transition under while holding 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 included in the snapshot or rolls back under + /// . Slow JSON serialization and store I/O run outside . + /// + public bool TryCommitBatchTransition( + string batchId, + Func stageLocked, + Action rollbackLocked, + Action? onCommittedLocked, + out bool staged) + { + staged = false; + lock (_persistGate) + { + CollabLedgerDocument doc; + long snapshotVersion; + HashSet 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; @@ -2177,6 +2244,10 @@ private bool FlushCore(bool isDisposing, string? requiredBatchId = null) 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. @@ -2187,43 +2258,53 @@ private bool FlushCore(bool isDisposing, string? requiredBatchId = null) { if (saved) { - if (snapshotVersion > _persistedVersion) _persistedVersion = snapshotVersion; - _persistedBatchIds = snapshotBatchIds; - _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 && (requiredBatchId is null || snapshotBatchIds.Contains(requiredBatchId)); + return saved; + } + } + + private void RecordPersistSuccessLocked(long snapshotVersion, HashSet 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)); + } } } diff --git a/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs b/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs index ccc278e8..40684eee 100644 --- a/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs +++ b/tests/Octopus.App.Tests/CollabBatchLedgerTests.cs @@ -630,6 +630,230 @@ public void Finished_batch_retention_keeps_recently_settled_older_batches_and_su } } + [Fact] + public void FlushBatch_cap_miss_preserves_previously_persisted_sealed_batch_and_keyed_event_without_overwriting_disk() + { + using var paths = NewPaths(); + var store = new CollabStateStore(paths); + string eventId; + string snapshotBeforeMiss; + + using (var ledger = new CollabLedger(store)) + { + CollabBatchRecord sealedBatch; + lock (ledger.Gate) + { + sealedBatch = NewBatch("batch-sealed-preserve"); + ledger.AddBatch(sealedBatch); + ledger.AddBatchMember(sealedBatch, NewMember("task-preserve", "worker-a")); + ledger.SealBatch(sealedBatch, 1); + + var evt = ledger.AppendEvent( + ownerItemId: "owner", + actorItemId: "worker-a", + kind: "report", + threadId: "thread-preserve", + taskId: "task-preserve", + deliveryId: "del-preserve", + state: "recorded", + payload: """{"message_id":"msg-1"}""", + tool: "reply_thread", + idempotencyKey: "key-preserve"); + eventId = evt.EventId; + } + Assert.True(ledger.Flush()); + snapshotBeforeMiss = File.ReadAllText(store.FilePath); + + lock (ledger.Gate) + { + Assert.True(ledger.TrySetEventState(eventId, "dispatching")); + sealedBatch.WakeDeliveryId = "bwake-displaced"; + ledger.MarkBatchTriggered(sealedBatch, "all_members_settled"); + + for (var i = 0; i < 200; i++) + { + var newer = NewBatch($"batch-cap-newer-{i:D3}"); + ledger.AddBatch(newer); + ledger.MarkBatchTriggered(newer, "all_members_settled"); + } + } + + Assert.False(ledger.FlushBatch("batch-sealed-preserve")); + Assert.Equal(snapshotBeforeMiss, File.ReadAllText(store.FilePath)); + + using (var reloadedAfterMiss = new CollabLedger(store)) + { + reloadedAfterMiss.Restore(); + var restoredBatch = reloadedAfterMiss.FindBatch("batch-sealed-preserve"); + Assert.NotNull(restoredBatch); + Assert.Equal(CollabBatchState.Sealed, restoredBatch.State); + Assert.False(restoredBatch.Triggered); + Assert.Null(restoredBatch.WakeDeliveryId); + var restoredEvent = reloadedAfterMiss.FindEvent(eventId); + Assert.NotNull(restoredEvent); + Assert.Equal("recorded", restoredEvent.State); + } + + // A subsequent FlushBatch for an included newer batch still saves cleanly within the 200-finished cap. + Assert.True(ledger.FlushBatch("batch-cap-newer-199")); + } + + using var finalReload = new CollabLedger(store); + finalReload.Restore(); + Assert.Equal(200, finalReload.Batches.Values.Count(b => b.IsFinished)); + Assert.NotNull(finalReload.FindBatch("batch-cap-newer-199")); + } + + [Fact] + public void TryCommitBatchTransition_rolls_back_atomically_under_persist_gate_on_cap_miss_and_store_failure() + { + using var paths = NewPaths(); + var store = new CollabStateStore(paths); + using var ledger = new CollabLedger(store); + + CollabBatchRecord sealedBatch; + string eventId; + lock (ledger.Gate) + { + sealedBatch = NewBatch("batch-atomic-transition"); + ledger.AddBatch(sealedBatch); + ledger.AddBatchMember(sealedBatch, NewMember("task-atomic", "worker-a")); + ledger.SealBatch(sealedBatch, 1); + eventId = ledger.AppendEvent( + ownerItemId: "owner", + actorItemId: "worker-a", + kind: "report", + threadId: "thread-atomic", + taskId: "task-atomic", + deliveryId: "del-atomic", + state: "recorded", + payload: """{"message_id":"msg-atomic"}""", + tool: "reply_thread", + idempotencyKey: "key-atomic").EventId; + } + Assert.True(ledger.Flush()); + var baselineBytes = File.ReadAllText(store.FilePath); + + // 1. Cap-miss rejection leaves disk untouched and rolls back batch + event before releasing persist gate. + lock (ledger.Gate) + { + var highBase = ledger.LatestEventSeq + 1000; + for (var i = 0; i < 200; i++) + { + var newer = NewBatch($"batch-atomic-newer-{i:D3}"); + newer.State = CollabBatchState.Settled; + newer.Triggered = true; + newer.SettledAt = DateTimeOffset.UtcNow; + newer.UpdatedSeq = highBase + i; + ledger.Batches[newer.BatchId] = newer; + } + } + var committed = false; + var capOk = ledger.TryCommitBatchTransition( + sealedBatch.BatchId, + stageLocked: () => + { + Assert.True(ledger.TrySetEventState(eventId, "dispatching")); + sealedBatch.WakeDeliveryId = "bwake-cap"; + ledger.MarkBatchTriggered(sealedBatch, "manual_resume"); + return true; + }, + rollbackLocked: () => + { + Assert.True(ledger.TrySetEventState(eventId, "recorded")); + sealedBatch.Triggered = false; + sealedBatch.TriggeredReason = null; + sealedBatch.State = CollabBatchState.Sealed; + sealedBatch.SettledAt = null; + sealedBatch.WakeDeliveryId = null; + ledger.Touch(sealedBatch); + }, + onCommittedLocked: () => committed = true, + out var staged); + Assert.True(staged); + Assert.False(capOk); + Assert.False(committed); + Assert.Equal(baselineBytes, File.ReadAllText(store.FilePath)); + + // 2. Store write failure also rolls back before releasing persist gate so a subsequent Flush never leaks staged state. + var realData = paths.DataDirectory; + var blocked = Path.Combine(realData, "blocked"); + Directory.CreateDirectory(blocked); + File.WriteAllText(Path.Combine(blocked, "collab"), "not a directory"); + paths.DataDirectory = blocked; + + lock (ledger.Gate) + { + // Advance past the 200 seeded finished batches so the candidate snapshot includes sealedBatch, isolating store failure. + typeof(CollabLedger) + .GetField("_eventSeq", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! + .SetValue(ledger, ledger.LatestEventSeq + 2000); + } + + var saveOk = ledger.TryCommitBatchTransition( + sealedBatch.BatchId, + stageLocked: () => + { + Assert.True(ledger.TrySetEventState(eventId, "dispatching")); + sealedBatch.WakeDeliveryId = "bwake-outage"; + ledger.MarkBatchTriggered(sealedBatch, "manual_resume"); + return true; + }, + rollbackLocked: () => + { + Assert.True(ledger.TrySetEventState(eventId, "recorded")); + sealedBatch.Triggered = false; + sealedBatch.TriggeredReason = null; + sealedBatch.State = CollabBatchState.Sealed; + sealedBatch.SettledAt = null; + sealedBatch.WakeDeliveryId = null; + ledger.Touch(sealedBatch); + }, + onCommittedLocked: () => committed = true, + out var outageStaged); + Assert.True(outageStaged); + Assert.False(saveOk); + Assert.False(committed); + + paths.DataDirectory = realData; + Assert.True(ledger.Flush()); + using (var afterOutage = new CollabLedger(store)) + { + afterOutage.Restore(); + var restoredBatch = afterOutage.FindBatch(sealedBatch.BatchId); + Assert.NotNull(restoredBatch); + Assert.Equal(CollabBatchState.Sealed, restoredBatch.State); + Assert.False(restoredBatch.Triggered); + Assert.Null(restoredBatch.WakeDeliveryId); + Assert.Equal("recorded", afterOutage.FindEvent(eventId)?.State); + } + + // 3. Retry succeeds cleanly once storage is healthy and persists within the 200-finished cap. + var retryOk = ledger.TryCommitBatchTransition( + sealedBatch.BatchId, + stageLocked: () => + { + Assert.True(ledger.TrySetEventState(eventId, "dispatching")); + sealedBatch.WakeDeliveryId = "bwake-retry-ok"; + ledger.MarkBatchTriggered(sealedBatch, "manual_resume"); + return true; + }, + rollbackLocked: () => throw new InvalidOperationException("Should not roll back on healthy save."), + onCommittedLocked: () => committed = true, + out var retryStaged); + Assert.True(retryStaged); + Assert.True(retryOk); + Assert.True(committed); + + using var afterRetry = new CollabLedger(store); + afterRetry.Restore(); + Assert.Equal(200, afterRetry.Batches.Values.Count(b => b.IsFinished)); + var finalBatch = afterRetry.FindBatch(sealedBatch.BatchId); + Assert.NotNull(finalBatch); + Assert.True(finalBatch.Triggered); + Assert.Equal("bwake-retry-ok", finalBatch.WakeDeliveryId); + } + [Fact] public void Existing_c1_records_and_batch_one_shot_state_survive_restart_together() { diff --git a/tests/Octopus.App.Tests/CollabBatchManualTests.cs b/tests/Octopus.App.Tests/CollabBatchManualTests.cs index fd4994b8..505e4233 100644 --- a/tests/Octopus.App.Tests/CollabBatchManualTests.cs +++ b/tests/Octopus.App.Tests/CollabBatchManualTests.cs @@ -803,4 +803,255 @@ public async Task A_long_lived_manual_batch_handles_flush_failure_truthfully_wit Assert.Equal("delivered", replay["wake_delivery_state"]!.GetValue()); Assert.Empty(fresh.DeliveredPrompts); } + + private static CollabLedger LedgerOf(CollabCoordinator coordinator) => + (CollabLedger)typeof(CollabCoordinator) + .GetField("_ledger", BindingFlags.NonPublic | BindingFlags.Instance)! + .GetValue(coordinator)!; + + private static long Seed200HigherSequenceFinishedBatchesLocked(CollabLedger ledger, string ownerItemId, DateTimeOffset oldCreatedAt, string prefix) + { + var baseSeq = ledger.LatestEventSeq + 1000; + for (var i = 0; i < 200; i++) + { + var createdAt = oldCreatedAt.AddTicks((i + 1) * 10); + var newer = new CollabBatchRecord + { + BatchId = $"{prefix}_{i:D3}", + CallerItemId = ownerItemId, + Title = $"Cap collider {i}", + JoinPolicy = CollabBatchJoinPolicy.All, + WakePolicy = CollabBatchWakePolicy.IdleOnly, + State = CollabBatchState.Settled, + ExpectedMemberCount = 1, + CreatedAt = createdAt, + SealedAt = createdAt, + SettledAt = createdAt, + Triggered = true, + TriggeredReason = "all_members_settled", + WakeDeliveryId = $"bwake_{prefix}_{i:D3}", + WakeDeliveryState = "delivered", + UpdatedSeq = baseSeq + i, + }; + ledger.Batches[newer.BatchId] = newer; + } + return baseSeq + 200; + } + + private static void AdvanceEventSeqLocked(CollabLedger ledger, long targetSeq) + { + var field = typeof(CollabLedger).GetField("_eventSeq", BindingFlags.NonPublic | BindingFlags.Instance)!; + var current = (long)field.GetValue(ledger)!; + if (targetSeq > current) field.SetValue(ledger, targetSeq); + } + + [AvaloniaFact, FreshApp] + public async Task A_manual_resume_cap_miss_preserves_previously_persisted_sealed_batch_on_disk_and_retries_cleanly() + { + var ct = TestContext.Current.CancellationToken; + using var paths = new TempPaths(Directory.CreateTempSubdirectory("octopus-0c-batch-manual-cap-miss-").FullName); + var store = new CollabStateStore(paths); + var f = await CreateAsync(1, store); + var batchId = await OpenManualAsync(f.Coordinator, f.Parent, ct); + var task = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Manual cap-miss work.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + await ReportAsync(f.Coordinator, f.Workers[0], task["thread_id"]!.GetValue(), "Cap-miss manual result.", "agreed", ct); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + var ledger = LedgerOf(f.Coordinator); + long highSeq; + lock (ledger.Gate) + { + highSeq = Seed200HigherSequenceFinishedBatchesLocked(ledger, f.Parent.Id, ledger.FindBatch(batchId)!.CreatedAt, "batch_manual_cap"); + } + + // First resume misses the 200-finished cap in the candidate snapshot: must fail without wake and keep sealed on disk. + var missed = await ResumeAsync(f.Coordinator, f.Parent, batchId, ct); + Assert.True(missed["isError"]?.GetValue() ?? false, Message(missed)); + Assert.Contains("could not be saved", Message(missed), StringComparison.OrdinalIgnoreCase); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + // Reload the actual persisted snapshot immediately (simulating crash before any later flush). + using (var reloadedAfterMiss = new CollabLedger(store)) + { + reloadedAfterMiss.Restore(); + var persisted = reloadedAfterMiss.FindBatch(batchId); + Assert.NotNull(persisted); + Assert.Equal(CollabBatchState.Sealed, persisted.State); + Assert.False(persisted.Triggered); + Assert.Null(persisted.WakeDeliveryId); + } + + // Even if a subsequent shared Flush runs after rollback, the batch stays sealed (never leaks Settled). + Assert.True(ledger.Flush()); + using (var reloadedAfterFlush = new CollabLedger(store)) + { + reloadedAfterFlush.Restore(); + var persisted = reloadedAfterFlush.FindBatch(batchId); + Assert.NotNull(persisted); + Assert.Equal(CollabBatchState.Sealed, persisted.State); + Assert.False(persisted.Triggered); + } + + // Once sequence is monotonic past the 200 finished batches, retry succeeds with one wake and persists receipt. + lock (ledger.Gate) + { + AdvanceEventSeqLocked(ledger, highSeq); + } + var retried = Body(await ResumeAsync(f.Coordinator, f.Parent, batchId, ct)); + Assert.True(retried["triggered"]!.GetValue()); + Assert.Equal("settled", retried["state"]!.GetValue()); + Assert.Equal("delivered", retried["delivery"]!.GetValue()); + var wakeDeliveryId = retried["wake_delivery"]!.GetValue(); + Assert.StartsWith("bwake_", wakeDeliveryId, StringComparison.Ordinal); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains("Cap-miss manual result.", prompt, StringComparison.Ordinal); + f.Coordinator.Dispose(); + + using (var restoredLedger = new CollabLedger(store)) + { + restoredLedger.Restore(); + Assert.Equal(200, restoredLedger.Batches.Values.Count(b => b.IsFinished)); + var saved = restoredLedger.FindBatch(batchId); + Assert.NotNull(saved); + Assert.True(saved.Triggered); + Assert.Equal(wakeDeliveryId, saved.WakeDeliveryId); + Assert.Equal("delivered", saved.WakeDeliveryState); + } + + var reopened = new CollabCoordinator( + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + AppHost.Get(), + new CollabMcpServer(), + store: store); + reopened.Server.Start(); + using var _ = reopened; + var fresh = new RecordingBridge(f.Parent.Id, "claude", f.Parent.Title, f.Project.Path); + reopened.RegisterGuiSession(fresh); + + var replay = Body(await ResumeAsync(reopened, f.Parent, batchId, ct)); + Assert.True(replay["deduplicated"]!.GetValue()); + Assert.Equal(wakeDeliveryId, replay["wake_delivery"]!.GetValue()); + Assert.Equal("delivered", replay["wake_delivery_state"]!.GetValue()); + Assert.Empty(fresh.DeliveredPrompts); + } + + [AvaloniaFact, FreshApp] + public async Task A_keyed_automatic_report_cap_miss_preserves_sealed_batch_and_recorded_marker_and_retries_cleanly() + { + var ct = TestContext.Current.CancellationToken; + using var paths = new TempPaths(Directory.CreateTempSubdirectory("octopus-0c-batch-keyed-cap-miss-").FullName); + var store = new CollabStateStore(paths); + var f = await CreateAsync(1, store); + var opened = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, + "batch_open", + new JsonObject { ["title"] = "Auto keyed wave", ["join_policy"] = "all", ["wake_policy"] = "idle_only" }, + ct)); + var batchId = opened["batch_id"]!.GetValue(); + var task = await DelegateAsync(f.Coordinator, f.Parent, f.Workers[0], "Auto keyed work.", batchId, ct); + await f.Coordinator.CallToolAsync(f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct); + + var ledger = LedgerOf(f.Coordinator); + long highSeq; + lock (ledger.Gate) + { + highSeq = Seed200HigherSequenceFinishedBatchesLocked(ledger, f.Parent.Id, ledger.FindBatch(batchId)!.CreatedAt, "batch_keyed_cap"); + } + + // First: direct TrySettleBatchAsync crash-window check with a persisted "recorded" keyed report event. + string directEventId; + CollabBatchRecord batchRecord; + lock (ledger.Gate) + { + batchRecord = ledger.FindBatch(batchId)!; + var evt = ledger.AppendEvent( + ownerItemId: f.Parent.Id, + actorItemId: f.Workers[0].Id, + kind: "report", + threadId: task["thread_id"]!.GetValue(), + taskId: task["task_id"]!.GetValue(), + deliveryId: "del_direct_cap_miss", + state: "recorded", + payload: """{"message_id":"msg_direct"}""", + tool: "reply_thread", + idempotencyKey: "direct-cap-miss-key"); + directEventId = evt.EventId; + } + Assert.True(ledger.Flush()); + + var trySettle = typeof(CollabCoordinator).GetMethod("TrySettleBatchAsync", BindingFlags.NonPublic | BindingFlags.Instance)!; + var directTask = (Task)trySettle.Invoke(f.Coordinator, [batchRecord, directEventId, ct, true, "all_members_settled", null])!; + await directTask; + var directResult = directTask.GetType().GetProperty("Result")!.GetValue(directTask)!; + Assert.True((bool)directResult.GetType().GetProperty("SaveFailed")!.GetValue(directResult)!); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + using (var reloadedDirect = new CollabLedger(store)) + { + reloadedDirect.Restore(); + var restoredBatch = reloadedDirect.FindBatch(batchId); + Assert.NotNull(restoredBatch); + Assert.Equal(CollabBatchState.Sealed, restoredBatch.State); + Assert.False(restoredBatch.Triggered); + var restoredEvent = reloadedDirect.FindEvent(directEventId); + Assert.NotNull(restoredEvent); + Assert.Equal("recorded", restoredEvent.State); + } + + // Second: full public keyed reply_thread hitting cap miss during settlement, followed by normal batch_seal retry. + var keyedReport = Body(await f.Coordinator.CallToolAsync( + f.Workers[0].Id, + "reply_thread", + new JsonObject + { + ["thread_id"] = task["thread_id"]!.GetValue(), + ["message"] = "Keyed report under cap miss.", + ["status"] = "agreed", + ["idempotency_key"] = "keyed-cap-miss-public", + }, + ct)); + Assert.Equal("batched_pending_seal", keyedReport["delivery"]!.GetValue()); + var publicEventId = keyedReport["event_id"]!.GetValue(); + Assert.Empty(f.ParentBridge.DeliveredPrompts); + + using (var reloadedPublic = new CollabLedger(store)) + { + reloadedPublic.Restore(); + var restoredBatch = reloadedPublic.FindBatch(batchId); + Assert.NotNull(restoredBatch); + Assert.Equal(CollabBatchState.Sealed, restoredBatch.State); + Assert.False(restoredBatch.Triggered); + var restoredEvent = reloadedPublic.FindEvent(publicEventId); + Assert.NotNull(restoredEvent); + Assert.Equal("recorded", restoredEvent.State); + } + + // Restore monotonic sequence and retry settlement via keyless batch_seal -> exactly one aggregate wake. + lock (ledger.Gate) + { + AdvanceEventSeqLocked(ledger, highSeq); + } + var settled = Body(await f.Coordinator.CallToolAsync( + f.Parent.Id, "batch_seal", new JsonObject { ["batch_id"] = batchId }, ct)); + Assert.True(settled["triggered"]!.GetValue()); + Assert.Equal("settled", settled["state"]!.GetValue()); + Assert.Equal("delivered", settled["delivery"]!.GetValue()); + var wakeDeliveryId = settled["wake_delivery"]!.GetValue(); + Assert.StartsWith("bwake_", wakeDeliveryId, StringComparison.Ordinal); + var prompt = Assert.Single(f.ParentBridge.DeliveredPrompts); + Assert.Contains("Keyed report under cap miss.", prompt, StringComparison.Ordinal); + f.Coordinator.Dispose(); + + using var finalLedger = new CollabLedger(store); + finalLedger.Restore(); + Assert.Equal(200, finalLedger.Batches.Values.Count(b => b.IsFinished)); + var finalBatch = finalLedger.FindBatch(batchId); + Assert.NotNull(finalBatch); + Assert.True(finalBatch.Triggered); + Assert.Equal(wakeDeliveryId, finalBatch.WakeDeliveryId); + Assert.Equal("delivered", finalBatch.WakeDeliveryState); + } }