You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
VT server: object tree is used from the CAN thread and the application thread without a lock #775
This came up in the review of #772. I'm opening it separately, like we agreed there.
vtObjectTree in VirtualTerminalWorkingSetBase is used from more than one thread, and nothing protects it. managedWorkingSetMutex only guards a few fields, not the map.
The parse thread fills the map again with add_or_replace_object().
The application reads the same objects while it paints. In AgIsoVirtualTerminal that is the JUCE message thread.
So when a working set reloads its active pool, the map is cleared and refilled while the application can still be painting it. Before #772 the race was only on single objects. Now it is on the map structure itself.
Additional context
I think we first need to agree on the threading contract for VT server applications.
One option is that the stack owns a lock around the object tree, and the application also takes it while it paints. A lock only around the map is not enough, because the commands change the objects and the renderer reads them.
The other option is that the stack documents that a managed working set is only touched from one thread, and the application makes sure update() and its rendering run on the same thread.
Two data points from espVT (https://github.com/MatNav1/espVT), an ESP32-S3 VT built on the VT server. It renders on its own FreeRTOS task, separate from the CAN and update threads.
Even a plain lookup wrote to the map. Until now, get_object_by_id() used operator[]. Every lookup of an ID that isn't in the pool, including NULL_OBJECT_ID for an unset soft key mask, inserted an empty entry. Two threads that only read the pool, such as the renderer and the CAN thread handling a command, both wrote to the map. A fix that makes lookups read-only is in preparation: it uses find() and returns nullptr. It doesn't solve this issue, because the parser and clear_object_pool_data() still write while others read, but it removes the writes from the read path.
The working-set list has the same problem.managedWorkingSetList is also used from several threads without a lock: the CAN thread, update(), and an application that renders the active working set. espVT adds a std::recursive_mutex around the list in its local copy. A recursive one, because the server calls back into the application while it holds the list.
On the contract question: on a microcontroller, rendering usually can't run on the thread that calls update(), because a full repaint takes far longer than the update period. For us, the option where the stack owns the lock and the application takes it while painting would work, as long as the lock covers the object tree and the working-set list, and the application can take it from outside.
Thanks @franz-ms-muc, those are really useful data points and I have merged the issue 1 PR. I went through where the VT server touches the working sets on current main. I also had a look at espVT to understand the microcontroller case better.
On main a part of this is already single threaded. Since #731, #800 and #801, the shutdown reports, object_pool_parse_finished(), select_working_set() and object_pool_deleted() all run from update(). What still runs outside of update(), mostly on the stack update thread, is:
adding and removing working sets in managedWorkingSetList
every command which changes an object, and the repaint, active mask and focus event dispatchers
clearing the tree on Load Version, and the load_version() / save_version() hooks, so file or flash I/O also runs on that thread
process_macro() and execute_macro(), which end in process_rx_message(). AgIsoVirtualTerminal calls process_macro() from its GUI code, so commands can be processed on two threads at same time.
Also the parser thread writes into the live tree. I think this part we can fix the same way whatever we choose: parse into a private tree, and swap it in under a short lock or from update().
I think there are three ways to go.
The stack owns a lock and holds it while it processes commands, like espVT does now. The lock has to cover the list, the trees and the values. The thing which worries me is who waits for whom. Commands are processed on the stack update thread, so when the renderer holds the lock for a whole frame, that thread waits, and with it the TP/ETP sessions, the address claim and the receive callbacks of everything else on that thread. Also the server calls into the application while it holds the lock, that is why espVT needed a recursive mutex.
Commands only in update(). The PGN callback only copies the message into a queue, and update() processes it. TaskControllerServer does already something similar with store_rx_message(), but it keeps the queue mutex during the whole processing. I would swap the queue out under a short lock instead, so the CAN side never waits for the command processing. Then all changes which the stack does to the list, the trees and the values happens inside update(), and macros go the same path.
The stack publishes immutable snapshots for the renderer. It works on any thread, but the objects can not be changed in place anymore and that is a big rewrite of the stack and of the renderers.
I believe that 2nd option might be better one here. And I think it can also give you what you asked for, a lock which the application can take from outside:
update() holds a mutex which the stack hands out, but only around the changes to the model, so when it applies the queued commands and when it swaps in a parsed pool.
It doesn't call into the application while it holds it. The event dispatchers run after it released the mutex and load_version() / save_version() are called without the mutex and the result is applied after. So nothing has to be recursive.
Functions which the application calls, like process_macro(), only put something into the queue. So they are fine to call while the application holds the mutex.
The application takes the same mutex when it reads the model and when it changes it itself, for example for the input from the touch screen. So there can still be two writers, but with one lock and the commands are always processed on one thread.
In espVT I saw that update() runs on the stack update thread and the renderer walks get_object_tree() after the list lock is released. So a value changed by a command can still race with the drawing today, even with the recursive mutex.
With the above, the queue alone doesn't stop a long frame from blocking the stack update thread, if update() stays on the periodic dispatcher and waits for the mutex there. So either update() runs on its own task, or it only tries the mutex and skips the VT part for this round when the renderer has it. Then a long frame only delays the VT part and the CAN thread keeps moving frames. If a frame is very long, the renderer can also copy the values it needs under the mutex and draw outside of it. Only copying the shared_ptrs is not enough for that, because the objects can still change. Would this work for you?
Some things I think still have to be decided
what happens when the queue is full during a long stall
how the VT status and the timeouts behave during a long frame, because both use the working set list
whether a Load Version on the displayed pool keeps showing the old pool until the new one is parsed (I think yes). Then the old and the new pool are both in memory for a while. And what happens with commands for that working set in meantime.
the working set maintenance timeout. I think the server should record the time for the working set already when the maintenance message is queued and the timeout reads that. If the time is taken when the message is processed, a long stall times out working sets whose messages are still waiting in the queue and a working set which is already gone looks alive for too long.
Sorry for the late answer, @sujandumaru, and thanks for looking at espVT. Yes, option 2 works for us, and I agree with your reasons against option 1.
You're right about the race in espVT. Our renderer runs on its own FreeRTOS task (core 0), update() runs from the periodic update dispatcher of the stack's update thread, and the renderer walks the object tree after the list lock is released. So commands still change values while we draw. Our recursive list mutex only protects the list itself. I would rather fix that with your design than make our lock bigger.
What matters for us:
Frame time: a full software render of a large pool takes 150 to 380 ms on the ESP32-S3. So holding the model mutex for a whole frame is only acceptable if update() doesn't wait for it. try_lock, and skipping the VT part for this round, is what we would want. For very long frames we can copy the values we need under the mutex and draw outside of it.
The parser: parsing into a private tree and swapping it in is also good for us. Right now we run the parser on a pthread with its stack in PSRAM, because internal RAM is scarce. If the parse thread stays, it would help if the application can choose where its stack goes, but that is a separate question.
On the open points:
Full queue: I would drop the new message and log it, not block. The CAN side must never wait for command processing. The client gets no response and handles that like any other lost message, with its timeout and retry. The queue size could be a constructor or setter parameter, so a small target can pick a size that fits its RAM.
VT status and timeouts during a long frame: I think they should not need the model mutex. The status message only needs the active working set address and mask IDs, which update() could keep in a few plain fields after each change. The timeouts only need the timestamps.
Load Version on the displayed pool: yes, keep showing the old pool until the new one is parsed and swapped in. Commands for that working set stay in the queue until then, and are applied to the new pool. Having both pools in memory for a while is fine for us with PSRAM, but the documentation should mention it.
Maintenance timeout: agreed, take the time when the message is queued. Otherwise a long stall makes working sets time out whose maintenance messages are already waiting in the queue.
If this direction is OK for you and @GwnDaan, I can start on it in smaller PRs: first the command queue processed in update(), then the model mutex with the rules for the application, then the parser with its own tree. espVT would switch to it, and we can test it on the ESP32-S3 and the ESP32-P4 with real implements.
Thanks @franz-ms-muc, good to hear that option 2 works for you, and I agree with your answers on the maintenance timeout and on keeping the old pool shown.
On the implementation, I was thinking to take the command queue PR myself. It changes on which thread AgIsoVirtualTerminal gets its callbacks, so I have to change that side anyway. Could you take the parser with its own tree? It doesn't depend on the queue, so it can start now, and you can measure the memory on the ESP32 which I can not. The model mutex comes after the queue, we can decide about that one later. It would help alot if you could test each PR on the ESP32-S3 and the point 4, I don't have the hardware here.
Two things on the open points:
Commands during a parse: I would not hold them in the queue. With one queue that blocks the other working sets too. The client waits for the Load Version or End of Object Pool response before it sends more, so it should be rare. I think the server can just apply them to the old pool.
Full queue: dropping and logging is fine for normal commands. But if an Object Pool Transfer is dropped, the upload has to fail, so End of Object Pool answers with an error. Otherwise the server parses a pool with a hole in it. Also the limit should probably be in bytes, because one pool transfer can be very big.
Thanks, @sujandumaru, that split works for us. I'll take the parser with its own tree and start on it now, fork first as usual, and I'll test your queue PR and the later ones on the ESP32-S3 and the ESP32-P4 with real implements.
On your two points:
Commands during a parse: agreed, applying them to the old pool is simpler and doesn't block the other working sets. I was wrong to hold them in the queue.
Full queue: agreed on both. A dropped Object Pool Transfer should mark the upload as failed, so End of Object Pool answers with an error instead of parsing a pool with a hole. And a limit in bytes makes sense, as one transfer can be larger than many commands together. The limit then has to be at least as large as the largest pool transfer the server accepts, or a big pool can never be uploaded. Maybe the default could follow from that.
For the parser PR my plan is: the parse thread builds the objects into a tree that only it owns, and the finished tree is swapped into the working set from update(), or under a short lock until the queue is in. A failed parse leaves the old tree untouched. I'll report the peak memory on the ESP32-S3 with a large pool in the PR.
The parser part is up as #949: the parsing thread fills an object tree of its own, and join_parsing_thread() takes it over from update() if the pool was parsed successfully. Keeping the old pool shown during a Load Version and choosing the parsing thread's stack will follow as separate PRs. I'll test your queue PR on the ESP32-S3 and the ESP32-P4 once it's up.
Activity
franz-ms-muc commentedon Nov 1, 2026
Two data points from espVT (https://github.com/MatNav1/espVT), an ESP32-S3 VT built on the VT server. It renders on its own FreeRTOS task, separate from the CAN and update threads.
Even a plain lookup wrote to the map. Until now,
get_object_by_id()usedoperator[]. Every lookup of an ID that isn't in the pool, includingNULL_OBJECT_IDfor an unset soft key mask, inserted an empty entry. Two threads that only read the pool, such as the renderer and the CAN thread handling a command, both wrote to the map. A fix that makes lookups read-only is in preparation: it usesfind()and returnsnullptr. It doesn't solve this issue, because the parser andclear_object_pool_data()still write while others read, but it removes the writes from the read path.The working-set list has the same problem.
managedWorkingSetListis also used from several threads without a lock: the CAN thread,update(), and an application that renders the active working set. espVT adds astd::recursive_mutexaround the list in its local copy. A recursive one, because the server calls back into the application while it holds the list.On the contract question: on a microcontroller, rendering usually can't run on the thread that calls
update(), because a full repaint takes far longer than the update period. For us, the option where the stack owns the lock and the application takes it while painting would work, as long as the lock covers the object tree and the working-set list, and the application can take it from outside.sujandumaru commentedon Nov 1, 2026
Thanks @franz-ms-muc, those are really useful data points and I have merged the issue 1 PR. I went through where the VT server touches the working sets on current main. I also had a look at espVT to understand the microcontroller case better.
On main a part of this is already single threaded. Since #731, #800 and #801, the shutdown reports,
object_pool_parse_finished(),select_working_set()andobject_pool_deleted()all run fromupdate(). What still runs outside ofupdate(), mostly on the stack update thread, is:managedWorkingSetListload_version()/save_version()hooks, so file or flash I/O also runs on that threadprocess_macro()andexecute_macro(), which end inprocess_rx_message(). AgIsoVirtualTerminal callsprocess_macro()from its GUI code, so commands can be processed on two threads at same time.Also the parser thread writes into the live tree. I think this part we can fix the same way whatever we choose: parse into a private tree, and swap it in under a short lock or from
update().I think there are three ways to go.
update(). The PGN callback only copies the message into a queue, andupdate()processes it.TaskControllerServerdoes already something similar with store_rx_message(), but it keeps the queue mutex during the whole processing. I would swap the queue out under a short lock instead, so the CAN side never waits for the command processing. Then all changes which the stack does to the list, the trees and the values happens insideupdate(), and macros go the same path.I believe that 2nd option might be better one here. And I think it can also give you what you asked for, a lock which the application can take from outside:
load_version()/save_version()are called without the mutex and the result is applied after. So nothing has to be recursive.process_macro(), only put something into the queue. So they are fine to call while the application holds the mutex.In espVT I saw that
update()runs on the stack update thread and the renderer walksget_object_tree()after the list lock is released. So a value changed by a command can still race with the drawing today, even with the recursive mutex.With the above, the queue alone doesn't stop a long frame from blocking the stack update thread, if
update()stays on the periodic dispatcher and waits for the mutex there. So eitherupdate()runs on its own task, or it only tries the mutex and skips the VT part for this round when the renderer has it. Then a long frame only delays the VT part and the CAN thread keeps moving frames. If a frame is very long, the renderer can also copy the values it needs under the mutex and draw outside of it. Only copying theshared_ptrs is not enough for that, because the objects can still change. Would this work for you?Some things I think still have to be decided
@GwnDaan what is your opinion on this?
franz-ms-muc commentedon Nov 14, 2026
Sorry for the late answer, @sujandumaru, and thanks for looking at espVT. Yes, option 2 works for us, and I agree with your reasons against option 1.
You're right about the race in espVT. Our renderer runs on its own FreeRTOS task (core 0),
update()runs from the periodic update dispatcher of the stack's update thread, and the renderer walks the object tree after the list lock is released. So commands still change values while we draw. Our recursive list mutex only protects the list itself. I would rather fix that with your design than make our lock bigger.What matters for us:
update()doesn't wait for it.try_lock, and skipping the VT part for this round, is what we would want. For very long frames we can copy the values we need under the mutex and draw outside of it.On the open points:
update()could keep in a few plain fields after each change. The timeouts only need the timestamps.If this direction is OK for you and @GwnDaan, I can start on it in smaller PRs: first the command queue processed in
update(), then the model mutex with the rules for the application, then the parser with its own tree. espVT would switch to it, and we can test it on the ESP32-S3 and the ESP32-P4 with real implements.sujandumaru commentedon Nov 14, 2026
Thanks @franz-ms-muc, good to hear that option 2 works for you, and I agree with your answers on the maintenance timeout and on keeping the old pool shown.
On the implementation, I was thinking to take the command queue PR myself. It changes on which thread AgIsoVirtualTerminal gets its callbacks, so I have to change that side anyway. Could you take the parser with its own tree? It doesn't depend on the queue, so it can start now, and you can measure the memory on the ESP32 which I can not. The model mutex comes after the queue, we can decide about that one later. It would help alot if you could test each PR on the ESP32-S3 and the point 4, I don't have the hardware here.
Two things on the open points:
What do you think?
franz-ms-muc commentedon Nov 15, 2026
Thanks, @sujandumaru, that split works for us. I'll take the parser with its own tree and start on it now, fork first as usual, and I'll test your queue PR and the later ones on the ESP32-S3 and the ESP32-P4 with real implements.
On your two points:
For the parser PR my plan is: the parse thread builds the objects into a tree that only it owns, and the finished tree is swapped into the working set from
update(), or under a short lock until the queue is in. A failed parse leaves the old tree untouched. I'll report the peak memory on the ESP32-S3 with a large pool in the PR.franz-ms-muc commentedon Nov 15, 2026
The parser part is up as #949: the parsing thread fills an object tree of its own, and
join_parsing_thread()takes it over fromupdate()if the pool was parsed successfully. Keeping the old pool shown during a Load Version and choosing the parsing thread's stack will follow as separate PRs. I'll test your queue PR on the ESP32-S3 and the ESP32-P4 once it's up.sujandumaru commentedon Nov 15, 2026
Sounds good. Thanks for offering to test this in real implements.
Parse the object pool into an object tree of its own (#949)