InvalidOperationException: two NativeArrays may not be the same (aliasing).

Hello Everyone!
can anyone help me with this error ?
Thanks in advance!

/// </summary>
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(PlayersNetworkingInteractionsSystem))]
public class PlayersStreamDataCollectorSystem : JobComponentSystem
{

    /// <summary>
    /// Collect Players Inputs and Add them to the  OutgoingUnreliableMessages Buffer
    /// </summary>
  //  [BurstCompile]
    [RequireComponentTag(typeof(ConnectedPlayer))]
    struct CollectingInputsJobs : IJobForEachWithEntity<AimInput, MovementInput>
    {
        [ReadOnly]
        [NativeDisableParallelForRestriction]
        public BufferFromEntity<NearbyRelatedUsers> nearbyRelatedUsersFromEntity;

        [ReadOnly]
        [NativeDisableParallelForRestriction]
        public ComponentDataFromEntity<AimInput> aimInputFromEntity;

        [ReadOnly]
        [NativeDisableParallelForRestriction]
        public ComponentDataFromEntity<MovementInput> movementInputFromEntity;

        [ReadOnly]
        [NativeDisableParallelForRestriction]
        public NativeArray<Entity> allPlayers;

        [NativeDisableParallelForRestriction]
        public BufferFromEntity<OutgoingUnreliableMessages> outgoingUnreliableMessagesFromEntity;

