perf(object-data-cache): take fill off the GET path and fix the metrics (#4678)

* fix(object-data-cache): make cache metrics one-increment-per-GET

Rework the object data cache observability so each counter carries one
clear meaning, and drop dead per-entry state.

ODC-17 (backlog#1122): split requests_total, which was incremented by
both plan_get and lookup_body, into plan_total{decision,reason,size_class}
(emitted only by plan_get) and lookup_total{result,size_class} (emitted
only by lookup_body). Each is now incremented exactly once per GET per
layer; help text states this.

ODC-18 (backlog#1123): add a JoinedInflightFill result (label
joined_inflight) so a singleflight waiter is no longer counted as an
insert. record_fill_result now always counts the outcome but records
fill bytes only when non-zero and the duration histogram only when
present, so joined_inflight / skipped_by_mode / skipped_size_mismatch
no longer inflate fill_bytes_total or add non-fill duration samples.
The waiter->JoinedInflightFill mapping lives in MokaBackend (owned by a
concurrent branch); cache.rs handles the variant already.

ODC-29 (backlog#1134): stop refreshing the cache-state gauge on every
lookup, and debounce it on fill/invalidate to at most once per second
via an AtomicU64 millis timestamp, since moka's entry_count is a
settling approximation.

ODC-36 (backlog#1141): give invalidations_total an outcome label
(removed|noop) and skip the gauge refresh on the no-op path. Extend
ObjectDataCacheInvalidationResult with Removed{keys}/NoOp (Success kept
as a transitional variant until MokaBackend reports the removal count);
NoopBackend now reports NoOp.

ODC-30 (backlog#1141): drop the dead content_length/etag/inserted_at
fields (and getters) from ObjectDataCacheEntry, which are redundant with
the moka key identity; the constructor keeps its arity so the
out-of-scope MokaBackend caller still compiles. Gate is_null_version
behind cfg(test).

Tests use a thread-local metrics recorder to avoid the global-singleton
flakiness. Fill-enabled test configs set min_free_memory_percent=0 so
the cgroup gate does not refuse fills in CI pods.

Co-Authored-By: heihutu <heihutu@gmail.com>

* fix(object-data-cache): move fill off GET path, bound & harden the fill

Implements five object-data-cache audit findings.

ODC-15 (backlog#1120): the GET response no longer blocks on cache fill.
The buffered/materialized body is already in hand, so the fill now runs
in a detached task and the response is built immediately. Singleflight is
made non-blocking: `try_acquire` returns Leader or Busy, and a non-leader
skips its own fill (SkippedSingleflightBusy) instead of waiting on another
request's leader. The inner fill spawn is KEPT: once the index key is
registered, the recheck/undo must complete even if the enclosing fill
future is aborted, so removing it would weaken the cancellation-safety
guarantee (ODC-13 test) and the invalidation-race undo.

ODC-11 (backlog#1116): enforce the fill-concurrency knobs. MokaBackend
now holds a Semaphore sized min(per_cpu * parallelism, max), acquired
after winning leadership and before the memory gate. On saturation it
rejects (try_acquire_owned) with SkippedFillConcurrency rather than
queueing, so the fill path never reintroduces GET-latency coupling.

ODC-14 (backlog#1119): the memory gate no longer does a blocking sysinfo
refresh under a mutex on the async fill path. A dedicated periodic
refresher (tokio interval + spawn_blocking) updates an atomic snapshot
every 5s; allows_fill is now lock-free. The min_free_memory_percent == 0
short-circuit still runs before any snapshot read. No runtime at
construction (sync unit tests) simply keeps the seed snapshot.

ODC-32 (backlog#1137): singleflight no longer emits metrics while holding
the map mutex. try_acquire/remove_entry capture the map length under the
guard, drop it, then emit the gauge/counter.

ODC-07 (backlog#1112): the materialize read is bounded via
take(capacity + 1) so an over-long stream cannot grow the buffer past the
in-memory GET threshold, and any length mismatch is now a hard error
matching the direct-memory GET path, instead of warn-and-serve.

cache.rs is owned by a concurrent branch; this commit only appends the
SkippedFillConcurrency and SkippedSingleflightBusy variants + label arms.

Co-Authored-By: heihutu <heihutu@gmail.com>

* fix(object-data-cache): report JoinedInflightFill and invalidation outcome

Reconciles the moka_backend half of two metrics-semantics findings after
merging fix/odc-metrics-semantics (which landed the cache.rs half).

ODC-18 (backlog#1123): the singleflight non-leader path now returns
JoinedInflightFill instead of counting as an insert, so N concurrent GETs
of one cold key record one insert, not N. This composes with the ODC-15
redesign: the non-leader does NOT wait for the leader (it already owns the
body and never re-serves from the fill result), so no blocking wait is
reintroduced. Drops the redundant local SkippedSingleflightBusy variant in
favor of the canonical JoinedInflightFill (mapped to no bytes / no duration
by the facade). SkippedFillConcurrency (ODC-11) is retained.

ODC-36 (backlog#1141): MokaBackend::invalidate_object now returns
Removed { keys } / NoOp instead of the transitional Success, so the facade
labels invalidations_total{outcome=removed|noop} and skips the cache-state
gauge refresh on the no-op path.

Tests: duplicate-fill test asserts JoinedInflightFill (bites when reverted
to Inserted); new no-op invalidation test; matching-identity test asserts
Removed { keys: 1 }.

Co-Authored-By: heihutu <heihutu@gmail.com>

* fix(object-data-cache): drop unused mut on materialize stream binding

The ODC-07 change moves `final_stream` into `AsyncReadExt::take`, so the
`build_get_object_body_with_cache` parameter is no longer mutated in place.

Co-Authored-By: heihutu <heihutu@gmail.com>

* refactor(object-data-cache): close the cross-branch coordination seams

Merging the metrics and hot-path branches left four transitional shims that
only existed because each side could not edit the other's files. With both
sides present they are dead weight, and two of them actively misreport.

- ObjectDataCacheEntry::new took content_length and etag only to keep the
  caller in moka_backend.rs compiling, then discarded both. Drop them; the
  entry is a Bytes wrapper and the caller now passes only the body.

- SkippedSingleflightClosed lost its only producer when the waiter model was
  replaced by Leader/Busy election. Remove the variant.

- The fill-accounting match ended in a wildcard that charged fill_bytes and a
  duration to every non-Inserted outcome, so a fill rejected by the memory
  gate or the concurrency semaphore — which never touched the backend and
  wrote nothing — still inflated fill_bytes_total. Enumerate every variant
  explicitly: only outcomes that wrote the body report bytes and duration.
  Exhaustiveness also forces a future variant to state its accounting rather
  than inherit a wrong default.

- InvalidationResult::Success mapped a no-op to outcome=removed, the exact lie
  backlog#1141 set out to fix, and its doc comment claimed MokaBackend still
  returned it after that backend had been widened. It has no producer left.
  Remove it, and tighten the app-layer test from "any successful variant" to
  the real contract: the pre-mutation call reports Removed{keys:1}, the
  post-delete call NoOp.

Refs: backlog#1123, backlog#1141, backlog#1135

Co-Authored-By: heihutu <heihutu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
This commit is contained in:
houseme
2026-07-10 20:25:23 +08:00
committed by GitHub
parent 8039a4ceae
commit b604074217
12 changed files with 1061 additions and 287 deletions
@@ -147,12 +147,17 @@ mod tests {
body_variant: ObjectDataCacheBodyVariant::FullObjectPlainV1,
});
let fill = adapter.fill_body(&plan, Bytes::from_static(b"hello")).await;
let _ = invalidate_object_data_cache_before_mutation(&adapter, "bucket", "object").await;
let invalidation = invalidate_object_data_cache_after_delete_success(&adapter, "bucket", "object").await;
let before_mutation = invalidate_object_data_cache_before_mutation(&adapter, "bucket", "object").await;
let after_delete = invalidate_object_data_cache_after_delete_success(&adapter, "bucket", "object").await;
let lookup = adapter.lookup_body(&plan).await;
assert_eq!(fill, ObjectDataCacheFillResult::Inserted);
assert_eq!(invalidation, ObjectDataCacheInvalidationResult::Success);
// The two-phase invalidation is deliberate hygiene, and the outcomes must
// distinguish real churn from its no-op half: the first call evicts the
// cached body, the second finds the identity already empty. Dashboards
// read that split (backlog#1141).
assert_eq!(before_mutation, ObjectDataCacheInvalidationResult::Removed { keys: 1 });
assert_eq!(after_delete, ObjectDataCacheInvalidationResult::NoOp);
assert!(matches!(lookup, ObjectDataCacheLookup::Miss));
}
+125 -7
View File
@@ -3130,7 +3130,7 @@ impl DefaultObjectUsecase {
#[allow(clippy::too_many_arguments)]
async fn build_get_object_body_with_cache<R>(
cache_adapter: &ObjectDataCacheAdapter,
mut final_stream: R,
final_stream: R,
info: &ObjectInfo,
response_content_length: i64,
optimal_buffer_size: usize,
@@ -3171,7 +3171,21 @@ impl DefaultObjectUsecase {
}
if let Some(buffered_body) = buffered_body {
let _fill_result = fill_get_object_body_cache_from_buffered_body(cache_adapter, &cache_plan, &buffered_body).await;
// ODC-15: the body is already fully in hand, so keep the fill off the
// response's critical path. For a cacheable plan, run the fill in a
// detached task (Bytes is a cheap clone) and return immediately. For
// a non-cacheable plan the fill is a pure metric-only skip with no
// I/O, so record it inline to preserve observability.
if matches!(cache_plan, GetObjectBodyCachePlan::Cacheable(_)) {
let cache_adapter = cache_adapter.clone();
let cache_plan = cache_plan.clone();
let fill_bytes = buffered_body.clone();
tokio::spawn(async move {
let _ = fill_get_object_body_cache_from_buffered_body(&cache_adapter, &cache_plan, &fill_bytes).await;
});
} else {
let _ = fill_get_object_body_cache_from_buffered_body(cache_adapter, &cache_plan, &buffered_body).await;
}
return Ok(Self::build_memory_bytes_blob(
buffered_body,
@@ -3215,23 +3229,43 @@ impl DefaultObjectUsecase {
.await;
};
let mut buf = Vec::with_capacity(materialized_capacity);
// ODC-07: bound the read so a stream yielding more than the declared
// length cannot grow `buf` past the in-memory GET threshold. Reading
// one byte past the capacity is enough to detect an over-long stream.
let mut bounded_stream = tokio::io::AsyncReadExt::take(final_stream, materialized_capacity as u64 + 1);
let buffer_read_start = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
let read_result = tokio::io::AsyncReadExt::read_to_end(&mut final_stream, &mut buf).await;
let read_result = tokio::io::AsyncReadExt::read_to_end(&mut bounded_stream, &mut buf).await;
record_get_object_s3_handler_stage_duration(GET_OBJECT_STAGE_BODY_CACHE_MATERIALIZE_READ, buffer_read_start);
match read_result {
Ok(_) => {
// ODC-07: treat a length mismatch as a hard error, matching
// the direct-memory GET path. Serving a body whose decoded
// length disagrees with the declared content length would
// ship a truncated or over-long response.
if buf.len() != materialized_capacity {
warn!(
lifecycle.finish_err();
error!(
expected = response_content_length,
actual = buf.len(),
"Object size mismatch during materialize-fill read"
"materialize-fill GET decoded length mismatch"
);
return Err(ApiError::from(StorageError::other(format!(
"materialize-fill GET decoded length mismatch: expected {response_content_length}, got {}",
buf.len()
)))
.into());
}
let bytes = Bytes::from(buf);
let _fill_result =
fill_get_object_body_cache_from_materialized_body(cache_adapter, &cache_plan, &bytes).await;
// ODC-15: fill off the response's critical path (see the
// buffered-body branch above).
let cache_adapter = cache_adapter.clone();
let cache_plan = cache_plan.clone();
let fill_bytes = bytes.clone();
tokio::spawn(async move {
let _ = fill_get_object_body_cache_from_materialized_body(&cache_adapter, &cache_plan, &fill_bytes).await;
});
return Ok(Self::build_memory_bytes_blob(
bytes,
@@ -7075,6 +7109,32 @@ mod tests {
));
}
/// Polls the cache until the detached fill (ODC-15) populates the entry, so
/// a follow-up GET is a deterministic hit rather than racing the fill task.
async fn wait_for_cache_hit(
adapter: &crate::app::object_data_cache::ObjectDataCacheAdapter,
bucket: &str,
object: &str,
etag: &str,
size: u64,
) {
let plan = adapter.plan_get(rustfs_object_data_cache::ObjectDataCacheGetRequest {
bucket,
object,
version_id: None,
etag,
size,
body_variant: rustfs_object_data_cache::ObjectDataCacheBodyVariant::FullObjectPlainV1,
});
for _ in 0..400 {
if matches!(adapter.lookup_body(&plan).await, rustfs_object_data_cache::ObjectDataCacheLookup::Hit(_)) {
return;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
panic!("detached fill did not populate the cache within the timeout");
}
struct ReadProbeReader {
reads: Arc<AtomicUsize>,
}
@@ -7612,6 +7672,10 @@ mod tests {
.await
.expect("buffered-body handoff should succeed");
// ODC-15: the fill is detached from the response path, so wait for it to
// populate the cache before the follow-up GET to keep the hit deterministic.
wait_for_cache_hit(&adapter, "test-bucket", "cached-object", "etag", 5).await;
let _second_body = DefaultObjectUsecase::build_get_object_body_with_cache(
&adapter,
second_reader,
@@ -7748,6 +7812,10 @@ mod tests {
.await
.expect("materialize-fill handoff should succeed");
// ODC-15: the fill is detached from the response path, so wait for it to
// populate the cache before the follow-up GET to keep the hit deterministic.
wait_for_cache_hit(&adapter, "test-bucket", "materialized-object", "etag", 5).await;
let _second_body = DefaultObjectUsecase::build_get_object_body_with_cache(
&adapter,
second_reader,
@@ -7779,6 +7847,56 @@ mod tests {
);
}
// ODC-07: a materialize read that yields more than the declared content
// length must be a hard error, not a warn-and-serve, matching the
// direct-memory GET path. The bounded `take` reads one byte past capacity so
// the over-long stream is detected without buffering it unbounded.
#[tokio::test]
async fn build_get_object_body_with_cache_materialize_rejects_length_mismatch() {
let reads = Arc::new(AtomicUsize::new(0));
// Declared content length is 5, but the stream yields 6 bytes.
let reader = DataProbeReader {
reads: Arc::clone(&reads),
data: std::io::Cursor::new(b"hello!".to_vec()),
};
let info = ObjectInfo {
size: 5,
etag: Some("etag".to_string()),
..Default::default()
};
let adapter =
crate::app::object_data_cache::ObjectDataCacheAdapter::new(rustfs_object_data_cache::ObjectDataCacheConfig {
mode: rustfs_object_data_cache::ObjectDataCacheMode::FillMaterializeEnabled,
max_bytes: 8_388_608,
min_free_memory_percent: 0,
..rustfs_object_data_cache::ObjectDataCacheConfig::default()
})
.expect("materialize-fill cache adapter should initialize");
let result = DefaultObjectUsecase::build_get_object_body_with_cache(
&adapter,
reader,
&info,
5,
128 * 1024,
false,
1,
None,
false,
false,
None,
"test-bucket",
"mismatch-object",
GetObjectBodyLifecycle::disabled(),
)
.await;
assert!(
result.is_err(),
"an over-long materialize read must be a hard error, not a truncated served body"
);
}
#[tokio::test]
async fn build_get_object_body_with_cache_skips_materialize_when_too_large_for_cache() {
let reads = Arc::new(AtomicUsize::new(0));