Drain intents through one class: attempt marker, enable epoch, per-tick bound

BrokkrCommandDrain owns every rule between a pending intent and its receipt.
The service and the scenario harness now run the same drain instead of two
copies of the loop.

- An "attempted" receipt is written and flushed before Execute. A crash or a
  failing final receipt write can no longer re-run an intent; the next drain
  rewrites a leftover marker as "interrupted" and the operator decides.
- The host snapshot carries the sink's enable epoch. Intents stored before the
  latest enable get an "expired" receipt and never run (operator ruling
  2026-09-30).
- One drain handles at most 16 intents, expired and denied ones included.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-29 16:16:41 +02:00
commit c694f582c2
9 changed files with 432 additions and 49 deletions

View file

@ -0,0 +1,192 @@
using GameCult.Brokkr;
using GameCult.Caching;
namespace Brokkr.Contracts.Tests;
// The rules BrokkrCommandDrain owns, through the same drain the editor service runs, over a real directory store.
public sealed class BrokkrCommandDrainTests
{
private static BrokkrUnityCommandReceipt[] Receipts(ScratchProject project)
{
using var audit = project.OpenCache();
return audit.AllStoredDocuments.Select(entry => entry.Document).OfType<BrokkrUnityCommandReceipt>().ToArray();
}
private static string StatusOf(ScratchProject project, string commandId) =>
Receipts(project).Single(receipt => receipt.commandId == commandId).status;
[Fact]
public async Task IntentStoredBeforeTheSinkWasEnabledExpiresAndNeverRuns()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.AgentCommandsEnabled = false;
await project.WriteCommandAsync("written-while-off");
await editor.TickAsync();
Assert.Empty(editor.Executed);
await Task.Delay(30);
editor.EnabledAt = DateTimeOffset.UtcNow;
editor.AgentCommandsEnabled = true;
await Task.Delay(30);
await project.WriteCommandAsync("written-after-enable");
await editor.TickAsync();
await editor.TickAsync();
Assert.Equal(new[] { "written-after-enable" }, editor.Executed.Select(command => command.commandId));
Assert.Equal("expired", StatusOf(project, "written-while-off"));
Assert.Equal("accepted", StatusOf(project, "written-after-enable"));
}
[Fact]
public async Task ReEnablingExpiresWhatWaitedThroughTheOffPeriod()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.EnabledAt = DateTimeOffset.UtcNow;
await Task.Delay(30);
await project.WriteCommandAsync("ran-while-on");
await editor.TickAsync();
editor.AgentCommandsEnabled = false;
await Task.Delay(30);
await project.WriteCommandAsync("waited-while-off");
await Task.Delay(30);
editor.EnabledAt = DateTimeOffset.UtcNow;
editor.AgentCommandsEnabled = true;
await editor.TickAsync();
Assert.Equal(new[] { "ran-while-on" }, editor.Executed.Select(command => command.commandId));
Assert.Equal("expired", StatusOf(project, "waited-while-off"));
}
[Fact]
public async Task AttemptReceiptIsDurableBeforeTheExecutorRuns()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
string? seenByAnotherProcess = null;
editor.OnExecute = command => seenByAnotherProcess = Receipts(project)
.SingleOrDefault(receipt => receipt.commandId == command.commandId)?.status;
await project.WriteCommandAsync("marked");
await editor.TickAsync();
Assert.Equal("attempted", seenByAnotherProcess);
Assert.Equal("accepted", StatusOf(project, "marked"));
}
[Fact]
public async Task CrashDuringExecutionNeverRerunsTheIntentAndReportsItInterrupted()
{
using var project = new ScratchProject();
await project.WriteCommandAsync("crashy");
var firstRun = await EditorProbe.StartAsync(project.StorePath);
firstRun.OnExecute = _ => throw new InvalidOperationException("the editor died");
await Assert.ThrowsAsync<InvalidOperationException>(firstRun.TickAsync);
firstRun.Dispose();
await project.WriteCommandAsync("bystander");
using var restarted = await EditorProbe.StartAsync(project.StorePath);
for (var tick = 0; tick < 5; tick++)
await restarted.TickAsync();
Assert.Equal(new[] { "bystander" }, restarted.Executed.Select(command => command.commandId));
Assert.Equal("interrupted", StatusOf(project, "crashy"));
}
[Fact]
public async Task FailingFinalReceiptWriteNeverRerunsTheIntent()
{
// A receipt write that throws every second must not turn createGameObject into one object per second.
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.FailReceiptWrite = receipt => receipt.status == "accepted";
await project.WriteCommandAsync("unlucky");
await Assert.ThrowsAsync<IOException>(editor.TickAsync);
for (var tick = 0; tick < 5; tick++)
{
try { await editor.TickAsync(); } catch (IOException) { }
}
Assert.Single(editor.Executed);
editor.FailReceiptWrite = null;
await editor.TickAsync();
Assert.Single(editor.Executed);
Assert.Equal("interrupted", StatusOf(project, "unlucky"));
}
[Fact]
public async Task FailingAttemptWriteExecutesNothing()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.FailReceiptWrite = receipt => receipt.status == "attempted";
await project.WriteCommandAsync("unmarked");
await Assert.ThrowsAsync<IOException>(editor.TickAsync);
Assert.Empty(editor.Executed);
}
[Fact]
public async Task OneTickHandlesAtMostTheBoundAndTheRestWaits()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
var total = BrokkrCommandDrain.MaxPerTick * 2 + 3;
for (var index = 0; index < total; index++)
await project.WriteCommandAsync($"flood-{index}");
var first = await editor.TickAsync();
Assert.Equal(BrokkrCommandDrain.MaxPerTick, first);
Assert.Equal(BrokkrCommandDrain.MaxPerTick, editor.Executed.Count);
while (await editor.TickAsync() > 0) { }
Assert.Equal(total, editor.Executed.Count);
Assert.Equal(total, editor.Executed.Select(command => command.commandId).Distinct().Count());
}
[Fact]
public async Task ExpiredIntentsCountTowardTheBoundToo()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
for (var index = 0; index < BrokkrCommandDrain.MaxPerTick + 4; index++)
await project.WriteCommandAsync($"stale-{index}");
await Task.Delay(30);
editor.EnabledAt = DateTimeOffset.UtcNow;
Assert.Equal(BrokkrCommandDrain.MaxPerTick, await editor.TickAsync());
Assert.Equal(4, await editor.TickAsync());
Assert.Empty(editor.Executed);
}
[Fact]
public async Task DisallowedActionIsDeniedAndNeverExecuted()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
await project.WriteCommandAsync("nope", "saveScene");
await editor.TickAsync();
Assert.Empty(editor.Executed);
Assert.Equal("denied", StatusOf(project, "nope"));
}
[Fact]
public async Task SinkOffExecutesNothingAndAnswersNothing()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.AgentCommandsEnabled = false;
await project.WriteCommandAsync("waiting");
await editor.TickAsync();
Assert.Empty(editor.Executed);
Assert.Empty(Receipts(project));
}
}

