This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new dda0e224b7 fix(services/foyer): apply the memory budget in bytes
(#9410)
dda0e224b7 is described below
commit dda0e224b704670d9a8b8c6e877f30cef659c8a1
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 30 08:54:02 2026 +0800
fix(services/foyer): apply the memory budget in bytes (#9410)
---
.../src/main/java/org/apache/opendal/ServiceConfig.java | 6 +++++-
bindings/python/python/opendal/config.py | 2 +-
core/layers/foyer/src/lib.rs | 2 +-
core/services/foyer/src/backend.rs | 15 ++++++++++-----
core/services/foyer/src/config.rs | 7 ++++++-
core/services/foyer/src/core.rs | 11 +++++++----
core/services/foyer/src/docs.md | 11 ++++++++---
core/services/foyer/src/lib.rs | 16 ++++++++++++++++
website/data/services.json | 8 ++++----
9 files changed, 58 insertions(+), 20 deletions(-)
diff --git a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
index da66e72166..5741a8fa3c 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
@@ -1412,7 +1412,11 @@ public interface ServiceConfig {
*/
public final String diskPath;
/**
- * <p>Memory capacity in bytes for the cache.</p>
+ * <p>Memory eviction budget in bytes for the automatically built
cache.</p>
+ * <p>Each entry counts the byte length of its stored path plus the
logical
+ * length of its value, with a minimum charge of one byte. The stored
path
+ * includes the normalized root and omits the leading slash. Foyer can
+ * retain an entry whose weight exceeds its shard's budget. Default is
1 GiB.</p>
*/
public final Long memory;
/**
diff --git a/bindings/python/python/opendal/config.py
b/bindings/python/python/opendal/config.py
index f7cd0c67b6..4271094cc2 100644
--- a/bindings/python/python/opendal/config.py
+++ b/bindings/python/python/opendal/config.py
@@ -465,7 +465,7 @@ class FoyerConfig(TypedDict):
disk_path: NotRequired[str]
"""Disk cache directory path. If set, enables hybrid cache with disk
storage. Data will be persisted to this directory when memory cache is full."""
memory: NotRequired[int]
- """Memory capacity in bytes for the cache."""
+ """Memory eviction budget in bytes for the automatically built cache.
Each entry counts the byte length of its stored path plus the logical length of
its value, with a minimum charge of one byte. The stored path includes the
normalized root and omits the leading slash. Foyer can retain an entry whose
weight exceeds its shard's budget. Default is 1 GiB."""
name: NotRequired[str]
"""Name for this cache instance."""
recover_mode: NotRequired[str]
diff --git a/core/layers/foyer/src/lib.rs b/core/layers/foyer/src/lib.rs
index 52f5a1ba82..7b98c574c9 100644
--- a/core/layers/foyer/src/lib.rs
+++ b/core/layers/foyer/src/lib.rs
@@ -802,7 +802,7 @@ impl DeletedKeys {
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let cache = HybridCacheBuilder::new()
-/// .memory(64 * 1024 * 1024) // 64MB memory cache
+/// .memory(1024) // 1,024 entries with Foyer's default weighter
/// .with_shards(4)
/// .storage()
/// .build()
diff --git a/core/services/foyer/src/backend.rs
b/core/services/foyer/src/backend.rs
index aef866c3de..39564cebb7 100644
--- a/core/services/foyer/src/backend.rs
+++ b/core/services/foyer/src/backend.rs
@@ -89,7 +89,7 @@ impl FoyerBuilder {
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let cache = HybridCacheBuilder::new()
- /// .memory(64 * 1024 * 1024)
+ /// .memory(1024) // 1,024 entries with Foyer's default weighter
/// .storage()
/// .build()
/// .await?;
@@ -115,12 +115,17 @@ impl FoyerBuilder {
self
}
- /// Set the memory capacity in bytes for the cache.
+ /// Set the memory eviction budget in bytes for the automatically built
cache.
///
- /// This is used when the cache is lazily initialized (i.e., when no
pre-built cache
- /// is provided via [`Self::cache`]).
+ /// Each entry counts the byte length of its stored path plus the logical
+ /// length of its value, with a minimum charge of one byte. The stored path
+ /// includes the normalized root and omits the leading slash. Process
memory
+ /// also includes cache bookkeeping and allocator overhead. Foyer can
retain
+ /// an entry whose weight exceeds its shard's budget after evicting other
+ /// entries in that shard.
///
- /// Default is 1 GiB (1024 * 1024 * 1024 bytes).
+ /// Default is 1 GiB (1024 * 1024 * 1024 bytes). A cache supplied via
+ /// [`Self::cache`] uses its own memory configuration.
pub fn memory(mut self, size: usize) -> Self {
self.config.memory = Some(size);
self
diff --git a/core/services/foyer/src/config.rs
b/core/services/foyer/src/config.rs
index 534b07e10d..6f604ae058 100644
--- a/core/services/foyer/src/config.rs
+++ b/core/services/foyer/src/config.rs
@@ -30,7 +30,12 @@ pub struct FoyerConfig {
pub name: Option<String>,
/// Root path of this backend.
pub root: Option<String>,
- /// Memory capacity in bytes for the cache.
+ /// Memory eviction budget in bytes for the automatically built cache.
+ ///
+ /// Each entry counts the byte length of its stored path plus the logical
+ /// length of its value, with a minimum charge of one byte. The stored path
+ /// includes the normalized root and omits the leading slash. Foyer can
+ /// retain an entry whose weight exceeds its shard's budget. Default is 1
GiB.
pub memory: Option<usize>,
/// Disk cache directory path.
///
diff --git a/core/services/foyer/src/core.rs b/core/services/foyer/src/core.rs
index b82f93a160..26746e64d2 100644
--- a/core/services/foyer/src/core.rs
+++ b/core/services/foyer/src/core.rs
@@ -436,6 +436,9 @@ impl FoyerCore {
let mut builder = HybridCacheBuilder::new()
.memory(memory)
.with_shards(shards)
+ .with_weighter(|key: &FoyerKey, value: &FoyerValue| {
+ key.path.len().saturating_add(value.len()).max(1)
+ })
.storage()
.with_recover_mode(recover_mode);
@@ -694,8 +697,8 @@ mod tests {
fn disk_core(dir: &tempfile::TempDir) -> FoyerCore {
FoyerCore::try_new(FoyerConfig {
- // The memory cache capacity is an entry count, not a byte size.
- memory: Some(4),
+ // Leave room for a 512 KiB target and several 1 KiB fillers.
+ memory: Some(516 * 1024),
shards: Some(1),
disk_path: Some(dir.path().to_string_lossy().into_owned()),
disk_capacity: Some(64 * 1024 * 1024),
@@ -741,8 +744,8 @@ mod tests {
/// Force `key` out of the memory cache and onto disk.
async fn move_to_disk(core: &FoyerCore, cache: &HybridCache<FoyerKey,
FoyerValue>, key: &str) {
- // The memory cache holds four entries, so these inserts evict `key`
- // into the disk write queue without touching `key` itself.
+ // These inserts exceed the memory budget while the target is resident,
+ // sending it to the disk write queue without a read of the target.
for i in 0..8 {
core.insert(&format!("/filler-{i}"), Buffer::from(vec![b'f';
1024]))
.await
diff --git a/core/services/foyer/src/docs.md b/core/services/foyer/src/docs.md
index 15e153e86c..fd82c3ca82 100644
--- a/core/services/foyer/src/docs.md
+++ b/core/services/foyer/src/docs.md
@@ -35,7 +35,12 @@ Foyer service can be configured in two ways:
When using the builder API without providing a pre-built cache, the following
options are available:
-- `memory`: Memory cache capacity (default: 1 GiB)
+- `memory` sets the memory eviction budget in bytes (default 1 GiB). Each entry
+ counts the byte length of its stored path plus the logical length of its
+ value, with a minimum charge of one byte. The stored path includes the
+ normalized root and omits the leading slash. Foyer can retain an entry whose
+ weight exceeds its shard's budget after evicting other entries in that shard.
+ Process memory also includes cache bookkeeping and allocator overhead.
- `disk_path`: Directory path for disk cache (enables hybrid caching)
- `disk_capacity`: Total disk cache capacity
- `disk_file_size`: Individual cache file size (default: 1 MiB)
@@ -60,7 +65,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_capacity(1024 * 1024 * 1024)
.build()?;
let cache = HybridCacheBuilder::new()
- .memory(64 * 1024 * 1024) // 64MB memory cache
+ .memory(1024) // 1,024 entries with Foyer's default weighter
.storage()
.with_engine_config(BlockEngineConfig::new(device))
.build()
@@ -88,7 +93,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create operator with hybrid cache (memory + disk)
let op = Operator::new(
Foyer::new()
- .memory(64 * 1024 * 1024) // 64MB memory
+ .memory(64 * 1024 * 1024) // 64 MiB eviction budget
.disk_path("/tmp/foyer_cache") // Enable disk cache
.disk_capacity(1024 * 1024 * 1024) // 1GB disk
.disk_file_size(1024 * 1024) // 1MB per file
diff --git a/core/services/foyer/src/lib.rs b/core/services/foyer/src/lib.rs
index cae21b06c2..c384437dd4 100644
--- a/core/services/foyer/src/lib.rs
+++ b/core/services/foyer/src/lib.rs
@@ -247,6 +247,22 @@ mod tests {
assert!(buf.is_empty());
}
+ #[tokio::test]
+ async fn test_auto_cache_memory_budget_counts_path_and_value_bytes() {
+ let op = Operator::new(Foyer::new().root("cache").memory(24)).unwrap();
+ op.write("é", "abc").await.unwrap();
+ assert_eq!(op.read("é").await.unwrap().to_vec(), b"abc");
+
+ // The stored paths "cache/é" and "cache/b" and their values weigh 25
bytes together.
+ op.write("b", "1234567").await.unwrap();
+ assert_eq!(op.read("b").await.unwrap().to_vec(), b"1234567");
+ let err = op
+ .read("é")
+ .await
+ .expect_err("the memory budget must evict the first entry");
+ assert_eq!(err.kind(), ErrorKind::NotFound);
+ }
+
#[tokio::test]
async fn test_hybrid_cache_via_config() {
let dir = tempfile::tempdir().unwrap();
diff --git a/website/data/services.json b/website/data/services.json
index 93034d8744..a480298162 100644
--- a/website/data/services.json
+++ b/website/data/services.json
@@ -1808,7 +1808,7 @@
"type": "integer",
"required": false,
"group": "General",
- "comments": "Memory capacity in bytes for the cache."
+ "comments": "Memory eviction budget in bytes for the automatically
built cache.\n\nEach entry counts the byte length of its stored path plus the
logical\nlength of its value, with a minimum charge of one byte. The stored
path\nincludes the normalized root and omits the leading slash. Foyer
can\nretain an entry whose weight exceeds its shard's budget. Default is 1 GiB."
},
{
"name": "disk_path",
@@ -1851,19 +1851,19 @@
"binding": "rust",
"language": "rust",
"minimal": "use opendal::Operator;\n\nlet operator =
Operator::via_iter(\"foyer\", [\n])?;",
- "full": "use opendal::Operator;\n\nlet operator =
Operator::via_iter(\"foyer\", [\n // Name for this cache instance.\n //
(\"name\".to_string(), \"...\".to_string()),\n\n // Root path of this
backend.\n // (\"root\".to_string(), \"...\".to_string()),\n\n // Memory
capacity in bytes for the cache.\n // (\"memory\".to_string(),
\"1000\".to_string()),\n\n // Disk cache directory path.\n //\n // If
set, enables hybrid cache with disk storage. Data will be [...]
+ "full": "use opendal::Operator;\n\nlet operator =
Operator::via_iter(\"foyer\", [\n // Name for this cache instance.\n //
(\"name\".to_string(), \"...\".to_string()),\n\n // Root path of this
backend.\n // (\"root\".to_string(), \"...\".to_string()),\n\n // Memory
eviction budget in bytes for the automatically built cache.\n //\n //
Each entry counts the byte length of its stored path plus the logical\n //
length of its value, with a minimum charge of on [...]
},
{
"binding": "python",
"language": "python",
"minimal": "import opendal\n\noperator = opendal.Operator(\n
\"foyer\",\n)",
- "full": "import opendal\n\noperator = opendal.Operator(\n
\"foyer\",\n # Name for this cache instance.\n # name=\"...\",\n\n #
Root path of this backend.\n # root=\"...\",\n\n # Memory capacity in
bytes for the cache.\n # memory=\"1000\",\n\n # Disk cache directory
path.\n #\n # If set, enables hybrid cache with disk storage. Data will
be persisted to\n # this directory when memory cache is full.\n #
disk_path=\"...\",\n\n # Disk cache tot [...]
+ "full": "import opendal\n\noperator = opendal.Operator(\n
\"foyer\",\n # Name for this cache instance.\n # name=\"...\",\n\n #
Root path of this backend.\n # root=\"...\",\n\n # Memory eviction budget
in bytes for the automatically built cache.\n #\n # Each entry counts the
byte length of its stored path plus the logical\n # length of its value,
with a minimum charge of one byte. The stored path\n # includes the
normalized root and omits the leadin [...]
},
{
"binding": "go",
"language": "go",
"minimal": "import
(\n\t\"github.com/apache/opendal-go-services/foyer\"\n\topendal
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err :=
opendal.NewOperator(foyer.Scheme, opendal.OperatorOptions{\n})",
- "full": "import
(\n\t\"github.com/apache/opendal-go-services/foyer\"\n\topendal
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err :=
opendal.NewOperator(foyer.Scheme, opendal.OperatorOptions{\n\t// Name for this
cache instance.\n\t// \"name\": \"...\",\n\n\t// Root path of this
backend.\n\t// \"root\": \"...\",\n\n\t// Memory capacity in bytes for the
cache.\n\t// \"memory\": \"1000\",\n\n\t// Disk cache directory
path.\n\t//\n\t// If set, enables hybrid cache with [...]
+ "full": "import
(\n\t\"github.com/apache/opendal-go-services/foyer\"\n\topendal
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err :=
opendal.NewOperator(foyer.Scheme, opendal.OperatorOptions{\n\t// Name for this
cache instance.\n\t// \"name\": \"...\",\n\n\t// Root path of this
backend.\n\t// \"root\": \"...\",\n\n\t// Memory eviction budget in bytes for
the automatically built cache.\n\t//\n\t// Each entry counts the byte length of
its stored path plus the logical\ [...]
}
]
},