From 86375082b879b7f8c244c785b98264ba6b2edccb Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 05:20:58 +0100 Subject: [PATCH 01/12] Defer player contract activation until the offer reservation is durable --- Shared/Cluster/ContractLedger.PlayerAccept.cs | 309 ++++++++++++++++++ Shared/Cluster/ContractLedger.cs | 162 +++++++-- Shared/Cluster/Patches/MyContractPatch.cs | 4 +- Shared/Cluster/Patches/MyStoreBlockPatch.cs | 25 +- Shared/Cluster/Seams/MyContractSeams.cs | 8 +- Shared/Cluster/StorePaymentJournal.cs | 34 +- Shared/Patches/MyContractBlockPatch.cs | 8 + Shared/Patches/MyContractPatch.cs | 20 +- .../Source/CommandResponseDropRoutes.cs | 6 +- .../Source/ContractTestRoutes.cs | 26 +- .../Source/GlobalSaveHoldRoutes.cs | 5 +- Test/scenarios_contracts.py | 111 ++++++- 12 files changed, 663 insertions(+), 55 deletions(-) create mode 100644 Shared/Cluster/ContractLedger.PlayerAccept.cs diff --git a/Shared/Cluster/ContractLedger.PlayerAccept.cs b/Shared/Cluster/ContractLedger.PlayerAccept.cs new file mode 100644 index 00000000..ad4753e4 --- /dev/null +++ b/Shared/Cluster/ContractLedger.PlayerAccept.cs @@ -0,0 +1,309 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using Sandbox; +using Sandbox.Engine.Multiplayer; +using Sandbox.Game.Contracts; +using Sandbox.Game.Entities; +using Sandbox.Game.Entities.Blocks; +using Sandbox.Game.World; +using VRage.Network; + +namespace ClusterPlugin; + +internal static partial class ContractLedger +{ + private sealed class PlayerAccept(MyContract offer, long player) + { + public readonly MyContract Offer = offer; + public readonly long Player = player; + public readonly Guid Operation = Guid.NewGuid(); + public bool Completing; + public bool Committed; + } + + // Local game-thread state. The authority reserves an offer without activating it. + private static readonly Dictionary PlayerAccepts = new(); + + private sealed record Intent(Request Offer, Guid Decision); + + private static volatile string m_intents; + + internal static bool AllowActivation(MyContract offer, long player, out Guid approved) + { + approved = Guid.Empty; + if (!PlayerAccepts.TryGetValue(offer.Id, out var pending)) + return true; + if (pending.Offer != offer || pending.Player != player) + return false; + if (!pending.Completing) + return false; + approved = pending.Operation; + return true; + } + + // Called once by the payment journal's startup worker. Publish the directory only + // after taking its inventory so recovery cannot cancel a new player's reservation. + internal static void RecoverPlayerAccepts(string data, IEnumerable commitOperations) + { + string folder = Path.Combine(data, "contract-accepts"); + try + { + Directory.CreateDirectory(folder); + string[] files = Directory.GetFiles(folder, "*.intent"); + if (files.Length != 0) + { + var commits = new HashSet(commitOperations); + foreach (string path in files) + _ = Task.Run(() => RecoverIntent(path, commits)); + } + m_intents = folder; + } + catch (IOException error) + { + Console.WriteLine($"[ClusterPlugin] contract reservations unavailable: {error}"); + } + catch (UnauthorizedAccessException error) + { + Console.WriteLine($"[ClusterPlugin] contract reservations unavailable: {error}"); + } + } + + private static async Task RecoverIntent(string path, HashSet committed) + { + try + { + var intent = + JsonSerializer.Deserialize(File.ReadAllText(path)) + ?? throw new InvalidDataException("Empty contract acceptance intent"); + await ResolveIntent(intent, path, committed.Contains(intent.Offer.AcceptanceOperation)); + } + catch (Exception error) + { + Console.WriteLine( + $"[ClusterPlugin] leaving unresolved contract intent {path}: {error}" + ); + } + } + + internal static void PlayerDepositCommitted(long contract, Guid operation) + { + if (PlayerAccepts.TryGetValue(contract, out var pending) && pending.Operation == operation) + pending.Committed = true; + } + + private static async Task AwaitReservation(Intent intent) + { + while (true) + { + var reply = Send(intent.Offer, intent.Offer.AcceptanceOperation); + if (reply != null) + return reply; + await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); + } + } + + private static async Task ResolveIntent(Intent intent, string path, bool confirm) + { + // A release cannot overtake an unanswered Reserve on another connection. + if (!confirm && !(await AwaitReservation(intent)).Success) + { + ForgetIntent(path); + return; + } + var decision = new Request( + confirm ? "Confirm" : "Release", + intent.Offer.ContractId, + AcceptanceOperation: intent.Offer.AcceptanceOperation + ); + Result answer; + while ((answer = Send(decision, intent.Decision)) == null) + await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false); + if (!answer.Success) + throw new InvalidDataException( + $"Authority refused {decision.Kind} for contract {decision.ContractId}: {answer.Reason}" + ); + ForgetIntent(path); + } + + private static void ForgetIntent(string path) + { + try + { + File.Delete(path); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + // A later restart can replay the same decision. + Console.WriteLine( + $"[ClusterPlugin] settled contract intent retained at {path}: {error}" + ); + } + } + + internal static bool TryStartPlayerAccept(MyContractBlock block, long player, long contract) + { + var system = System; + if ( + !RegularNode + || m_intents == null + || contract <= 0 + || system == null + || !block.HasAccess() + || !system.m_inactiveContracts.TryGetValue(contract, out var offer) + ) + return false; + long Station() => + MySession.Static.Factions.GetStationByGridId(block.CubeGrid.EntityId)?.Id ?? 0; + if (offer.StartStation != Station() && offer.StartBlock != block.EntityId) + return false; + var sender = MyEventContext.Current.Sender; + void Reply(MyContractResults result) => + MyMultiplayer.RaiseEvent(block, x => x.ReceiveAcceptContract, result, sender); + if (sender.Value != 0 && MySession.Static.Players.TryGetIdentityId(sender.Value) != player) + { + Reply(MyContractResults.Fail_CannotAccess); + return true; + } + var pending = new PlayerAccept(offer, player); + if (!PlayerAccepts.TryAdd(contract, pending)) + { + Reply(MyContractResults.Fail_NotPossible); + return true; + } + + var session = MySession.Static; + var game = MySandboxGame.Static; + try + { + long owner = (MyEntities.GetEntityById(offer.StartBlock) as MyCubeBlock)?.OwnerId ?? 0; + var request = AcceptRequest(offer, player, owner, pending.Operation) with + { + Kind = "Reserve", + }; + var intent = new Intent(request, Guid.NewGuid()); + string prefix = Path.Combine(m_intents, pending.Operation.ToString("N")); + string path = prefix + ".intent"; + _ = Task.Run(async () => + { + Result answer = null; + try + { + // Write before sending so a restarted origin can release an unclaimed reservation. + using ( + var stream = new FileStream( + prefix + ".tmp", + FileMode.CreateNew, + FileAccess.Write, + FileShare.None + ) + ) + { + JsonSerializer.Serialize(stream, intent); + stream.Flush(true); + } + File.Move(prefix + ".tmp", path); + answer = await AwaitReservation(intent); + } + catch (Exception error) + { + Console.WriteLine($"[ClusterPlugin] contract reservation failed: {error}"); + } + game.Invoke(() => Complete(intent, path, answer), "contract reservation"); + }); + } + catch + { + PlayerAccepts.Remove(contract); + throw; + } + return true; + + void Complete(Intent intent, string path, Result answer) + { + var result = MyContractResults.Fail_NotPossible; + bool uncertain = false; + try + { + if ( + answer?.Success == true + && session == MySession.Static + && !session.IsUnloading + && !block.Closed + && !block.MarkedForClose + && !IsSettled(contract) + && system.m_inactiveContracts.TryGetValue(contract, out var current) + && current == offer + && ( + sender.Value == 0 + || session + .Players.GetPlayerById(new MyPlayer.PlayerId(sender.Value, 0)) + ?.Identity.IdentityId == player + ) + && (block.AnyoneCanUse || block.HasPlayerAccess(player)) + ) + { + pending.Completing = true; + result = system.ActivateContract(player, contract, Station(), block.EntityId); + if (result == MyContractResults.Success) + { + lock (Sync) + AcceptedHere[contract] = ClusterRuntime.LocalMilliseconds; + } + } + else if (answer?.Reason == "contract limit") + result = + MyContractResults.Fail_ActivationConditionsNotMet_ContractLimitReachedHard; + else if (answer?.Reason == AlreadySettled) + { + lock (Sync) + Remember(contract); + system.RemoveInactiveContract(contract); + } + } + catch (Exception error) + { + // A mod callback or a journal write may have failed during vanilla activation. + // Recovery reads the durable payment decision before releasing the reservation. + uncertain = pending.Completing && !pending.Committed; + Console.WriteLine( + $"[ClusterPlugin] player activation failed for {contract}: {error}" + ); + } + finally + { + bool confirm = pending.Committed; + _ = Task.Run(async () => + { + try + { + if (!uncertain && File.Exists(path)) + await ResolveIntent(intent, path, confirm); + } + catch (Exception error) + { + result = MyContractResults.Fail_NotPossible; + Console.WriteLine( + $"[ClusterPlugin] leaving unresolved contract intent {path}: {error}" + ); + } + game.Invoke( + () => + { + PlayerAccepts.Remove(contract); + if ( + session == MySession.Static + && !session.IsUnloading + && !block.Closed + ) + Reply(result); + }, + "contract acceptance result" + ); + }); + } + } + } +} diff --git a/Shared/Cluster/ContractLedger.cs b/Shared/Cluster/ContractLedger.cs index 85eeb9af..a0e39d14 100644 --- a/Shared/Cluster/ContractLedger.cs +++ b/Shared/Cluster/ContractLedger.cs @@ -25,6 +25,12 @@ namespace ClusterPlugin; /// /// SE1-0247, WorldAuthority.md ยง6.3: the World Authority keeps the accepted contracts. /// +/// A player accepting at a block first reserves the offer and a contract slot at the World Authority. While its +/// save is pending the node keeps simulating. Vanilla validates the offer and grants it on the game thread once +/// the reservation is durable. The origin confirms or releases the reservation in the background. After a restart +/// the deposit journal identifies the grants to confirm, including those with zero collateral. +/// +/// /// Its own is the ledger: activation on a regular node hands the /// contract over (Accept, refused for a contract already accepted or over the player's limit), and the /// global save keeps it with the rest of the checkpoint, so it outlives the node it was accepted on and a World @@ -61,7 +67,7 @@ namespace ClusterPlugin; /// (ClusterEntityContractUpdates), and regular nodes run no contract updates. /// /// -internal static class ContractLedger +internal static partial class ContractLedger { private const string Subsystem = "contracts"; private const string AlreadySettled = "already settled"; @@ -131,7 +137,15 @@ private sealed record Result(bool Success, string Reason = null); private sealed record Snapshot(string Contracts, Settlement[] Settled); - private sealed record Record(Acceptance[] Accepted, long[] Settled); + private sealed record Reservation(string Origin, Request Offer, long[] Owners); + + private static readonly Dictionary Reservations = new(); + + private sealed record Record( + Acceptance[] Accepted, + long[] Settled, + Reservation[] Reserved = null + ); private sealed record Unanswered(string Kind, Guid Operation, string Payload, bool PunishOwner); @@ -175,6 +189,17 @@ private static bool Accept(MyContract contract, long playerId, Guid operation) (MyEntities.GetEntityById(contract.StartBlock) as MyCubeBlock)?.OwnerId ?? 0; if (ClusterRuntime.IsWorldAuthority) { + lock (Sync) + if ( + Reservations.ContainsKey(contract.Id) + || contract + .Owners.Append(playerId) + .Any(owner => + MySession.Static.Players.TryGetIdentity(owner) is MyIdentity identity + && AtLimit(identity) + ) + ) + return false; // The World Authority's own activation (a station contract a mod accepts there) is vanilla already. lock (Sync) Accepted[contract.Id] = new Acceptance( @@ -186,21 +211,7 @@ private static bool Accept(MyContract contract, long playerId, Guid operation) ); return true; } - MyObjectBuilder_Contract builder = contract.GetObjectBuilder(); - builder.State = MyContractStateEnum.Active; - builder.Owners = new MySerializableList(contract.Owners.Append(playerId)); - Result result = Send( - new Request( - "Accept", - contract.Id, - Serialize(new[] { builder }), - playerId, - contract.StartBlock, - blockOwner, - AcceptanceOperation: operation - ), - operation - ); + Result result = Send(AcceptRequest(contract, playerId, blockOwner, operation), operation); if (result?.Success != true) { Console.WriteLine( @@ -228,6 +239,27 @@ private static bool Accept(MyContract contract, long playerId, Guid operation) return true; } + private static Request AcceptRequest( + MyContract contract, + long playerId, + long blockOwner, + Guid operation + ) + { + MyObjectBuilder_Contract builder = contract.GetObjectBuilder(); + builder.State = MyContractStateEnum.Active; + builder.Owners = new MySerializableList(contract.Owners.Append(playerId)); + return new Request( + "Accept", + contract.Id, + Serialize(new[] { builder }), + playerId, + contract.StartBlock, + blockOwner, + AcceptanceOperation: operation + ); + } + private static void Withdraw(long contractId, Guid operation) { if (!ClusterRuntime.IsClustered || contractId <= 0) @@ -498,7 +530,8 @@ request.Kind is not ("Finish" or "Fail") throw new InvalidOperationException("Invalid contract ledger request"); Result result = request.Kind switch { - "Accept" => AcceptHere(request), + "Accept" or "Reserve" => AcceptHere(origin, request), + "Confirm" or "Release" => FinishReservation(origin, request), "Withdraw" => WithdrawHere(request.ContractId, request.AcceptanceOperation), "Update" => UpdateHere(request), "Finish" or "Fail" => Settle(request, origin, ranHere: false), @@ -521,7 +554,7 @@ request.Kind is not ("Finish" or "Fail") return result; } - private static Result AcceptHere(Request request) + private static Result AcceptHere(string origin, Request request) { MySessionComponentContractSystem system = System ?? throw new InvalidOperationException("No contract system"); @@ -534,6 +567,14 @@ private static Result AcceptHere(Request request) || builder.Owners.Count == 0 ) throw new InvalidOperationException("Invalid accepted contract"); + lock (Sync) + if (Reservations.TryGetValue(builder.Id, out var existing)) + return new Result( + request.Kind == "Reserve" + && existing.Origin == origin + && existing.Offer.AcceptanceOperation == request.AcceptanceOperation, + "offer reserved" + ); if (system.m_activeContracts.ContainsKey(builder.Id)) return new Result(false, "already accepted"); lock (Sync) @@ -547,16 +588,63 @@ private static Result AcceptHere(Request request) .ToArray(); if (identities.Any(identity => identity == null)) return new Result(false, "unknown owner"); - if ( - identities.Any(identity => - system.GetContractLimitPerPlayer() <= identity.ActiveContracts.Count - ) - ) + if (identities.Any(AtLimit)) return new Result(false, "contract limit"); + if (request.Kind == "Reserve") + { + if (request.AcceptanceOperation == Guid.Empty) + return new Result(false, "missing reservation operation"); + lock (Sync) + Reservations.Add( + builder.Id, + new Reservation(origin, request, builder.Owners.ToArray()) + ); + return new Result(true); + } + InstallAcceptance(request, builder); + return new Result(true); + } + + private static bool AtLimit(MyIdentity identity) => + identity.ActiveContracts.Count + + Reservations.Values.Count(r => r.Owners.Contains(identity.IdentityId)) + >= System.GetContractLimitPerPlayer(); + + private static Result FinishReservation(string origin, Request request) + { + Reservation reserved; + lock (Sync) + { + if (!Reservations.TryGetValue(request.ContractId, out reserved)) + return new Result( + request.Kind == "Release" + || SettledIds.Contains(request.ContractId) + || Accepted.TryGetValue(request.ContractId, out var accepted) + && accepted.Operation == request.AcceptanceOperation + ); + if ( + reserved.Origin != origin + || reserved.Offer.AcceptanceOperation != request.AcceptanceOperation + ) + return new Result(request.Kind == "Release", "different reservation"); + } + if (request.Kind == "Confirm") + InstallAcceptance(reserved.Offer, Parse(reserved.Offer.Contract).Single()); + lock (Sync) + Reservations.Remove(request.ContractId); + return new Result(true); + } + + private static void InstallAcceptance(Request request, MyObjectBuilder_Contract builder) + { + var system = System; system.RemoveInactiveContract(builder.Id); // the offer this World Authority loaded with the world system.AddContract(MyContractFactory.CreateInstance(builder)); - foreach (MyIdentity identity in identities) - if (!identity.ActiveContracts.Contains(builder.Id)) + foreach (long owner in builder.Owners) + if ( + MySession.Static.Players.TryGetIdentity(owner) is MyIdentity identity + && !identity.ActiveContracts.Contains(builder.Id) + ) identity.ActiveContracts.Add(builder.Id); lock (Sync) Accepted[builder.Id] = new Acceptance( @@ -566,7 +654,6 @@ private static Result AcceptHere(Request request) request.Player, request.AcceptanceOperation ); - return new Result(true); } private static Result WithdrawHere(long contractId, Guid operation) @@ -608,6 +695,7 @@ private static Result UpdateHere(Request request) private static Result BlockGoneHere(long blockId) { lock (Sync) + { foreach ( Acceptance acceptance in Accepted .Values.Where(acceptance => @@ -616,6 +704,16 @@ Acceptance acceptance in Accepted .ToArray() ) Accepted[acceptance.Id] = acceptance with { BlockOwner = 0 }; + foreach ( + var reserved in Reservations + .Values.Where(r => r.Offer.Block == blockId && r.Offer.BlockOwner != 0) + .ToArray() + ) + Reservations[reserved.Offer.ContractId] = reserved with + { + Offer = reserved.Offer with { BlockOwner = 0 }, + }; + } return new Result(true); } @@ -829,7 +927,8 @@ internal static string PersistedRecord() return JsonSerializer.Serialize( new Record( Accepted.Values.OrderBy(acceptance => acceptance.Id).ToArray(), - SettledOrder.ToArray() + SettledOrder.ToArray(), + Reservations.Values.ToArray() ) ); } @@ -844,6 +943,9 @@ internal static void RestoreRecord(string payload) : JsonSerializer.Deserialize(payload); lock (Sync) { + Reservations.Clear(); + foreach (var reservation in restored?.Reserved ?? Array.Empty()) + Reservations.Add(reservation.Offer.ContractId, reservation); Accepted.Clear(); foreach (Acceptance acceptance in restored?.Accepted ?? Array.Empty()) Accepted[acceptance.Id] = acceptance; @@ -973,7 +1075,9 @@ private static void Apply(string payload) foreach ( long id in AcceptedHere .Keys.Where(id => - wanted.ContainsKey(id) || now - AcceptedHere[id] > AcceptGraceMilliseconds + wanted.ContainsKey(id) + || !PlayerAccepts.ContainsKey(id) + && now - AcceptedHere[id] > AcceptGraceMilliseconds ) .ToArray() ) diff --git a/Shared/Cluster/Patches/MyContractPatch.cs b/Shared/Cluster/Patches/MyContractPatch.cs index e5c21408..70385ed9 100644 --- a/Shared/Cluster/Patches/MyContractPatch.cs +++ b/Shared/Cluster/Patches/MyContractPatch.cs @@ -29,6 +29,6 @@ private static (IDisposable Scope, bool Approved) SeamBeginDeposit(long payerId, return (deposit, deposit.Approved); } - private static void SeamCommitDeposit(IDisposable scope) => - ((MyStoreBlockPatch.StorePaymentScope)scope).Commit(); + private static void SeamCommitDeposit(IDisposable scope, Guid operation) => + ((MyStoreBlockPatch.StorePaymentScope)scope).Commit(operation); } diff --git a/Shared/Cluster/Patches/MyStoreBlockPatch.cs b/Shared/Cluster/Patches/MyStoreBlockPatch.cs index 0042dd1d..36de0697 100644 --- a/Shared/Cluster/Patches/MyStoreBlockPatch.cs +++ b/Shared/Cluster/Patches/MyStoreBlockPatch.cs @@ -224,15 +224,24 @@ internal bool Observe(long ownerId, long amount) ); } - public void Commit() + public void Commit() => Commit(Guid.Empty); + + internal void Commit(Guid contractOperation) { if (m_async) { - CommitAsync(); + CommitAsync(contractOperation); return; } - if (!Approved || m_committed || m_change == null) + if (!Approved || m_committed) return; + if (m_change == null) + { + if (contractOperation != Guid.Empty) + StorePaymentJournal.CommitWithoutDeposit(contractOperation); + m_committed = true; + return; + } if (!m_debitObserved) throw new InvalidOperationException( "Store payment did not apply its prepared debit" @@ -249,13 +258,14 @@ public void Commit() m_amount, m_creditOperation, m_payeeId, - m_credit + m_credit, + contractOperation ); else - StorePaymentJournal.Close(m_reserveOperation); + StorePaymentJournal.Close(m_reserveOperation, contractOperation); } - private void CommitAsync() + private void CommitAsync(Guid contractOperation) { if (!Approved || m_committed) return; @@ -272,7 +282,8 @@ private void CommitAsync() m_amount, m_creditOperation, m_payeeId, - m_credit + m_credit, + contractOperation ); } diff --git a/Shared/Cluster/Seams/MyContractSeams.cs b/Shared/Cluster/Seams/MyContractSeams.cs index eb112847..899b7c1f 100644 --- a/Shared/Cluster/Seams/MyContractSeams.cs +++ b/Shared/Cluster/Seams/MyContractSeams.cs @@ -9,13 +9,11 @@ namespace ClusterPlugin; /// public static class MyContractSeams { - // Activate: reserve the starting deposit at the World Authority before any contract state changes. + // Reserve the deposit before activation. A player reservation passes its operation ID into the payment commit. public static Func ClusterBeginDeposit; - public static Action ClusterCommitDeposit; + public static Action ClusterCommitDeposit; - // Activate, after the deposit: the World Authority takes the contract into its ledger of accepted contracts - // (contract, accepting player). False refuses the activation. Withdraw (contract id) undoes it when Activate - // does not get as far as the commit. + // Synchronous activation and rollback carry the same operation ID so only the winning attempt can undo its grant. public static Func ClusterAccept; public static Action ClusterWithdraw; diff --git a/Shared/Cluster/StorePaymentJournal.cs b/Shared/Cluster/StorePaymentJournal.cs index c997fcd5..3926543a 100644 --- a/Shared/Cluster/StorePaymentJournal.cs +++ b/Shared/Cluster/StorePaymentJournal.cs @@ -56,7 +56,11 @@ private sealed record Entry( Guid CreditId = default, long Payee = 0, long Credit = 0, - bool Async = false + bool Async = false, + [property: System.Text.Json.Serialization.JsonIgnore( + Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault + )] + Guid ContractOperation = default ); /// : the reserve leg is known to have applied, so only the refund is left. @@ -86,8 +90,13 @@ internal static void Install() internal static void Reserve(Guid reserveId, Guid refundId, long payer, long amount) => Append(new Entry("reserve", reserveId, refundId, payer, amount)); - internal static void Close(Guid reserveId) => - Append(new Entry("closed", reserveId, Guid.Empty, 0, 0)); + internal static void Close(Guid reserveId, Guid contractOperation = default) => + Append( + new Entry("closed", reserveId, Guid.Empty, 0, 0, ContractOperation: contractOperation) + ); + + internal static void CommitWithoutDeposit(Guid operation) => + Append(new Entry("contract", Guid.Empty, Guid.Empty, 0, 0, ContractOperation: operation)); /// /// The payment did not commit: the reserve was refused, unanswered or applied without a settlement. Settles in the @@ -120,7 +129,8 @@ internal static void Commit( long amount, Guid creditId, long payee, - long credit + long credit, + Guid contractOperation = default ) { var commit = new Entry( @@ -131,7 +141,8 @@ long credit amount, creditId, payee, - credit + credit, + ContractOperation: contractOperation ); Append(commit); Enqueue( @@ -157,7 +168,8 @@ internal static void CommitAsync( long amount, Guid creditId, long payee, - long credit + long credit, + Guid contractOperation = default ) { var entry = new Entry( @@ -169,7 +181,8 @@ long credit creditId, payee, credit, - Async: true + Async: true, + ContractOperation: contractOperation ); Append(entry); Enqueue(new Work(null, entry, entry, false, "settled", command)); @@ -318,7 +331,10 @@ Func command return; m_reconciled = true; if (!File.Exists(m_path)) + { + ContractLedger.RecoverPlayerAccepts(Path.GetDirectoryName(m_path), Array.Empty()); return; + } List entries; lock (Sync) entries = File.ReadAllLines(m_path) @@ -336,6 +352,10 @@ Func command }) .Where(entry => entry != null) .ToList(); + ContractLedger.RecoverPlayerAccepts( + Path.GetDirectoryName(m_path), + entries.Where(e => e.ContractOperation != Guid.Empty).Select(e => e.ContractOperation) + ); HashSet closed = entries .Where(entry => entry.Op == "closed") .Select(entry => entry.ReserveId) diff --git a/Shared/Patches/MyContractBlockPatch.cs b/Shared/Patches/MyContractBlockPatch.cs index 7aadfa20..d92e0ad9 100644 --- a/Shared/Patches/MyContractBlockPatch.cs +++ b/Shared/Patches/MyContractBlockPatch.cs @@ -14,6 +14,14 @@ namespace Shared.Patches; /// public static class MyContractBlockPatch { + [HarmonyPatch(typeof(MyContractBlock), "AcceptContract", typeof(long), typeof(long))] + private static class AcceptOffer + { + [HarmonyPrefix] + private static bool Prefix(MyContractBlock __instance, long identityId, long contractId) => + !ContractLedger.TryStartPlayerAccept(__instance, identityId, contractId); + } + [HarmonyPatch( typeof(MyContractBlock), nameof(MyContractBlock.Init), diff --git a/Shared/Patches/MyContractPatch.cs b/Shared/Patches/MyContractPatch.cs index 79cbda21..53c8076f 100644 --- a/Shared/Patches/MyContractPatch.cs +++ b/Shared/Patches/MyContractPatch.cs @@ -41,6 +41,9 @@ public static class MyContractPatch [ThreadStatic] private static IDisposable s_deposit; + [ThreadStatic] + private static (long Contract, Guid Operation) s_playerReservation; + [ThreadStatic] private static (long Contract, Guid Operation) s_accepted; @@ -130,6 +133,7 @@ private static void Finalizer() { IDisposable scope = s_deposit; var accepted = s_accepted; + s_playerReservation = default; s_deposit = null; s_accepted = default; scope?.Dispose(); @@ -232,6 +236,8 @@ IList rejection /// Called from the injected IL of Activate. Returns false when the deposit was refused. public static bool BeginDeposit(MyContract self, long playerId) { + if (!ContractLedger.AllowActivation(self, playerId, out Guid approvedOperation)) + return false; var seam = MyContractSeams.ClusterBeginDeposit; if (seam == null) return true; @@ -248,6 +254,11 @@ public static bool BeginDeposit(MyContract self, long playerId) return false; // A refused acceptance leaves the reserved deposit to the finalizer, which refunds it. var accept = MyContractSeams.ClusterAccept; + if (approvedOperation != Guid.Empty) + { + s_playerReservation = (self.Id, approvedOperation); + return true; + } if (accept != null) { Guid operation = Guid.NewGuid(); @@ -264,7 +275,14 @@ public static void CommitDeposit() s_accepted = default; IDisposable scope = s_deposit; if (scope != null) - MyContractSeams.ClusterCommitDeposit?.Invoke(scope); + { + MyContractSeams.ClusterCommitDeposit?.Invoke(scope, s_playerReservation.Operation); + if (s_playerReservation.Operation != Guid.Empty) + ContractLedger.PlayerDepositCommitted( + s_playerReservation.Contract, + s_playerReservation.Operation + ); + } } /// Called from the injected IL of Finish/Fail. Returns false when another node settled first. diff --git a/Test/ClusterTestPlugin/Source/CommandResponseDropRoutes.cs b/Test/ClusterTestPlugin/Source/CommandResponseDropRoutes.cs index 546bd2ec..667cd6fd 100644 --- a/Test/ClusterTestPlugin/Source/CommandResponseDropRoutes.cs +++ b/Test/ClusterTestPlugin/Source/CommandResponseDropRoutes.cs @@ -26,7 +26,11 @@ public static void Register() context => { string subsystem = TestRoutes.Query(context, "subsystem"); - long count = TestRoutes.Long(context, "count"); + long count = long.Parse( + TestRoutes.Query(context, "count"), + System.Globalization.CultureInfo.InvariantCulture + ); + ArgumentOutOfRangeException.ThrowIfNegative(count); lock (typeof(CommandResponseDropRoutes)) { EnsurePatched(); diff --git a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs index 6431a039..4626e0cf 100644 --- a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text.Json; using ClusterPlugin; +using Sandbox; using Sandbox.Common.ObjectBuilders; using Sandbox.Common.ObjectBuilders.Definitions; using Sandbox.Definitions; @@ -390,7 +391,7 @@ public static void Register() TestRoutes.Text(context, 200, GlobalStateChannel.SendCommand("contracts", payload)); } ); - // POST /contract-test-rpc?op=accept|finish|abandon&userId=&block=&contract= - the contract block's own server + // POST /contract-test-rpc?op=accept|queue-accept|finish|abandon|status&userId=&block=&contract= - the contract block's own server // request handler for an attached player, as if the player's client had sent it (the client has no contract // screen to drive headless). Finish names the player's character as the delivering entity. TestRoutes.Add( @@ -405,6 +406,26 @@ public static void Register() ); long block = TestRoutes.Long(context, "block"), contract = TestRoutes.Long(context, "contract"); + if (op == "queue-accept") + { + // The listener must remain free to serve an independent game-thread probe. + MySandboxGame.Static.Invoke( + () => + { + try + { + Request("accept", user, block, contract); + } + catch (Exception error) + { + Plugin.Log($"Queued acceptance of {contract} failed: {error}"); + } + }, + "ClusterTestPlugin queue contract acceptance" + ); + TestRoutes.Json(context, 202, new { queued = contract }); + return; + } TestRoutes.Json( context, 200, @@ -647,6 +668,7 @@ private static object Active(long contractId, long identityId) return new { contract = contractId, + reserved = ContractLedger.Reservations.ContainsKey(contractId), active = system.IsContractActive(contractId), offered = system.IsContractInInactive(contractId), state = contract?.State.ToString(), @@ -697,6 +719,8 @@ item.Content is MyObjectBuilder_Package package case "abandon": block.AbandonContract(identity, contractId); break; + case "status": + break; default: throw new ArgumentException("Unknown op " + op); } diff --git a/Test/ClusterTestPlugin/Source/GlobalSaveHoldRoutes.cs b/Test/ClusterTestPlugin/Source/GlobalSaveHoldRoutes.cs index 6b40ccd5..cf790348 100644 --- a/Test/ClusterTestPlugin/Source/GlobalSaveHoldRoutes.cs +++ b/Test/ClusterTestPlugin/Source/GlobalSaveHoldRoutes.cs @@ -23,7 +23,10 @@ public static void Register() "/global-save-register-hold", context => { - long ms = TestRoutes.Long(context, "ms"); + long ms = long.Parse( + TestRoutes.Query(context, "ms"), + System.Globalization.CultureInfo.InvariantCulture + ); if (ms is < 0 or > 600000) throw new ArgumentOutOfRangeException("ms"); Interlocked.Exchange( diff --git a/Test/scenarios_contracts.py b/Test/scenarios_contracts.py index 4ab6bf72..a6e49894 100644 --- a/Test/scenarios_contracts.py +++ b/Test/scenarios_contracts.py @@ -446,6 +446,115 @@ def _client_partition(bench, user: int) -> tuple[str, int] | None: return None +def _accept_while_save_held( + bench, ledger, node: str, block: int, contract: int, identity: int, competitor: int +) -> dict: + query = f"&userId={CLIENT_ID}&block={block}&contract={contract}" + hold = "/global-save-register-hold" + before = ledger.node(ledger.wa, hold) + + def pending() -> dict | None: + status = ledger.node(ledger.wa, hold) + if ( + status["heldSaves"] <= before["heldSaves"] + or not status["channel"]["heldResponses"] + ): + return None + active = ledger.active(ledger.wa, contract, identity) + return status if active.get("reserved") and not active["active"] else None + + drop = "/test-drop-command-responses" + copy = ledger.node(node, f"/contract-test-offer-copy?contract={contract}")["offer"] + other = _other(node) + ledger.node(other, f"/contract-test-reoffer?offer={copy}", "POST") + ledger.node(node, drop + "?subsystem=contracts&count=100", "POST") + ledger.node(ledger.wa, hold + "?ms=20000", "POST") + try: + queued = ledger.node(node, "/contract-test-rpc?op=queue-accept" + query, "POST") + _require( + bench, + "the node queued the player's acceptance", + queued.get("queued") == contract, + ) + held = _poll(pending, 3, interval=0.1) + _require( + bench, + "the WA reserves the offer without activating it while the save is held", + held is not None, + ) + # This route dispatches to the node's game thread. A blocked activation cannot answer it. + started = time.monotonic() + clock = _try(lambda: bench.cluster.node(node, "/plugin-clock", timeout=1)) + elapsed_ms = round((time.monotonic() - started) * 1000, 2) + bench.record( + "accept-during-held-save", + {"wa": held, "clock": clock, "roundTripMs": elapsed_ms}, + ) + bench.check( + "the accepting node serves a game-thread read while the WA holds its reply", + clock.get("node") == node and pending() is not None, + f"{elapsed_ms} ms, {json.dumps(clock)}", + ) + if clock.get("node") == node: + state = ledger.node(node, "/contract-test-rpc?op=status" + query, "POST") + bench.check( + "the courier receives no package before the durable reply", + state.get("packagesAfter") == 0 and pending() is not None, + json.dumps(state), + ) + finally: + ledger.node(ledger.wa, hold + "?ms=0", "POST") + + _require( + bench, + "the origin lost the response after the reservation became durable", + _poll(lambda: ledger.node(node, drop)["dropped"] > 0 or None, 30, interval=0.2) + is not None, + ) + race = ledger.node( + other, + f"/contract-test-accept?contract={contract}&block={block}&identity={competitor}", + "POST", + ) + _require( + bench, + "the other player cannot win the reserved offer", + race.get("accepted") is False, + json.dumps(race), + ) + _require( + bench, + "the authority refused the competing operation because the offer was reserved", + _node_line( + bench, + ledger.wa, + f"kind=Accept id={contract} origin={other} success=False reason=offer reserved", + ) + is not None, + ) + generation = int(bench.cluster.get("/registry/world-authority")["Generation"]) + _wa_failover(bench, generation, fresh=True) + ledger.wa = "wa-2" + restored = ledger.active(ledger.wa, contract, identity) + _require( + bench, + "the replacement restored the reservation without activating it", + restored.get("reserved") and not restored["active"], + json.dumps(restored), + ) + ledger.node(node, drop + "?subsystem=contracts&count=0", "POST") + + def delivered() -> dict | None: + state = ledger.node(node, "/contract-test-rpc?op=status" + query, "POST") + return ( + state + if state["contract"]["active"] and state["packagesAfter"] == 1 + else None + ) + + return _poll(delivered, HANDOVER_TIMEOUT) or {} + + def p3_con_clients(bench) -> None: """SE1-0247 - accepted at a block on one node by an attached player, delivered at a block on another.""" bench.start_cluster(nodes=["node-1", "node-2", "wa-1"]) @@ -493,7 +602,7 @@ def p3_con_clients(bench) -> None: contract = int(posted["contractId"]) ledger.wait_balance("posted: B paid the reward in", b, paid[b] - REWARD) - accepted = ledger.node(node_a, f"/contract-test-rpc?op=accept&userId={CLIENT_ID}&block={start}&contract={contract}", "POST") + accepted = _accept_while_save_held(bench, ledger, node_a, start, contract, a, b) bench.record("accept", accepted) bench.check(f"accept: A accepted at the start block on {node_a} and got the package", (accepted.get("contract") or {}).get("active") is True and accepted.get("packagesAfter") == 1, From d0ce01524957a88e49eba05bf351d26d78aa9480 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 05:18:32 +0100 Subject: [PATCH 02/12] Exercise courier acceptance across an origin crash --- .../Source/ContractConfirmHoldRoutes.cs | 63 ++++ .../Source/ContractTestRoutes.cs | 3 +- Test/ClusterTestPlugin/Source/TestRoutes.cs | 1 + Test/run_suite.py | 3 +- Test/scenarios_contract_origin.py | 293 ++++++++++++++++++ 5 files changed, 361 insertions(+), 2 deletions(-) create mode 100644 Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs create mode 100644 Test/scenarios_contract_origin.py diff --git a/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs new file mode 100644 index 00000000..e1958070 --- /dev/null +++ b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs @@ -0,0 +1,63 @@ +using System; +using System.Threading; +using HarmonyLib; + +namespace ClusterTestPlugin; + +/// Hold one outbound confirmation until the origin process is killed. Its replacement sends normally. +internal static class ContractConfirmHoldRoutes +{ + private static long m_contract; + private static int m_held; + private static bool m_patched; + + public static void Register() + { + TestRoutes.Add( + "POST", + "/contract-test-hold-confirm", + context => + { + long contract = TestRoutes.Long(context, "contract"); + if (contract <= 0) + throw new ArgumentOutOfRangeException(nameof(contract)); + if (!m_patched) + { + var ledger = AccessTools.TypeByName("ClusterPlugin.ContractLedger"); + var send = + AccessTools.Method(ledger, "Send") + ?? throw new MissingMethodException("ContractLedger.Send"); + new Harmony("ClusterTestPlugin.ContractConfirmHold").Patch( + send, + prefix: new HarmonyMethod( + typeof(ContractConfirmHoldRoutes), + nameof(BeforeSend) + ) + ); + m_patched = true; + } + Interlocked.Exchange(ref m_held, 0); + Interlocked.Exchange(ref m_contract, contract); + TestRoutes.Json(context, 200, new { contract }); + } + ); + TestRoutes.Add( + "GET", + "/contract-test-hold-confirm", + context => TestRoutes.Json(context, 200, new { held = Volatile.Read(ref m_held) }) + ); + } + + private static bool BeforeSend(object request) + { + var fields = Traverse.Create(request); + if ( + fields.Property("Kind").GetValue() != "Confirm" + || fields.Property("ContractId").GetValue() != Interlocked.Read(ref m_contract) + ) + return true; + // Send returns null for a missing answer. The normal worker retries until the origin dies. + Interlocked.Increment(ref m_held); + return false; + } +} diff --git a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs index 4626e0cf..9642e0c5 100644 --- a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs @@ -692,7 +692,8 @@ private static object Request(string op, ulong user, long blockId, long contract ?? throw new InvalidOperationException( "Player " + user + " is not attached to this node" ); - if (MyEntities.GetEntityById(blockId) is not MyContractBlock block) + var block = MyEntities.GetEntityById(blockId) as MyContractBlock; + if (block == null && op != "status") throw new ArgumentException("No contract block " + blockId + " on this node"); long identity = player.Identity.IdentityId; MyCharacter character = player.Character; diff --git a/Test/ClusterTestPlugin/Source/TestRoutes.cs b/Test/ClusterTestPlugin/Source/TestRoutes.cs index 47429b0e..e2c60ebd 100644 --- a/Test/ClusterTestPlugin/Source/TestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/TestRoutes.cs @@ -88,6 +88,7 @@ public static void RegisterAll() BotShipTestRoutes.Register(); // SE-1316 bot identities and a seated pilot for the bot ship cleanup BlueprintTestRoutes.Register(); // T-0401 parked ship pastes (Visitor Ion) for the Add bench BlockCoverageHarness.Register(); // SE1-0163 one fixture per vanilla functional block type + ContractConfirmHoldRoutes.Register(); ContractTestRoutes.Register(); // SE1-0232 contract offers across handover and restart GridDeleteFaultRoutes.Register(); // #1295 a grid whose BeforeDelete throws in a cluster close CollisionFilterFaultRoutes.Register(); // SE-1491 a stale collision filter refresh left by a drain's close diff --git a/Test/run_suite.py b/Test/run_suite.py index b88dbc15..e434362f 100644 --- a/Test/run_suite.py +++ b/Test/run_suite.py @@ -96,6 +96,7 @@ def _early_package(argv: list[str]) -> None: from scenarios_mods import SCENARIOS_MODS # noqa: E402 from scenarios_spawn_preview import SCENARIOS_SPAWN_PREVIEW # noqa: E402 from scenarios_blocks import SCENARIOS_BLOCKS # noqa: E402 +from scenarios_contract_origin import SCENARIOS_CONTRACT_ORIGIN # noqa: E402 from scenarios_contracts import SCENARIOS_CONTRACTS # noqa: E402 from scenarios_asleep import SCENARIOS_ASLEEP # noqa: E402 from scenarios_staged_bags import SCENARIOS_STAGED_BAGS # noqa: E402 @@ -109,7 +110,7 @@ def _early_package(argv: list[str]) -> None: SCENARIOS = {**SCENARIOS_CORE, **SCENARIOS_JUMP, **SCENARIOS_ADMIN_SYNC, **SCENARIOS_LIVE, **SCENARIOS_EXT, **SCENARIOS_ADMIN, **SCENARIOS_PLAYER, **SCENARIOS_RECOVERY, **SCENARIOS_RESTART, **SCENARIOS_SAVES, **SCENARIOS_TOPOLOGY, **SCENARIOS_WA, **SCENARIOS_WA_OPS, **SCENARIOS_AI, **SCENARIOS_OFFLINE, **SCENARIOS_REJOIN, **SCENARIOS_PLANET, **SCENARIOS_PRESENCE, **SCENARIOS_SUITE, **SCENARIOS_FAST, **SCENARIOS_BIG_GRID, **SCENARIOS_ORPHAN, **SCENARIOS_DELETE_FAULT, **SCENARIOS_GRID_DELETE, **SCENARIOS_RECOVERY_FRAMES, **SCENARIOS_STORE_BULK, **SCENARIOS_VOXEL_RESET, **SCENARIOS_STOP_AFTER_WARM_START, **SCENARIOS_NPC, **SCENARIOS_BOT_SHIPS, **SCENARIOS_PLAYER_FORGET, **SCENARIOS_MODS, **SCENARIOS_REDELIVER, **SCENARIOS_PROPERTY_SYNC, **SCENARIOS_PANEL, **SCENARIOS_DRIFT, **SCENARIOS_SPAWN_PREVIEW, **SCENARIOS_BLOCKS, **SCENARIOS_CHARACTERS_CHURN, - **SCENARIOS_CONTRACTS, **SCENARIOS_STALE_MEMBER, **SCENARIOS_RETIRE_LOADING, **SCENARIOS_BODYLESS, **SCENARIOS_MEMBER_LIMIT, + **SCENARIOS_CONTRACTS, **SCENARIOS_CONTRACT_ORIGIN, **SCENARIOS_STALE_MEMBER, **SCENARIOS_RETIRE_LOADING, **SCENARIOS_BODYLESS, **SCENARIOS_MEMBER_LIMIT, **SCENARIOS_CHAT_NAMES, **SCENARIOS_CHAT_LATENCY, **SCENARIOS_PLAYER_PROFILES, **SCENARIOS_RESPAWNS_OFFLINE, **SCENARIOS_ADMIN_ECONOMY, **SCENARIOS_ADMIN_SHOW_PLAYERS, **SCENARIOS_RENAME, **SCENARIOS_CHAT_EVENT, **SCENARIOS_ASLEEP, **SCENARIOS_STAGED_BAGS, **SCENARIOS_CLIENT_BALANCE, **SCENARIOS_SEED_ID, **SCENARIOS_SEED_COLLIDE, **SCENARIOS_STALE_VIEW, **SCENARIOS_SKINS, **SCENARIOS_ADMIN_MENU} #: The longest a single scenario may take; used for the network-window guard. diff --git a/Test/scenarios_contract_origin.py b/Test/scenarios_contract_origin.py new file mode 100644 index 00000000..549e1d71 --- /dev/null +++ b/Test/scenarios_contract_origin.py @@ -0,0 +1,293 @@ +"""Crash a regular node on either side of its real player's courier grant.""" + +import json +from uuid import UUID + +from cluster import ClusterHttpError, wait_until +from scenarios_blocks import _identity +from scenarios_contracts import ( + CLIENT_ID, + COLLATERAL, + FUNDS, + REGULAR, + REWARD, + _block_grid, + _client_node, + _client_partition, + _Ledger, + _restart, +) +from scenarios_recovery import RECOVERY_TIMEOUT, _nodes +from scenarios_saves import _newest +from scenarios_wa_ops import _require + + +def _capture(bench, origin, partition): + def sequence(): + return ((_newest(bench, partition) or {}).get("SaveId") or {}).get( + "Sequence", 0 + ) + + def queue(): + try: + bench.cluster.node(origin, f"/save-capture?partition={partition}", "POST") + return True + except ClusterHttpError as error: + if error.status == 409: + return False + raise + + # The next registered save could already be in flight when the observation was made. + # The following one must contain a capture from after that observation. + for _ in range(2): + before = sequence() + wait_until(queue, RECOVERY_TIMEOUT, f"queue a save of {partition}") + wait_until( + lambda: sequence() > before, RECOVERY_TIMEOUT, f"new save of {partition}" + ) + + +def _intent(folder, contract): + for path in folder.glob("*.intent"): + intent = json.loads(path.read_text()) + if intent["Offer"]["ContractId"] == contract: + return path, UUID(intent["Offer"]["AcceptanceOperation"]) + return None + + +def _commits(journal, operation): + if not journal.exists(): + return [] + rows = [ + json.loads(line) for line in journal.read_text().splitlines() if line.strip() + ] + return [ + row + for row in rows + if row.get("ContractOperation") and UUID(row["ContractOperation"]) == operation + ] + + +def _run(bench, committed): + bench.start_cluster(nodes=[*REGULAR, "wa-1"]) + ledger = _Ledger(bench) + poster = _identity(bench, "ContractRestartPoster") + bench.start_client(CLIENT_ID) + bench.wait_spawned(CLIENT_ID) + origin, partition = wait_until( + lambda: _client_partition(bench, CLIENT_ID), + RECOVERY_TIMEOUT, + "player partition", + ) + bench.cluster.post("/automatic/pause") + try: + for node in REGULAR: + ledger.node(node, "/contract-test-trash?enabled=0", "POST") + payer = int( + ledger.node(origin, f"/respawn-test-player?userId={CLIENT_ID}")[ + "identityId" + ] + ) + starting = ledger.balance(payer) + _require(bench, "payer's opening balance is known", isinstance(starting, int)) + ledger.node( + origin, f"/banking-test-change?ownerId={payer}&amount={FUNDS}", "POST" + ) + balance = starting + FUNDS + wait_until( + lambda: ledger.balance(payer) == balance, RECOVERY_TIMEOUT, "funded payer" + ) + _, start, sp = _block_grid(bench, ledger, poster, 900000, origin, anyone=True) + _, end, ep = _block_grid(bench, ledger, poster, 930000, origin, anyone=True) + posted = ledger.node( + origin, + f"/contract-test-post-hauling?block={start}&end={end}&reward={REWARD}" + f"&collateral={COLLATERAL}&minutes=60", + "POST", + ) + _require(bench, "courier posted", posted.get("success") is True, str(posted)) + contract = int(posted["contractId"]) + query = f"&userId={CLIENT_ID}&contract={contract}" + path = "/contract-test-rpc?op=" + + def inventory(node): + return ledger.node(node, path + "status" + query + "&block=0", "POST") + + def authority(reserved, active): + row = ledger.active(ledger.wa, contract, payer) + if row.get("reserved") is reserved and row.get("active") is active: + return row + return None + + before = inventory(origin) + character = before["character"] + _require( + bench, + "the original character starts with no package for this contract", + character != 0 + and before["identity"] == payer + and before["packagesAfter"] == 0, + str(before), + ) + for part in {partition, sp, ep}: + _capture(bench, origin, part) + + if committed: + ledger.node( + origin, f"/contract-test-hold-confirm?contract={contract}", "POST" + ) + else: + ledger.node( + origin, + "/test-drop-command-responses?subsystem=contracts&count=100", + "POST", + ) + + queued = ledger.node( + origin, path + "queue-accept" + query + f"&block={start}", "POST" + ) + _require( + bench, + "queued the attached player's acceptance", + queued.get("queued") == contract, + str(queued), + ) + if committed: + wait_until( + lambda: ledger.node(origin, "/contract-test-hold-confirm")["held"] > 0, + RECOVERY_TIMEOUT, + "the outbound confirmation was held before transmission", + ) + else: + wait_until( + lambda: ledger.node(origin, "/test-drop-command-responses")["dropped"] + > 0, + RECOVERY_TIMEOUT, + "the origin lost the reserve response", + ) + pending = wait_until( + lambda: authority(True, False), + RECOVERY_TIMEOUT, + "WA reserved the inactive contract", + ) + data = bench.cluster.config.node_data(_nodes(bench)[origin]) / "cluster" + intent, operation = wait_until( + lambda: _intent(data / "contract-accepts", contract), + RECOVERY_TIMEOUT, + "durable origin intent", + ) + journal = data / "store-payments.jsonl" + local = inventory(origin) + expected_packages = int(committed) + expected_balance = balance - (COLLATERAL if committed else 0) + _require( + bench, + "the crash gate caught the expected package and payment decision", + local["character"] == character + and local["packagesAfter"] == expected_packages + and bool(_commits(journal, operation)) == committed, + str(local), + ) + wait_until( + lambda: ledger.balance(payer) == expected_balance, + RECOVERY_TIMEOUT, + "pre-crash balance", + ) + if committed: + _capture(bench, origin, partition) + _require( + bench, + "WA is still reserved at the crash boundary", + bool(authority(True, False)), + ) + bench.record( + "before-origin-crash", + { + "authority": pending, + "local": local, + "balance": expected_balance, + "intent": json.loads(intent.read_text()), + "payment": _commits(journal, operation), + "playerPartition": partition, + }, + ) + + _restart(bench, origin, partition) + settled = wait_until( + lambda: authority(False, committed), + RECOVERY_TIMEOUT, + "WA recovered the origin's decision", + ) + wait_until( + lambda: not intent.exists(), + RECOVERY_TIMEOUT, + "origin removed the resolved intent", + ) + _require( + bench, + "WA lists exactly the committed owner", + settled["owners"] == ([payer] if committed else []), + str(settled), + ) + bench.kill_client(CLIENT_ID) + bench.start_client(CLIENT_ID, label="contract-origin-reconnected") + bench.wait_spawned(CLIENT_ID) + serving = wait_until( + lambda: _client_node(bench, CLIENT_ID), + RECOVERY_TIMEOUT, + "reattached player", + ) + after = inventory(serving) + _require( + bench, + "same recovered character has the expected number of matching packages", + after["identity"] == payer + and after["character"] == character + and after["packagesAfter"] == expected_packages, + str(after), + ) + _require( + bench, + "recovery preserved the payer's exact balance", + ledger.balance(payer) == expected_balance, + ) + _require( + bench, + "durable payment decision still matches the crash gate", + bool(_commits(journal, operation)) == committed, + ) + bench.record( + "after-origin-restart", + {"authority": settled, "local": after, "balance": ledger.balance(payer)}, + ) + bench.exercised( + contract=contract, + origin=origin, + served=serving, + acceptance=str(operation), + committed=committed, + ) + finally: + bench.cluster.post("/automatic/resume") + + +def p3_con_origin_release(bench): + _run(bench, committed=False) + + +def p3_con_origin_confirm(bench): + _run(bench, committed=True) + + +SCENARIOS_CONTRACT_ORIGIN = { + "P3-CON-ORIGIN-RELEASE": ( + p3_con_origin_release, + "Release an ungranted courier after an origin crash", + "3", + ), + "P3-CON-ORIGIN-CONFIRM": ( + p3_con_origin_confirm, + "Confirm a committed courier after an origin crash", + "3", + ), +} From 2801925c31b16a643e7646bfcfe70354c282780c Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 05:23:16 +0100 Subject: [PATCH 03/12] Verify the synchronous collateral commit on recovery --- Test/scenarios_contract_origin.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Test/scenarios_contract_origin.py b/Test/scenarios_contract_origin.py index 549e1d71..d2f44d30 100644 --- a/Test/scenarios_contract_origin.py +++ b/Test/scenarios_contract_origin.py @@ -70,6 +70,11 @@ def _commits(journal, operation): def _run(bench, committed): bench.start_cluster(nodes=[*REGULAR, "wa-1"]) + if committed: + bench.record( + "config-sync-deposit", + bench.cluster.handover_config({"store.asyncPayments": "false"}), + ) ledger = _Ledger(bench) poster = _identity(bench, "ContractRestartPoster") bench.start_client(CLIENT_ID) @@ -111,7 +116,9 @@ def _run(bench, committed): path = "/contract-test-rpc?op=" def inventory(node): - return ledger.node(node, path + "status" + query + "&block=0", "POST") + return ledger.node( + node, path + "status" + query + f"&block={start}", "POST" + ) def authority(reserved, active): row = ledger.active(ledger.wa, contract, payer) @@ -177,6 +184,15 @@ def authority(reserved, active): "durable origin intent", ) journal = data / "store-payments.jsonl" + if committed: + records = _commits(journal, operation) + _require( + bench, + "the synchronous payment journal durably closed the collateral reserve", + [row["Op"] for row in records] == ["closed"] + and records[0]["ReserveId"] != "00000000-0000-0000-0000-000000000000", + str(records), + ) local = inventory(origin) expected_packages = int(committed) expected_balance = balance - (COLLATERAL if committed else 0) From ada3f0b1dde77c0f01aaffaee3a167284b7de1cd Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 05:23:41 +0100 Subject: [PATCH 04/12] Keep courier fixtures across regular-node restarts --- Test/scenarios_contract_origin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Test/scenarios_contract_origin.py b/Test/scenarios_contract_origin.py index d2f44d30..1c6d97bf 100644 --- a/Test/scenarios_contract_origin.py +++ b/Test/scenarios_contract_origin.py @@ -86,7 +86,7 @@ def _run(bench, committed): ) bench.cluster.post("/automatic/pause") try: - for node in REGULAR: + for node in (ledger.wa, *REGULAR): ledger.node(node, "/contract-test-trash?enabled=0", "POST") payer = int( ledger.node(origin, f"/respawn-test-player?userId={CLIENT_ID}")[ From b3591583597d943e7bdc08f36033e7d23109e333 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 05:24:46 +0100 Subject: [PATCH 05/12] Keep courier fixtures across authority replacement --- Test/scenarios_contract_origin.py | 4 ++-- Test/scenarios_contracts.py | 25 +++++++++++++++++++++---- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/Test/scenarios_contract_origin.py b/Test/scenarios_contract_origin.py index 1c6d97bf..805709ed 100644 --- a/Test/scenarios_contract_origin.py +++ b/Test/scenarios_contract_origin.py @@ -12,6 +12,7 @@ REGULAR, REWARD, _block_grid, + _disable_contract_fixture_trash, _client_node, _client_partition, _Ledger, @@ -86,8 +87,7 @@ def _run(bench, committed): ) bench.cluster.post("/automatic/pause") try: - for node in (ledger.wa, *REGULAR): - ledger.node(node, "/contract-test-trash?enabled=0", "POST") + _disable_contract_fixture_trash(ledger) payer = int( ledger.node(origin, f"/respawn-test-player?userId={CLIENT_ID}")[ "identityId" diff --git a/Test/scenarios_contracts.py b/Test/scenarios_contracts.py index a6e49894..f9b6f23d 100644 --- a/Test/scenarios_contracts.py +++ b/Test/scenarios_contracts.py @@ -446,6 +446,25 @@ def _client_partition(bench, user: int) -> tuple[str, int] | None: return None +def _disable_contract_fixture_trash(ledger): + # Four-block unpowered grids need to survive a World Authority replacement. + settings = ledger.node("node-1", "/admin-sync-trash") + ledger.node( + "node-1", + f"/admin-sync-trash-upload?enable=false&blockCount={settings['BlockCountThreshold']}" + f"&voxelAge={settings['VoxelAgeThreshold']}", + "POST", + ) + wait_until( + lambda: all( + ledger.node(node, "/admin-sync-trash")["TrashRemovalEnabled"] is False + for node in (*REGULAR, ledger.wa) + ), + 20, + "cluster-wide trash removal disabled for the contract grids", + ) + + def _accept_while_save_held( bench, ledger, node: str, block: int, contract: int, identity: int, competitor: int ) -> dict: @@ -575,9 +594,7 @@ def p3_con_clients(bench) -> None: bench.cluster.post("/automatic/pause") contract = 0 try: - # The contract blocks are small unpowered grids far from both players: vanilla's trash removal takes them. - for node in REGULAR: - ledger.node(node, "/contract-test-trash?enabled=0", "POST") + _disable_contract_fixture_trash(ledger) node_a = where["a"][0] node_b = _other(node_a) _hand_over(bench, where["b"][1], node_b, client=CLIENT2_ID) @@ -604,7 +621,7 @@ def p3_con_clients(bench) -> None: accepted = _accept_while_save_held(bench, ledger, node_a, start, contract, a, b) bench.record("accept", accepted) - bench.check(f"accept: A accepted at the start block on {node_a} and got the package", + _require(bench, f"accept: A accepted at the start block on {node_a} and got the package", (accepted.get("contract") or {}).get("active") is True and accepted.get("packagesAfter") == 1, json.dumps(accepted)[:500]) ledger.wait_balance("accept: A paid the collateral", a, paid[a] - COLLATERAL) From d640878fb1f3ee5bb6f7576972ae7558dbe61554 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 05:26:57 +0100 Subject: [PATCH 06/12] Exercise acquisition contracts with zero collateral --- .../Source/ContractTestRoutes.cs | 1 + Test/scenarios_contracts.py | 32 +++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs index 9642e0c5..fc683f6c 100644 --- a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs @@ -671,6 +671,7 @@ private static object Active(long contractId, long identityId) reserved = ContractLedger.Reservations.ContainsKey(contractId), active = system.IsContractActive(contractId), offered = system.IsContractInInactive(contractId), + type = contract?.GetType().Name, state = contract?.State.ToString(), owners = contract?.Owners.ToArray() ?? Array.Empty(), conditionFinished = contract?.ContractCondition?.IsFinished, diff --git a/Test/scenarios_contracts.py b/Test/scenarios_contracts.py index f9b6f23d..d4cbfeb6 100644 --- a/Test/scenarios_contracts.py +++ b/Test/scenarios_contracts.py @@ -647,8 +647,36 @@ def delivered(): replay = ledger.node(node_b, f"/contract-test-rpc?op=finish&userId={CLIENT_ID}&block={end}&contract={contract}", "POST") bench.record("finish-replay", replay) time.sleep(5) - bench.check("finish: a second delivery request pays nothing more", ledger.balance(a) == paid[a] + REWARD, - f"balance {ledger.balance(a)}, expected {paid[a] + REWARD}") + bench.check( + "finish: a second delivery request pays nothing more", + ledger.balance(a) == paid[a] + REWARD, + f"balance {ledger.balance(a)}, expected {paid[a] + REWARD}", + ) + + # The Octahedron report involved item acquisition contracts. This fixture also + # exercises a successful payment decision for an offer with zero collateral. + acquisition = ledger.node( + node_b, f"/contract-test-post?block={start}&reward={REWARD}", "POST" + ) + _require(bench, "the acquisition contract was posted", acquisition["success"]) + acquisition_id = acquisition["contractId"] + opening = ledger.balance(a) + ledger.node( + node_b, + f"/contract-test-rpc?op=queue-accept&userId={CLIENT_ID}&block={start}&contract={acquisition_id}", + "POST", + ) + ledger.wait_listed( + "all nodes list the accepted acquisition contract", acquisition_id, a, True + ) + active = ledger.active(ledger.wa, acquisition_id, a) + bench.check( + "the production contract type confirms without debiting zero collateral", + active.get("type") == "MyContractObtainAndDeliver" + and active["owners"] == [a] + and ledger.balance(a) == opening, + json.dumps(active), + ) finally: _try(lambda: bench.cluster.post("/automatic/resume")) bench.exercised(contract=contract, clients=[CLIENT_ID, CLIENT2_ID], where=where) From 1d2826fbf1e2c1c7f766ab1eaa201b36e8eec26d Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 05:29:49 +0100 Subject: [PATCH 07/12] Consume the player grant once during vanilla activation --- Shared/Cluster/ContractLedger.PlayerAccept.cs | 20 +++++++++---------- Shared/Patches/MyContractPatch.cs | 11 +++++----- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/Shared/Cluster/ContractLedger.PlayerAccept.cs b/Shared/Cluster/ContractLedger.PlayerAccept.cs index ad4753e4..285a822c 100644 --- a/Shared/Cluster/ContractLedger.PlayerAccept.cs +++ b/Shared/Cluster/ContractLedger.PlayerAccept.cs @@ -20,7 +20,7 @@ private sealed class PlayerAccept(MyContract offer, long player) public readonly MyContract Offer = offer; public readonly long Player = player; public readonly Guid Operation = Guid.NewGuid(); - public bool Completing; + public bool AllowGrant; public bool Committed; } @@ -36,10 +36,9 @@ internal static bool AllowActivation(MyContract offer, long player, out Guid app approved = Guid.Empty; if (!PlayerAccepts.TryGetValue(offer.Id, out var pending)) return true; - if (pending.Offer != offer || pending.Player != player) - return false; - if (!pending.Completing) + if (pending.Offer != offer || pending.Player != player || !pending.AllowGrant) return false; + pending.AllowGrant = false; approved = pending.Operation; return true; } @@ -61,11 +60,7 @@ internal static void RecoverPlayerAccepts(string data, IEnumerable commitO } m_intents = folder; } - catch (IOException error) - { - Console.WriteLine($"[ClusterPlugin] contract reservations unavailable: {error}"); - } - catch (UnauthorizedAccessException error) + catch (Exception error) when (error is IOException or UnauthorizedAccessException) { Console.WriteLine($"[ClusterPlugin] contract reservations unavailable: {error}"); } @@ -225,6 +220,7 @@ void Complete(Intent intent, string path, Result answer) { var result = MyContractResults.Fail_NotPossible; bool uncertain = false; + bool activating = false; try { if ( @@ -245,7 +241,8 @@ void Complete(Intent intent, string path, Result answer) && (block.AnyoneCanUse || block.HasPlayerAccess(player)) ) { - pending.Completing = true; + activating = true; + pending.AllowGrant = true; result = system.ActivateContract(player, contract, Station(), block.EntityId); if (result == MyContractResults.Success) { @@ -267,13 +264,14 @@ void Complete(Intent intent, string path, Result answer) { // A mod callback or a journal write may have failed during vanilla activation. // Recovery reads the durable payment decision before releasing the reservation. - uncertain = pending.Completing && !pending.Committed; + uncertain = activating && !pending.Committed; Console.WriteLine( $"[ClusterPlugin] player activation failed for {contract}: {error}" ); } finally { + pending.AllowGrant = false; bool confirm = pending.Committed; _ = Task.Run(async () => { diff --git a/Shared/Patches/MyContractPatch.cs b/Shared/Patches/MyContractPatch.cs index 53c8076f..1eed076b 100644 --- a/Shared/Patches/MyContractPatch.cs +++ b/Shared/Patches/MyContractPatch.cs @@ -273,15 +273,14 @@ public static bool BeginDeposit(MyContract self, long playerId) public static void CommitDeposit() { s_accepted = default; + var reservation = s_playerReservation; + s_playerReservation = default; IDisposable scope = s_deposit; if (scope != null) { - MyContractSeams.ClusterCommitDeposit?.Invoke(scope, s_playerReservation.Operation); - if (s_playerReservation.Operation != Guid.Empty) - ContractLedger.PlayerDepositCommitted( - s_playerReservation.Contract, - s_playerReservation.Operation - ); + MyContractSeams.ClusterCommitDeposit?.Invoke(scope, reservation.Operation); + if (reservation.Operation != Guid.Empty) + ContractLedger.PlayerDepositCommitted(reservation.Contract, reservation.Operation); } } From a14de8175cead67a604066da3029675f62ac5573 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 06:06:41 +0100 Subject: [PATCH 08/12] Isolate contract deposit state for each activation --- Shared/Patches/ContractActivation.cs | 33 ++++++++++++++ Shared/Patches/MyContractPatch.cs | 41 ++++++----------- .../ContractActivation.csproj | 4 ++ Test/ContractActivation/Program.cs | 44 +++++++++++++++++++ 4 files changed, 95 insertions(+), 27 deletions(-) create mode 100644 Shared/Patches/ContractActivation.cs create mode 100644 Test/ContractActivation/ContractActivation.csproj create mode 100644 Test/ContractActivation/Program.cs diff --git a/Shared/Patches/ContractActivation.cs b/Shared/Patches/ContractActivation.cs new file mode 100644 index 00000000..6ac9eb27 --- /dev/null +++ b/Shared/Patches/ContractActivation.cs @@ -0,0 +1,33 @@ +using System; + +namespace Shared.Patches; + +internal sealed class ContractActivation +{ + [ThreadStatic] + private static ContractActivation current; + private readonly ContractActivation parent = current; + + public static ContractActivation Current => current; + public IDisposable Deposit; + public (long Contract, Guid Operation) PlayerReservation; + public (long Contract, Guid Operation) Accepted; + + public static ContractActivation Enter() => current = new ContractActivation(); + + public void Close(Action withdraw) + { + if (current != this) + return; + try + { + Deposit?.Dispose(); + if (Accepted.Contract != 0) + withdraw?.Invoke(Accepted.Contract, Accepted.Operation); + } + finally + { + current = parent; + } + } +} diff --git a/Shared/Patches/MyContractPatch.cs b/Shared/Patches/MyContractPatch.cs index 1eed076b..0d617f90 100644 --- a/Shared/Patches/MyContractPatch.cs +++ b/Shared/Patches/MyContractPatch.cs @@ -38,15 +38,6 @@ namespace Shared.Patches; /// public static class MyContractPatch { - [ThreadStatic] - private static IDisposable s_deposit; - - [ThreadStatic] - private static (long Contract, Guid Operation) s_playerReservation; - - [ThreadStatic] - private static (long Contract, Guid Operation) s_accepted; - private static readonly MethodInfo CanActivateInternal = EconomyIl.Required( AccessTools.Method(typeof(MyContract), "CanActivate_Internal"), "MyContract.CanActivate_Internal" @@ -76,6 +67,11 @@ public static class MyContractPatch [HarmonyPatch(typeof(MyContract), nameof(MyContract.Activate))] private static class Activate { + // A custom contract may activate another contract inside its callback. + [HarmonyPrefix] + private static void Prefix(out ContractActivation __state) => + __state = ContractActivation.Enter(); + [HarmonyTranspiler] private static IEnumerable Transpiler( IEnumerable instructions, @@ -129,17 +125,8 @@ MethodBase original // Stands in for a `using` scope: refund on every exit after the reservation. [HarmonyFinalizer] - private static void Finalizer() - { - IDisposable scope = s_deposit; - var accepted = s_accepted; - s_playerReservation = default; - s_deposit = null; - s_accepted = default; - scope?.Dispose(); - if (accepted.Contract != 0) - MyContractSeams.ClusterWithdraw?.Invoke(accepted.Contract, accepted.Operation); - } + private static void Finalizer(ContractActivation __state) => + __state?.Close(MyContractSeams.ClusterWithdraw); } // ClusterPlugin seam: Finish - arbitrate the terminal transition once, cluster-wide. @@ -249,14 +236,14 @@ public static bool BeginDeposit(MyContract self, long playerId) clusterDepositPayer, self.StartingDeposit > 0 ? self.StartingDeposit : 0 ); - s_deposit = scope; + ContractActivation.Current.Deposit = scope; if (!approved) return false; // A refused acceptance leaves the reserved deposit to the finalizer, which refunds it. var accept = MyContractSeams.ClusterAccept; if (approvedOperation != Guid.Empty) { - s_playerReservation = (self.Id, approvedOperation); + ContractActivation.Current.PlayerReservation = (self.Id, approvedOperation); return true; } if (accept != null) @@ -264,7 +251,7 @@ public static bool BeginDeposit(MyContract self, long playerId) Guid operation = Guid.NewGuid(); if (!accept(self, playerId, operation)) return false; - s_accepted = (self.Id, operation); + ContractActivation.Current.Accepted = (self.Id, operation); } return true; } @@ -272,10 +259,10 @@ public static bool BeginDeposit(MyContract self, long playerId) /// Called from the injected IL of Activate, right after Activate_Internal. public static void CommitDeposit() { - s_accepted = default; - var reservation = s_playerReservation; - s_playerReservation = default; - IDisposable scope = s_deposit; + ContractActivation.Current.Accepted = default; + var reservation = ContractActivation.Current.PlayerReservation; + ContractActivation.Current.PlayerReservation = default; + IDisposable scope = ContractActivation.Current.Deposit; if (scope != null) { MyContractSeams.ClusterCommitDeposit?.Invoke(scope, reservation.Operation); diff --git a/Test/ContractActivation/ContractActivation.csproj b/Test/ContractActivation/ContractActivation.csproj new file mode 100644 index 00000000..92124518 --- /dev/null +++ b/Test/ContractActivation/ContractActivation.csproj @@ -0,0 +1,4 @@ + + Exenet10.0enable14 + + diff --git a/Test/ContractActivation/Program.cs b/Test/ContractActivation/Program.cs new file mode 100644 index 00000000..e097dfb4 --- /dev/null +++ b/Test/ContractActivation/Program.cs @@ -0,0 +1,44 @@ +using Shared.Patches; + +var outer = ContractActivation.Enter(); +var deposit = new Probe(); +var operation = Guid.NewGuid(); +outer.Deposit = deposit; +outer.PlayerReservation = (1, operation); +var rolledBack = new List(); +void Withdraw(long contract, Guid _) => rolledBack.Add(contract); + +// An inner callback can return before opening a deposit. +ContractActivation.Enter().Close(Withdraw); +if ( + ContractActivation.Current != outer + || deposit.Closed + || outer.PlayerReservation != (1, operation) +) + throw new Exception("An empty inner activation changed its caller"); + +var inner = ContractActivation.Enter(); +var otherDeposit = new Probe(); +inner.Deposit = otherDeposit; +inner.Accepted = (2, Guid.NewGuid()); +inner.Close(Withdraw); +if ( + ContractActivation.Current != outer + || deposit.Closed + || !otherDeposit.Closed + || !rolledBack.SequenceEqual([2L]) +) + throw new Exception("Inner cleanup did not stay within its own invocation"); + +outer.Close(Withdraw); +if (ContractActivation.Current != null || !deposit.Closed || rolledBack.Count != 1) + throw new Exception("Outer cleanup did not complete exactly once"); + +Console.WriteLine("Nested activation scope checks passed"); + +sealed class Probe : IDisposable +{ + public bool Closed { get; private set; } + + public void Dispose() => Closed = true; +} From 5cc52fa446f78b39bb817584f6c19c12a33a863d Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 06:08:31 +0100 Subject: [PATCH 09/12] Remember released contract reservations across retries --- Shared/Cluster/ContractAcceptIntentFile.cs | 31 +++++++++++++ Shared/Cluster/ContractLedger.PlayerAccept.cs | 22 ++++++--- .../ContractAcceptIntent.csproj | 10 +++++ Test/ContractAcceptIntent/Program.cs | 45 +++++++++++++++++++ Test/scenarios_contract_origin.py | 2 +- 5 files changed, 103 insertions(+), 7 deletions(-) create mode 100644 Shared/Cluster/ContractAcceptIntentFile.cs create mode 100644 Test/ContractAcceptIntent/ContractAcceptIntent.csproj create mode 100644 Test/ContractAcceptIntent/Program.cs diff --git a/Shared/Cluster/ContractAcceptIntentFile.cs b/Shared/Cluster/ContractAcceptIntentFile.cs new file mode 100644 index 00000000..ab3df21d --- /dev/null +++ b/Shared/Cluster/ContractAcceptIntentFile.cs @@ -0,0 +1,31 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace ClusterPlugin; + +internal static class ContractAcceptIntentFile +{ + public static string[] Pending(string directory) => + Directory + .GetFiles(directory, "*.intent") + .Concat(Directory.GetFiles(directory, "*.release")) + .ToArray(); + + public static bool IsReleasing(string path) => + path.EndsWith(".release", StringComparison.Ordinal); + + public static async Task PrepareRelease(string path, Func> ensureReserved) + { + // Recreating a reservation after its Release can strand it if the authority + // still remembers the Release result but has evicted the older Reserve. + if (IsReleasing(path)) + return path; + if (!await ensureReserved().ConfigureAwait(false)) + return null; + string release = Path.ChangeExtension(path, ".release"); + File.Move(path, release); + return release; + } +} diff --git a/Shared/Cluster/ContractLedger.PlayerAccept.cs b/Shared/Cluster/ContractLedger.PlayerAccept.cs index 285a822c..d622052e 100644 --- a/Shared/Cluster/ContractLedger.PlayerAccept.cs +++ b/Shared/Cluster/ContractLedger.PlayerAccept.cs @@ -51,7 +51,7 @@ internal static void RecoverPlayerAccepts(string data, IEnumerable commitO try { Directory.CreateDirectory(folder); - string[] files = Directory.GetFiles(folder, "*.intent"); + string[] files = ContractAcceptIntentFile.Pending(folder); if (files.Length != 0) { var commits = new HashSet(commitOperations); @@ -73,7 +73,10 @@ private static async Task RecoverIntent(string path, HashSet committed) var intent = JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new InvalidDataException("Empty contract acceptance intent"); - await ResolveIntent(intent, path, committed.Contains(intent.Offer.AcceptanceOperation)); + bool confirm = + !ContractAcceptIntentFile.IsReleasing(path) + && committed.Contains(intent.Offer.AcceptanceOperation); + await ResolveIntent(intent, path, confirm); } catch (Exception error) { @@ -102,11 +105,18 @@ private static async Task AwaitReservation(Intent intent) private static async Task ResolveIntent(Intent intent, string path, bool confirm) { - // A release cannot overtake an unanswered Reserve on another connection. - if (!confirm && !(await AwaitReservation(intent)).Success) + if (!confirm) { - ForgetIntent(path); - return; + string release = await ContractAcceptIntentFile.PrepareRelease( + path, + async () => (await AwaitReservation(intent)).Success + ); + if (release == null) + { + ForgetIntent(path); + return; + } + path = release; } var decision = new Request( confirm ? "Confirm" : "Release", diff --git a/Test/ContractAcceptIntent/ContractAcceptIntent.csproj b/Test/ContractAcceptIntent/ContractAcceptIntent.csproj new file mode 100644 index 00000000..62de3167 --- /dev/null +++ b/Test/ContractAcceptIntent/ContractAcceptIntent.csproj @@ -0,0 +1,10 @@ + + + Exe + net10.0 + enable + + + + + diff --git a/Test/ContractAcceptIntent/Program.cs b/Test/ContractAcceptIntent/Program.cs new file mode 100644 index 00000000..3bef7263 --- /dev/null +++ b/Test/ContractAcceptIntent/Program.cs @@ -0,0 +1,45 @@ +using ClusterPlugin; + +var folder = Directory.CreateTempSubdirectory(); +try +{ + string intent = Path.Combine(folder.FullName, "one.intent"); + const string contents = """{"Decision":"92e7973e-0262-433a-9060-9d1bb41f727f"}"""; + File.WriteAllText(intent, contents); + File.WriteAllText(Path.Combine(folder.FullName, "incomplete.tmp"), ""); + int reservations = 0; + Task Reserve() + { + reservations++; + return Task.FromResult(true); + } + + var first = ContractAcceptIntentFile.Pending(folder.FullName).Single(); + if (first != intent || ContractAcceptIntentFile.IsReleasing(first)) + throw new InvalidOperationException("Expected the original pending intent"); + if (await ContractAcceptIntentFile.PrepareRelease(intent, () => Task.FromResult(false)) != null) + throw new InvalidOperationException("A refused reservation advanced to release"); + + string release = await ContractAcceptIntentFile.PrepareRelease(intent, Reserve); + if ( + release != Path.ChangeExtension(intent, ".release") + || File.Exists(intent) + || File.ReadAllText(release) != contents + ) + throw new InvalidOperationException("The release phase must retain the original decision"); + + var recovered = ContractAcceptIntentFile.Pending(folder.FullName).Single(); + if ( + !ContractAcceptIntentFile.IsReleasing(recovered) + || await ContractAcceptIntentFile.PrepareRelease(recovered, Reserve) != release + || reservations != 1 + ) + throw new InvalidOperationException("Recovery must replay only the release"); + Console.WriteLine( + "PASS: a resumed release uses the original decision and does not request a second reservation." + ); +} +finally +{ + folder.Delete(recursive: true); +} diff --git a/Test/scenarios_contract_origin.py b/Test/scenarios_contract_origin.py index 805709ed..5e28b371 100644 --- a/Test/scenarios_contract_origin.py +++ b/Test/scenarios_contract_origin.py @@ -235,7 +235,7 @@ def authority(reserved, active): "WA recovered the origin's decision", ) wait_until( - lambda: not intent.exists(), + lambda: not intent.exists() and not intent.with_suffix(".release").exists(), RECOVERY_TIMEOUT, "origin removed the resolved intent", ) From 2ef06c1eee0d8a44ff0da8fe3ab2d4fe6b065d14 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 06:14:53 +0100 Subject: [PATCH 10/12] Coalesce repeated contract accept clicks while awaiting confirmation --- Shared/Cluster/ContractLedger.PlayerAccept.cs | 32 ++++++++++---- .../Source/ContractConfirmHoldRoutes.cs | 6 +-- .../Source/ContractTestRoutes.cs | 44 +++++++++++++++++++ Test/scenarios_contracts.py | 41 ++++++++++++++++- 4 files changed, 110 insertions(+), 13 deletions(-) diff --git a/Shared/Cluster/ContractLedger.PlayerAccept.cs b/Shared/Cluster/ContractLedger.PlayerAccept.cs index d622052e..18eda122 100644 --- a/Shared/Cluster/ContractLedger.PlayerAccept.cs +++ b/Shared/Cluster/ContractLedger.PlayerAccept.cs @@ -15,10 +15,19 @@ namespace ClusterPlugin; internal static partial class ContractLedger { - private sealed class PlayerAccept(MyContract offer, long player) + private sealed class PlayerAccept( + MyContract offer, + long player, + MyContractBlock block, + EndpointId sender + ) { public readonly MyContract Offer = offer; public readonly long Player = player; + + public bool IsSameClick(MyContractBlock source, long identity, EndpointId endpoint) => + block == source && Player == identity && sender == endpoint; + public readonly Guid Operation = Guid.NewGuid(); public bool AllowGrant; public bool Committed; @@ -157,13 +166,8 @@ internal static bool TryStartPlayerAccept(MyContractBlock block, long player, lo || contract <= 0 || system == null || !block.HasAccess() - || !system.m_inactiveContracts.TryGetValue(contract, out var offer) ) return false; - long Station() => - MySession.Static.Factions.GetStationByGridId(block.CubeGrid.EntityId)?.Id ?? 0; - if (offer.StartStation != Station() && offer.StartBlock != block.EntityId) - return false; var sender = MyEventContext.Current.Sender; void Reply(MyContractResults result) => MyMultiplayer.RaiseEvent(block, x => x.ReceiveAcceptContract, result, sender); @@ -172,13 +176,25 @@ void Reply(MyContractResults result) => Reply(MyContractResults.Fail_CannotAccess); return true; } - var pending = new PlayerAccept(offer, player); - if (!PlayerAccepts.TryAdd(contract, pending)) + // The client keeps a single callback on this block. An early duplicate reply + // would consume it even after local activation, while confirmation is pending. + PlayerAccepts.TryGetValue(contract, out var existing); + if (existing?.IsSameClick(block, player, sender) == true) + return true; + if (!system.m_inactiveContracts.TryGetValue(contract, out var offer)) + return false; + long Station() => + MySession.Static.Factions.GetStationByGridId(block.CubeGrid.EntityId)?.Id ?? 0; + if (offer.StartStation != Station() && offer.StartBlock != block.EntityId) + return false; + if (existing != null) { Reply(MyContractResults.Fail_NotPossible); return true; } + var pending = new PlayerAccept(offer, player, block, sender); + PlayerAccepts.Add(contract, pending); var session = MySession.Static; var game = MySandboxGame.Static; try diff --git a/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs index e1958070..b0ba984b 100644 --- a/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs @@ -4,7 +4,7 @@ namespace ClusterTestPlugin; -/// Hold one outbound confirmation until the origin process is killed. Its replacement sends normally. +/// Hold one outbound confirmation until released or the origin process exits. internal static class ContractConfirmHoldRoutes { private static long m_contract; @@ -19,7 +19,7 @@ public static void Register() context => { long contract = TestRoutes.Long(context, "contract"); - if (contract <= 0) + if (contract < 0) throw new ArgumentOutOfRangeException(nameof(contract)); if (!m_patched) { @@ -56,7 +56,7 @@ private static bool BeforeSend(object request) || fields.Property("ContractId").GetValue() != Interlocked.Read(ref m_contract) ) return true; - // Send returns null for a missing answer. The normal worker retries until the origin dies. + // Send returns null for a missing answer. The normal worker retries. Interlocked.Increment(ref m_held); return false; } diff --git a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs index fc683f6c..bd0471b8 100644 --- a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text.Json; using ClusterPlugin; +using HarmonyLib; using Sandbox; using Sandbox.Common.ObjectBuilders; using Sandbox.Common.ObjectBuilders.Definitions; @@ -50,6 +51,45 @@ private sealed class Received private static readonly Dictionary Callbacks = new(); + private static ulong m_watchedUser; + private static int m_acceptReplies; + private static bool m_watchingReplies; + + private static void WatchAcceptReplies(ulong user) + { + if (!m_watchingReplies) + { + var dispatch = AccessTools.DeclaredMethod( + typeof(MyReplicationServer), + "DispatchEvent", + [ + typeof(IPacketData), + typeof(CallSite), + typeof(EndpointId), + typeof(IMyNetObject), + typeof(Vector3D?), + ] + ); + new Harmony("ClusterTestPlugin.ContractReplies").Patch( + dispatch, + prefix: new HarmonyMethod(typeof(ContractTestRoutes), nameof(CountAcceptReply)) + ); + m_watchingReplies = true; + } + m_watchedUser = user; + m_acceptReplies = 0; + } + + private static void CountAcceptReply(CallSite site, EndpointId target) + { + if ( + target.Value == m_watchedUser + && site.MethodInfo.DeclaringType == typeof(MyContractBlock) + && site.MethodInfo.Name == nameof(MyContractBlock.ReceiveAcceptContract) + ) + m_acceptReplies++; + } + public static void Register() { // POST /contract-test-block?owner=&x=&y=&z=[&anyone=1] - a dynamic grid (an armor bed and a contract block) @@ -712,6 +752,9 @@ item.Content is MyObjectBuilder_Package package { switch (op) { + case "watch-accept-replies": + WatchAcceptReplies(user); + break; case "accept": block.AcceptContract(identity, contractId); break; @@ -734,6 +777,7 @@ item.Content is MyObjectBuilder_Package package identity, block = blockId, character = character?.EntityId ?? 0, + acceptReplies = user == m_watchedUser ? (int?)m_acceptReplies : null, packagesBefore = before, packagesAfter = Packages(), contract = Active(contractId, identity), diff --git a/Test/scenarios_contracts.py b/Test/scenarios_contracts.py index d4cbfeb6..eb32f593 100644 --- a/Test/scenarios_contracts.py +++ b/Test/scenarios_contracts.py @@ -482,6 +482,10 @@ def pending() -> dict | None: active = ledger.active(ledger.wa, contract, identity) return status if active.get("reserved") and not active["active"] else None + def player_request(op: str) -> dict: + return ledger.node(node, f"/contract-test-rpc?op={op}" + query, "POST") + + player_request("watch-accept-replies") drop = "/test-drop-command-responses" copy = ledger.node(node, f"/contract-test-offer-copy?contract={contract}")["offer"] other = _other(node) @@ -501,6 +505,12 @@ def pending() -> dict | None: "the WA reserves the offer without activating it while the save is held", held is not None, ) + duplicate = player_request("accept") + bench.check( + "a repeat click while reserving leaves the player's result callback pending", + duplicate["acceptReplies"] == 0, + json.dumps(duplicate), + ) # This route dispatches to the node's game thread. A blocked activation cannot answer it. started = time.monotonic() clock = _try(lambda: bench.cluster.node(node, "/plugin-clock", timeout=1)) @@ -561,7 +571,26 @@ def pending() -> dict | None: restored.get("reserved") and not restored["active"], json.dumps(restored), ) - ledger.node(node, drop + "?subsystem=contracts&count=0", "POST") + confirm = "/contract-test-hold-confirm" + ledger.node(node, f"{confirm}?contract={contract}", "POST") + try: + ledger.node(node, drop + "?subsystem=contracts&count=0", "POST") + _require( + bench, + "the courier has activated locally and is waiting for confirmation", + _poll( + lambda: ledger.node(node, confirm)["held"] > 0 or None, HANDOVER_TIMEOUT + ) + is not None, + ) + duplicate = player_request("accept") + bench.check( + "a repeat click after the grant leaves the player's result callback pending", + duplicate["packagesAfter"] == 1 and duplicate["acceptReplies"] == 0, + json.dumps(duplicate), + ) + finally: + ledger.node(node, confirm + "?contract=0", "POST") def delivered() -> dict | None: state = ledger.node(node, "/contract-test-rpc?op=status" + query, "POST") @@ -571,7 +600,15 @@ def delivered() -> dict | None: else None ) - return _poll(delivered, HANDOVER_TIMEOUT) or {} + delivered_state = _poll(delivered, HANDOVER_TIMEOUT) or {} + bench.check( + "the server sends one acceptance reply to the player for the three clicks", + _poll( + lambda: player_request("status")["acceptReplies"] or None, HANDOVER_TIMEOUT + ) + == 1, + ) + return delivered_state def p3_con_clients(bench) -> None: From 40855b96ced8c4b73e2ce69b64b78197181f1898 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 06:20:10 +0100 Subject: [PATCH 11/12] Accept zero to release the confirmation test hold --- Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs index b0ba984b..422e79ab 100644 --- a/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Threading; using HarmonyLib; @@ -18,7 +19,10 @@ public static void Register() "/contract-test-hold-confirm", context => { - long contract = TestRoutes.Long(context, "contract"); + long contract = long.Parse( + TestRoutes.Query(context, "contract"), + CultureInfo.InvariantCulture + ); if (contract < 0) throw new ArgumentOutOfRangeException(nameof(contract)); if (!m_patched) From a5cc7dde5c2a312eae72a88de0ca2c49df0c5e55 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 19:48:49 +0100 Subject: [PATCH 12/12] Let stranded contract reservations expire and settle before confirmation A reservation at the World Authority was only ever cleared by its origin. An origin that lost its intent folder, or failed during activation before the payment commit, left the offer blocked and the player's contract slot taken until the next restart, or for good. - A reservation older than contracts.reservationSeconds (default 900) gives way to another acceptance and no longer counts against the limit. - Confirm and Release carry the offer. A confirmation that arrives after its reservation expired still installs the grant when nobody else took the offer. A refused confirmation keeps the intent and logs contract_grant_refused instead of telling the player the grant failed. - A failed activation decides its intent from the payment journal at once, and a failed resolution retries every minute instead of waiting for a restart. - A settlement or update from the origin installs its pending grant first, so a player can abandon or finish a contract before the confirmation lands. Updates in that window are no longer lost. - BeginDeposit records the player reservation before any early return, and CommitDeposit reports it even without a deposit scope. The ledger scenario strands a reservation and checks that it expires. The client scenario abandons a contract while its confirmation is held. --- Shared/Cluster/ClusterConfig.cs | 4 + Shared/Cluster/ContractLedger.PlayerAccept.cs | 80 +++++++++---- Shared/Cluster/ContractLedger.cs | 109 +++++++++++++++--- Shared/Cluster/StorePaymentJournal.cs | 53 ++++++--- Shared/Patches/MyContractPatch.cs | 12 +- .../Source/ContractTestRoutes.cs | 24 ++++ Test/scenarios_contracts.py | 80 ++++++++++++- 7 files changed, 292 insertions(+), 70 deletions(-) diff --git a/Shared/Cluster/ClusterConfig.cs b/Shared/Cluster/ClusterConfig.cs index d89f7f99..f72da2bc 100644 --- a/Shared/Cluster/ClusterConfig.cs +++ b/Shared/Cluster/ClusterConfig.cs @@ -81,6 +81,10 @@ public static class ClusterConfig // SE-1525: a store trade finishes against the node's banking replica and settles with the World Authority in the // background. false: every trade waits on the game thread for the WA to approve its debit, as before. ["store.asyncPayments"] = "true", + // SE-1909: a player's contract reservation at the World Authority that its origin has neither confirmed nor + // released this long no longer blocks the offer or counts against the contract limit. A later confirmation + // still installs the contract if nobody else took the offer in the meantime. + ["contracts.reservationSeconds"] = "900", // SE-1892: a station purchase of ore, ingots, components or ammo adds its items in one call, not one per unit. // false: vanilla's per-unit loop (a 78,063-ingot purchase was a 300-840 ms frame on the live cluster). ["store.batchPurchases"] = "true", diff --git a/Shared/Cluster/ContractLedger.PlayerAccept.cs b/Shared/Cluster/ContractLedger.PlayerAccept.cs index 18eda122..9bf1dbf7 100644 --- a/Shared/Cluster/ContractLedger.PlayerAccept.cs +++ b/Shared/Cluster/ContractLedger.PlayerAccept.cs @@ -75,23 +75,44 @@ internal static void RecoverPlayerAccepts(string data, IEnumerable commitO } } + // Decides an intent from the durable payment journal: a recorded grant is confirmed, anything else released. + // A failure other than an unreadable intent tries again a minute later, so it does not wait for a restart. private static async Task RecoverIntent(string path, HashSet committed) { - try - { - var intent = - JsonSerializer.Deserialize(File.ReadAllText(path)) - ?? throw new InvalidDataException("Empty contract acceptance intent"); - bool confirm = - !ContractAcceptIntentFile.IsReleasing(path) - && committed.Contains(intent.Offer.AcceptanceOperation); - await ResolveIntent(intent, path, confirm); - } - catch (Exception error) + while (true) { - Console.WriteLine( - $"[ClusterPlugin] leaving unresolved contract intent {path}: {error}" - ); + // The release phase renames the intent; an earlier attempt may have got that far. + string release = Path.ChangeExtension(path, ".release"); + if (!File.Exists(path) && File.Exists(release)) + path = release; + if (!File.Exists(path)) + return; + try + { + var intent = + JsonSerializer.Deserialize(File.ReadAllText(path)) + ?? throw new InvalidDataException("Empty contract acceptance intent"); + bool confirm = + !ContractAcceptIntentFile.IsReleasing(path) + && committed.Contains(intent.Offer.AcceptanceOperation); + await ResolveIntent(intent, path, confirm); + return; + } + catch (Exception error) when (error is JsonException or InvalidDataException) + { + Console.WriteLine( + $"[ClusterPlugin] leaving unreadable contract intent {path}: {error}" + ); + return; + } + catch (Exception error) + { + Console.WriteLine( + $"[ClusterPlugin] contract intent {path} failed, retrying in a minute: {error}" + ); + } + await Task.Delay(TimeSpan.FromMinutes(1)).ConfigureAwait(false); + committed = StorePaymentJournal.ContractOperations(); } } @@ -127,18 +148,25 @@ private static async Task ResolveIntent(Intent intent, string path, bool confirm } path = release; } - var decision = new Request( - confirm ? "Confirm" : "Release", - intent.Offer.ContractId, - AcceptanceOperation: intent.Offer.AcceptanceOperation - ); + // The decision carries the offer, so a confirmation that arrives after the reservation expired can still + // install the grant when nobody else took the offer. + var decision = intent.Offer with + { + Kind = confirm ? "Confirm" : "Release", + }; Result answer; while ((answer = Send(decision, intent.Decision)) == null) await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false); if (!answer.Success) - throw new InvalidDataException( - $"Authority refused {decision.Kind} for contract {decision.ContractId}: {answer.Reason}" + { + // Only a late confirmation can be refused: another player took the offer after this reservation + // expired. The intent stays for an operator and for the next start. + Console.WriteLine( + $"[ClusterPlugin] contract_grant_refused id={decision.ContractId} kind={decision.Kind}" + + $" reason={answer.Reason} intent={path}" ); + return; + } ForgetIntent(path); } @@ -303,15 +331,19 @@ void Complete(Intent intent, string path, Result answer) { try { - if (!uncertain && File.Exists(path)) + // An activation that failed before its commit decides from the journal, like a restart. + if (uncertain) + await RecoverIntent(path, StorePaymentJournal.ContractOperations()); + else if (File.Exists(path)) await ResolveIntent(intent, path, confirm); } catch (Exception error) { - result = MyContractResults.Fail_NotPossible; + // The player's result stands: a granted contract is theirs, a refused one stays refused. Console.WriteLine( - $"[ClusterPlugin] leaving unresolved contract intent {path}: {error}" + $"[ClusterPlugin] contract intent {path} failed, retrying: {error}" ); + _ = RecoverIntent(path, StorePaymentJournal.ContractOperations()); } game.Invoke( () => diff --git a/Shared/Cluster/ContractLedger.cs b/Shared/Cluster/ContractLedger.cs index a0e39d14..fdc8044b 100644 --- a/Shared/Cluster/ContractLedger.cs +++ b/Shared/Cluster/ContractLedger.cs @@ -137,7 +137,12 @@ private sealed record Result(bool Success, string Reason = null); private sealed record Snapshot(string Contracts, Settlement[] Settled); - private sealed record Reservation(string Origin, Request Offer, long[] Owners); + private sealed record Reservation( + string Origin, + Request Offer, + long[] Owners, + DateTime ReservedUtc = default + ); private static readonly Dictionary Reservations = new(); @@ -191,7 +196,7 @@ private static bool Accept(MyContract contract, long playerId, Guid operation) { lock (Sync) if ( - Reservations.ContainsKey(contract.Id) + Reservations.TryGetValue(contract.Id, out var reserved) && !Expired(reserved) || contract .Owners.Append(playerId) .Any(owner => @@ -533,7 +538,7 @@ request.Kind is not ("Finish" or "Fail") "Accept" or "Reserve" => AcceptHere(origin, request), "Confirm" or "Release" => FinishReservation(origin, request), "Withdraw" => WithdrawHere(request.ContractId, request.AcceptanceOperation), - "Update" => UpdateHere(request), + "Update" => UpdateHere(origin, request), "Finish" or "Fail" => Settle(request, origin, ranHere: false), "BlockGone" => BlockGoneHere(request.Block), _ => throw new InvalidOperationException( @@ -569,12 +574,24 @@ private static Result AcceptHere(string origin, Request request) throw new InvalidOperationException("Invalid accepted contract"); lock (Sync) if (Reservations.TryGetValue(builder.Id, out var existing)) - return new Result( + { + bool same = request.Kind == "Reserve" - && existing.Origin == origin - && existing.Offer.AcceptanceOperation == request.AcceptanceOperation, - "offer reserved" + && existing.Origin == origin + && existing.Offer.AcceptanceOperation == request.AcceptanceOperation; + if (same || !Expired(existing)) + return new Result(same, "offer reserved"); + // Its origin neither confirmed nor released it in time, for example because it lost its intent folder. + Reservations.Remove(builder.Id); + Console.WriteLine( + "[ClusterPlugin] contract reservation expired id=" + + builder.Id + + " origin=" + + existing.Origin + + " operation=" + + existing.Offer.AcceptanceOperation ); + } if (system.m_activeContracts.ContainsKey(builder.Id)) return new Result(false, "already accepted"); lock (Sync) @@ -597,7 +614,7 @@ private static Result AcceptHere(string origin, Request request) lock (Sync) Reservations.Add( builder.Id, - new Reservation(origin, request, builder.Owners.ToArray()) + new Reservation(origin, request, builder.Owners.ToArray(), DateTime.UtcNow) ); return new Result(true); } @@ -607,27 +624,36 @@ private static Result AcceptHere(string origin, Request request) private static bool AtLimit(MyIdentity identity) => identity.ActiveContracts.Count - + Reservations.Values.Count(r => r.Owners.Contains(identity.IdentityId)) + + Reservations.Values.Count(r => !Expired(r) && r.Owners.Contains(identity.IdentityId)) >= System.GetContractLimitPerPlayer(); + private static bool Expired(Reservation reservation) => + DateTime.UtcNow - reservation.ReservedUtc + > TimeSpan.FromSeconds(ClusterConfig.GetInt("contracts.reservationSeconds")); + private static Result FinishReservation(string origin, Request request) { Reservation reserved; lock (Sync) { if (!Reservations.TryGetValue(request.ContractId, out reserved)) - return new Result( - request.Kind == "Release" - || SettledIds.Contains(request.ContractId) - || Accepted.TryGetValue(request.ContractId, out var accepted) - && accepted.Operation == request.AcceptanceOperation - ); - if ( + { + if (request.Kind == "Release" || SettledIds.Contains(request.ContractId)) + return new Result(true); + if (Accepted.TryGetValue(request.ContractId, out var accepted)) + return new Result( + accepted.Operation == request.AcceptanceOperation, + "different acceptance" + ); + } + else if ( reserved.Origin != origin || reserved.Offer.AcceptanceOperation != request.AcceptanceOperation ) return new Result(request.Kind == "Release", "different reservation"); } + if (reserved == null) + return LateConfirm(origin, request); if (request.Kind == "Confirm") InstallAcceptance(reserved.Offer, Parse(reserved.Offer.Contract).Single()); lock (Sync) @@ -635,6 +661,42 @@ private static Result FinishReservation(string origin, Request request) return new Result(true); } + // The reservation expired and gave way. Nobody has taken the offer since, so the origin's grant still stands. + private static Result LateConfirm(string origin, Request request) + { + if (request.Contract == null) + return new Result(false, "no reservation"); + if (System.m_activeContracts.ContainsKey(request.ContractId)) + return new Result(false, "already accepted"); + InstallAcceptance(request, Parse(request.Contract).Single()); + Console.WriteLine( + "[ClusterPlugin] contract confirmed after its reservation expired id=" + + request.ContractId + + " origin=" + + origin + ); + return new Result(true); + } + + // A settlement or update from the origin means its player already holds the grant, so the pending + // confirmation can only succeed. Installing it now keeps the request from being refused meanwhile. + private static void InstallPendingGrant(string origin, long contractId) + { + Reservation reserved; + lock (Sync) + if (!Reservations.TryGetValue(contractId, out reserved) || reserved.Origin != origin) + return; + InstallAcceptance(reserved.Offer, Parse(reserved.Offer.Contract).Single()); + lock (Sync) + Reservations.Remove(contractId); + Console.WriteLine( + "[ClusterPlugin] contract installed ahead of its confirmation id=" + + contractId + + " origin=" + + origin + ); + } + private static void InstallAcceptance(Request request, MyObjectBuilder_Contract builder) { var system = System; @@ -676,8 +738,9 @@ private static Result WithdrawHere(long contractId, Guid operation) return new Result(true); } - private static Result UpdateHere(Request request) + private static Result UpdateHere(string origin, Request request) { + InstallPendingGrant(origin, request.ContractId); MySessionComponentContractSystem system = System ?? throw new InvalidOperationException("No contract system"); if ( @@ -726,6 +789,8 @@ private static Result Settle(Request request, string origin, bool ranHere) return new Result(ProbesSettled.Add(id), "probe"); MySessionComponentContractSystem system = System ?? throw new InvalidOperationException("No contract system"); + if (!ranHere) + InstallPendingGrant(origin, id); if ( !system.m_activeContracts.TryGetValue(id, out MyContract contract) || contract.State != MyContractStateEnum.Active @@ -945,7 +1010,15 @@ internal static void RestoreRecord(string payload) { Reservations.Clear(); foreach (var reservation in restored?.Reserved ?? Array.Empty()) - Reservations.Add(reservation.Offer.ContractId, reservation); + Reservations.Add( + reservation.Offer.ContractId, + reservation.ReservedUtc == default + ? reservation with + { + ReservedUtc = DateTime.UtcNow, + } + : reservation + ); Accepted.Clear(); foreach (Acceptance acceptance in restored?.Accepted ?? Array.Empty()) Accepted[acceptance.Id] = acceptance; diff --git a/Shared/Cluster/StorePaymentJournal.cs b/Shared/Cluster/StorePaymentJournal.cs index 5dd15d83..5c262258 100644 --- a/Shared/Cluster/StorePaymentJournal.cs +++ b/Shared/Cluster/StorePaymentJournal.cs @@ -335,26 +335,10 @@ Func command ContractLedger.RecoverPlayerAccepts(Path.GetDirectoryName(m_path), Array.Empty()); return; } - List entries; - lock (Sync) - entries = File.ReadAllLines(m_path) - .Where(line => !string.IsNullOrWhiteSpace(line)) - .Select(line => - { - try - { - return JsonSerializer.Deserialize(line); - } - catch - { - return null; - } - }) - .Where(entry => entry != null) - .ToList(); + List entries = ReadEntries(); ContractLedger.RecoverPlayerAccepts( Path.GetDirectoryName(m_path), - entries.Where(e => e.ContractOperation != Guid.Empty).Select(e => e.ContractOperation) + ContractOperations(entries) ); HashSet closed = entries .Where(entry => entry.Op == "closed") @@ -382,6 +366,39 @@ Entry entry in entries.Where(entry => Enqueue(new Work(null, entry, entry, false, "reconciled", command)); } + private static List ReadEntries() + { + lock (Sync) + return !File.Exists(m_path) + ? new List() + : File.ReadAllLines(m_path) + .Where(line => !string.IsNullOrWhiteSpace(line)) + .Select(line => + { + try + { + return JsonSerializer.Deserialize(line); + } + catch + { + return null; + } + }) + .Where(entry => entry != null) + .ToList(); + } + + private static HashSet ContractOperations(IEnumerable entries) => + entries + .Where(entry => entry.ContractOperation != Guid.Empty) + .Select(entry => entry.ContractOperation) + .ToHashSet(); + + /// The contract grants whose payment decision is in the journal. Reads the file, so callers run it off + /// the game thread. + internal static HashSet ContractOperations() => + m_ready ? ContractOperations(ReadEntries()) : new HashSet(); + private static void Enqueue(Work work) { lock (Sync) diff --git a/Shared/Patches/MyContractPatch.cs b/Shared/Patches/MyContractPatch.cs index 0d617f90..6b40b0e2 100644 --- a/Shared/Patches/MyContractPatch.cs +++ b/Shared/Patches/MyContractPatch.cs @@ -225,6 +225,9 @@ public static bool BeginDeposit(MyContract self, long playerId) { if (!ContractLedger.AllowActivation(self, playerId, out Guid approvedOperation)) return false; + // Recorded before any early return, so the commit below always reports a granted reservation. + if (approvedOperation != Guid.Empty) + ContractActivation.Current.PlayerReservation = (self.Id, approvedOperation); var seam = MyContractSeams.ClusterBeginDeposit; if (seam == null) return true; @@ -242,10 +245,7 @@ public static bool BeginDeposit(MyContract self, long playerId) // A refused acceptance leaves the reserved deposit to the finalizer, which refunds it. var accept = MyContractSeams.ClusterAccept; if (approvedOperation != Guid.Empty) - { - ContractActivation.Current.PlayerReservation = (self.Id, approvedOperation); return true; - } if (accept != null) { Guid operation = Guid.NewGuid(); @@ -264,11 +264,9 @@ public static void CommitDeposit() ContractActivation.Current.PlayerReservation = default; IDisposable scope = ContractActivation.Current.Deposit; if (scope != null) - { MyContractSeams.ClusterCommitDeposit?.Invoke(scope, reservation.Operation); - if (reservation.Operation != Guid.Empty) - ContractLedger.PlayerDepositCommitted(reservation.Contract, reservation.Operation); - } + if (reservation.Operation != Guid.Empty) + ContractLedger.PlayerDepositCommitted(reservation.Contract, reservation.Operation); } /// Called from the injected IL of Finish/Fail. Returns false when another node settled first. diff --git a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs index bd0471b8..960f3555 100644 --- a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs @@ -431,6 +431,30 @@ public static void Register() TestRoutes.Text(context, 200, GlobalStateChannel.SendCommand("contracts", payload)); } ); + // POST /contract-test-strand-reservation?contract=&identity= - reserves the offer at the World Authority for + // the identity without writing an intent, as if its origin had lost its contract-accepts folder. + TestRoutes.Add( + "POST", + "/contract-test-strand-reservation", + context => + { + long contract = TestRoutes.Long(context, "contract"), + identity = TestRoutes.Long(context, "identity"); + string payload = TestRoutes.OnGameThread(() => + JsonSerializer + .Serialize( + ContractLedger.AcceptRequest( + System().m_inactiveContracts[contract], + identity, + 0, + Guid.NewGuid() + ) + ) + .Replace("\"Kind\":\"Accept\"", "\"Kind\":\"Reserve\"") + ); + TestRoutes.Text(context, 200, GlobalStateChannel.SendCommand("contracts", payload)); + } + ); // POST /contract-test-rpc?op=accept|queue-accept|finish|abandon|status&userId=&block=&contract= - the contract block's own server // request handler for an attached player, as if the player's client had sent it (the client has no contract // screen to drive headless). Finish names the player's character as the delivering entity. diff --git a/Test/scenarios_contracts.py b/Test/scenarios_contracts.py index cf29b197..8a7ad7cb 100644 --- a/Test/scenarios_contracts.py +++ b/Test/scenarios_contracts.py @@ -41,7 +41,7 @@ from cluster import wait_until from scenarios import _all_partitions, _force_handover from scenarios_blocks import _identity -from scenarios_core import CLIENT_ID, HANDOVER_TIMEOUT, _handover_url, _partitions +from scenarios_core import CLIENT_ID, HANDOVER_TIMEOUT, _handover_url, _nodes, _partitions from scenarios_ext import _wait_arrival, _wait_partition from scenarios_recovery import RECOVERY_TIMEOUT from scenarios_redeliver import CLIENT2_ID, CLIENT2_PORT @@ -281,11 +281,52 @@ def newest() -> int: answer = ledger.node(holder, f"/contract-test-abandon?contract={lost}&identity={acceptor}", "POST") bench.check("lost accept: the retried contract can be abandoned", answer.get("result") == "Success", json.dumps(answer)) expect("abandon after the lost answers", REWARD + COLLATERAL, 0) + + # -- a reservation whose origin forgot it blocks the offer only until it expires -- + stranded = ledger.post(holder, block) + expect("posted for the stranded reservation", -REWARD, 0) + reply = ledger.node(holder, f"/contract-test-strand-reservation?contract={stranded}&identity={acceptor}", "POST") + _require(bench, "stranded: the World Authority reserved the offer", reply.get("Success") is True, json.dumps(reply)) + answer = ledger.node(holder, f"/contract-test-accept?contract={stranded}&identity={acceptor}&block={block}", "POST") + bench.check("stranded: a live reservation refuses another acceptance", not answer.get("accepted"), json.dumps(answer)) + expect("stranded: the refused acceptance cost nothing", 0, 0) + + def reservation_seconds(value: str) -> None: + # The World Authority decides expiry; set its config directly, the way p1_wa_heap_limit does. + values = dict(ledger.node(ledger.wa, "/config")["values"], **{"contracts.reservationSeconds": value}) + bench.cluster._request("PUT", "/cluster/config", _nodes(bench)[ledger.wa].control, 30, values) + wait_until( + lambda: ledger.node(ledger.wa, "/config")["values"]["contracts.reservationSeconds"] == value, + 30, + f"the World Authority to apply a {value} s reservation lifetime", + ) + + reservation_seconds("5") + try: + taken = _poll( + lambda: ledger.node( + holder, f"/contract-test-accept?contract={stranded}&identity={acceptor}&block={block}", "POST" + ).get("accepted") or None, + 30, + interval=2, + ) + finally: + reservation_seconds("900") + bench.check("stranded: the expired reservation gave way to a new acceptance", taken is not None) + bench.check( + "stranded: the World Authority logged the expiry", + _node_line(bench, ledger.wa, f"contract reservation expired id={stranded} ", 10) is not None, + ) + expect("accepted after the reservation expired", 0, -COLLATERAL) + ledger.wait_listed("stranded: the new acceptance is listed everywhere", stranded, acceptor, True) + answer = ledger.node(holder, f"/contract-test-abandon?contract={stranded}&identity={acceptor}", "POST") + bench.check("stranded: the contract can be abandoned", answer.get("result") == "Success", json.dumps(answer)) + expect("abandon after the expiry", REWARD + COLLATERAL, 0) finally: _try(lambda: bench.cluster.post("/automatic/resume")) - bench.exercised(block=block, contracts=[finished, timed, restarted, failover, lost], + bench.exercised(block=block, contracts=[finished, timed, restarted, failover, lost, stranded], legs="accept, timeout at the WA, finish on the other node, replay, node restart, WA failover, " - "lost acceptance answers") + "lost acceptance answers, expired reservation") def _node_line(bench, node: str, pattern: str, timeout: float = 5) -> str | None: @@ -736,6 +777,39 @@ def delivered(): and ledger.balance(a) == opening, json.dumps(active), ) + + # A abandons while the origin's confirmation is still on its way. The World Authority installs the grant + # for the settlement, and the late confirmation then finds the contract settled. + early = ledger.node(node_b, f"/contract-test-post?block={start}&reward={REWARD}", "POST") + _require(bench, "the second acquisition contract was posted", early["success"]) + early_id = early["contractId"] + confirm = "/contract-test-hold-confirm" + ledger.node(node_b, f"{confirm}?contract={early_id}", "POST") + try: + ledger.node( + node_b, + f"/contract-test-rpc?op=queue-accept&userId={CLIENT_ID}&block={start}&contract={early_id}", + "POST", + ) + _require( + bench, + "the grant is waiting for its confirmation", + _poll(lambda: ledger.node(node_b, confirm)["held"] > 0 or None, HANDOVER_TIMEOUT) is not None, + ) + answer = ledger.node(node_b, f"/contract-test-abandon?contract={early_id}&identity={a}", "POST") + bench.record("abandon-before-confirm", answer) + bench.check( + "A can abandon the contract before its confirmation lands", + answer.get("result") == "Success", + json.dumps(answer), + ) + finally: + ledger.node(node_b, confirm + "?contract=0", "POST") + ledger.wait_listed("the contract abandoned before its confirmation is listed nowhere", early_id, a, False) + bench.check( + "the late confirmation of the settled contract succeeds", + _node_line(bench, ledger.wa, f"kind=Confirm id={early_id} origin={node_b} success=True", 60) is not None, + ) finally: _try(lambda: bench.cluster.post("/automatic/resume")) bench.exercised(contract=contract, clients=[CLIENT_ID, CLIENT2_ID], where=where)