Merge branch 'tcp-pusher-nonblocking' into rc175: TCP pusher never blocks the receiver thread
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EizBKhTqrAYago9KJG3dA3
This commit is contained in:
commit
7f33344a7a
7 files changed
+104
-53
No files matched your search
@@ -23,6 +23,7 @@ Options:
|
||||
-f<int> | --zmq_file_port=<int> ZeroMQ port for PUB socket for notifications on finalized files
|
||||
-w<int> | --rcv_watermark=<int> Receiving ZeroMQ socket watermark (default = 100)
|
||||
-W<int> | --repub_watermark=<int> Republish ZeroMQ socket watermark (default = 1000)
|
||||
-b<int> | --rcv_buffer=<int> Receiving TCP socket buffer in bytes (only with -T; disables autotuning, capped by net.core.rmem_max)
|
||||
-v | --verbose Verbose output
|
||||
-h This message
|
||||
```
|
||||
|
||||
@@ -162,9 +162,10 @@ TCPStreamPusher::~TCPStreamPusher() {
|
||||
}
|
||||
|
||||
void TCPStreamPusher::TearDownConnection(Connection& c) {
|
||||
// Broken first, so the writer thread returns the queued slots instead of sending them.
|
||||
c.broken = true;
|
||||
StopDataCollectionThreads(c);
|
||||
c.connected = false;
|
||||
c.broken = true;
|
||||
CloseFd(c.fd);
|
||||
JoinPersistentAck(c);
|
||||
}
|
||||
@@ -600,7 +601,7 @@ void TCPStreamPusher::AcceptorThread() {
|
||||
}
|
||||
|
||||
void TCPStreamPusher::SetupNewConnection(int new_fd, uint32_t socket_number) {
|
||||
auto c = std::make_shared<Connection>(send_queue_size);
|
||||
auto c = std::make_shared<Connection>();
|
||||
c->socket_number = socket_number;
|
||||
c->fd.store(new_fd);
|
||||
|
||||
@@ -755,20 +756,10 @@ void TCPStreamPusher::StopDataCollectionThreads(Connection& c) {
|
||||
if (!c.active)
|
||||
return;
|
||||
|
||||
c.active = false;
|
||||
|
||||
// Avoid potential shutdown deadlock if queue is full and writer is stalled.
|
||||
if (!c.queue.PutTimeout({.end = true}, std::chrono::milliseconds(200))) {
|
||||
c.broken = true;
|
||||
CloseFd(c.fd);
|
||||
// active==false makes WriterThread exit without draining, so return any
|
||||
// queued-but-unsent slots to the image buffer pool ourselves.
|
||||
ImagePusherQueueElement e{};
|
||||
while (c.queue.Get(e)) {
|
||||
if (e.z)
|
||||
e.z->release();
|
||||
}
|
||||
(void)c.queue.Put({.end = true});
|
||||
{
|
||||
std::lock_guard lg(c.enqueue_mutex);
|
||||
c.active = false;
|
||||
c.queue.Put({.end = true});
|
||||
}
|
||||
|
||||
c.ack_cv.notify_all();
|
||||
@@ -1034,9 +1025,6 @@ bool TCPStreamPusher::SendImage(const uint8_t *image_data, size_t image_size, in
|
||||
}
|
||||
|
||||
bool TCPStreamPusher::SendImage(ZeroCopyReturnValue &z) {
|
||||
// Look up the target connection while holding the mutex, but do NOT call
|
||||
// PutBlocking while holding it — that can block indefinitely and deadlock
|
||||
// against AcceptorThread/KeepaliveThread.
|
||||
std::shared_ptr<Connection> target;
|
||||
{
|
||||
std::lock_guard lg(connections_mutex);
|
||||
@@ -1055,28 +1043,19 @@ bool TCPStreamPusher::SendImage(ZeroCopyReturnValue &z) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A full queue means the writer is applying backpressure (e.g. briefly stalled on a
|
||||
// freshly-created file at startup). Keep waiting as long as it proves it is alive —
|
||||
// BUSY heartbeats / ACKs refresh last_peer_activity_ns from a thread independent of
|
||||
// its stalled write path — so a slow-but-healthy writer is held back, not dropped.
|
||||
// Only a peer that has gone completely silent for the liveness window is declared dead;
|
||||
// a writer that heartbeats but never drains is caught by SendAll's max_backpressure cap.
|
||||
while (!target->broken && target->active) {
|
||||
if (target->queue.PutTimeout(ImagePusherQueueElement{
|
||||
// Never blocks: the queue is bounded only by the image-buffer slots. A writer that stops
|
||||
// draining is caught in SendAll (peer liveness / max backpressure), after which WriterThread
|
||||
// returns the queued slots without sending them.
|
||||
{
|
||||
std::lock_guard lg(target->enqueue_mutex);
|
||||
if (!target->broken && target->active) {
|
||||
target->queue.Put(ImagePusherQueueElement{
|
||||
.z = &z,
|
||||
.end = false
|
||||
}, std::chrono::milliseconds(50)))
|
||||
});
|
||||
return true;
|
||||
|
||||
const int64_t silent_ns = SteadyNowNs() - target->last_peer_activity_ns.load(std::memory_order_relaxed);
|
||||
if (silent_ns > std::chrono::duration_cast<std::chrono::nanoseconds>(peer_liveness_timeout).count()) {
|
||||
logger.Warning("No liveness from writer on socket " + std::to_string(target->socket_number) +
|
||||
" for " + std::to_string(silent_ns / 1000000) + " ms while enqueuing; marking broken");
|
||||
target->broken = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
z.release();
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
/// - Per-connection WriterThread: drains the connection's queue, sends DATA frames
|
||||
/// - Per-connection PersistentAckThread: reads ACKs and keepalive pongs from the peer
|
||||
///
|
||||
/// Lock ordering: connections_mutex → send_mutex → ack_mutex
|
||||
/// Lock ordering: connections_mutex → send_mutex → ack_mutex; teardown_mutex → enqueue_mutex
|
||||
/// IMPORTANT: Never call blocking queue operations while holding connections_mutex.
|
||||
///
|
||||
/// Concurrency contract:
|
||||
@@ -40,14 +40,16 @@
|
||||
|
||||
class TCPStreamPusher : public ImagePusher {
|
||||
struct Connection {
|
||||
explicit Connection(size_t queue_size) : queue(queue_size) {}
|
||||
|
||||
std::atomic<int> fd{-1};
|
||||
uint32_t socket_number = 0;
|
||||
std::atomic<bool> active{false}; // data-collection threads running
|
||||
std::atomic<bool> broken{false};
|
||||
std::atomic<bool> connected{false}; // persistent connection is alive
|
||||
|
||||
// Unbounded on purpose: every element owns a distinct image-buffer slot, so the queue can
|
||||
// never hold more than the image buffer has slots. A slow writer then backs up into the
|
||||
// image buffer - where the receiver drops only the write, after analysis - instead of
|
||||
// blocking the receiver thread in SendImage, which stalls the FPGA and loses packets.
|
||||
ThreadSafeFIFO<ImagePusherQueueElement> queue;
|
||||
std::future<void> writer_future;
|
||||
|
||||
@@ -60,6 +62,12 @@ class TCPStreamPusher : public ImagePusher {
|
||||
// Held only around the joins, never around a send, and no thread it joins takes it.
|
||||
std::mutex teardown_mutex;
|
||||
|
||||
// Makes "check active, then enqueue" in SendImage atomic against "clear active, then enqueue
|
||||
// the end sentinel" in StopDataCollectionThreads, so no image can land behind the sentinel -
|
||||
// where WriterThread never sees it and its image-buffer slot would leak. Never held across
|
||||
// anything that blocks: the queue is unbounded, so Put returns at once.
|
||||
std::mutex enqueue_mutex;
|
||||
|
||||
std::mutex send_mutex;
|
||||
std::mutex ack_mutex;
|
||||
std::condition_variable ack_cv;
|
||||
@@ -97,7 +105,6 @@ class TCPStreamPusher : public ImagePusher {
|
||||
std::string endpoint;
|
||||
size_t max_connections;
|
||||
std::optional<int32_t> send_buffer_size;
|
||||
size_t send_queue_size = 128;
|
||||
|
||||
// Persistent connection pool, guarded by connections_mutex.
|
||||
// IMPORTANT: never call PutBlocking/GetBlocking on a queue while holding this mutex.
|
||||
|
||||
@@ -513,8 +513,8 @@ void JFJochReceiverFPGA::FrameTransformationThread(uint32_t threadid) {
|
||||
zmq_metadata_socket->AddDataMessage(message);
|
||||
|
||||
if (push_images_to_writer) {
|
||||
// Only count images the pusher accepted; TCP can drop on a
|
||||
// broken/absent connection or an expired enqueue deadline.
|
||||
// Only count images the pusher accepted; TCP refuses them on a broken/absent
|
||||
// connection. Images actually written are GetImagesWritten() (ACK-based).
|
||||
if (image_pusher.SendImage(*loc))
|
||||
++images_sent;
|
||||
} else
|
||||
|
||||
@@ -393,8 +393,8 @@ void JFJochReceiverLite::DataAnalysisThread(uint32_t id) {
|
||||
zmq_metadata_socket->AddDataMessage(data_msg);
|
||||
|
||||
if (push_images_to_writer) {
|
||||
// Only count images the pusher accepted; TCP can drop on a
|
||||
// broken/absent connection or an expired enqueue deadline.
|
||||
// Only count images the pusher accepted; TCP refuses them on a broken/absent
|
||||
// connection. Images actually written are GetImagesWritten() (ACK-based).
|
||||
if (image_pusher.SendImage(*loc))
|
||||
++images_sent;
|
||||
} else
|
||||
|
||||
@@ -1020,11 +1020,11 @@ private:
|
||||
|
||||
TEST_CASE("TCPImageCommTest_StalledWriter_SurvivesViaHeartbeat", "[TCP]") {
|
||||
// A writer that is alive (still heartbeating) but has stopped draining — e.g. wedged
|
||||
// on a slow filesystem at high frame rate — must NOT be dropped mid-run. The pusher
|
||||
// rides out the backpressure on the production zero-copy queue path until the writer
|
||||
// recovers. Regression for the queue-path send giving up on a fixed deadline, and for
|
||||
// the BUSY heartbeat keeping the connection alive past the peer-liveness window.
|
||||
constexpr int64_t N = 1000; // > queue depth + socket buffers
|
||||
// on a slow filesystem at high frame rate — must NOT be dropped mid-run. The backlog
|
||||
// waits in the image buffer, and SendImage must never block the caller (the receiver
|
||||
// thread) meanwhile. Regression for the queue-path send blocking on a short fixed queue,
|
||||
// and for the BUSY heartbeat keeping the connection alive past the peer-liveness window.
|
||||
constexpr int64_t N = 1000; // > socket buffers, < image buffer slots
|
||||
constexpr auto liveness = std::chrono::milliseconds(2000);
|
||||
constexpr auto stall = std::chrono::milliseconds(4000); // > liveness AND > old send deadline
|
||||
|
||||
@@ -1058,10 +1058,10 @@ TEST_CASE("TCPImageCommTest_StalledWriter_SurvivesViaHeartbeat", "[TCP]") {
|
||||
}
|
||||
});
|
||||
|
||||
// During the stall the queue is full; SendImage must block, not drop the connection.
|
||||
// During the stall every image is queued at once, holding its slot, and the connection stays.
|
||||
std::this_thread::sleep_for(stall);
|
||||
CHECK(pusher.GetConnectedWriters() == 1);
|
||||
CHECK(sender.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready);
|
||||
CHECK(sender.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
|
||||
|
||||
// Writer recovers and starts draining.
|
||||
writer.Release();
|
||||
@@ -1144,3 +1144,57 @@ TEST_CASE("TCPImageCommTest_WedgedWriter_DroppedByBackpressureCap", "[TCP]") {
|
||||
|
||||
image_buffer.Finalize(std::chrono::seconds(5));
|
||||
}
|
||||
|
||||
TEST_CASE("TCPImageCommTest_SendImageRacingEnd_NoSlotLeak", "[TCP]") {
|
||||
// Producers keep calling SendImage while EndDataCollection runs. Every image must either be
|
||||
// accepted and delivered before END, or refused with its slot returned - none may land behind
|
||||
// the end sentinel, where its slot would leak and CheckIfBufferReturned would fail.
|
||||
for (int iteration = 0; iteration < 10; iteration++) {
|
||||
TCPStreamPusher pusher("tcp://127.0.0.1:*", 1);
|
||||
|
||||
StallableWriterDouble writer(pusher.GetAddress()[0], 1024 * 1024);
|
||||
REQUIRE(writer.Connected());
|
||||
writer.Release();
|
||||
|
||||
for (int attempt = 0; attempt < 200 && pusher.GetConnectedWriters() < 1; ++attempt)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(25));
|
||||
REQUIRE(pusher.GetConnectedWriters() == 1);
|
||||
|
||||
ImageBuffer image_buffer(16 * 1024 * 1024);
|
||||
image_buffer.StartMeasurement(static_cast<size_t>(4096));
|
||||
|
||||
StartMessage start{.images_per_file = 1000, .write_master_file = true};
|
||||
pusher.StartDataCollection(start);
|
||||
|
||||
std::atomic<bool> stop{false};
|
||||
std::atomic<int64_t> next_image{0};
|
||||
std::atomic<size_t> accepted{0};
|
||||
std::vector<std::future<void>> senders;
|
||||
for (int t = 0; t < 4; t++) {
|
||||
senders.emplace_back(std::async(std::launch::async, [&] {
|
||||
while (!stop) {
|
||||
ZeroCopyReturnValue *slot = image_buffer.GetImageSlot();
|
||||
if (slot == nullptr)
|
||||
continue;
|
||||
slot->SetImageNumber(next_image++);
|
||||
slot->SetImageSize(256);
|
||||
slot->ReadyToSend();
|
||||
if (pusher.SendImage(*slot))
|
||||
accepted++;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
EndMessage end{};
|
||||
CHECK(pusher.EndDataCollection(end));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20)); // producers still running after END
|
||||
stop = true;
|
||||
for (auto &s: senders)
|
||||
s.get();
|
||||
|
||||
CHECK(image_buffer.CheckIfBufferReturned(std::chrono::seconds(5)));
|
||||
CHECK(writer.DataFramesReceived() == accepted.load());
|
||||
image_buffer.Finalize(std::chrono::seconds(5));
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ void print_usage() {
|
||||
logger.Info("-f<int> | --zmq_file_port=<int> ZeroMQ port for PUB socket to inform about finalized files");
|
||||
logger.Info("-w<int> | --rcv_watermark=<int> Receiving ZeroMQ socket watermark (default = 100)");
|
||||
logger.Info("-W<int> | --repub_watermark=<int> Republish ZeroMQ socket watermark (default = 1000)");
|
||||
logger.Info("-b<int> | --rcv_buffer=<int> Receiving TCP socket buffer in bytes (only with -T; disables autotuning, capped by net.core.rmem_max)");
|
||||
logger.Info("-v | --verbose Verbose output");
|
||||
logger.Info("-h This message");
|
||||
logger.Info("");
|
||||
@@ -72,6 +73,7 @@ int main(int argc, char **argv) {
|
||||
std::string root_dir = "";
|
||||
std::optional<int32_t> rcv_watermark;
|
||||
std::optional<int32_t> repub_watermark;
|
||||
std::optional<int32_t> rcv_buffer;
|
||||
bool verbose = false;
|
||||
|
||||
static struct option long_options[] = {
|
||||
@@ -81,6 +83,7 @@ int main(int argc, char **argv) {
|
||||
{"zmq_file_port", required_argument, 0, 'f'},
|
||||
{"rcv_watermark", required_argument, 0, 'w'},
|
||||
{"repub_watermark", required_argument, 0, 'W'},
|
||||
{"rcv_buffer", required_argument, 0, 'b'},
|
||||
{"verbose", no_argument, 0, 'v'},
|
||||
{"tcp", no_argument, 0, 'T'},
|
||||
{"nproc", required_argument, 0, 'j'},
|
||||
@@ -90,7 +93,7 @@ int main(int argc, char **argv) {
|
||||
int option_index = 0;
|
||||
int opt;
|
||||
bool raw_tcp = false;
|
||||
while ((opt = getopt_long(argc, argv, "?hH:r:f:R:d:W:w:vTj:",long_options, &option_index)) != -1 ) {
|
||||
while ((opt = getopt_long(argc, argv, "?hH:r:f:R:d:W:w:b:vTj:",long_options, &option_index)) != -1 ) {
|
||||
switch (opt) {
|
||||
case 'j':
|
||||
nforks = atoi(optarg);
|
||||
@@ -119,6 +122,13 @@ int main(int argc, char **argv) {
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
break;
|
||||
case 'b':
|
||||
rcv_buffer = atoi(optarg);
|
||||
if (rcv_buffer.value() <= 0) {
|
||||
std::cerr << "Receive buffer must be positive number" << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
break;
|
||||
case 'W':
|
||||
repub_watermark = atoi(optarg);
|
||||
if (repub_watermark.value() <= 0) {
|
||||
@@ -230,7 +240,7 @@ int main(int argc, char **argv) {
|
||||
|
||||
std::unique_ptr<ImagePuller> puller;
|
||||
if (raw_tcp)
|
||||
puller = std::make_unique<TCPImagePuller>(argv[first_argc], std::nullopt, repub_zmq_addr, repub_watermark);
|
||||
puller = std::make_unique<TCPImagePuller>(argv[first_argc], rcv_buffer, repub_zmq_addr, repub_watermark);
|
||||
else
|
||||
puller = std::make_unique<ZMQImagePuller>(argv[first_argc], repub_zmq_addr, rcv_watermark, repub_watermark);
|
||||
|
||||
|
||||
Reference in new issue
Block a user