        public void Execute(Entity currentPlayerEntity, int index, ref AimInput aimInput, ref MovementInput movementInput)
        {
            var nearbyPlayers = nearbyRelatedUsersFromEntity[currentPlayerEntity];

            if (nearbyPlayers.Length == 0)
                return;
            
            uint playersConcernedIndex = 0;
            for(var i=0;i< nearbyPlayers.Length; i++)
            {
                NetworkingUtils.SetBitByIndex(ref playersConcernedIndex, nearbyPlayers[i].userIndex);
            }

         
            using(DataStreamWriter streamWriter = new DataStreamWriter( ( 1/*MessageType*/ +  4 /*Players Mask*/+  (UnsafeUtility.SizeOf<JoystickInputs>() *2) * nearbyPlayers.Length /*2 JoystickInputs * nearby Players*/), Allocator.Temp ))
            {
                // Set Message id
                streamWriter.Write(MessageBufferIndexes.Server_PlayersJoySticksInputs);

                // Set Concerned Players
                streamWriter.Write(playersConcernedIndex);

                // Set Inputs of all Concerned players
                for (var i = 0; i < nearbyPlayers.Length; i++)
                {
                   var moveInputs = movementInputFromEntity[allPlayers[nearbyPlayers[i].userIndex]];
                    moveInputs.ToJoystickInput().Serialize(streamWriter);

                    var aimInputs = aimInputFromEntity[allPlayers[nearbyPlayers[i].userIndex]];
                    aimInputs.ToJoystickInput().Serialize(streamWriter);
                }

                var outgoingStreamBuffer = outgoingUnreliableMessagesFromEntity[currentPlayerEntity];
                outgoingStreamBuffer.CopyFromWriter(streamWriter);
            }
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var collectionJob = new CollectingInputsJobs { // Error Here  Line:89
            aimInputFromEntity = GetComponentDataFromEntity<AimInput>(true),
            movementInputFromEntity = GetComponentDataFromEntity<MovementInput>(true),
            nearbyRelatedUsersFromEntity = GetBufferFromEntity<NearbyRelatedUsers>(true),
            outgoingUnreliableMessagesFromEntity = GetBufferFromEntity<OutgoingUnreliableMessages>(),
            allPlayers = ServerGameManager.instance.playersEntities,
        }.Schedule(this, inputDeps);

        return collectionJob;
    }
}
#endif

Error:

InvalidOperationException: The writable NativeArray CollectingInputsJobs.Iterator is the same NativeArray as CollectingInputsJobs.Data.aimInputFromEntity, two NativeArrays may not be the same (aliasing).
Unity.Entities.JobForEachExtensions.Schedule (System.Void* fullData, Unity.Collections.NativeArray`1[T] prefilterData, System.Int32 unfilteredLength, System.Int32 innerloopBatchCount, System.Boolean isParallelFor, System.Boolean isFiltered, Unity.Entities.JobForEachExtensions+JobForEachCache& cache, System.Void* deferredCountData, Unity.Jobs.JobHandle dependsOn, Unity.Jobs.LowLevel.Unsafe.ScheduleMode mode) (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/IJobForEach.cs:431)
Unity.Entities.JobForEachExtensions.ScheduleInternal_ECC[T] (T& jobData, Unity.Entities.ComponentSystemBase system, Unity.Entities.EntityQuery query, System.Int32 innerloopBatchCount, Unity.Jobs.JobHandle dependsOn, Unity.Jobs.LowLevel.Unsafe.ScheduleMode mode) (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/IJobForEach.gen.cs:2021)
Unity.Entities.JobForEachExtensions.Schedule[T] (T jobData, Unity.Entities.ComponentSystemBase system, Unity.Jobs.JobHandle dependsOn) (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/IJobForEach.gen.cs:813)
PlayersStreamDataCollectorSystem.OnUpdate (Unity.Jobs.JobHandle inputDeps) (at Assets/Scripts/ECS/Systems/ServerSideOnly/Networking/PlayersStreamDataCollectorSystem.cs:89)
Unity.Entities.JobComponentSystem.InternalUpdate () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:933)
Unity.Entities.ComponentSystemBase.Update () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:284)
Unity.Entities.ComponentSystemGroup.OnUpdate () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystemGroup.cs:602)
UnityEngine.Debug:LogException(Exception)
Unity.Debug:LogException(Exception) (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/Stubs/Unity/Debug.cs:25)
Unity.Entities.ComponentSystemGroup:OnUpdate() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystemGroup.cs:606)
Unity.Entities.ComponentSystem:InternalUpdate() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:800)
Unity.Entities.ComponentSystemBase:Update() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:284)
Unity.Entities.DummyDelegateWrapper:TriggerUpdate() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ScriptBehaviourUpdateOrder.cs:144)
  1. Just side note - why you doing that?
[ReadOnly]
[NativeDisableParallelForRestriction]

If you have ReadOnly you can access all indicies for R.
If you have NativeDisableParallelForRestriction you can access all indicies for RW.
These are two mutually exclusive things.
2) You have public ComponentDataFromEntity<AimInput> aimInputFromEntity; and ref AimInput aimInput it’s not allowed, cause it’s same arrays internaly. Moreover you’re not using ref AimInput aimInput, and using ComponentDataFromEntity. Move AimInput from IJobForEachWithEntity to RequireComponentTag and use only ComponentDataFromEntity instance.

1 Like

Thank you very much :slight_smile: i didnt noticed im referencing these CD and passing the ComponentDataFromEntity to the same job.

the [NativeDisableParallelForRestriction] i just added it to the end to test if that was the problem and i forgot them too XD.

thank you very much.

can you please show me what is the right way to use the UdpNetworkDriver for parallel access ?

my code :

[UpdateInGroup(typeof(PresentationSystemGroup))]
public class ServerSendMessagesSystem : JobComponentSystem
{
    ServerNetworkingManagerSystem serverNetworkingManagerSystem;

    /// <summary>
    /// Send Streams to Clients
    /// </summary>
    //[BurstCompile] // Disabled only when testing
    [RequireComponentTag(typeof(OutgoingUnreliableMessages))]
    public struct SendUnreliableMessagesJob : IJobForEachWithEntity<ConnectedPlayer>
    {
        public UdpNetworkDriver.Concurrent driver;
        [ReadOnly] public NetworkPipeline unreliablePipeline;

        [NativeDisableParallelForRestriction] public BufferFromEntity<OutgoingUnreliableMessages> outGoingBufferFromEntity;
        [ReadOnly] [NativeDisableParallelForRestriction] public NativeArray<NetworkConnection> connections;

        public void Execute(Entity entity, int index, ref ConnectedPlayer connectionId)
        {
            var connection = connections[connectionId.Id];
            if (!connection.IsCreated)
            {
                Debug.Log("connection is not Created");
                return;
            }
            var ouGoingDynamicBuffer = outGoingBufferFromEntity[entity];

            if (ouGoingDynamicBuffer.Length == 0)
                return;



            // Send the Client Stream Messages and Clear the Buffer
            using (var dataStreamWriter = new DataStreamWriter(ouGoingDynamicBuffer.Length, Allocator.Temp))
            {
                dataStreamWriter.CopyFromDynamicBufferAndClearIt(ouGoingDynamicBuffer);
                driver.Send(unreliablePipeline, connection, dataStreamWriter);
            } 
        }

    }


    /// <summary>
    /// Send RPCs to Clients
    /// </summary>
    //[BurstCompile] // Disabled only when testing
    [RequireComponentTag(typeof(OutgoingReliableMessages))]
    public struct SendReliableMessagesJob : IJobForEachWithEntity<ConnectedPlayer>
    {
        public UdpNetworkDriver.Concurrent driver;
        [NativeDisableParallelForRestriction] public BufferFromEntity<OutgoingReliableMessages> outGoingBufferFromEntity;
        [ReadOnly] public NetworkPipeline ReliablePipeline;
        [ReadOnly] [NativeDisableParallelForRestriction] public NativeArray<NetworkConnection> connections;

        public void Execute(Entity entity, int index, ref ConnectedPlayer connectionId)
        {
            var connection = connections[connectionId.Id];
            if (!connection.IsCreated)
            {
                Debug.Log("SendReliableMessagesJob connection is Unexpectedly disconnected");
                return;
            }
            var outGoingDynamicBuffer = outGoingBufferFromEntity[entity];

            if (outGoingDynamicBuffer.Length == 0)
                return;


            // Send the Client Stream Messages and Clear the Buffer
            using (var dataStreamWriter = new DataStreamWriter(outGoingDynamicBuffer.Length, Allocator.Temp))
            {
                dataStreamWriter.CopyFromDynamicBufferAndClearIt(outGoingDynamicBuffer);
                driver.Send(ReliablePipeline, connection, dataStreamWriter);
            }
        }

    }

    protected override void OnCreate()
    {
        serverNetworkingManagerSystem = World.Active.GetOrCreateSystem<ServerNetworkingManagerSystem>();
    }

    //TODO: Implement Burst For All Jobs (Need Debugs For Testing)

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        inputDeps=  serverNetworkingManagerSystem.m_Driver.ScheduleUpdate(inputDeps);

        // initializing Messaging Jobs
        var SendReliableMessagesJob = new SendReliableMessagesJob
        {
            driver = serverNetworkingManagerSystem.m_Driver.ToConcurrent(),
            ReliablePipeline = serverNetworkingManagerSystem.reliablePipeline,
            outGoingBufferFromEntity = GetBufferFromEntity<OutgoingReliableMessages>(isReadOnly: false),
            connections = serverNetworkingManagerSystem.m_Connections,
        };

        var SendUnreliableMessagesJob = new SendUnreliableMessagesJob
        {
            driver = serverNetworkingManagerSystem.m_Driver.ToConcurrent(),
            unreliablePipeline = serverNetworkingManagerSystem.unreliablePipeline,
            outGoingBufferFromEntity = GetBufferFromEntity<OutgoingUnreliableMessages>(isReadOnly: false),
            connections = serverNetworkingManagerSystem.m_Connections,
        };

        return JobHandle.CombineDependencies(SendReliableMessagesJob.Schedule(this, inputDeps), SendUnreliableMessagesJob.Schedule(this, inputDeps));
    }
}

error:

InvalidOperationException: The previously scheduled job IPv4UDPSocket:ReceiveJob`1 writes to the NativeArray ReceiveJob`1.receiver.m_EventQueue.m_ConnectionEventHeadTail. You must call JobHandle.Complete() on the job IPv4UDPSocket:ReceiveJob`1, before you can write to the NativeArray safely.
Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckWriteAndThrowNoEarlyOut (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at <dfc62061cb3f4b1bb57c5179a5db6830>:0)
Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckWriteAndThrow (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at <dfc62061cb3f4b1bb57c5179a5db6830>:0)
Unity.Networking.Transport.NetworkEventQueue+Concurrent+ConcurrentConnectionQueue..ctor (Unity.Collections.NativeList`1[T] queue) (at Packages/com.unity.transport/Runtime/NetworkEventQueue.cs:186)
Unity.Networking.Transport.NetworkEventQueue.ToConcurrent () (at Packages/com.unity.transport/Runtime/NetworkEventQueue.cs:162)
Unity.Networking.Transport.GenericNetworkDriver`2[T,TNetworkPipelineStageCollection].ToConcurrent () (at Packages/com.unity.transport/Runtime/NetworkDriver.cs:33)
Unity.Networking.Transport.UdpNetworkDriver.ToConcurrent () (at Packages/com.unity.transport/Runtime/NetworkDriver.cs:1199)
ServerSendMessagesSystem.OnUpdate (Unity.Jobs.JobHandle inputDeps) (at Assets/Scripts/ECS/Systems/ServerSideOnly/Networking/ServerSendMessagesSystem.cs:104)
Unity.Entities.JobComponentSystem.InternalUpdate () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:933)
Unity.Entities.ComponentSystemBase.Update () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:284)
Unity.Entities.ComponentSystemGroup.OnUpdate () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystemGroup.cs:602)
UnityEngine.Debug:LogException(Exception)
Unity.Debug:LogException(Exception) (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/Stubs/Unity/Debug.cs:25)
Unity.Entities.ComponentSystemGroup:OnUpdate() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystemGroup.cs:606)
Unity.Entities.ComponentSystem:InternalUpdate() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:800)
Unity.Entities.ComponentSystemBase:Update() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ComponentSystem.cs:284)
Unity.Entities.DummyDelegateWrapper:TriggerUpdate() (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities/ScriptBehaviourUpdateOrder.cs:144)