From d7521bf1ea2bdaa03a6593c5e84ae9b4b1299612 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sat, 10 Oct 2026 20:33:50 +0200 Subject: [PATCH] TCP pusher: never block the receiver thread; queue bounded by image-buffer slots TCPStreamPusher::SendImage is called from the receiver's frame-transformation threads. It used a 128-deep per-connection queue and waited when it was full. With images routed per file ((n / images_per_file) % writers), every writer receives a whole file as a burst at the full frame rate (1000 images/file at 2 kHz fills 128 in ~64 ms), so the queue filled on every burst and all transformation threads ended up waiting on one writer. They then stopped returning FPGA frame buffers, and the FPGA dropped packets: partial images, images without a background estimate, data loss on every writer. The ZeroMQ pusher has an unbounded queue and never blocks, which is why it coped. - The per-connection queue is unbounded: every element owns a distinct image-buffer slot, so the bound is the image buffer's slot count. When slots run out the receiver drops only the write (GetImageSlot() == nullptr), after analysis. Absorbing one file burst therefore needs an image buffer of about images_per_file slots (~20 GB for a 9M at 1000 images/file); below that, images are still dropped, now as writer-queue-full instead of packet loss. - SendImage never blocks. A dead or wedged writer is still caught in SendAll (15 s silence / 60 s without progress), after which WriterThread returns the queued slots unsent. - The 200 ms fallback in StopDataCollectionThreads is gone: at END it closed the connection of any writer whose queue stayed full for 200 ms - a normal state for a slow but healthy writer - discarding up to 128 queued images and never sending END. END now follows the whole backlog. - A per-connection enqueue mutex makes "check active, enqueue" atomic against "clear active, enqueue the end sentinel": an image could land behind the sentinel when a connection was torn down mid-run, leaking its slot (CheckIfBufferReturned then threw) or being sent as stale data in the next run. New stress test SendImageRacingEnd_NoSlotLeak (verified to fail with the race widened and the lock removed). - TearDownConnection marks the connection broken first, so the destructor returns a backlog instead of sending it. Writer side: - jfjoch_writer -b/--rcv_buffer sets the TCP receive socket buffer (was hardcoded to the kernel default). Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/JFJOCH_WRITER.md | 1 + image_pusher/TCPStreamPusher.cpp | 51 +++++++----------------- image_pusher/TCPStreamPusher.h | 15 +++++-- receiver/JFJochReceiverFPGA.cpp | 4 +- receiver/JFJochReceiverLite.cpp | 4 +- tests/TCPImagePusherTest.cpp | 68 ++++++++++++++++++++++++++++---- writer/jfjoch_writer.cpp | 14 ++++++- 7 files changed, 104 insertions(+), 53 deletions(-) diff --git a/docs/JFJOCH_WRITER.md b/docs/JFJOCH_WRITER.md index 8fbe49441..3bd9f8823 100644 --- a/docs/JFJOCH_WRITER.md +++ b/docs/JFJOCH_WRITER.md @@ -23,6 +23,7 @@ Options: -f | --zmq_file_port= ZeroMQ port for PUB socket for notifications on finalized files -w | --rcv_watermark= Receiving ZeroMQ socket watermark (default = 100) -W | --repub_watermark= Republish ZeroMQ socket watermark (default = 1000) +-b | --rcv_buffer= Receiving TCP socket buffer in bytes (only with -T; disables autotuning, capped by net.core.rmem_max) -v | --verbose Verbose output -h This message ``` diff --git a/image_pusher/TCPStreamPusher.cpp b/image_pusher/TCPStreamPusher.cpp index 00d94614c..0cf2083ad 100644 --- a/image_pusher/TCPStreamPusher.cpp +++ b/image_pusher/TCPStreamPusher.cpp @@ -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(send_queue_size); + auto c = std::make_shared(); 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 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(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; } diff --git a/image_pusher/TCPStreamPusher.h b/image_pusher/TCPStreamPusher.h index 8663ce357..bb93477b3 100644 --- a/image_pusher/TCPStreamPusher.h +++ b/image_pusher/TCPStreamPusher.h @@ -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 fd{-1}; uint32_t socket_number = 0; std::atomic active{false}; // data-collection threads running std::atomic broken{false}; std::atomic 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 queue; std::future 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 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. diff --git a/receiver/JFJochReceiverFPGA.cpp b/receiver/JFJochReceiverFPGA.cpp index 23288259e..3e914d5d1 100644 --- a/receiver/JFJochReceiverFPGA.cpp +++ b/receiver/JFJochReceiverFPGA.cpp @@ -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 diff --git a/receiver/JFJochReceiverLite.cpp b/receiver/JFJochReceiverLite.cpp index 001a8f6f5..a84a8487a 100644 --- a/receiver/JFJochReceiverLite.cpp +++ b/receiver/JFJochReceiverLite.cpp @@ -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 diff --git a/tests/TCPImagePusherTest.cpp b/tests/TCPImagePusherTest.cpp index a01179def..19b5b0ae9 100644 --- a/tests/TCPImagePusherTest.cpp +++ b/tests/TCPImagePusherTest.cpp @@ -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(4096)); + + StartMessage start{.images_per_file = 1000, .write_master_file = true}; + pusher.StartDataCollection(start); + + std::atomic stop{false}; + std::atomic next_image{0}; + std::atomic accepted{0}; + std::vector> 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)); + } +} diff --git a/writer/jfjoch_writer.cpp b/writer/jfjoch_writer.cpp index 9e4166dc4..f5c4001f0 100644 --- a/writer/jfjoch_writer.cpp +++ b/writer/jfjoch_writer.cpp @@ -27,6 +27,7 @@ void print_usage() { logger.Info("-f | --zmq_file_port= ZeroMQ port for PUB socket to inform about finalized files"); logger.Info("-w | --rcv_watermark= Receiving ZeroMQ socket watermark (default = 100)"); logger.Info("-W | --repub_watermark= Republish ZeroMQ socket watermark (default = 1000)"); + logger.Info("-b | --rcv_buffer= 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 rcv_watermark; std::optional repub_watermark; + std::optional 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 puller; if (raw_tcp) - puller = std::make_unique(argv[first_argc], std::nullopt, repub_zmq_addr, repub_watermark); + puller = std::make_unique(argv[first_argc], rcv_buffer, repub_zmq_addr, repub_watermark); else puller = std::make_unique(argv[first_argc], repub_zmq_addr, rcv_watermark, repub_watermark);