diskcache-rs 0.4.8__tar.gz → 0.4.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. diskcache_rs-0.4.9/.release-please-manifest.json +3 -0
  2. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/CHANGELOG.md +13 -0
  3. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/Cargo.lock +1 -1
  4. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/Cargo.toml +1 -1
  5. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/PKG-INFO +1 -1
  6. diskcache_rs-0.4.9/benchmarks/batch_write_comparison.py +161 -0
  7. diskcache_rs-0.4.9/benchmarks/pickle_bridge_comparison.py +73 -0
  8. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/justfile +6 -0
  9. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/pyproject.toml +2 -0
  10. diskcache_rs-0.4.9/python/diskcache_rs/rust_pickle.py +77 -0
  11. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/cache.rs +55 -13
  12. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/storage/optimized_backend.rs +31 -19
  13. diskcache_rs-0.4.9/tests/test_batch_operations.py +183 -0
  14. diskcache_rs-0.4.9/tests/test_rust_pickle_performance.py +339 -0
  15. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/uv.lock +371 -0
  16. diskcache_rs-0.4.8/.release-please-manifest.json +0 -3
  17. diskcache_rs-0.4.8/benchmarks/batch_write_comparison.py +0 -90
  18. diskcache_rs-0.4.8/python/diskcache_rs/rust_pickle.py +0 -71
  19. diskcache_rs-0.4.8/tests/test_batch_operations.py +0 -83
  20. diskcache_rs-0.4.8/tests/test_rust_pickle_performance.py +0 -266
  21. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  22. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  23. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/actions/build-and-test/action.yml +0 -0
  24. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/actions/setup-diskcache-rs/action.yml +0 -0
  25. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/pull_request_template.md +0 -0
  26. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/workflows/benchmark.yml +0 -0
  27. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/workflows/build-abi3.yml +0 -0
  28. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/workflows/build.yml +0 -0
  29. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/workflows/ci.yml +0 -0
  30. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.github/workflows/release.yml +0 -0
  31. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.gitignore +0 -0
  32. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/.pre-commit-config.yaml +0 -0
  33. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/API_COMPATIBILITY.md +0 -0
  34. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/Dockerfile.test +0 -0
  35. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/LICENSE +0 -0
  36. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/README.md +0 -0
  37. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/comprehensive_performance_test.py +0 -0
  38. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/detailed_profiling.py +0 -0
  39. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/final_performance_comparison.py +0 -0
  40. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/high_performance_test.py +0 -0
  41. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/memory_usage_test.py +0 -0
  42. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/micro_benchmark.py +0 -0
  43. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/optimization_validation_test.py +0 -0
  44. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/performance_comparison.py +0 -0
  45. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/precise_benchmark.py +0 -0
  46. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/benchmarks/set_performance_analysis.py +0 -0
  47. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/docker-compose.test.yml +0 -0
  48. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/examples/basic_usage.py +0 -0
  49. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/examples/special_chars_keys_example.py +0 -0
  50. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/__init__.py +0 -0
  51. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/__init__.pyi +0 -0
  52. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/_diskcache_rs.pyi +0 -0
  53. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/cache.py +0 -0
  54. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/constants.py +0 -0
  55. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/core.py +0 -0
  56. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/disk.py +0 -0
  57. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/fast_cache.py +0 -0
  58. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/pickle_cache.py +0 -0
  59. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/python/diskcache_rs/recipes.py +0 -0
  60. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/release-please-config.json +0 -0
  61. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/renovate.json +0 -0
  62. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/scripts/generate_stubs.py +0 -0
  63. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/scripts/sync_version.py +0 -0
  64. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/scripts/test-docker-network.sh +0 -0
  65. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/error.rs +0 -0
  66. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/eviction.rs +0 -0
  67. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/lib.rs +0 -0
  68. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/memory_cache.rs +0 -0
  69. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/migration.rs +0 -0
  70. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/pickle_cache.rs +0 -0
  71. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/serialization.rs +0 -0
  72. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/storage/tests.rs +0 -0
  73. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/storage.rs +0 -0
  74. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/src/utils.rs +0 -0
  75. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/__init__.py +0 -0
  76. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/benchmark_official.py +0 -0
  77. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/conftest.py +0 -0
  78. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_api_compatibility.py +0 -0
  79. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_basic_operations.py +0 -0
  80. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_ci_benchmark.py +0 -0
  81. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_compatibility.py +0 -0
  82. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_complete_api_gaps.py +0 -0
  83. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_cross_platform_network.py +0 -0
  84. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_diskcache_rs_persistence_suite.py +0 -0
  85. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_docker_network.py +0 -0
  86. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_fast_cache.py +0 -0
  87. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_full_api_compatibility.py +0 -0
  88. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_issue_17_configurable_threshold.py +0 -0
  89. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_issue_73_deterministic_hashing.py +0 -0
  90. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_issue_78_expire_method.py +0 -0
  91. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_network_filesystem.py +0 -0
  92. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_performance.py +0 -0
  93. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_pickle_cache.py +0 -0
  94. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_recipes_and_constants.py +0 -0
  95. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_special_chars_keys.py +0 -0
  96. {diskcache_rs-0.4.8 → diskcache_rs-0.4.9}/tests/test_version_and_disk_threshold.py +0 -0
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "0.4.9"
3
+ }
@@ -4,6 +4,19 @@
4
4
 