View file

@ -8,12 +8,17 @@ namespace Brokkr.Contracts.Tests;
// The scenario harness: an editor without Unity. It opens the store exactly as BrokkrCultMeshMirror does (a CultMesh
// node with StartServer=false over a directory store and durable shard logs) and runs one service tick in the
// service order: pull, drain pending intents through the ledger, receipt, soft flush, host snapshot, soft flush.
// "Executing" an intent only records it, so the scenarios measure delivery and once-only execution, not Unity.
// service order: pull, drain pending intents through BrokkrCommandDrain (the same class the service uses), host
// snapshot, soft flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only
// execution, not Unity.
internal sealed class EditorProbe : IDisposable
{
private readonly CultMeshNode node;
private readonly BrokkrCommandLedger ledger;
private readonly BrokkrCommandPolicy policy = new("probe", BrokkrCommandPolicy.DefaultAllowedActions.Concat(new[]
{
"createPrefabVariant", "createScriptableObject"
}));
internal List<BrokkrUnityCommand> Executed { get; } = new();
@ -23,6 +28,15 @@ internal sealed class EditorProbe : IDisposable
// What the host snapshot says about the sink; the real editor reports the operator's toggle.
internal bool AgentCommandsEnabled { get; set; } = true;
// When the operator last enabled the sink; intents stored earlier expire.
internal DateTimeOffset EnabledAt { get; set; } = DateTimeOffset.MinValue;
// Runs inside the "executor", after the intent is recorded.
internal Action<BrokkrUnityCommand>? OnExecute { get; set; }
// Makes a receipt write throw, as a full disk or a lease timeout would.
internal Func<BrokkrUnityCommandReceipt, bool>? FailReceiptWrite { get; set; }
private EditorProbe(CultMeshNode node)
{
this.node = node;
@ -42,33 +56,50 @@ internal sealed class EditorProbe : IDisposable
return new EditorProbe(node);
}
internal async Task TickAsync()
// Returns how many intents the drain answered.
internal async Task<int> TickAsync()
{
await ledger.PullAsync();
var drained = 0;
while (ledger.TryNextPending(out var command))
var handled = 0;
if (AgentCommandsEnabled)
{
if (++drained > 10000)
throw new InvalidOperationException("The ledger keeps offering answered intents; a regression would otherwise hang the suite.");
Executed.Add(command);
await node.Database.PutAsync(
BrokkrCommandLedger.ReceiptKey(command.commandId),
new BrokkrUnityCommandReceipt
await ledger.PullAsync();
var drain = new BrokkrCommandDrain(
ledger,
policy,
command =>
{
commandId = command.commandId,
status = StatusFor(command),
message = "probe",
observedAt = DateTime.UtcNow.ToString("O")
Executed.Add(command);
OnExecute?.Invoke(command);
return new BrokkrUnityCommandReceipt
{
commandId = command.commandId,
status = StatusFor(command),
message = "probe",
observedAt = DateTime.UtcNow.ToString("O")
};
},
async receipt =>
{
if (FailReceiptWrite?.Invoke(receipt) == true)
throw new IOException("receipt write failed");
await node.Database.PutAsync(BrokkrCommandLedger.ReceiptKey(receipt.commandId), receipt);
await node.FlushAsync(soft: true);
});
await node.FlushAsync(soft: true);
handled = await drain.DrainAsync(EnabledAt);
}
await node.Database.PutAsync(
new CultRecordKey("unity/host/current"),
new BrokkrHostSnapshot { observedAt = DateTime.UtcNow.ToString("O"), projectPath = "probe", agentCommandsEnabled = AgentCommandsEnabled });
new BrokkrHostSnapshot
{
observedAt = DateTime.UtcNow.ToString("O"),
projectPath = "probe",
agentCommandsEnabled = AgentCommandsEnabled,
agentCommandsEnabledAt = AgentCommandsEnabled ? EnabledAt.ToString("O") : ""
});
await node.FlushAsync(soft: true);
return handled;
}
public void Dispose() => node.Dispose();
}

