From 49e85491b06dfd8afe6df3024178323f7a8f8986 Mon Sep 17 00:00:00 2001 From: Viktor Ferenczi Date: Wed, 25 Nov 2026 04:56:53 +0100 Subject: [PATCH] Bind contract withdrawal to the winning acceptance --- Shared/Cluster/ContractLedger.cs | 48 ++++++++++++++----- Shared/Cluster/Seams/MyContractSeams.cs | 4 +- Shared/Patches/MyContractPatch.cs | 22 +++++---- .../Source/ContractTestRoutes.cs | 19 ++++++++ Test/scenarios_contracts.py | 10 ++++ 5 files changed, 79 insertions(+), 24 deletions(-) diff --git a/Shared/Cluster/ContractLedger.cs b/Shared/Cluster/ContractLedger.cs index a4780308..85eeb9af 100644 --- a/Shared/Cluster/ContractLedger.cs +++ b/Shared/Cluster/ContractLedger.cs @@ -102,7 +102,13 @@ internal static class ContractLedger private static readonly Dictionary UnansweredSettlements = new(); private static double m_nextUnansweredRetry; - internal sealed record Acceptance(long Id, long Block, long BlockOwner, long Player); + internal sealed record Acceptance( + long Id, + long Block, + long BlockOwner, + long Player, + Guid Operation = default + ); internal sealed record Settlement(long Id, string Kind, long Player); @@ -117,7 +123,8 @@ private sealed record Request( bool PunishOwner = true, long FirstOwner = 0, long[] Owners = null, - bool ConditionFinished = false + bool ConditionFinished = false, + Guid AcceptanceOperation = default ); private sealed record Result(bool Success, string Reason = null); @@ -160,7 +167,7 @@ public static void Install() // ---- seams, on the node running the vanilla code (game thread) ---- - private static bool Accept(MyContract contract, long playerId) + private static bool Accept(MyContract contract, long playerId, Guid operation) { if (!ClusterRuntime.IsClustered || contract.Id <= 0) return true; @@ -174,7 +181,8 @@ private static bool Accept(MyContract contract, long playerId) contract.Id, contract.StartBlock, blockOwner, - playerId + playerId, + operation ); return true; } @@ -188,8 +196,10 @@ private static bool Accept(MyContract contract, long playerId) Serialize(new[] { builder }), playerId, contract.StartBlock, - blockOwner - ) + blockOwner, + AcceptanceOperation: operation + ), + operation ); if (result?.Success != true) { @@ -203,7 +213,7 @@ private static bool Accept(MyContract contract, long playerId) ); // Unanswered, the World Authority may have taken it all the same. if (result == null) - Send(new Request("Withdraw", contract.Id)); + Send(new Request("Withdraw", contract.Id, AcceptanceOperation: operation)); // A stale offer: the block's entry stops carrying it at the next save (ContractOffers.Saving). else if (result.Reason == AlreadySettled) { @@ -218,19 +228,23 @@ private static bool Accept(MyContract contract, long playerId) return true; } - private static void Withdraw(long contractId) + private static void Withdraw(long contractId, Guid operation) { if (!ClusterRuntime.IsClustered || contractId <= 0) return; if (ClusterRuntime.IsWorldAuthority) { lock (Sync) - Accepted.Remove(contractId); + if ( + Accepted.TryGetValue(contractId, out var accepted) + && accepted.Operation == operation + ) + Accepted.Remove(contractId); return; } lock (Sync) AcceptedHere.Remove(contractId); - Send(new Request("Withdraw", contractId)); + Send(new Request("Withdraw", contractId, AcceptanceOperation: operation)); } private static bool TrySettle(MyContract contract, string kind, bool punishOwner) @@ -485,7 +499,7 @@ request.Kind is not ("Finish" or "Fail") Result result = request.Kind switch { "Accept" => AcceptHere(request), - "Withdraw" => WithdrawHere(request.ContractId), + "Withdraw" => WithdrawHere(request.ContractId, request.AcceptanceOperation), "Update" => UpdateHere(request), "Finish" or "Fail" => Settle(request, origin, ranHere: false), "BlockGone" => BlockGoneHere(request.Block), @@ -549,13 +563,21 @@ private static Result AcceptHere(Request request) builder.Id, request.Block, request.BlockOwner, - request.Player + request.Player, + request.AcceptanceOperation ); return new Result(true); } - private static Result WithdrawHere(long contractId) + private static Result WithdrawHere(long contractId, Guid operation) { + // Both the acceptance and its refusal may lose their replies. Only the winning attempt can undo it. + lock (Sync) + if ( + !Accepted.TryGetValue(contractId, out var accepted) + || accepted.Operation != operation + ) + return new Result(false, "different acceptance"); MySessionComponentContractSystem system = System ?? throw new InvalidOperationException("No contract system"); if ( diff --git a/Shared/Cluster/Seams/MyContractSeams.cs b/Shared/Cluster/Seams/MyContractSeams.cs index 828a586d..eb112847 100644 --- a/Shared/Cluster/Seams/MyContractSeams.cs +++ b/Shared/Cluster/Seams/MyContractSeams.cs @@ -16,8 +16,8 @@ public static class MyContractSeams // 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. - public static Func ClusterAccept; - public static Action ClusterWithdraw; + public static Func ClusterAccept; + public static Action ClusterWithdraw; // Finish/Fail: every node holding a copy of a contract could reach a terminal state on its own - a player // finishing here while the World Authority's timeout fails it there - and each would settle the reward and diff --git a/Shared/Patches/MyContractPatch.cs b/Shared/Patches/MyContractPatch.cs index a800ebd8..79cbda21 100644 --- a/Shared/Patches/MyContractPatch.cs +++ b/Shared/Patches/MyContractPatch.cs @@ -42,7 +42,7 @@ public static class MyContractPatch private static IDisposable s_deposit; [ThreadStatic] - private static long s_accepted; + private static (long Contract, Guid Operation) s_accepted; private static readonly MethodInfo CanActivateInternal = EconomyIl.Required( AccessTools.Method(typeof(MyContract), "CanActivate_Internal"), @@ -129,12 +129,12 @@ MethodBase original private static void Finalizer() { IDisposable scope = s_deposit; - long accepted = s_accepted; + var accepted = s_accepted; s_deposit = null; - s_accepted = 0; + s_accepted = default; scope?.Dispose(); - if (accepted != 0) - MyContractSeams.ClusterWithdraw?.Invoke(accepted); + if (accepted.Contract != 0) + MyContractSeams.ClusterWithdraw?.Invoke(accepted.Contract, accepted.Operation); } } @@ -248,16 +248,20 @@ 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 (accept != null && !accept(self, playerId)) - return false; - s_accepted = self.Id; + if (accept != null) + { + Guid operation = Guid.NewGuid(); + if (!accept(self, playerId, operation)) + return false; + s_accepted = (self.Id, operation); + } return true; } /// Called from the injected IL of Activate, right after Activate_Internal. public static void CommitDeposit() { - s_accepted = 0; + s_accepted = default; IDisposable scope = s_deposit; if (scope != null) MyContractSeams.ClusterCommitDeposit?.Invoke(scope); diff --git a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs index 6a60075e..6431a039 100644 --- a/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs +++ b/Test/ClusterTestPlugin/Source/ContractTestRoutes.cs @@ -4,6 +4,8 @@ using System.IO; using System.IO.Compression; using System.Linq; +using System.Text.Json; +using ClusterPlugin; using Sandbox.Common.ObjectBuilders; using Sandbox.Common.ObjectBuilders.Definitions; using Sandbox.Definitions; @@ -371,6 +373,23 @@ public static void Register() ); } ); + TestRoutes.Add( + "POST", + "/contract-test-withdraw-other-attempt", + context => + { + long contract = TestRoutes.Long(context, "contract"); + string payload = JsonSerializer.Serialize( + new + { + Kind = "Withdraw", + ContractId = contract, + AcceptanceOperation = Guid.NewGuid(), + } + ); + 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 // 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 cceea348..4ab6bf72 100644 --- a/Test/scenarios_contracts.py +++ b/Test/scenarios_contracts.py @@ -244,6 +244,16 @@ def newest() -> int: ledger.wa = "wa-2" ledger.wait_listed("failover: after the World Authority failover every node and wa-2 list the contract", failover, acceptor, True) away = _other(_all_partitions(bench).get(partition) or "node-1") + # A competing accept that lost both replies may try to undo the winner after failover. + rollback = ledger.node( + away, f"/contract-test-withdraw-other-attempt?contract={failover}", "POST" + ) + _require( + bench, + "a different acceptance attempt cannot withdraw the winner after failover", + rollback.get("Success") is False, + json.dumps(rollback), + ) answer = ledger.node(away, f"/contract-test-abandon?contract={failover}&identity={acceptor}", "POST") bench.record("abandon-after-failover", answer) bench.check(f"failover: {away}, away from the block, abandoned the contract", answer.get("result") == "Success", json.dumps(answer))