diff --git a/Shared/Cluster/ClusterConfig.cs b/Shared/Cluster/ClusterConfig.cs index d89f7f9..f72da2b 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/ContractAcceptIntentFile.cs b/Shared/Cluster/ContractAcceptIntentFile.cs new file mode 100644 index 0000000..ab3df21 --- /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 new file mode 100644 index 0000000..9bf1dbf --- /dev/null +++ b/Shared/Cluster/ContractLedger.PlayerAccept.cs @@ -0,0 +1,365 @@ +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, + 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; + } + + // 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 || !pending.AllowGrant) + return false; + pending.AllowGrant = 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 = ContractAcceptIntentFile.Pending(folder); + if (files.Length != 0) + { + var commits = new HashSet(commitOperations); + foreach (string path in files) + _ = Task.Run(() => RecoverIntent(path, commits)); + } + m_intents = folder; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + Console.WriteLine($"[ClusterPlugin] contract reservations unavailable: {error}"); + } + } + + // 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) + { + while (true) + { + // 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(); + } + } + + 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) + { + if (!confirm) + { + string release = await ContractAcceptIntentFile.PrepareRelease( + path, + async () => (await AwaitReservation(intent)).Success + ); + if (release == null) + { + ForgetIntent(path); + return; + } + path = release; + } + // 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) + { + // 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); + } + + 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() + ) + 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; + } + // 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 + { + 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; + bool activating = 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)) + ) + { + activating = true; + pending.AllowGrant = 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 = activating && !pending.Committed; + Console.WriteLine( + $"[ClusterPlugin] player activation failed for {contract}: {error}" + ); + } + finally + { + pending.AllowGrant = false; + bool confirm = pending.Committed; + _ = Task.Run(async () => + { + try + { + // 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) + { + // The player's result stands: a granted contract is theirs, a refused one stays refused. + Console.WriteLine( + $"[ClusterPlugin] contract intent {path} failed, retrying: {error}" + ); + _ = RecoverIntent(path, StorePaymentJournal.ContractOperations()); + } + 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 85eeb9a..fdc8044 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,20 @@ 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, + DateTime ReservedUtc = default + ); + + 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 +194,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.TryGetValue(contract.Id, out var reserved) && !Expired(reserved) + || 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 +216,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 +244,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,9 +535,10 @@ 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), + "Update" => UpdateHere(origin, request), "Finish" or "Fail" => Settle(request, origin, ranHere: false), "BlockGone" => BlockGoneHere(request.Block), _ => throw new InvalidOperationException( @@ -521,7 +559,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 +572,26 @@ 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)) + { + bool same = + request.Kind == "Reserve" + && 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) @@ -547,16 +605,108 @@ 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(), DateTime.UtcNow) + ); + return new Result(true); + } + InstallAcceptance(request, builder); + return new Result(true); + } + + private static bool AtLimit(MyIdentity identity) => + identity.ActiveContracts.Count + + 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)) + { + 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) + Reservations.Remove(request.ContractId); + 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; 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 +716,6 @@ private static Result AcceptHere(Request request) request.Player, request.AcceptanceOperation ); - return new Result(true); } private static Result WithdrawHere(long contractId, Guid operation) @@ -589,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 ( @@ -608,6 +758,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 +767,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); } @@ -628,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 @@ -829,7 +992,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 +1008,17 @@ 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.ReservedUtc == default + ? reservation with + { + ReservedUtc = DateTime.UtcNow, + } + : reservation + ); Accepted.Clear(); foreach (Acceptance acceptance in restored?.Accepted ?? Array.Empty()) Accepted[acceptance.Id] = acceptance; @@ -973,7 +1148,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 e5c2140..70385ed 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 0042dd1..36de069 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 eb11284..899b7c1 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 86e78d9..5c26225 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,24 +331,15 @@ 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) - .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), + ContractOperations(entries) + ); HashSet closed = entries .Where(entry => entry.Op == "closed") .Select(entry => entry.ReserveId) @@ -362,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/ContractActivation.cs b/Shared/Patches/ContractActivation.cs new file mode 100644 index 0000000..6ac9eb2 --- /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/MyContractBlockPatch.cs b/Shared/Patches/MyContractBlockPatch.cs index 7aadfa2..d92e0ad 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 79cbda2..6b40b0e 100644 --- a/Shared/Patches/MyContractPatch.cs +++ b/Shared/Patches/MyContractPatch.cs @@ -38,12 +38,6 @@ namespace Shared.Patches; /// public static class MyContractPatch { - [ThreadStatic] - private static IDisposable s_deposit; - - [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" @@ -73,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, @@ -126,16 +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_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. @@ -232,6 +223,11 @@ 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; + // 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; @@ -243,17 +239,19 @@ 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) + return true; if (accept != null) { Guid operation = Guid.NewGuid(); if (!accept(self, playerId, operation)) return false; - s_accepted = (self.Id, operation); + ContractActivation.Current.Accepted = (self.Id, operation); } return true; } @@ -261,10 +259,14 @@ 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; - 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); + MyContractSeams.ClusterCommitDeposit?.Invoke(scope, 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/CommandResponseDropRoutes.cs b/Test/ClusterTestPlugin/Source/CommandResponseDropRoutes.cs index 546bd2e..667cd6f 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/ContractConfirmHoldRoutes.cs b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs new file mode 100644 index 0000000..422e79a --- /dev/null +++ b/Test/ClusterTestPlugin/Source/ContractConfirmHoldRoutes.cs @@ -0,0 +1,67 @@ +using System; +using System.Globalization; +using System.Threading; +using HarmonyLib; + +namespace ClusterTestPlugin; + +/// Hold one outbound confirmation until released or the origin process exits. +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 = long.Parse( + TestRoutes.Query(context, "contract"), + CultureInfo.InvariantCulture + ); + 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. + Interlocked.Increment(ref m_held); + return false; + } +} diff --git a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs index 6431a03..960f355 100644 --- a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs @@ -6,6 +6,8 @@ using System.Linq; using System.Text.Json; using ClusterPlugin; +using HarmonyLib; +using Sandbox; using Sandbox.Common.ObjectBuilders; using Sandbox.Common.ObjectBuilders.Definitions; using Sandbox.Definitions; @@ -49,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) @@ -390,7 +431,31 @@ 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-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. TestRoutes.Add( @@ -405,6 +470,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,8 +732,10 @@ 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), + type = contract?.GetType().Name, state = contract?.State.ToString(), owners = contract?.Owners.ToArray() ?? Array.Empty(), conditionFinished = contract?.ContractCondition?.IsFinished, @@ -670,7 +757,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; @@ -688,6 +776,9 @@ item.Content is MyObjectBuilder_Package package { switch (op) { + case "watch-accept-replies": + WatchAcceptReplies(user); + break; case "accept": block.AcceptContract(identity, contractId); break; @@ -697,6 +788,8 @@ item.Content is MyObjectBuilder_Package package case "abandon": block.AbandonContract(identity, contractId); break; + case "status": + break; default: throw new ArgumentException("Unknown op " + op); } @@ -708,6 +801,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/ClusterTestPlugin/Source/GlobalSaveHoldRoutes.cs b/Test/ClusterTestPlugin/Source/GlobalSaveHoldRoutes.cs index 6b40ccd..cf79034 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/ClusterTestPlugin/Source/TestRoutes.cs b/Test/ClusterTestPlugin/Source/TestRoutes.cs index 47429b0..e2c60eb 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/ContractAcceptIntent/ContractAcceptIntent.csproj b/Test/ContractAcceptIntent/ContractAcceptIntent.csproj new file mode 100644 index 0000000..62de316 --- /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 0000000..3bef726 --- /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/ContractActivation/ContractActivation.csproj b/Test/ContractActivation/ContractActivation.csproj new file mode 100644 index 0000000..9212451 --- /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 0000000..e097dfb --- /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; +} diff --git a/Test/run_suite.py b/Test/run_suite.py index b88dbc1..e434362 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 0000000..5e28b37 --- /dev/null +++ b/Test/scenarios_contract_origin.py @@ -0,0 +1,309 @@ +"""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, + _disable_contract_fixture_trash, + _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"]) + 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) + 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: + _disable_contract_fixture_trash(ledger) + 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 + f"&block={start}", "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" + 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) + _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() and not intent.with_suffix(".release").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", + ), +} diff --git a/Test/scenarios_contracts.py b/Test/scenarios_contracts.py index 67a1887..97d2bec 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 @@ -276,11 +276,52 @@ def newest() -> int: json.dumps(answer)) expect("lost accept: the collateral came back", 0, 0) ledger.wait_listed("lost accept: the winning attempt withdrew its own acceptance everywhere", lost, acceptor, False) + + # -- 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: @@ -463,6 +504,171 @@ 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: + 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 + + 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) + 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, + ) + 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)) + 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), + ) + 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") + return ( + state + if state["contract"]["active"] and state["packagesAfter"] == 1 + else None + ) + + 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: """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"]) @@ -483,9 +689,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) @@ -510,9 +714,9 @@ 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", + _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) @@ -538,8 +742,69 @@ 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), + ) + + # 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)