What exactly is the sequence number used for?
It's somewhat of a 'relic' from the earlier versions of ROS. The idea was that it could be useful to be able to correlate messages to each other, or deal with out-of-order delivery over transports that do not guarantee in-order delivery.
That never really got used (afaik), and on multiple occasions proposals to remove seq
from Header
have been put forth -- ROS 2 RFC: Remove seq from Header.msg on the ros-sig-ng-ros
list being one of the more recent ones. That posting by @William also explains some of the shortcomings of seq
, and might also answer some of your other questions about it.
In which circumstances can we have two (or more) messages with the same sequence number?
There is no guarantee whatsoever that seq
is unique, in any way. From the posting linked earlier:
[..] in ROS 1, the seq
field is sometimes set by the middleware, but inconsistently not set in other cases. For example, it is set when publishing, but not when sending a Service Request. Also, some client libraries don’t set the seq
field on publish [..]
and:
[..] seq
is specific to a single publishing source, or topic depending on the middleware's behavior [..]
Uniqueness guarantees would also be really hard to implement robustly. Imagine a highly distributed system with 100+ hosts with tens of nodes of each. seq
is a simple uint32
, so setting up some oracle that can reliably generate unique nrs would be almost impossible due to the limited width of the integer and because of the necessity to somehow keep track of nrs already used across all involved graph participants.
So there can be many situations in which multiple msgs have identical sequence nrs. Most commonly it can occur if publishers (or the underlying client library) don't initialise seq
at all (it stays 0
). In other cases seq
could be set by the caller, who could happen to have started counting at the same nr (say 0
) as some other publishing entity in your node graph. This would also lead to the possibility of receiving different msgs with identical seq
values.
In conclusion: no, seq
is not required nor guaranteed to be unique - not even within a single process - and you should not rely on it being unique. It's only still there because of its history and for reasons of backwards compatibility. It probably won't be maintained as part of a Header
(or equivalent structure) in ROS2 and if we could, it would've been removed from ROS1 a long time ago already.
Edit: found some related discussion: Is the sequence number in Header message deprecated on ROS Discourse. The linked ros2/common_interfaces#1 on Github is also interesting, especially this comment.