perf(vision_target_estimator): cap OOSM observation storage (#29395)

Co-authored-by: jonas <jonas.perolini@rigi.tech>
This commit is contained in:
Jonas Peroliniandjonas authored and GitHub committed 2026-10-25 10:08:42 -05:00
1 parent cafa463630
commit 77c37ea4f6
8 files changed
+152 -35

No files matched your search

@@ -422,13 +422,15 @@ Finally, it predicts to 220 ms and replaces the previous estimate with this rebu
Vision and target GNSS samples stamped less than 20 ms in the future, usually from clock-sync jitter, are moved to the current time and fused as current.
Samples further in the future are dropped with a "timestamp in the future" warning.
Validity and reset timeouts count from the capture time of the newest fused position or yaw sample, so a delayed sample does not extend them.
These timestamps follow the current replay decisions: rejecting or accepting a stored sample can move freshness backwards or forwards.
The separate freshness check for EKF2 auxiliary velocity aiding likewise follows the newest accepted vision observation.
### OOSM Implementation
Each filter retains up to 25 post-update snapshots of the time, state, covariance and prediction input.
At 50 Hz, 25 snapshots span 480 ms from oldest to newest.
A separate fixed-size buffer stores the gated scalar observations, accepted or rejected, with their measurement matrix, variance and latest gate decision.
It is sized for one observation per aid source and cycle: 100 per position axis (up to four sources in moving-target mode) and 25 for yaw.
It keeps up to 48 observations per position axis, sized for 50 Hz vision and three 10 Hz GNSS streams over the whole window with some margin, and 25 for yaw (one per cycle).
For a delayed observation:
@@ -476,9 +478,12 @@ On successful replay within the observation-log capacity, the final state and co
Replay diagnostics use this shared trajectory, so an older observation's `replay_test_ratio_max` can include the influence of later observations accepted in the same batch.
Other new batch observations are not included in `replayed_count`; it counts only previously stored observations.
Observations outside the available history or the 500 ms maximum delay are rejected.
Stored observations older than the oldest retained posterior are discarded: that posterior already contains the accepted ones, and their decisions can no longer change.
The buffer cannot overflow while each aid source contributes at most one observation per cycle.
If adding an observation would exceed its capacity, history restarts from the live posterior: the state is preserved, but older delayed observations are rejected until history accumulates again.
Stored observations at or before the oldest usable posterior are discarded: that posterior already contains the accepted ones, and their decisions can no longer change.
When the buffer is full, the oldest usable snapshot advances to the first snapshot at or after the oldest observation, and observations through that snapshot are discarded.
This shrinks the replay window: delayed observations captured before that snapshot are rejected as `STATUS_REJECT_TOO_OLD`.
If no snapshot contains the oldest observation yet, history restarts from the live posterior instead.
Observations are dropped after a cycle's replay, so this only limits later cycles.
The cap limits each replay to at most 48 distinct stored observations per position axis; rejected candidates can cause repeated gate evaluations, as described below.
When all `B` delayed observations in a cycle are accepted, each axis requires at most `N_snapshots + N_observations + B + 1` predictions and `N_observations + B` measurement updates.
Here, `N_snapshots` counts snapshots after the floor of the oldest one (at most 24), and `N_observations` counts stored observations replayed from that floor to now.
@@ -620,7 +625,7 @@ The `fusion_status` field records which fusion branch the filter.
| 2 | `STATUS_FUSED_OOSM` | Measurement was delayed and fused via the OOSM history buffer; check `history_steps`, and `time_since_meas_ms`. | Healthy. `history_steps` is at most 24; values close to it mean a delay near the 500 ms limit. |
| 3 | `STATUS_REJECT_NIS` | Innovation failed the chi-squared gate. | Check sensor variance, frame rotations, time skew. Compare with `test_ratio` and the matching `vte_input` sample. |
| 4 | `STATUS_REJECT_COV` | Innovation covariance was non-finite or non-positive. A stored observation failing on replay clears history. | Numerical issue: check process-noise parameters and that the state has not diverged. |
| 5 | `STATUS_REJECT_TOO_OLD` | Sample older than the OOSM buffer (`kOosmMaxTimeUs = 500 ms`) or older than the oldest stored snapshot. | Reduce sensor latency, raise the publication rate, or check transport timestamps. |
| 5 | `STATUS_REJECT_TOO_OLD` | Sample older than the OOSM buffer (`kOosmMaxTimeUs = 500 ms`) or than the oldest snapshot a replay can use. | Reduce sensor latency, raise the publication rate, or check transport timestamps. |
| 6 | `STATUS_REJECT_TOO_NEW` | Sample timestamped 20 ms or more after the latest filter prediction. | Time-sync problem: verify `mavlink_timesync` or the sensor clock. Built-in sources drop these with a warning. |
| 7 | `STATUS_REJECT_STALE` | Filter history was reset because no prediction had run for longer than the buffer span. | Expected after long pauses; otherwise investigate scheduler stalls. |
| 8 | `STATUS_REJECT_EMPTY` | History buffer not yet populated when the measurement arrived. | Expected after a history reset; position initialisation itself reports `STATUS_INITIALIZED`. |
@@ -638,6 +643,8 @@ Additional fields make latency and replay tractable without manual timestamp ari
`replay_test_ratio_max` is the highest `test_ratio` among those accepted before the replay (-1 if none).
A value above 1 means the replay rejected an observation accepted before (see [OOSM Implementation](#oosm-implementation)).
The delayed observations of one cycle share a replay, so their values can also reflect each other.
These counters are reported only for accepted delayed observations and exclude stored observations before their capture time.
A revised decision encountered while rebuilding a rejected observation's prior can therefore change the estimate without appearing in these counters.
### Main Input Feeds
+1 -1
View File
@@ -22,7 +22,7 @@ uint8 STATUS_FUSED_CURRENT = 1 # Fused immediately (low latency)
uint8 STATUS_FUSED_OOSM = 2 # Fused via history buffer
uint8 STATUS_REJECT_NIS = 3 # Rejected by Normalized Innovation Squared check
uint8 STATUS_REJECT_COV = 4 # Rejected due to invalid/infinite covariance or numerical error; clears history if a replayed observation failed
uint8 STATUS_REJECT_TOO_OLD = 5 # Rejected: older than buffer limit (kOosmMaxTimeUs) or oldest sample
uint8 STATUS_REJECT_TOO_OLD = 5 # Rejected: older than buffer limit (kOosmMaxTimeUs) or the oldest snapshot a replay can use
uint8 STATUS_REJECT_TOO_NEW = 6 # Rejected: timestamp in the future (beyond tolerance)
uint8 STATUS_REJECT_STALE = 7 # Rejected: history was reset due to staleness/discontinuity
uint8 STATUS_REJECT_EMPTY = 8 # Rejected: history buffer not yet populated
+1 -1
View File
@@ -22,7 +22,7 @@ uint8 STATUS_FUSED_CURRENT = 1 # Fused immediately (low latency)
uint8 STATUS_FUSED_OOSM = 2 # Fused via history buffer
uint8 STATUS_REJECT_NIS = 3 # Rejected by Normalized Innovation Squared check
uint8 STATUS_REJECT_COV = 4 # Rejected due to invalid/infinite covariance or numerical error; clears history if a replayed observation failed
uint8 STATUS_REJECT_TOO_OLD = 5 # Rejected: older than buffer limit (kOosmMaxTimeUs) or oldest sample
uint8 STATUS_REJECT_TOO_OLD = 5 # Rejected: older than buffer limit (kOosmMaxTimeUs) or the oldest snapshot a replay can use
uint8 STATUS_REJECT_TOO_NEW = 6 # Rejected: timestamp in the future (beyond tolerance)
uint8 STATUS_REJECT_STALE = 7 # Rejected: history was reset due to staleness/discontinuity
uint8 STATUS_REJECT_EMPTY = 8 # Rejected: history buffer not yet populated
@@ -62,7 +62,7 @@ public:
using VectorState = matrix::Vector<float, kSize>;
using SquareMatrixState = matrix::SquareMatrix<float, kSize>;
friend class OOSMManager<KF_orientation, kSize, EmptyInput, kOosmHistorySize, 1>;
friend class OOSMManager<KF_orientation, kSize, EmptyInput, kOosmHistorySize, kOosmHistorySize>;
KF_orientation() = default;
~KF_orientation() = default;
@@ -127,7 +127,7 @@ private:
// OOSM history buffer:
// 0.5 s window @ 50 Hz predict rate = 25 samples.
// Note that the 0.5 s window is enforced with kOosmMaxTimeUs = 500_ms.
// VTEOrientation fuses at most one vision yaw sample per cycle.
OOSMManager<KF_orientation, kSize, EmptyInput, kOosmHistorySize, 1> _oosm;
// VTEOrientation fuses at most one vision yaw sample per cycle, so the log holds one per snapshot.
OOSMManager<KF_orientation, kSize, EmptyInput, kOosmHistorySize, kOosmHistorySize> _oosm;
};
} // namespace vision_target_estimator
@@ -60,7 +60,7 @@ public:
using VectorState = matrix::Vector<float, kStateSize>;
using SquareMatrixState = matrix::SquareMatrix<float, kStateSize>;
friend class OOSMManager<KF_position, kStateSize, float>;
friend class OOSMManager<KF_position, kStateSize, float, kOosmHistorySize, kOosmMaxStoredObs>;
KF_position() = default;
~KF_position() = default;
@@ -135,6 +135,7 @@ private:
// OOSM history buffer:
// 0.5 s window @ 50 Hz predict rate = 25 samples.
// Note that the 0.5 s window is enforced with kOosmMaxTimeUs = 500_ms.
OOSMManager<KF_position, kStateSize, float, kOosmHistorySize> _oosm;
// The observation log keeps the kOosmMaxStoredObs most recent observations.
OOSMManager<KF_position, kStateSize, float, kOosmHistorySize, kOosmMaxStoredObs> _oosm;
};
} // namespace vision_target_estimator
+38 -17
View File
@@ -87,8 +87,8 @@ struct EmptyInput {};
* @tparam InputT Control input stored per snapshot (e.g. acceleration for
* the position filter, or EmptyInput for orientation).
* @tparam HistorySize Capacity of the ring buffer (max 255).
* @tparam MaxObsPerSnapshot Most scalar observations fused between two snapshots, one per aid
* source and cycle (up to four for the position filter). Sizes the log.
* @tparam MaxStoredObs Capacity of the observation log, which also bounds the stored observations
* one replay gates again. When full, the oldest observation is dropped.
*
* FilterT concept (the OOSM manager never touches the filter's internal state
* directly, it drives it exclusively through this interface):
@@ -103,7 +103,7 @@ struct EmptyInput {};
*
* ScalarMeasT concept: default-constructible with members time_us, val, unc, H and source.
*/
template <typename FilterT, int StateDim, typename InputT, int HistorySize = 25, int MaxObsPerSnapshot = 4>
template <typename FilterT, int StateDim, typename InputT, int HistorySize = 25, int MaxStoredObs = 4 * HistorySize>
class OOSMManager
{
public:
@@ -119,12 +119,9 @@ public:
static_assert(HistorySize > 0, "HistorySize must be > 0");
static_assert(HistorySize <= 255, "HistorySize must fit in uint8_t");
static_assert(MaxObsPerSnapshot > 0, "MaxObsPerSnapshot must be > 0");
static_assert(MaxStoredObs > 0, "MaxStoredObs must be > 0");
static constexpr uint8_t kHistorySize = static_cast<uint8_t>(HistorySize);
// Retained observations were gated within the last HistorySize cycles, so the log
// only fills if the filter gates more than MaxObsPerSnapshot per cycle.
static constexpr size_t kMeasurementCapacity = static_cast<size_t>(MaxObsPerSnapshot) * HistorySize;
static constexpr size_t kMeasurementCapacity = static_cast<size_t>(MaxStoredObs);
static constexpr uint64_t kOosmMinTimeUs = vision_target_estimator::kOosmMinTimeUs;
static constexpr uint64_t kOosmMaxTimeUs = vision_target_estimator::kOosmMaxTimeUs;
static_assert(kOosmMinTimeUs <= INT16_MAX, "Fast-path capture-time offset must fit in int16_t");
@@ -139,6 +136,7 @@ public:
void reset(FusionTimes times = {})
{
_measurement_count = 0;
_min_floor_time_us = 0;
_baseline_times = times;
_fusion_times = times;
@@ -284,18 +282,34 @@ private:
};
StoredMeasurement _measurements[kMeasurementCapacity] {};
size_t _measurement_count{0};
FusionTimes _baseline_times{}; // Accepted observations already incorporated in the oldest snapshot.
uint64_t _min_floor_time_us{0}; // Replays start at or after it: older snapshots lack a dropped observation
FusionTimes _baseline_times{}; // Accepted observations already incorporated in the oldest usable snapshot.
FusionTimes _fusion_times{}; // Committed live posterior, unchanged while replay is speculative.
// Oldest snapshot a replay can start from.
uint64_t oldestFloorTime()
{
const uint8_t newest_idx = _history.get_newest_index();
uint8_t idx = _history.get_oldest_index();
while ((idx != newest_idx) && (_history[idx].time_us < _min_floor_time_us)) {
idx = _history.next(idx);
}
return _history[idx].time_us;
}
void pruneMeasurements()
{
if (_history.entries() == 0) {
return;
}
// Observations at or before the oldest usable snapshot are contained in it.
const uint64_t floor_time = oldestFloorTime();
size_t obsolete = 0;
while (obsolete < _measurement_count && _measurements[obsolete].time_us <= _history.get_oldest().time_us) {
while (obsolete < _measurement_count && _measurements[obsolete].time_us <= floor_time) {
const StoredMeasurement &stored = _measurements[obsolete];
if (stored.accepted) {
@@ -323,10 +337,17 @@ private:
pruneMeasurements();
if (_measurement_count == kMeasurementCapacity) {
// Restart from the live posterior rather than drop an update a later replay needs.
reset(_fusion_times);
push(now_us, state, cov, input);
return;
if ((_history.entries() > 0) && (_measurements[0].time_us <= _history.get_newest().time_us)) {
// Drop the oldest observation. Replays then start from snapshots that contain it.
_min_floor_time_us = _measurements[0].time_us;
pruneMeasurements();
} else {
// No snapshot contains it yet: restart from the live posterior instead.
reset(_fusion_times);
push(now_us, state, cov, input);
return;
}
}
size_t pos = _measurement_count;
@@ -383,8 +404,8 @@ private:
return false;
}
// Measurement predates the buffer window: we cannot reconstruct a floor for it.
if ((now_us - meas.time_us) > kOosmMaxTimeUs || meas.time_us < _history.get_oldest().time_us) {
// Measurement predates the replay window: we cannot reconstruct a floor for it.
if ((now_us - meas.time_us) > kOosmMaxTimeUs || meas.time_us < oldestFloorTime()) {
res.status = FusionStatus::STATUS_REJECT_TOO_OLD;
return false;
}
@@ -411,7 +432,7 @@ private:
}
}
// Newest snapshot at or before time_us. checkDelayed() ensures the oldest one qualifies.
// Newest snapshot at or before time_us. checkDelayed() ensures the oldest usable one qualifies.
uint8_t floorIndex(uint64_t time_us)
{
const uint8_t oldest_idx = _history.get_oldest_index();
@@ -67,6 +67,9 @@ constexpr hrt_abstime kEstimatorUpdatePeriodUs = 20_ms;
constexpr hrt_abstime kOosmMinTimeUs = kEstimatorUpdatePeriodUs;
constexpr hrt_abstime kOosmMaxTimeUs = 500_ms;
constexpr int kOosmHistorySize = static_cast<int>(kOosmMaxTimeUs / kEstimatorUpdatePeriodUs);
// Observations kept per position axis for replays: 50 Hz vision and three 10 Hz GNSS streams need 40
// over the window, plus margin. Beyond that the oldest are dropped and the replay window shrinks.
constexpr int kOosmMaxStoredObs = 48;
constexpr int kExpectedAxisCount = 3;
constexpr int kExpectedStaticPositionStateCount = 3;
constexpr int kExpectedMovingPositionStateCount = 5;
@@ -367,8 +367,8 @@ TEST_F(VTEOosmTest, FusesCurrentMeasurement)
EXPECT_EQ(filter.applied_k.size(), 1u);
}
// Exhausting bounded replay storage must retain the live posterior and discard
// the unusable old timeline, rather than replaying with a missing observation.
// A full log whose oldest observation no snapshot contains yet cannot drop it: history restarts
// from the live posterior instead, rather than replaying with a missing observation.
TEST_F(VTEOosmTest, MeasurementCapacityRestartsHistoryFromLivePosterior)
{
using Access = vte::OOSMManagerTestAccess<Manager>;
@@ -432,11 +432,11 @@ TEST_F(VTEOosmTest, RetainsFreshnessAfterObservationIsPruned)
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, 0u);
}
// A log sized for one observation per snapshot must hold one fused observation per cycle
// indefinitely, so the orientation filter never restarts its history in steady state.
// A log with one slot per snapshot must hold one fused observation per cycle indefinitely,
// so the orientation filter never drops one in steady state.
TEST_F(VTEOosmTest, OneObservationPerCycleFitsMeasurementCapacity)
{
using OneObsManager = vte::OOSMManager<TestFilter, kStateDim, float, 8, 1>;
using OneObsManager = vte::OOSMManager<TestFilter, kStateDim, float, 8, 8>;
using Access = vte::OOSMManagerTestAccess<OneObsManager>;
OneObsManager one_obs{};
auto x = makeVec(0.f);
@@ -452,7 +452,7 @@ TEST_F(VTEOosmTest, OneObservationPerCycleFitsMeasurementCapacity)
vte::FusionStatus::STATUS_FUSED_CURRENT);
one_obs.push(now, x, P, curr_input);
// A restart would move the oldest snapshot to the current cycle.
// A restart would move the oldest snapshot to the current cycle; a drop would reject the oldest below.
const int retained = std::min(cycle + 1, static_cast<int>(OneObsManager::kHistorySize));
ASSERT_EQ(Access::historyOldestTime(one_obs), now - (retained - 1) * step);
}
@@ -461,6 +461,91 @@ TEST_F(VTEOosmTest, OneObservationPerCycleFitsMeasurementCapacity)
x, P, curr_input).status, vte::FusionStatus::STATUS_FUSED_OOSM);
}
// A full log drops its oldest observation instead of restarting history: replays then start from
// snapshots that contain it, so only delayed samples older than those are rejected.
TEST_F(VTEOosmTest, DropsOldestObservationWhenLogIsFull)
{
constexpr int kObservationCapacity = 4;
constexpr int kCycles = 10;
constexpr int kFloorCycle = kCycles - kObservationCapacity;
using SmallLogManager = vte::OOSMManager<TestFilter, kStateDim, float, 8, kObservationCapacity>;
using Access = vte::OOSMManagerTestAccess<SmallLogManager>;
SmallLogManager small_log{};
constexpr uint64_t t0 = 1_s;
constexpr uint64_t step = 20_ms;
constexpr uint64_t now = t0 + (kCycles + 1) * step;
constexpr uint64_t floor_time = t0 + kFloorCycle * step;
auto x = makeVec(0.f);
auto P = makeCov(1.f);
small_log.push(t0, x, P, 0.f);
// Fill the log, advance its floor, and wrap the snapshot ring.
for (int cycle = 1; cycle <= kCycles; ++cycle) {
const uint64_t t = t0 + cycle * step;
filter.predictState(step * 1e-6f, 0.f, x, P, x, P);
ScalarMeas meas = makeMeas(t - 5_ms, 0.1f * cycle, 0.5f);
meas.source = vte::FusionSource::Untracked;
if (cycle == kFloorCycle) {
// This relative observation leaves the log because of capacity, before its snapshot expires.
meas.source = vte::FusionSource::Relative;
}
ASSERT_EQ(small_log.fuse(filter, meas, t, 0.f, x, P, 0.f).status,
vte::FusionStatus::STATUS_FUSED_CURRENT);
small_log.push(t, x, P, 0.f);
}
EXPECT_EQ(Access::historyEntries(small_log), SmallLogManager::kHistorySize);
EXPECT_LT(Access::historyOldestTime(small_log), floor_time);
EXPECT_EQ(small_log.getFusionTimes().last_relative_fused, floor_time - 5_ms);
filter.predictState(step * 1e-6f, 0.f, x, P, x, P);
// Only snapshots that contain all dropped observations remain valid replay floors.
const ScalarMeas too_old = makeMeas(floor_time - 1_us, 0.f, 0.5f);
ScalarMeas delayed = makeMeas(floor_time, 0.f, 0.5f);
delayed.source = vte::FusionSource::Untracked;
EXPECT_EQ(small_log.fuse(filter, too_old, now, 0.f, x, P, 0.f).status, vte::FusionStatus::STATUS_REJECT_TOO_OLD);
ASSERT_EQ(small_log.fuse(filter, delayed, now, 0.f, x, P, 0.f).status, vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_EQ(small_log.getFusionTimes().last_fused, floor_time - 5_ms);
EXPECT_EQ(small_log.getFusionTimes().last_relative_fused, floor_time - 5_ms);
TestFilter truth_filter;
auto x_truth = makeVec(0.f);
auto P_truth = makeCov(1.f);
uint64_t truth_time = t0;
const auto fuse_truth = [&](const ScalarMeas & m, uint64_t t) {
truth_filter.predictState((t - truth_time) * 1e-6f, 0.f, x_truth, P_truth, x_truth, P_truth);
truth_time = t;
float innov = 0.f;
float innov_var = 0.f;
truth_filter.computeInnovation(x_truth, P_truth, m, innov, innov_var);
truth_filter.applyCorrection(x_truth, P_truth, (P_truth * m.H) / innov_var, innov, innov_var);
};
for (int cycle = 1; cycle <= kCycles; ++cycle) {
if (cycle == kFloorCycle + 1) {
fuse_truth(delayed, delayed.time_us);
}
const uint64_t t = t0 + cycle * step;
fuse_truth(makeMeas(t - 5_ms, 0.1f * cycle, 0.5f), t);
}
truth_filter.predictState((now - truth_time) * 1e-6f, 0.f, x_truth, P_truth, x_truth, P_truth);
EXPECT_NEAR(x(0), x_truth(0), kTolerance);
EXPECT_NEAR(P(0, 0), P_truth(0, 0), kTolerance);
// A reset also clears the capacity floor, even when starting a new timeline at an earlier time.
small_log.reset();
small_log.push(t0, x, P, 0.f);
filter.predictState(step * 1e-6f, 0.f, x, P, x, P);
small_log.push(t0 + step, x, P, 0.f);
filter.predictState(step * 1e-6f, 0.f, x, P, x, P);
EXPECT_EQ(small_log.fuse(filter, makeMeas(t0, 0.f, 0.5f), t0 + 2 * step, 0.f, x, P, 0.f).status,
vte::FusionStatus::STATUS_FUSED_OOSM);
}
// WHY: Near-zero innovation variance should never result in a correction.
// WHAT: Verify REJECT_COV and that the live state stays unchanged.
TEST_F(VTEOosmTest, RejectsInvalidInnovationVariance)