5
5
  - sync Cargo.toml version with .cz.toml and update CHANGELOG for v0.4.0
6
6
 
7
+ ## [0.4.9](https://github.com/loonghao/diskcache_rs/compare/diskcache_rs-v0.4.8...diskcache_rs-v0.4.9) (2026-03-25)
8
+
9
+
10
+ ### Bug Fixes
11
+
12
+ * unblock batch writes and expand perf coverage ([e28f9b5](https://github.com/loonghao/diskcache_rs/commit/e28f9b574b4375b90b38fa92a4f759e0820692b9))
13
+ * unblock batch writes and expand perf coverage ([d235250](https://github.com/loonghao/diskcache_rs/commit/d23525069ef524a92120f846104d7824a0a47fd5))
14
+
15
+
16
+ ### Performance Improvements
17
+
18
+ * default to CPython pickle fast path ([#101](https://github.com/loonghao/diskcache_rs/issues/101)) ([0e78be8](https://github.com/loonghao/diskcache_rs/commit/0e78be82eb48a05b642e6732da37543210fab59c))
19
+
7
20
  ## [0.4.8](https://github.com/loonghao/diskcache_rs/compare/diskcache_rs-v0.4.7...diskcache_rs-v0.4.8) (2026-03-24)
8
21
 
9
22
 
@@ -246,7 +246,7 @@ dependencies = [
246
246
 
247
247
  [[package]]
248
248
  name = "diskcache_rs"
249
- version = "0.4.8"
249
+ version = "0.4.9"
250
250
  dependencies = [
251
251
  "anyhow",
252
252
  "bincode",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "diskcache_rs"
3
- version = "0.4.8"
3
+ version = "0.4.9"
4
4
  edition = "2021"
5
5
  authors = ["longhao <hal.long@outlook.com>"]
6
6
  description = "A high-performance disk cache implementation in Rust with Python bindings"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: diskcache_rs
3
- Version: 0.4.8
3
+ Version: 0.4.9
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: Apache Software License
@@ -0,0 +1,161 @@
1
+ """Compare batch-write throughput across high-level and low-level cache APIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import statistics
6
+ import tempfile
7
+ import time
8
+ from collections.abc import Callable
9
+
10
+ import diskcache
11
+ from diskcache_rs import Cache, rust_pickle_dumps
12
+ from diskcache_rs._diskcache_rs import PyCache
13
+
14
+ PAYLOAD_COUNT = 500
15
+ PAYLOAD_SIZE = 1024
16
+ PREFILL_COUNT = 10_000
17
+ ROUNDS = 5
18
+
19
+ PAYLOAD = {f"key-{index}": b"x" * PAYLOAD_SIZE for index in range(PAYLOAD_COUNT)}
20
+ SERIALIZED_PAYLOAD = {key: rust_pickle_dumps(value) for key, value in PAYLOAD.items()}
21
+ PREFILL_PAYLOAD = {
22
+ f"prefill-{index}": b"p" * 128 for index in range(PREFILL_COUNT)
23
+ }
24
+ SERIALIZED_PREFILL_PAYLOAD = {
25
+ key: rust_pickle_dumps(value) for key, value in PREFILL_PAYLOAD.items()
26
+ }
27
+
28
+
29
+ BenchmarkFn = Callable[[], float]
30
+
31
+
32
+ def benchmark_diskcache_rs_loop(prefill: bool = False) -> float:
33
+ with tempfile.TemporaryDirectory(prefix="diskcache_rs_loop_") as cache_dir:
34
+ cache = Cache(cache_dir)
35
+ if prefill:
36
+ cache.set_many(PREFILL_PAYLOAD)
37
+
38
+ start = time.perf_counter()
39
+ for key, value in PAYLOAD.items():
40
+ cache.set(key, value)
41
+ cache.close()
42
+ return time.perf_counter() - start
43
+
44
+
45
+ def benchmark_diskcache_rs_batch(prefill: bool = False) -> float:
46
+ with tempfile.TemporaryDirectory(prefix="diskcache_rs_batch_") as cache_dir:
47
+ cache = Cache(cache_dir)
48
+ if prefill:
49
+ cache.set_many(PREFILL_PAYLOAD)
50
+
51
+ start = time.perf_counter()
52
+ cache.set_many(PAYLOAD)
53
+ cache.close()
54
+ return time.perf_counter() - start
55
+
56
+
57
+ def benchmark_diskcache_loop(prefill: bool = False) -> float:
58
+ with tempfile.TemporaryDirectory(prefix="diskcache_py_loop_") as cache_dir:
59
+ cache = diskcache.Cache(cache_dir)
60
+ if prefill:
61
+ for key, value in PREFILL_PAYLOAD.items():
62
+ cache.set(key, value)
63
+
64
+ start = time.perf_counter()
65
+ for key, value in PAYLOAD.items():
66
+ cache.set(key, value)
67
+ cache.close()
68
+ return time.perf_counter() - start
69
+
70
+
71
+ def benchmark_pycache_loop(prefill: bool = False) -> float:
72
+ with tempfile.TemporaryDirectory(prefix="diskcache_pycache_loop_") as cache_dir:
73
+ cache = PyCache(cache_dir)
74
+ if prefill:
75
+ cache.set_many(list(SERIALIZED_PREFILL_PAYLOAD.items()))
76
+
77
+ start = time.perf_counter()
78
+ for key, value in SERIALIZED_PAYLOAD.items():
79
+ cache.set(key, value)
80
+ cache.close()
81
+ return time.perf_counter() - start
82
+
83
+
84
+ def benchmark_pycache_batch(prefill: bool = False) -> float:
85
+ with tempfile.TemporaryDirectory(prefix="diskcache_pycache_batch_") as cache_dir:
86
+ cache = PyCache(cache_dir)
87
+ if prefill:
88
+ cache.set_many(list(SERIALIZED_PREFILL_PAYLOAD.items()))
89
+
90
+ start = time.perf_counter()
91
+ cache.set_many(list(SERIALIZED_PAYLOAD.items()))
92
+ cache.close()
93
+ return time.perf_counter() - start
94
+
95
+
96
+ def run_rounds(benchmark: BenchmarkFn) -> list[float]:
97
+ return [benchmark() for _ in range(ROUNDS)]
98
+
99
+
100
+ def average_duration(samples: list[float]) -> float:
101
+ return statistics.mean(samples)
102
+
103
+
104
+ def print_metric(name: str, samples: list[float]) -> None:
105
+ avg = average_duration(samples)
106
+ print(f"{name}_avg={avg:.6f}")
107
+ print(f"{name}_ops_per_sec={PAYLOAD_COUNT / avg:.1f}")
108
+
109
+
110
+ def print_scenario_results(name: str, samples: dict[str, list[float]]) -> None:
111
+ print(f"scenario={name}")
112
+ for metric_name, metric_samples in samples.items():
113
+ print_metric(f"{name}_{metric_name}", metric_samples)
114
+
115
+ rs_loop_avg = average_duration(samples["rs_loop"])
116
+ rs_batch_avg = average_duration(samples["rs_batch"])
117
+ py_loop_avg = average_duration(samples["py_loop"])
118
+ pycache_loop_avg = average_duration(samples["pycache_loop"])
119
+ pycache_batch_avg = average_duration(samples["pycache_batch"])
120
+
121
+ print(f"{name}_high_level_batch_speedup_vs_rs_loop={rs_loop_avg / rs_batch_avg:.2f}")
122
+ print(
123
+ f"{name}_low_level_batch_speedup_vs_pycache_loop={pycache_loop_avg / pycache_batch_avg:.2f}"
124
+ )
125
+ print(f"{name}_batch_speedup_vs_diskcache_loop={py_loop_avg / rs_batch_avg:.2f}")
126
+ print()
127
+
128
+
129
+ def main() -> None:
130
+ print(
131
+ f"payload_count={PAYLOAD_COUNT} payload_size={PAYLOAD_SIZE} prefill_count={PREFILL_COUNT} rounds={ROUNDS}"
132
+ )
133
+ print()
134
+
135
+ fresh_samples = {
136
+ "rs_loop": run_rounds(lambda: benchmark_diskcache_rs_loop(prefill=False)),
137
+ "rs_batch": run_rounds(lambda: benchmark_diskcache_rs_batch(prefill=False)),
138
+ "py_loop": run_rounds(lambda: benchmark_diskcache_loop(prefill=False)),
139
+ "pycache_loop": run_rounds(lambda: benchmark_pycache_loop(prefill=False)),
140
+ "pycache_batch": run_rounds(lambda: benchmark_pycache_batch(prefill=False)),
141
+ }
142
+ print_scenario_results("fresh", fresh_samples)
143
+
144
+ prefilled_samples = {
145
+ "rs_loop": run_rounds(lambda: benchmark_diskcache_rs_loop(prefill=True)),
146
+ "rs_batch": run_rounds(lambda: benchmark_diskcache_rs_batch(prefill=True)),
147
+ "py_loop": run_rounds(lambda: benchmark_diskcache_loop(prefill=True)),
148
+ "pycache_loop": run_rounds(lambda: benchmark_pycache_loop(prefill=True)),
149
+ "pycache_batch": run_rounds(lambda: benchmark_pycache_batch(prefill=True)),
150
+ }
151
+ print_scenario_results("prefilled", prefilled_samples)
152
+
153
+ print("analysis_hint=high_level Cache.set_many is still bounded by Python-side pickle serialization")
154
+ print("analysis_hint=low_level PyCache.set_many better isolates Rust storage batching gains")
155
+ print(
156
+ "analysis_hint=prefilled scenarios highlight the cost of per-write cache limit bookkeeping when the cache is already large"
157
+ )
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env python3
2
+ """Compare CPython pickle, diskcache_rs default pickle helpers, and the direct bridge path."""
3
+
4
+ import os
5
+ import pickle
6
+ import time
7
+
8
+ os.environ.pop("DISKCACHE_RS_USE_RUST_PICKLE_BRIDGE", None)
9
+
10
+ import diskcache_rs.rust_pickle as rust_pickle
11
+ from diskcache_rs import rust_pickle_dumps, rust_pickle_loads
12
+
13
+
14
+ def benchmark(label, dumps_fn, loads_fn, payload, iterations=200):
15
+ start = time.perf_counter()
16
+ for _ in range(iterations):
17
+ encoded = dumps_fn(payload)
18
+ _ = loads_fn(encoded)
19
+ elapsed = time.perf_counter() - start
20
+ ops_per_sec = iterations / elapsed if elapsed > 0 else float("inf")
21
+ return {"label": label, "elapsed": elapsed, "ops_per_sec": ops_per_sec}
22
+
23
+
24
+ def print_results(results):
25
+ print("\nPickle path comparison")
26
+ print("=" * 72)
27
+ print(f"{'Path':<24} {'Time':>12} {'Ops/sec':>16} {'Relative'}")
28
+ print("-" * 72)
29
+
30
+ baseline = results[0]["elapsed"]
31
+ for result in results:
32
+ relative = result["elapsed"] / baseline if baseline > 0 else 1.0
33
+ print(
34
+ f"{result['label']:<24} {result['elapsed']:>10.4f}s {result['ops_per_sec']:>14.1f} {relative:>8.2f}x"
35
+ )
36
+
37
+
38
+ def main():
39
+ payload = {
40
+ "text": "diskcache_rs" * 100,
41
+ "numbers": list(range(500)),
42
+ "nested": {"alpha": list(range(50)), "beta": {"ok": True}},
43
+ "binary": b"abc123" * 200,
44
+ }
45
+
46
+ results = [
47
+ benchmark("CPython pickle", pickle.dumps, pickle.loads, payload),
48
+ benchmark("default helper path", rust_pickle.dumps, rust_pickle.loads, payload),
49
+ ]
50
+
51
+ if rust_pickle_dumps is not None and rust_pickle_loads is not None:
52
+ results.append(
53
+ benchmark("direct Rust bridge", rust_pickle_dumps, rust_pickle_loads, payload)
54
+ )
55
+
56
+ print_results(results)
57
+
58
+ if len(results) > 2:
59
+ helper = results[1]
60
+ bridge = results[2]
61
+ if helper["elapsed"] > 0 and bridge["elapsed"] > 0:
62
+ if helper["elapsed"] < bridge["elapsed"]:
63
+ print(
64
+ f"\nDefault helper path is {bridge['elapsed'] / helper['elapsed']:.2f}x faster than the direct bridge."
65
+ )
66
+ else:
67
+ print(
68
+ f"\nDirect bridge is {helper['elapsed'] / bridge['elapsed']:.2f}x faster than the default helper path."
69
+ )
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()
@@ -97,11 +97,17 @@ bench:
97
97
  @echo "⚡ Running benchmarks..."
98
98
  uv run python -m pytest tests/ -v -k benchmark
99
99
 
100
+ # Compare pickle bridge overhead
101
+ bench-pickle:
102
+ @echo "⚡ Comparing pickle bridge overhead..."
103
+ uv run python benchmarks/pickle_bridge_comparison.py
104
+
100
105
  # Update dependencies
101
106
  update:
102
107
  @echo "⬆️ Updating dependencies..."
103
108
  uv sync --upgrade
104
109
 
110
+
105
111
  # Show project info
106
112
  info:
107
113
  @echo "📊 Project Information:"
@@ -39,8 +39,10 @@ dependencies = [
39
39
  test = [
40
40
  "pytest>=7.0.0",
41
41
  "pytest-benchmark>=4.0.0",
42
+ "pytest-cov>=5.0.0",
42
43
  "psutil>=5.9.0",
43
44
  ]
45
+
44
46
  benchmark = [
45
47
  { include-group = "test" },
46
48
  "diskcache>=5.6.3",
@@ -0,0 +1,77 @@
1
+ """
2
+ Pickle helpers for diskcache_rs.
3
+
4
+ By default we use CPython's built-in ``pickle`` fast path because the current
5
+ Rust bridge still delegates back to Python's pickle module internally. The
6
+ bridge remains available for explicit testing and benchmarking via the
7
+ ``DISKCACHE_RS_USE_RUST_PICKLE_BRIDGE`` environment variable.
8
+ """
9
+
10
+ import os
11
+ import pickle
12
+ from typing import Any
13
+
14
+ # Try to import Rust pickle functions
15
+ try:
16
+ from ._diskcache_rs import rust_pickle_dumps, rust_pickle_loads
17
+
18
+ RUST_PICKLE_AVAILABLE = True
19
+ except ImportError:
20
+ RUST_PICKLE_AVAILABLE = False
21
+
22
+ _BRIDGE_ENV = "DISKCACHE_RS_USE_RUST_PICKLE_BRIDGE"
23
+ _TRUTHY_VALUES = {"1", "true", "yes", "on"}
24
+
25
+
26
+ def is_rust_available() -> bool:
27
+ """Check if the Rust bridge functions are importable."""
28
+ return RUST_PICKLE_AVAILABLE
29
+
30
+
31
+ def is_rust_bridge_enabled() -> bool:
32
+ """Return ``True`` when the Rust pickle bridge is explicitly enabled."""
33
+ if not RUST_PICKLE_AVAILABLE:
34
+ return False
35
+
36
+ value = os.getenv(_BRIDGE_ENV, "")
37
+ return value.strip().lower() in _TRUTHY_VALUES
38
+
39
+
40
+ def dumps(obj: Any, protocol: int = pickle.HIGHEST_PROTOCOL) -> bytes:
41
+ """
42
+ Serialize an object.
43
+
44
+ The default path uses CPython's pickle implementation directly for best
45
+ end-to-end performance. Set ``DISKCACHE_RS_USE_RUST_PICKLE_BRIDGE=1`` to
46
+ benchmark or debug the Rust bridge path.
47
+ """
48
+ if is_rust_bridge_enabled():
49
+ try:
50
+ return rust_pickle_dumps(obj)
51
+ except Exception:
52
+ pass
53
+
54
+ return pickle.dumps(obj, protocol=protocol)
55
+
56
+
57
+ def loads(data: bytes) -> Any:
58
+ """
59
+ Deserialize an object.
60
+
61
+ The default path uses CPython's pickle implementation directly for best
62
+ end-to-end performance. Set ``DISKCACHE_RS_USE_RUST_PICKLE_BRIDGE=1`` to
63
+ benchmark or debug the Rust bridge path.
64
+ """
65
+ if is_rust_bridge_enabled():
66
+ try:
67
+ return rust_pickle_loads(data)
68
+ except Exception:
69
+ pass
70
+
71
+ return pickle.loads(data)
72
+
73
+
74
+ # For compatibility, expose the same interface as pickle module
75
+ HIGHEST_PROTOCOL = pickle.HIGHEST_PROTOCOL
76
+ DEFAULT_PROTOCOL = pickle.DEFAULT_PROTOCOL
77
+
@@ -7,7 +7,8 @@ use crate::storage::{OptimizedStorage, StorageBackend};
7
7
  use crate::utils::{current_timestamp, validate_cache_config, validate_key, CacheStats};
8
8
  use parking_lot::RwLock;
9
9
  use pyo3::prelude::*;
10
- use std::collections::HashMap;
10
+ use std::collections::{HashMap, HashSet};
11
+
11
12
  use std::path::PathBuf;
12
13
  use std::sync::Arc;
13
14
 
@@ -198,6 +199,8 @@ impl DiskCache {
198
199
  // Enforce cache size and entry limits
199
200
  self.enforce_cache_limits()?;
200
201
 
202
+ let existed = self.storage.exists(key)?;
203
+
201
204
  // Always use inline storage for simplicity (OptimizedStorage handles the optimization)
202
205
  let entry = CacheEntry::new_inline(key.to_string(), value.to_vec(), tags, expire_time);
203
206
 
@@ -214,7 +217,9 @@ impl DiskCache {
214
217
  let mut stats = self.stats.write();
215
218
  stats.sets += 1;
216
219
  stats.total_size += entry.size;
217
- stats.entry_count += 1;
220
+ if !existed {
221
+ stats.entry_count += 1;
222
+ }
218
223
 
219
224
  Ok(())
220
225
  }
@@ -235,12 +240,24 @@ impl DiskCache {
235
240
  let mut storage_entries = Vec::with_capacity(items.len());
236
241
  let mut cache_entries = Vec::with_capacity(items.len());
237
242
  let mut total_size = 0_u64;
243
+ let mut new_entries = 0_u64;
244
+ let mut seen_keys = HashSet::with_capacity(items.len());
238
245
 
239
246
  for (key, value) in items {
240
247
  validate_key(&key)?;
248
+
249
+ if seen_keys.insert(key.clone()) && !self.storage.exists(&key)? {
250
+ new_entries += 1;
251
+ }
252
+
241
253
  total_size += value.len() as u64;
242
254
  storage_entries.push((key.clone(), value.clone()));
243
- cache_entries.push(CacheEntry::new_inline(key, value, tags.clone(), expire_time));
255
+ cache_entries.push(CacheEntry::new_inline(
256
+ key,
257
+ value,
258
+ tags.clone(),
259
+ expire_time,
260
+ ));
244
261
  }
245
262
 
246
263
  self.storage.set_batch(storage_entries)?;
@@ -255,14 +272,14 @@ impl DiskCache {
255
272
  let mut stats = self.stats.write();
256
273
  stats.sets += cache_entries.len() as u64;
257
274
  stats.total_size += total_size;
258
- stats.entry_count += cache_entries.len() as u64;
275
+ stats.entry_count += new_entries;
276
+ drop(stats);
259
277
 
260
278
  self.enforce_cache_limits()?;
261
279
 
262
280
  Ok(())
263
281
  }
264
282
 
265
-
266
283
  /// Delete a value from the cache
267
284
  pub fn delete(&self, key: &str) -> CacheResult<bool> {
268
285
  validate_key(key)?;
@@ -343,8 +360,10 @@ impl DiskCache {
343
360
 
344
361
  /// Check cache limits and evict entries if necessary
345
362
  fn enforce_cache_limits(&self) -> CacheResult<()> {
346
- let current_size = self.size()?;
347
- let current_entries = self.keys()?.len() as u64;
363
+ let stats = self.stats.read();
364
+ let current_size = stats.total_size;
365
+ let current_entries = stats.entry_count;
366
+ drop(stats);
348
367
 
349
368
  let mut evict_count = 0;
350
369
 
@@ -512,12 +531,7 @@ impl PyCache {
512
531
  tags: Option<Vec<String>>,
513
532
  ) -> PyResult<()> {
514
533
  let tags = tags.unwrap_or_default();
515
-
516
- // For now, use individual operations but optimize the loop
517
- for (key, value) in items {
518
- self.cache.set(&key, &value, expire_time, tags.clone())?;
519
- }
520
-
534
+ self.cache.set_many(items, expire_time, tags)?;
521
535
  Ok(())
522
536
  }
523
537
 
@@ -833,3 +847,31 @@ impl RustFanoutCache {
833
847
  (hash_value as usize) % self.shards
834
848
  }
835
849
  }
850
+
851
+ #[cfg(test)]
852
+ mod tests {
853
+ use super::DiskCache;
854
+ use tempfile::TempDir;
855
+
856
+ #[test]
857
+ fn disk_cache_set_many_round_trip() {
858
+ let temp_dir = TempDir::new().unwrap();
859
+ let cache = DiskCache::with_directory(temp_dir.path()).unwrap();
860
+
861
+ cache
862
+ .set_many(
863
+ vec![
864
+ ("alpha".to_string(), b"one".to_vec()),
865
+ ("beta".to_string(), b"two".to_vec()),
866
+ ],
867
+ None,
868
+ vec![],
869
+ )
870
+ .unwrap();
871
+
872
+ assert_eq!(cache.get("alpha").unwrap(), Some(b"one".to_vec()));
873
+ assert_eq!(cache.get("beta").unwrap(), Some(b"two".to_vec()));
874
+
875
+ cache.close();
876
+ }
877
+ }
@@ -269,7 +269,6 @@ impl WriteBatcher {
269
269
  }
270
270
  }
271
271
 
272
-
273
272
  /// Performance statistics
274
273
  #[derive(Default)]
275
274
  struct StorageStats {
@@ -405,20 +404,34 @@ impl OptimizedStorage {
405
404
  )))
406
405
  })?;
407
406
 
407
+ let key = key.value().to_string();
408
+ let value_bytes = value.value();
409
+
408
410
  // Deserialize FileInfo from bytes
409
- let file_info: FileInfo =
410
- bincode::decode_from_slice(value.value(), bincode::config::standard())
411
- .map_err(|e| {
411
+ let (file_info, decoded_len): (FileInfo, usize) =
412
+ bincode::decode_from_slice(value_bytes, bincode::config::standard()).map_err(
413
+ |e| {
412
414
  CacheError::Io(std::io::Error::other(format!(
413
415
  "Failed to deserialize FileInfo: {}",
414
416
  e
415
417
  )))
416
- })?
417
- .0;
418
+ },
419
+ )?;
420
+
421
+ if file_info.path.to_string_lossy().starts_with("memory://") {
422
+ if value_bytes.len() > decoded_len {
423
+ self.hot_cache
424
+ .insert(key, Bytes::copy_from_slice(&value_bytes[decoded_len..]));
425
+ loaded_count += 1;
426
+ } else {
427
+ skipped_count += 1;
428
+ }
429
+ continue;
430
+ }
418
431
 
419
432
  // Verify file still exists before adding to index
420
433
  if file_info.path.exists() {
421
- index.insert(key.value().to_string(), file_info);
434
+ index.insert(key, file_info);
422
435
  loaded_count += 1;
423
436
  } else {
424
437
  skipped_count += 1;
@@ -449,7 +462,6 @@ impl OptimizedStorage {
449
462
  tracing::debug!("Closed redb database");
450
463
  }
451
464
 
452
-
453
465
  /// Flush all in-memory caches (hot_cache and warm_cache) to disk
454
466
  /// This ensures data persistence when closing the cache
455
467
  fn flush_memory_caches(&self) -> CacheResult<()> {
@@ -636,7 +648,6 @@ impl OptimizedStorage {
636
648
  }
637
649
  }
638
650
 
639
-
640
651
  let db_guard = self.index_db.read();
641
652
  let db = match db_guard.as_ref() {
642
653
  Some(db) => db,
@@ -711,12 +722,14 @@ impl OptimizedStorage {
711
722
  )))
712
723
  })?;
713
724
 
714
- table.insert(key.as_str(), value_bytes.as_slice()).map_err(|e| {
715
- CacheError::Io(std::io::Error::other(format!(
716
- "Failed to insert into redb: {}",
717
- e
718
- )))
719
- })?;
725
+ table
726
+ .insert(key.as_str(), value_bytes.as_slice())
727
+ .map_err(|e| {
728
+ CacheError::Io(std::io::Error::other(format!(
729
+ "Failed to insert into redb: {}",
730
+ e
731
+ )))
732
+ })?;
720
733
  }
721
734
  }
722
735
 
@@ -732,7 +745,6 @@ impl OptimizedStorage {
732
745
 
733
746
  /// Compress data if it provides significant space savings
734
747
  fn compress_if_beneficial(&self, data: &[u8]) -> (Bytes, bool) {
735
-
736
748
  if !self.config.use_compression || data.len() < self.config.compression_threshold {
737
749
  return (Bytes::copy_from_slice(data), false);
738
750
  }
@@ -971,7 +983,9 @@ impl StorageBackend for OptimizedStorage {
971
983
  compressed: is_compressed,
972
984
  };
973
985
 
974
- self.cold_index.write().insert(key.clone(), file_info.clone());
986
+ self.cold_index
987
+ .write()
988
+ .insert(key.clone(), file_info.clone());
975
989
 
976
990
  if self.config.use_file_locking {
977
991
  self.write_with_lock(&file_path, &compressed_data)?;
@@ -991,7 +1005,6 @@ impl StorageBackend for OptimizedStorage {
991
1005
  }
992
1006
 
993
1007
  fn delete(&self, key: &str) -> CacheResult<bool> {
994
-
995
1008
  let mut found = false;
996
1009
 
997
1010
  // Remove from all cache levels
@@ -1203,7 +1216,6 @@ impl OptimizedStorage {
1203
1216
  Ok(())
1204
1217
  }
1205
1218
 
1206
-
1207
1219
  /// Write data to file with exclusive lock (for NFS scenarios)
1208
1220
  fn write_with_lock(&self, file_path: &Path, data: &[u8]) -> CacheResult<()> {
1209
1221
  use fs4::fs_std::FileExt;