I am working on a Unity Transport + Jobs server system for my game that has the layout of:
recieve netcode packets → turn them to game events → parallel execution of systems → send back events from each system
Problem is that I keep getting an error:
InvalidOperationException:
The previously scheduled job CalculateWorkerVisibilityJob writes to the Unity.Collections.NativeArray1[System.Int32] CalculateWorkerVisibilityJob.driver.m_PendingBeginSend.
You are trying to schedule a new job CalculateMinionVisibilityJob, which writes to the same Unity.Collections.NativeArray1[System.Int32] (via CalculateMinionVisibilityJob.driver.m_PendingBeginSend).
To guarantee safety, you must include CalculateWorkerVisibilityJob as a dependency of the newly scheduled job.
But this makes no sense because I use the NetworkDriver.Concurrent that I get using NetworkDriver.ToConcurrent().
The root cause seems to be m_PendingBeginSend array that is just passed along in the internal NetworkDriver.Concurrent. Here are some relevant code snippets I found inside NetworkDriver.cs.
Constructor wrapper:
/// <summary>Create a <see cref="Concurrent"/> copy of the <c>NetworkDriver</c>.</summary>
/// <returns>A <see cref="Concurrent"/> instance for the driver.</returns>
public Concurrent ToConcurrent()
{
if (!IsCreated)
return default;
return new Concurrent
{
m_EventQueue = m_EventQueue.ToConcurrent(),
m_ConnectionList = m_NetworkStack.Connections,
m_PipelineProcessor = m_PipelineProcessor.ToConcurrent(),
m_DriverSender = m_DriverSender.ToConcurrent(),
m_DriverReceiver = m_DriverReceiver,
m_PacketPadding = m_NetworkStack.PacketPadding,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_ThreadIndex = 0,
m_PendingBeginSend = m_PendingBeginSend
#endif
};
}
What version of transport out of interest? We had a similar issue but I thought they had fixed it
2.5.2
Fixed an issue where scheduling multiple update or send jobs in the same job chain would result in safety exceptions being thrown when using WebSockets.
It could have been a similar but different issue though.
Is the netcode.ConcurrentDriver accessor a property that actually constructs a new NetworkDriver.Concurrent on every access? If so, have you tried constructing an instance first and then scheduling all your jobs with that instance? If it’s instead a field always containing the same Concurrent instance, have you tried constructing a new instance before scheduling your jobs?
In any case, I’ll have a look on our end. This isn’t expected behavior. In the meantime if you’re willing to modify the package locally, you can tag that native array with the NativeDisableContainerSafetyRestriction attribute to get that error to go away. This is safe to do, as there are no ways to get races on that data structure without also getting safety errors on pretty much all the containers in the driver.
I take back what I said about it being safe to disable safety restrictions on that array. I’m not so sure anymore that what you’re attempting to do is safe to do (or even supported by Unity Transport).
The issue here is that you have multiple separate parallel jobs (the worker/minion/sector visibility jobs) that are themselves executing in parallel. That’s not a use case we’ve really encountered before. Most of our uses of the concurrent driver is to achieve connection-based parallelization. We’ll have many jobs that parallelize the work for each connection, but these jobs will be chained together to avoid situations where two threads can work on the same connection at the same time. That’s something that’s possible in your use of the package (in fact I’d go so far as presuming that this is precisely what you want to achieve).
I’ll have to dig deeper in our jobs code to see if that’s a use case we can support. There would be limitations however (e.g. no pipelines). I’ll also make sure to clarify our documentation regarding the intended usage of the concurrent driver.
Yes. I have the single NetworkDriver.Concurrent cached away in a custom abstraction, but after the error I thought it was not how you are supposed to do it. Because of this I have tried:
Get NetworkDriver.Concurrent once at initialization
Get three different instances of NetworkDriver.Concurrent once at initialization
Get NetworkDriver.Concurrent at the start of every frame
Get NetworkDriver.Concurrent right after NetworkDriver.ScheduleUpdate(), but before scheduling the Jobs that throw the error
Get three different instances of NetworkDriver.Concurrent right after NetworkDriver.ScheduleUpdate(), but before scheduling the Jobs that throw the error
None of these change anything, but getting NetworkDriver.Concurrent instances after NetworkDriver.ScheduleUpdate() does somehow throw more errors. Although they are 100% caused by the job error exiting the whole server flow (no safety/throw checks in use yet).
“Structure that can be used to access a NetworkDriver from multiple jobs. Only a subset of operations are supported because not all operations are safe to perform concurrently. Must be obtained with the ToConcurrent() method.” - Struct NetworkDriver.Concurrent Documentation
This made me understand that you can use it in many Jobs concurrently, as long as you are ok with some of the limitations of it.
Would fixing this be anywhere in your upcoming plans? Do I make a bug report or is it a “feature” and thus you will change the documentation?
Edit: I just remembered that pipelines use a global static state that they can modify… I see why true concurrency might not be possible.
Also if I were to add another step for sending the packets, what would be the best way to collect all the packets needed for sending from multiple jobs at the same time? As in what native container to use.
Your point about the documentation is very valid. It very much needs clarification about exactly what concurrency situations the concurrent driver can deal with. Thanks for pointing that out.
For now I’ll modify the documentation since it’s the expected behavior. But I think your use case is quite interesting and there definitely would be value in supporting it, at least partially. For pipelines we might be able to relax the requirements a bit and say only require that no two jobs send on the same connection on the same pipeline at the same time. That’s going to require some extra investigation on our end though, and thus I can’t commit to anything.
NativeQueue has a parallel writer that can be used for that purpose.
Unfortunately it seems like NativeQueue<T>ParallelWriter Is having the same issues as the NetworkDriver.Concurrent.
I think the Unity Job system is simply not designed to support what I am trying to do. The plan was:
One job (parallel per connection) to convert NetcodePackets into GameEvents.
Many jobs (Worker, Minion, Sector) that consume their own GameEvents only. Just mark used and later cleaned up on the main thread.
Same number of jobs execute their behavior. They could even run one by one in a IJobParalelFor because I would use one buffer for last frame that all instances read from (to make minions see each other) and one buffer for write only that is the next/current frame output. Lastly a queue for raising GameEvents for the next frame.
Same number of jobs check visibility for all of their instances to see what updates need to be sent to what clients to prevent cheating/keeping mystery & fog of war. Because NetworkDriver.Concurrent doesn’t work like I wanted create a NetcodePacket queue.
Single job (parallel per connection) that reads the NetcodePacket queue and sends them out.
This just simply doesn’t work. It feels like the engine is fighting back at every level. Networking, Jobs, Burst… None of them like to share the same native containers, even if the data is “safe”, at least in theory.
Now I’m just not sure how do proceed. I know “premature optimization is the root of all evil” and all that, but the project that I’m embarking on has the gameplay run 99% on the server, the client is basically a visual interpretation on what is happening on the server. and the maximum amount of players connected at once is 4 +1 spectator max. running all simulation per connection instead of per system seems like a very unpolitical solution, especially because most of the systems interact on a small scale and are largely individual.
Honesty I am just writing it out here because of frustration, not some request for Unity. At the end of the day I will figure it out some other way, after a ton of pacing forwards and back in my room
Is there a particular reason you are not using Entities for this? If you have so many actors in your game that you feel that parallel jobs are needed to process them, it feels to me like you could be better served by an ECS architecture. Plus, our Entities package alleviates many of the frustrations of dealing with the lower-level jobs and containers. (I can understand not wanting to use Netcode for Entities since it’s not always a good fit for all game genres. Although if you haven’t looked into it, it might be worth investigating.)
And I know you mentioned being aware of it already, but I would also warn about premature optimization here. Scheduling jobs has a cost of its own, and even if you managed to have your plan working, you could end up in a situation where you’re losing performance overall versus a less parallelized approach. For example unless you’re processing a lot of traffic per tick, parallelizing sending/receiving for only 5 clients is probably not worth it.