From 131c49f84f41a66123c3fa1566e97d03338a748d Mon Sep 17 00:00:00 2001 From: Noel Stephens Date: Mon, 30 Nov 2026 10:39:24 -0600 Subject: [PATCH 1/2] fix: late time sync no longer steps client time back NetworkTimeSystem.Advance only hard-resets forward. A sync that puts the desired time more than HardResetThresholdSec behind now slews back at AdjustmentRatio instead. Reset() can still step time back. NetworkTransform's tick driver skips only a repeated tick; if the tick goes back it keeps sending with ticks above the last one sent, so receivers do not drop the states. --- com.unity.netcode.gameobjects/CHANGELOG.md | 1 + .../Runtime/Components/NetworkTransform.cs | 9 +- .../Runtime/Timing/NetworkTimeSystem.cs | 32 ++++-- .../Timing/ClientNetworkTimeSystemTests.cs | 60 +++++++++++ .../NetworkTransformClockStepBackTests.cs | 101 ++++++++++++++++++ ...NetworkTransformClockStepBackTests.cs.meta | 2 + 6 files changed, 197 insertions(+), 8 deletions(-) create mode 100644 com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs create mode 100644 com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs.meta diff --git a/com.unity.netcode.gameobjects/CHANGELOG.md b/com.unity.netcode.gameobjects/CHANGELOG.md index df8bec4dd2..628d844d7c 100644 --- a/com.unity.netcode.gameobjects/CHANGELOG.md +++ b/com.unity.netcode.gameobjects/CHANGELOG.md @@ -22,6 +22,7 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Fixed +- Issue where a time sync that arrived late could step a client's network time back, so the `NetworkTransform`s it owns sent no state updates until its time caught up again. A late time sync now slows the client's time down instead, and a `NetworkTransform` keeps sending with increasing ticks if the time does step back. (#XXXX) - Issue where `NetworkAnimator` logged an error for a trigger-conditioned transition into an Exit node, and a client that joined during that transition, or during one into a sub-state machine, did not synchronize with it. Transitions that pass through Exit, Entry or sub-state machine nodes now resolve to the state they reach, and a late-joining client cross-fades from the matching originating state when several states transition into the same destination. (#4240) - Fixed a NullReferenceException that would be thrown if a MonoBehaviour derived from NetworkManager defines it's own Awake or OnEnable. (#4237) - Issue where `NetworkTime` reported a `TickOffset` of almost a whole tick, instead of zero, for some times that land on a tick (for example 0.3 at a tick rate of 10), which put `TickWithPartial` one tick ahead or, in long sessions, `Tick` one tick behind. Times between minus one tick and zero now report tick -1 with a positive `TickOffset`, as other negative times do. (#4227) diff --git a/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs b/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs index 9ac503a926..1ba2794dff 100644 --- a/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs +++ b/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs @@ -4797,11 +4797,16 @@ public void Remove() /// internal void TickUpdate() { - // TODO FIX: The local NetworkTickSystem can invoke with the same network tick as before - if (CurrentTick <= m_LastTick) + if (CurrentTick == m_LastTick) { return; } + // If the clock stepped back, keep sending with ticks above the last one sent: + // non-authority instances drop any state that is not newer than the last one they received. + if (CurrentTick < m_LastTick) + { + CurrentTick = m_LastTick + 1; + } if (m_NetworkManager == null || m_NetworkManager.ShutdownInProgress || !m_NetworkManager.IsListening) { Remove(); diff --git a/com.unity.netcode.gameobjects/Runtime/Timing/NetworkTimeSystem.cs b/com.unity.netcode.gameobjects/Runtime/Timing/NetworkTimeSystem.cs index a967052a16..ddd7d06afb 100644 --- a/com.unity.netcode.gameobjects/Runtime/Timing/NetworkTimeSystem.cs +++ b/com.unity.netcode.gameobjects/Runtime/Timing/NetworkTimeSystem.cs @@ -227,7 +227,16 @@ public static NetworkTimeSystem ServerTimeSystem() /// /// The amount of time to advance. The delta time which passed since Advance was last called. /// True if a hard reset of the time system occurred due to large time offset differences. False if normal time advancement occurred + /// + /// A hard reset only moves time forward. When a sync puts the desired time more than + /// behind, time slows down by instead. + /// public bool Advance(double deltaTimeSec) + { + return Advance(deltaTimeSec, false); + } + + private bool Advance(double deltaTimeSec, bool allowBackwardReset) { m_PreviousTimeSec = m_TimeSec; m_TimeSec += deltaTimeSec; @@ -238,15 +247,26 @@ public bool Advance(double deltaTimeSec) TickLatency = (int)Mathf.Max(2.0f, Mathf.Round(m_TickLatencyAverage)); } - if (Math.Abs(m_DesiredLocalTimeOffset - m_CurrentLocalTimeOffset) > HardResetThresholdSec || Math.Abs(m_DesiredServerTimeOffset - m_CurrentServerTimeOffset) > HardResetThresholdSec) + var localStep = m_DesiredLocalTimeOffset - m_CurrentLocalTimeOffset; + var serverStep = m_DesiredServerTimeOffset - m_CurrentServerTimeOffset; + if (!allowBackwardReset) + { + // A sync that arrives late (a resend, or one read after a long frame) makes the server look further behind + // than it is, so only a forward gap hard-resets. + localStep = Math.Max(localStep, 0.0); + serverStep = Math.Max(serverStep, 0.0); + } + + if (Math.Abs(localStep) > HardResetThresholdSec || Math.Abs(serverStep) > HardResetThresholdSec) { - m_TimeSec += m_DesiredServerTimeOffset; + var serverOffset = m_CurrentServerTimeOffset + serverStep; + m_TimeSec += serverOffset; - m_DesiredLocalTimeOffset -= m_DesiredServerTimeOffset; - m_CurrentLocalTimeOffset = m_DesiredLocalTimeOffset; + m_CurrentLocalTimeOffset += localStep - serverOffset; + m_DesiredLocalTimeOffset -= serverOffset; - m_DesiredServerTimeOffset = 0; m_CurrentServerTimeOffset = 0; + m_DesiredServerTimeOffset -= serverOffset; return true; } @@ -265,7 +285,7 @@ public bool Advance(double deltaTimeSec) public void Reset(double serverTimeSec, double rttSec) { Sync(serverTimeSec, rttSec); - Advance(0); + Advance(0, true); } internal int SyncCount; /// diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs index fc7cb01d69..b1e16f5905 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs @@ -185,5 +185,65 @@ public void ResetTest() }); } + + /// + /// Validates that a sync putting the desired time more than the hard reset threshold behind, as a late + /// time sync does, slows time down rather than stepping it back. + /// + [Test] + public void LateSyncSlowsTimeInsteadOfSteppingBack() + { + const double deltaTime = 1.0d / 60.0d; + double receivedServerTime = 2; + var timeSystem = new NetworkTimeSystem(0.05d, 0.05d, 0.2d); + timeSystem.Reset(receivedServerTime, 0.1d); + timeSystem.Sync(receivedServerTime - 0.5d, 0.1d); + + var expectedStep = deltaTime * (1.0d - timeSystem.AdjustmentRatio); + for (int i = 0; i < 60; i++) + { + var localTime = timeSystem.LocalTime; + var serverTime = timeSystem.ServerTime; + Assert.IsFalse(timeSystem.Advance(deltaTime), $"A sync behind the current time hard-reset the clock on frame {i}."); + Assert.AreEqual(expectedStep, timeSystem.LocalTime - localTime, 1e-9d, $"Local time did not slow down on frame {i}."); + Assert.AreEqual(expectedStep, timeSystem.ServerTime - serverTime, 1e-9d, $"Server time did not slow down on frame {i}."); + } + } + + /// + /// Validates that a hard reset forward on server time leaves local time where it is when the same sync puts + /// local time behind, as it does when the RTT drops at the same time. + /// + [Test] + public void ForwardResetDoesNotStepLocalTimeBack() + { + const double deltaTime = 1.0d / 60.0d; + double receivedServerTime = 2; + var timeSystem = new NetworkTimeSystem(0.05d, 0.05d, 0.2d); + timeSystem.Reset(receivedServerTime, 2.0d); + var localTime = timeSystem.LocalTime; + + // Server time 0.5s ahead with the half RTT down from 1s to 0.05s puts desired local time 0.45s behind. + receivedServerTime += 0.5d; + timeSystem.Sync(receivedServerTime, 0.1d); + + Assert.IsTrue(timeSystem.Advance(deltaTime), "A sync 0.5s ahead did not hard-reset the clock."); + Assert.AreEqual(receivedServerTime + deltaTime - timeSystem.ServerBufferSec, timeSystem.ServerTime, 1e-9d); + Assert.AreEqual(localTime + deltaTime, timeSystem.LocalTime, 1e-9d, "Local time stepped back during the hard reset."); + } + + /// + /// Validates that still sets the given time when it is earlier than the current one. + /// + [Test] + public void ResetCanStepTimeBack() + { + var timeSystem = new NetworkTimeSystem(0.05d, 0.05d, 0.2d); + timeSystem.Reset(2.0d, 0.1d); + timeSystem.Reset(1.0d, 0.1d); + + Assert.AreEqual(1.0d - timeSystem.ServerBufferSec, timeSystem.ServerTime, 1e-9d); + Assert.AreEqual(1.0d + 0.05d + timeSystem.LocalBufferSec, timeSystem.LocalTime, 1e-9d); + } } } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs new file mode 100644 index 0000000000..5a9b070867 --- /dev/null +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs @@ -0,0 +1,101 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using Unity.Netcode.Components; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using UnityEngine.TestTools; + +namespace Unity.Netcode.RuntimeTests +{ + /// + /// Validates that an owner authoritative keeps sending state updates, with ticks + /// that keep increasing, after the owner's clock steps back. + /// + internal class NetworkTransformClockStepBackTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 1; + + // Far enough back to cover several ticks at any tick rate the tests run with. + private const double k_StepBackSeconds = 0.5d; + + // Well under the one second between time syncs, which would move the clock forward again. + private const float k_MoveSeconds = 0.3f; + + private const int k_MinimumStatesAfterStepBack = 3; + + private GameObject m_Prefab; + + internal class StateTickRecorder : NetworkTransform + { + public readonly List ReceivedTicks = new List(); + + protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState) + { + ReceivedTicks.Add(newState.NetworkTick); + base.OnNetworkTransformStateUpdated(ref oldState, ref newState); + } + } + + protected override void OnServerAndClientsCreated() + { + m_Prefab = CreateNetworkObjectPrefab("ClockStepBack"); + var networkTransform = m_Prefab.AddComponent(); + networkTransform.AuthorityMode = NetworkTransform.AuthorityModes.Owner; + base.OnServerAndClientsCreated(); + } + + [UnityTest] + public IEnumerator OwnerKeepsSendingAfterClockStepsBack() + { + var host = GetAuthorityNetworkManager(); + var client = GetNonAuthorityNetworkManager(); + var spawnedInstance = SpawnObject(m_Prefab, client); + yield return WaitForSpawnedOnAllOrTimeOut(spawnedInstance); + AssertOnTimeout($"Timed out waiting for {spawnedInstance.name} to spawn on all instances."); + + var networkObjectId = spawnedInstance.GetComponent().NetworkObjectId; + var ownerInstance = client.SpawnManager.SpawnedObjects[networkObjectId].gameObject; + var hostInstance = host.SpawnManager.SpawnedObjects[networkObjectId].GetComponent(); + + var receivedAtSpawn = hostInstance.ReceivedTicks.Count; + yield return WaitForConditionOrTimeOut(() => + { + ownerInstance.transform.position += Vector3.right * 0.1f; + return hostInstance.ReceivedTicks.Count > receivedAtSpawn; + }); + AssertOnTimeout("Timed out waiting for the first state update from the owner."); + + // A time sync just applied leaves about a second before the next one. + var syncCount = client.NetworkTimeSystem.SyncCount; + yield return WaitForConditionOrTimeOut(() => + { + ownerInstance.transform.position += Vector3.right * 0.1f; + return client.NetworkTimeSystem.SyncCount != syncCount; + }); + AssertOnTimeout("Timed out waiting for a time sync."); + + var lastTickBeforeStepBack = hostInstance.ReceivedTicks[hostInstance.ReceivedTicks.Count - 1]; + var receivedBeforeStepBack = hostInstance.ReceivedTicks.Count; + client.NetworkTimeSystem.Reset(client.ServerTime.Time - k_StepBackSeconds, client.NetworkTimeSystem.LastSyncedRttSec); + + var endTime = Time.realtimeSinceStartup + k_MoveSeconds; + while (Time.realtimeSinceStartup < endTime) + { + ownerInstance.transform.position += Vector3.right * 0.1f; + yield return null; + } + + var receivedAfterStepBack = hostInstance.ReceivedTicks.Count - receivedBeforeStepBack; + Assert.GreaterOrEqual(receivedAfterStepBack, k_MinimumStatesAfterStepBack, + $"The host received {receivedAfterStepBack} state updates in {k_MoveSeconds}s after the owner's clock stepped back."); + + var previousTick = lastTickBeforeStepBack; + for (int i = receivedBeforeStepBack; i < hostInstance.ReceivedTicks.Count; i++) + { + Assert.Greater(hostInstance.ReceivedTicks[i], previousTick, $"State update {i} was sent with tick {hostInstance.ReceivedTicks[i]}, not after tick {previousTick}."); + previousTick = hostInstance.ReceivedTicks[i]; + } + } + } +} diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs.meta b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs.meta new file mode 100644 index 0000000000..8bf747351f --- /dev/null +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformClockStepBackTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 159b3c480b9b4ac9a8aca5ed3456b951 From be835362c9ab34fe73ccac7b1d85ce90fadcdc80 Mon Sep 17 00:00:00 2001 From: Noel Stephens Date: Mon, 30 Nov 2026 12:03:11 -0600 Subject: [PATCH 2/2] chore: CHANGELOG PR number --- com.unity.netcode.gameobjects/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.netcode.gameobjects/CHANGELOG.md b/com.unity.netcode.gameobjects/CHANGELOG.md index 628d844d7c..d5ea9cdeb4 100644 --- a/com.unity.netcode.gameobjects/CHANGELOG.md +++ b/com.unity.netcode.gameobjects/CHANGELOG.md @@ -22,7 +22,7 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Fixed -- Issue where a time sync that arrived late could step a client's network time back, so the `NetworkTransform`s it owns sent no state updates until its time caught up again. A late time sync now slows the client's time down instead, and a `NetworkTransform` keeps sending with increasing ticks if the time does step back. (#XXXX) +- Issue where a time sync that arrived late could step a client's network time back, so the `NetworkTransform`s it owns sent no state updates until its time caught up again. A late time sync now slows the client's time down instead, and a `NetworkTransform` keeps sending with increasing ticks if the time does step back. (#4263) - Issue where `NetworkAnimator` logged an error for a trigger-conditioned transition into an Exit node, and a client that joined during that transition, or during one into a sub-state machine, did not synchronize with it. Transitions that pass through Exit, Entry or sub-state machine nodes now resolve to the state they reach, and a late-joining client cross-fades from the matching originating state when several states transition into the same destination. (#4240) - Fixed a NullReferenceException that would be thrown if a MonoBehaviour derived from NetworkManager defines it's own Awake or OnEnable. (#4237) - Issue where `NetworkTime` reported a `TickOffset` of almost a whole tick, instead of zero, for some times that land on a tick (for example 0.3 at a tick rate of 10), which put `TickWithPartial` one tick ahead or, in long sessions, `Tick` one tick behind. Times between minus one tick and zero now report tick -1 with a positive `TickOffset`, as other negative times do. (#4227)