View file

@ -8,7 +8,7 @@ namespace GameCult.Brokkr.Editor
{
// The only owner of command execution in the editor. It owns the mirror, the pull cadence and the drain; the
// window is a caller (it writes intents) and a display (it reads state from here). Nothing else calls
// BrokkrCommandLedger.TryNextPending or BrokkrUnityCommandExecutor.Execute.
// BrokkrCommandLedger.TryNextPending or BrokkrUnityCommandExecutor.Execute (both go through BrokkrCommandDrain).
//
// The command sink is off until the operator enables it for this project (BrokkrSettings.AgentCommandsEnabled).
// Loading the package opens no store and executes nothing.
@ -73,12 +73,19 @@ namespace GameCult.Brokkr.Editor
await PublishSnapshotAsync();
}
internal static async Task PublishSnapshotAsync()
// The only writer of unity/host/current. It captures fresh every time, so the published flags always
// describe the editor now; the window asks for a publish and never carries a snapshot of its own to the
// store. Returns what it published, or null when the mirror is not running.
internal static async Task<BrokkrHostSnapshot> PublishSnapshotAsync()
{
if (MirrorInstance.IsRunning)
if (!MirrorInstance.IsRunning)
{
await MirrorInstance.PublishSnapshotAsync(BrokkrUnitySnapshotBuilder.Capture());
return null;
}
var snapshot = BrokkrUnitySnapshotBuilder.Capture();
await MirrorInstance.PublishSnapshotAsync(snapshot);
return snapshot;
}
private static void Tick()
@ -93,7 +100,8 @@ namespace GameCult.Brokkr.Editor
LastSyncReceipt = syncReceipt;
}
if (!BrokkrSettings.AgentCommandsEnabled || EditorApplication.timeSinceStartup < nextPullAt)
var enabledSince = BrokkrSettings.AgentCommandsEnabledSince;
if (enabledSince == null || EditorApplication.timeSinceStartup < nextPullAt)
{
return;
}
@ -102,7 +110,7 @@ namespace GameCult.Brokkr.Editor
try
{
MirrorInstance.PullExternalUpdatesAsync().GetAwaiter().GetResult();
DrainCommands();
DrainCommands(enabledSince.Value);
}
catch (Exception error)
{
@ -110,26 +118,17 @@ namespace GameCult.Brokkr.Editor
}
}
private static void DrainCommands()
// Every rule about whether and when an intent runs lives in BrokkrCommandDrain; this only supplies the
// executor and the receipt writer.
private static void DrainCommands(DateTimeOffset enabledSince)
{
var projectRoot = Directory.GetParent(Application.dataPath)?.FullName ?? Application.dataPath;
var policy = new BrokkrCommandPolicy(projectRoot, BrokkrSettings.AllowedAgentActions);
var drained = false;
while (MirrorInstance.Ledger.TryNextPending(out var command))
{
// The one call path into the executor, and admission is its precondition.
var admission = policy.Decide(command);
var receipt = admission.Allowed
? BrokkrUnityCommandExecutor.Execute(command)
: admission.DeniedReceipt(command);
// The receipt answers exactly the id it ran, or the ledger would offer the intent again.
receipt.commandId = command.commandId;
receipt.requestedBy = command.requestedBy;
MirrorInstance.PublishReceiptAsync(receipt).GetAwaiter().GetResult();
drained = true;
}
if (drained)
var drain = new BrokkrCommandDrain(
MirrorInstance.Ledger,
new BrokkrCommandPolicy(projectRoot, BrokkrSettings.AllowedAgentActions),
BrokkrUnityCommandExecutor.Execute,
MirrorInstance.PublishReceiptAsync);
if (drain.DrainAsync(enabledSince).GetAwaiter().GetResult() > 0)
{
PublishSnapshotAsync().GetAwaiter().GetResult();
}

View file

@ -1,3 +1,5 @@
using System;
using System.Globalization;
using System.Linq;
using UnityEditor;
using UnityEngine;
@ -24,10 +26,43 @@ namespace GameCult.Brokkr.Editor
// Whether this editor executes intents that agents write into .brokkr. Off until the operator turns it on.
// EditorPrefs is shared by every project on the machine, so the store path and the flag both key on the project.
// Turning it on stamps the enable epoch; intents stored before that instant never run (BrokkrCommandDrain).
internal static bool AgentCommandsEnabled
{
get => EditorPrefs.GetBool(ProjectKey("AgentCommandsEnabled"), false);
set => EditorPrefs.SetBool(ProjectKey("AgentCommandsEnabled"), value);
set
{
if (value && !AgentCommandsEnabled)
{
EditorPrefs.SetString(ProjectKey("AgentCommandsEnabledAt"), DateTimeOffset.UtcNow.ToString("O"));
}
EditorPrefs.SetBool(ProjectKey("AgentCommandsEnabled"), value);
}
}
// The enable epoch: null while the sink is off. A sink enabled before the epoch was recorded is stamped now,
// so intents already waiting expire rather than run.
internal static DateTimeOffset? AgentCommandsEnabledSince
{
get
{
if (!AgentCommandsEnabled)
{
return null;
}
var key = ProjectKey("AgentCommandsEnabledAt");
if (DateTimeOffset.TryParse(EditorPrefs.GetString(key, ""), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var since))
{
return since;
}
since = DateTimeOffset.UtcNow;
EditorPrefs.SetString(key, since.ToString("O"));
return since;
}
}
private static string ProjectKey(string name) => $"GameCult.Brokkr.{name}.{Application.dataPath}";

View file

@ -45,6 +45,7 @@ namespace GameCult.Brokkr.Editor
.ToArray(),
assetCount = AssetDatabase.GetAllAssetPaths().Length,
agentCommandsEnabled = BrokkrSettings.AgentCommandsEnabled,
agentCommandsEnabledAt = BrokkrSettings.AgentCommandsEnabledSince?.ToString("O") ?? "",
isPlaying = EditorApplication.isPlaying,
isPaused = EditorApplication.isPaused,
isCompiling = EditorApplication.isCompiling,

View file

@ -0,0 +1,104 @@
#nullable disable
using System;
using System.Globalization;
using System.Threading.Tasks;
namespace GameCult.Brokkr
{
// The one decision path from a pending intent to a receipt. BrokkrEditorService supplies the executor and the
// receipt writer; the scenario harness supplies fakes. Nothing else may run an intent.
//
// Every intent leaves exactly one of these receipts, and any receipt retires its id (BrokkrCommandLedger):
// expired stored before the sink was last enabled; the operator never saw it, so it never runs
// denied admission refused it
// attempted written and flushed BEFORE execution; it stays only if the editor died or the final receipt
// could not be written, and the next drain rewrites it as interrupted
// interrupted an attempt that did not finish; it is never run again automatically, the operator decides
// accepted / failed / ... the executor's verdict
// A receipt write that fails therefore cannot make an intent run twice: at worst the marker is the answer.
public sealed class BrokkrCommandDrain
{
// The most intents one drain handles, receipts of every kind included. A flood cannot hold the editor's
// update loop; the remainder waits for the next tick.
public const int MaxPerTick = 16;
public const string AttemptedStatus = "attempted";
public const string InterruptedStatus = "interrupted";
public const string ExpiredStatus = "expired";
private readonly BrokkrCommandLedger ledger;
private readonly BrokkrCommandPolicy policy;
private readonly Func<BrokkrUnityCommand, BrokkrUnityCommandReceipt> execute;
private readonly Func<BrokkrUnityCommandReceipt, Task> publishReceipt;
public BrokkrCommandDrain(
BrokkrCommandLedger ledger,
BrokkrCommandPolicy policy,
Func<BrokkrUnityCommand, BrokkrUnityCommandReceipt> execute,
Func<BrokkrUnityCommandReceipt, Task> publishReceipt)
{
this.ledger = ledger ?? throw new ArgumentNullException(nameof(ledger));
this.policy = policy ?? throw new ArgumentNullException(nameof(policy));
this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
this.publishReceipt = publishReceipt ?? throw new ArgumentNullException(nameof(publishReceipt));
}
// sinkEnabledAt is when the operator last turned the sink on. Returns how many intents it answered.
public async Task<int> DrainAsync(DateTimeOffset sinkEnabledAt)
{
// Nothing is in flight at the start of a drain (execution is synchronous inside it), so an attempted
// receipt found here belongs to a run that never finished.
foreach (var attempt in ledger.AttemptedReceipts())
{
await publishReceipt(Receipt(attempt.commandId, attempt.requestedBy, InterruptedStatus,
"The editor stopped, or could not record the result, after starting this intent. It was not run "
+ "again. Check the project, then send a new intent if it should run."));
}
var handled = 0;
while (handled < MaxPerTick && ledger.TryNextPending(out var command, out var storedAt))
{
handled++;
if (!DateTimeOffset.TryParse(storedAt, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var stored)
|| stored < sinkEnabledAt)
{
await publishReceipt(Receipt(command, ExpiredStatus,
"This intent was stored before the command sink was last enabled, so the operator never saw "
+ "it. It was not run."));
continue;
}
var admission = policy.Decide(command);
if (!admission.Allowed)
{
var denied = admission.DeniedReceipt(command);
denied.requestedBy = command.requestedBy;
await publishReceipt(denied);
continue;
}
// Durable before any effect: a crash after this line leaves the marker, never a second run.
await publishReceipt(Receipt(command, AttemptedStatus, "Started; no result recorded yet."));
var receipt = execute(command);
receipt.commandId = command.commandId;
receipt.requestedBy = command.requestedBy;
await publishReceipt(receipt);
}
return handled;
}
private static BrokkrUnityCommandReceipt Receipt(BrokkrUnityCommand command, string status, string message) =>
Receipt(command.commandId, command.requestedBy, status, message);
private static BrokkrUnityCommandReceipt Receipt(string commandId, string requestedBy, string status, string message) =>
new BrokkrUnityCommandReceipt
{
commandId = commandId,
requestedBy = requestedBy,
status = status,
message = message,
observedAt = DateTime.UtcNow.ToString("O")
};
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 082d5a636de44bdbb60d1afa04ed3254

View file

@ -30,7 +30,10 @@ namespace GameCult.Brokkr
public Task PullAsync() => cache.PullAllBackingStoresAsync();
// The oldest unanswered intent by stored-at. Exact ties keep the cache's own order (schema, then key): the sort is stable.
public bool TryNextPending(out BrokkrUnityCommand command)
public bool TryNextPending(out BrokkrUnityCommand command) => TryNextPending(out command, out _);
// storedAt is the cache's own stamp for the intent (round-trip ISO 8601), minted when the writer stored it.
public bool TryNextPending(out BrokkrUnityCommand command, out string storedAt)
{
var stored = cache.AllStoredDocuments.ToArray();
var answered = new HashSet<string>(
@ -39,13 +42,26 @@ namespace GameCult.Brokkr
.Where(id => !string.IsNullOrWhiteSpace(id)),
StringComparer.Ordinal);
command = stored
var next = stored
.Where(entry => entry.Document is BrokkrUnityCommand)
.OrderBy(entry => entry.StoredAt, StringComparer.Ordinal)
.Select(entry => (BrokkrUnityCommand)entry.Document)
.FirstOrDefault(candidate => !string.IsNullOrWhiteSpace(candidate.commandId)
&& !answered.Contains(candidate.commandId));
.FirstOrDefault(entry =>
{
var candidate = (BrokkrUnityCommand)entry.Document;
return !string.IsNullOrWhiteSpace(candidate.commandId) && !answered.Contains(candidate.commandId);
});
command = next?.Document as BrokkrUnityCommand;
storedAt = next?.StoredAt;
return command != null;
}
// Receipts that say an intent was started and never finished (see BrokkrCommandDrain).
public BrokkrUnityCommandReceipt[] AttemptedReceipts() =>
cache.AllStoredDocuments
.Select(entry => entry.Document)
.OfType<BrokkrUnityCommandReceipt>()
.Where(receipt => string.Equals(receipt.status, BrokkrCommandDrain.AttemptedStatus, StringComparison.Ordinal)
&& !string.IsNullOrWhiteSpace(receipt.commandId))
.ToArray();
}
}

View file

@ -29,6 +29,9 @@ namespace GameCult.Brokkr
[Key(17)] public bool isUpdating;
// False means the editor executes no agent commands: the operator has not enabled the sink.
[Key(18)] public bool agentCommandsEnabled;
// When the operator last enabled the sink (round-trip ISO 8601), empty while it is off. Intents stored before
// this instant expire instead of running (BrokkrCommandDrain).
[Key(19)] public string agentCommandsEnabledAt = "";
}
[CultDocument("brokkr.unity.snapshot_receipt", "brokkr.unity.snapshot_receipt.v0")]