feat(dataman): handle zero-size cache and clear pending responses on new request

This commit is contained in:
jonas authored and Beat Küng committed 2026-06-16 07:56:40 +02:00
1 parent f62338dfb1
commit 5fd7fed8d8
3 files changed
+444 -16

No files matched your search

+77 -16
View File
@@ -90,6 +90,8 @@ bool DatamanClient::syncHandler(const dataman_request_s &request, dataman_respon
int32_t ret = 0;
hrt_abstime time_elapsed = hrt_elapsed_time(&start_time);
perf_begin(_sync_perf);
clearPendingResponse();
_dataman_request_pub.publish(request);
while (!response_received && (time_elapsed < timeout)) {
@@ -255,6 +257,24 @@ bool DatamanClient::clearSync(dm_item_t item, hrt_abstime timeout)
return success;
}
void DatamanClient::clearPendingResponse()
{
if (_dataman_response_sub < 0) {
return;
}
// Drain queued replies first so a response from an aborted or timed-out
// operation cannot be matched to the next request.
bool updated = false;
orb_check(_dataman_response_sub, &updated);
while (updated) {
dataman_response_s response{};
orb_copy(ORB_ID(dataman_response), _dataman_response_sub, &response);
orb_check(_dataman_response_sub, &updated);
}
}
bool DatamanClient::readAsync(dm_item_t item, uint32_t index, uint8_t *buffer, uint32_t length)
{
if (_client_id == CLIENT_ID_NOT_SET) {
@@ -269,6 +289,8 @@ bool DatamanClient::readAsync(dm_item_t item, uint32_t index, uint8_t *buffer, u
bool success = false;
if (_state == State::Idle) {
// Drop any queued stale replies before publishing a fresh async request.
clearPendingResponse();
hrt_abstime timestamp = hrt_absolute_time();
@@ -311,6 +333,8 @@ bool DatamanClient::writeAsync(dm_item_t item, uint32_t index, uint8_t *buffer,
bool success = false;
if (_state == State::Idle) {
// Drop any queued stale replies before publishing a fresh async request.
clearPendingResponse();
hrt_abstime timestamp = hrt_absolute_time();
@@ -350,6 +374,8 @@ bool DatamanClient::clearAsync(dm_item_t item)
bool success = false;
if (_state == State::Idle) {
// Drop any queued stale replies before publishing a fresh async request.
clearPendingResponse();
hrt_abstime timestamp = hrt_absolute_time();
@@ -464,6 +490,10 @@ void DatamanClient::abortCurrentOperation()
DatamanCache::DatamanCache(const char *cache_miss_perf_counter_name, uint32_t num_items)
: _cache_miss_perf(perf_alloc(PC_COUNT, cache_miss_perf_counter_name))
{
if (num_items == 0) {
return;
}
_items = new Item[num_items] {};
if (_items != nullptr) {
@@ -476,25 +506,47 @@ DatamanCache::DatamanCache(const char *cache_miss_perf_counter_name, uint32_t nu
DatamanCache::~DatamanCache()
{
_client.abortCurrentOperation();
delete[] _items;
perf_free(_cache_miss_perf);
}
void DatamanCache::resize(uint32_t num_items)
{
if (num_items == 0) {
// Allow callers to explicitly disable caching while leaving the DatamanClient usable.
_client.abortCurrentOperation();
delete[] _items;
_items = nullptr;
resetCacheState();
_num_items = 0;
return;
}
Item *new_items = new Item[num_items] {};
if (new_items != nullptr) {
_client.abortCurrentOperation();
uint32_t num_min = num_items < _num_items ? num_items : _num_items;
for (uint32_t i = 0; i < num_min; ++i) {
new_items[i] = _items[i];
if (new_items[i].cache_state == State::RequestSent) {
new_items[i].cache_state = State::RequestPrepared;
}
}
delete[] _items;
_items = new_items;
_num_items = num_items;
// ensure new bounds are respected after resize
_load_index = (_load_index < _num_items) ? _load_index : 0;
_update_index = (_update_index < _num_items) ? _update_index : 0;
_item_counter = (_item_counter < _num_items) ? _item_counter : _num_items;
} else {
PX4_ERR("alloc failed");
}
@@ -544,22 +596,20 @@ bool DatamanCache::loadWait(dm_item_t item, uint32_t index, uint8_t *buffer, uin
return false;
}
if (!_items) {
return false;
}
bool success = false;
bool item_found = false;
for (uint32_t i = 0; i < _num_items; ++i) {
if ((_items[i].response.item == item) &&
(_items[i].response.index == index)) {
item_found = true;
if (_items) {
for (uint32_t i = 0; i < _num_items; ++i) {
if ((_items[i].response.item == item) &&
(_items[i].response.index == index)) {
item_found = true;
if (_items[i].cache_state == State::ResponseReceived) {
memcpy(buffer, _items[i].response.data, length);
success = true;
break;
if (_items[i].cache_state == State::ResponseReceived) {
memcpy(buffer, _items[i].response.data, length);
success = true;
break;
}
}
}
}
@@ -569,7 +619,7 @@ bool DatamanCache::loadWait(dm_item_t item, uint32_t index, uint8_t *buffer, uin
success = _client.readSync(item, index, buffer, length, timeout);
// Cache the item if not found already (it could be in the process of being loaded)
if (success && !item_found && _item_counter < _num_items) {
if (success && !item_found && _items && (_item_counter < _num_items)) {
_items[_load_index].cache_state = State::ResponseReceived;
_items[_load_index].response.item = item;
_items[_load_index].response.index = index;
@@ -676,20 +726,31 @@ void DatamanCache::update()
}
}
void DatamanCache::resetCacheState()
{
_update_index = 0;
_item_counter = 0;
_load_index = 0;
}
void DatamanCache::invalidate()
{
for (uint32_t i = 0; i < _num_items; ++i) {
_items[i].cache_state = State::Idle;
}
_update_index = 0;
_item_counter = 0;
_load_index = 0;
resetCacheState();
_client.abortCurrentOperation();
}
inline void DatamanCache::changeUpdateIndex()
{
if (_num_items == 0) {
_update_index = 0;
_item_counter = 0;
return;
}
_update_index = (_update_index + 1) % _num_items;
if (_item_counter > 0) {
+3
View File
@@ -173,6 +173,8 @@ private:
/* Synchronous response/request handler */
bool syncHandler(const dataman_request_s &request, dataman_response_s &response,
const hrt_abstime &start_time, hrt_abstime timeout);
/* Drain any queued stale replies before a new request starts. */
void clearPendingResponse();
State _state{State::Idle};
Request _active_request{};
@@ -292,6 +294,7 @@ private:
State cache_state;
};
void resetCacheState();
inline void changeUpdateIndex();
Item *_items{nullptr};
+364
View File
@@ -87,9 +87,16 @@ private:
bool testAsyncMutipleClients();
bool testAsyncWriteReadAllItemsMaxSize();
bool testAsyncClearAll();
bool testAsyncAbortAndReissue();
//Cache
bool testCache();
bool testCacheZeroSize();
bool testCacheResizeToZero();
bool testCacheResizeShrink();
// Helper: process cache until it has no more items to load (or the timeout hits).
bool processCacheUntilLoaded(DatamanCache &cache, hrt_abstime timeout);
//This will reset the items but it will not restore the compact key.
bool testResetItems();
@@ -102,6 +109,7 @@ private:
DatamanClient _dataman_client_thread3{};
DatamanCache _dataman_cache{"test_dm_cache_miss", 10};
DatamanCache _zero_dataman_cache{"test_dm_cache_zero", 0};
static void *testAsyncThread(void *arg);
@@ -762,6 +770,101 @@ DatamanTest::testAsyncClearAll()
return true;
}
bool
DatamanTest::testAsyncAbortAndReissue()
{
// When an async operation is abandoned without its response being consumed,
// the next async request must drain that stale reply (DatamanClient::clearPendingResponse)
// and still return current data.
const dm_item_t item = DM_KEY_WAYPOINTS_OFFBOARD_0;
const uint32_t length = g_per_item_size[item];
const uint32_t index = 7;
const uint8_t value = 0xC3;
// Store a known value.
memset(_buffer_write, value, sizeof(_buffer_write));
if (!_dataman_client1.writeSync(item, index, _buffer_write, length)) {
PX4_ERR("seed writeSync failed");
return false;
}
// Start an async read but never call update():
// this leaves a reply queued on the response topic.
uint8_t scratch[DM_MAX_DATA_SIZE] = {};
if (!_dataman_client1.readAsync(item, index, scratch, length)) {
PX4_ERR("first readAsync failed");
return false;
}
// Give the dataman task time to answer while we deliberately skip update().
px4_usleep(100_ms);
// Abandon the operation. The queued reply is now stale.
_dataman_client1.abortCurrentOperation();
// A fresh async read must drain the stale reply and return the current value.
memset(_buffer_read, 0, sizeof(_buffer_read));
if (!_dataman_client1.readAsync(item, index, _buffer_read, length)) {
PX4_ERR("second readAsync failed");
return false;
}
bool completed = false;
hrt_abstime start_time = hrt_absolute_time();
while (!completed) {
_dataman_client1.update();
if (_dataman_client1.lastOperationCompleted(_response_success)) {
completed = true;
}
if (hrt_elapsed_time(&start_time) > 1_s) {
PX4_ERR("Test timeout!");
return false;
}
px4_usleep(1_ms);
}
if (!_response_success) {
PX4_ERR("reissued read did not complete successfully");
return false;
}
for (uint32_t i = 0; i < length; ++i) {
if (_buffer_read[i] != value) {
PX4_ERR("reissued read returned wrong data at %" PRIu32, i);
return false;
}
}
return true;
}
bool
DatamanTest::processCacheUntilLoaded(DatamanCache &cache, hrt_abstime timeout)
{
hrt_abstime start_time = hrt_absolute_time();
while (cache.isLoading()) {
px4_usleep(1_ms);
cache.update();
if (hrt_elapsed_time(&start_time) > timeout) {
PX4_ERR("cache load timeout");
return false;
}
}
return true;
}
//Cache
bool
DatamanTest::testCache()
@@ -942,6 +1045,263 @@ DatamanTest::testCache()
return true;
}
bool
DatamanTest::testCacheZeroSize()
{
// A cache created with zero items must not allocate storage and must remain
// safe to use: no division-by-zero, no out-of-bounds access, and the
// underlying DatamanClient must stay functional.
const dm_item_t item = DM_KEY_WAYPOINTS_OFFBOARD_0;
const uint32_t length = g_per_item_size[item];
DatamanCache &zero_cache = _zero_dataman_cache;
if (zero_cache.size() != 0) {
PX4_ERR("zero-size cache reported size %d", zero_cache.size());
return false;
}
// Nothing can be queued for caching.
if (zero_cache.load(item, 0)) {
PX4_ERR("load() unexpectedly succeeded on zero-size cache");
return false;
}
if (zero_cache.isLoading()) {
PX4_ERR("zero-size cache reports loading");
return false;
}
// These must not divide by zero or read out of bounds.
zero_cache.update();
zero_cache.invalidate();
// Nothing is cached and there is no fallback without a timeout.
if (zero_cache.loadWait(item, 0, _buffer_read, length)) {
PX4_ERR("loadWait unexpectedly succeeded on zero-size cache");
return false;
}
// The client behind the cache is still usable directly.
memset(_buffer_write, 0x5A, sizeof(_buffer_write));
if (!zero_cache.client().writeSync(item, 0, _buffer_write, length)) {
PX4_ERR("writeSync through zero-size cache client failed");
return false;
}
if (!zero_cache.client().readSync(item, 0, _buffer_read, length)) {
PX4_ERR("readSync through zero-size cache client failed");
return false;
}
for (uint32_t i = 0; i < length; ++i) {
if (_buffer_read[i] != 0x5A) {
PX4_ERR("readSync through zero-size cache client returned wrong data");
return false;
}
}
memset(_buffer_read, 0, sizeof(_buffer_read));
if (!zero_cache.loadWait(item, 0, _buffer_read, length, 100_ms)) {
PX4_ERR("loadWait read-through on zero-size cache failed");
return false;
}
for (uint32_t i = 0; i < length; ++i) {
if (_buffer_read[i] != 0x5A) {
PX4_ERR("loadWait read-through on zero-size cache returned wrong data");
return false;
}
}
if (zero_cache.loadWait(item, 0, _buffer_read, length)) {
PX4_ERR("loadWait unexpectedly cached read-through data on zero-size cache");
return false;
}
return true;
}
bool
DatamanTest::testCacheResizeToZero()
{
// Shrinking a cache to zero must free its storage,
// reset variables and abort any client request.
const dm_item_t item = DM_KEY_WAYPOINTS_OFFBOARD_0;
const uint32_t length = g_per_item_size[item];
DatamanCache &cache = _dataman_cache;
cache.invalidate();
cache.resize(5);
// Queue three items so an item counter exists when we shrink.
for (uint32_t index = 0; index < 3; ++index) {
memset(_buffer_write, static_cast<uint8_t>(0x40 + index), sizeof(_buffer_write));
if (!cache.client().writeSync(item, index, _buffer_write, length)) {
PX4_ERR("writeSync failed at index %" PRIu32, index);
return false;
}
if (!cache.load(item, index)) {
PX4_ERR("load failed at index %" PRIu32, index);
return false;
}
}
if (!cache.isLoading()) {
PX4_ERR("cache should be loading");
return false;
}
// Start a request so the client holds a buffer pointing into
// the storage that resize(0) is about to free.
cache.update();
cache.resize(0);
if (cache.size() != 0) {
PX4_ERR("resize(0) left size %d", cache.size());
return false;
}
if (cache.isLoading()) {
PX4_ERR("cache still loading after resize(0)");
return false;
}
// Must be safe on a zero-size cache.
cache.update();
cache.invalidate();
if (cache.load(item, 0)) {
PX4_ERR("load() unexpectedly succeeded after resize(0)");
return false;
}
memset(_buffer_read, 0, sizeof(_buffer_read));
if (!cache.loadWait(item, 0, _buffer_read, length, 100_ms)) {
PX4_ERR("loadWait read-through failed after resize(0)");
return false;
}
for (uint32_t i = 0; i < length; ++i) {
if (_buffer_read[i] != 0x40) {
PX4_ERR("loadWait read-through after resize(0) returned wrong data");
return false;
}
}
// Growing the cache again must restore normal caching behaviour.
cache.resize(3);
if (cache.size() != 3) {
PX4_ERR("resize(3) reported size %d", cache.size());
return false;
}
for (uint32_t index = 0; index < 3; ++index) {
if (!cache.load(item, index)) {
PX4_ERR("load failed after regrow at index %" PRIu32, index);
return false;
}
}
if (!processCacheUntilLoaded(cache, 2_s)) {
return false;
}
for (uint32_t index = 0; index < 3; ++index) {
if (!cache.loadWait(item, index, _buffer_read, length)) {
PX4_ERR("loadWait failed after regrow at index %" PRIu32, index);
return false;
}
for (uint32_t i = 0; i < length; ++i) {
if (_buffer_read[i] != static_cast<uint8_t>(0x40 + index)) {
PX4_ERR("wrong data after regrow at index %" PRIu32, index);
return false;
}
}
}
cache.invalidate();
return true;
}
bool
DatamanTest::testCacheResizeShrink()
{
// Shrinking a cache below its current internal indices must keep
// those indices within the new bounds.
const dm_item_t item = DM_KEY_WAYPOINTS_OFFBOARD_0;
const uint32_t length = g_per_item_size[item];
DatamanCache &cache = _dataman_cache;
cache.invalidate();
cache.resize(10);
// Load eight items. This advances the internal load index to 8.
for (uint32_t index = 0; index < 8; ++index) {
memset(_buffer_write, static_cast<uint8_t>(0x80 + index), sizeof(_buffer_write));
if (!cache.client().writeSync(item, index, _buffer_write, length)) {
PX4_ERR("writeSync failed at index %" PRIu32, index);
return false;
}
if (!cache.load(item, index)) {
PX4_ERR("load failed at index %" PRIu32, index);
return false;
}
}
if (!processCacheUntilLoaded(cache, 2_s)) {
return false;
}
// Shrink below the current load index.
cache.resize(3);
if (cache.size() != 3) {
PX4_ERR("resize(3) reported size %d", cache.size());
return false;
}
// Pull in an index that is no longer cached.
const uint32_t reload_index = 5;
if (!cache.load(item, reload_index)) {
PX4_ERR("load failed after shrink");
return false;
}
cache.update();
// Use a timeout so the value is fetched even if the cache has not finished loading it yet.
if (!cache.loadWait(item, reload_index, _buffer_read, length, 1_s)) {
PX4_ERR("loadWait failed after shrink");
return false;
}
for (uint32_t i = 0; i < length; ++i) {
if (_buffer_read[i] != static_cast<uint8_t>(0x80 + reload_index)) {
PX4_ERR("wrong data after shrink");
return false;
}
}
if (!processCacheUntilLoaded(cache, 2_s)) {
return false;
}
cache.invalidate();
return true;
}
bool
DatamanTest::testResetItems()
{
@@ -1007,8 +1367,12 @@ bool DatamanTest::run_tests()
ut_run_test(testAsyncMutipleClients);
ut_run_test(testAsyncWriteReadAllItemsMaxSize);
ut_run_test(testAsyncClearAll);
ut_run_test(testAsyncAbortAndReissue);
ut_run_test(testCache);
ut_run_test(testCacheZeroSize);
ut_run_test(testCacheResizeToZero);
ut_run_test(testCacheResizeShrink);
ut_run_test(testResetItems);