dependency-cache 0.3.0__tar.gz → 0.4.0__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 (30) hide show
  1. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/Cargo.toml +2 -0
  2. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/PKG-INFO +3 -3
  3. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/README.md +2 -2
  4. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/pyproject.toml +1 -1
  5. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/dependency_cache/plot_dependency_graph.py +1 -1
  6. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/test_python.py +1 -1
  7. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/test_python_automagic.py +1 -1
  8. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/src/decorator.rs +20 -8
  9. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/src/decorator_factory.rs +6 -6
  10. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/src/dependency_cache_base.rs +42 -44
  11. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/src/dependency_graph.rs +39 -53
  12. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/src/lib.rs +1 -0
  13. dependency_cache-0.4.0/src/metadata_hash_manager.rs +60 -0
  14. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/uv.lock +1 -1
  15. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/.github/workflows/CI.yml +0 -0
  16. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/.github/workflows/Test.yml +0 -0
  17. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/.gitignore +0 -0
  18. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/Cargo.lock +0 -0
  19. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/LICENSE +0 -0
  20. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/dependency_cache/__init__.py +0 -0
  21. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/dependency_cache/dependency_cache.pyi +0 -0
  22. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/automagic_dependency_example.py +0 -0
  23. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/example.py +0 -0
  24. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/inheritance_example.py +0 -0
  25. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/manual_dependency_example.py +0 -0
  26. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/runtime_dependencies_example.py +0 -0
  27. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/runtime_function_calls_example.py +0 -0
  28. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/static_function_calls_example.py +0 -0
  29. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/python/examples/use_cache_example.py +0 -0
  30. {dependency_cache-0.3.0 → dependency_cache-0.4.0}/src/py_introspection_utils.rs +0 -0
@@ -24,6 +24,8 @@ features = [
24
24
  lto = "fat"
25
25
  codegen-units = 1
26
26
  opt-level = 3
27
+ strip = true
28
+ panic = "abort"
27
29
 
28
30
  [lints.clippy]
29
31
  needless_return = "allow"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dependency_cache
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -119,8 +119,8 @@ This project is still a work in progress, with everything from API to underlying
119
119
 
120
120
  Current TODO list (in no particular order):
121
121
  - scenario analysis capability (add temporary cache to base)
122
- - add validation to static dependencies, ensure methods are of decorator class
123
- - improve plot_dependency_graph (maybe to GUI?) with moveable nodes
122
+ - add validation to static dependencies, ensure methods are of decorator class (?)
123
+ - improve plot_dependency_graph (maybe to GUI?) with interactive nodes
124
124
  - add object thread safety for python 3.14+
125
125
  - work out how best to handle nested objects
126
126
 
@@ -101,7 +101,7 @@ This project is still a work in progress, with everything from API to underlying
101
101
 
102
102
  Current TODO list (in no particular order):
103
103
  - scenario analysis capability (add temporary cache to base)
104
- - add validation to static dependencies, ensure methods are of decorator class
105
- - improve plot_dependency_graph (maybe to GUI?) with moveable nodes
104
+ - add validation to static dependencies, ensure methods are of decorator class (?)
105
+ - improve plot_dependency_graph (maybe to GUI?) with interactive nodes
106
106
  - add object thread safety for python 3.14+
107
107
  - work out how best to handle nested objects
@@ -11,7 +11,7 @@ classifiers = [
11
11
  "Programming Language :: Python :: Implementation :: PyPy",
12
12
  ]
13
13
  keywords = ["caching", "dependency-graph", "invalidation"]
14
- version = "0.3.0"
14
+ version = "0.4.0"
15
15
  description = "A caching library for Python object methods that utilises a dependency graph to track relationships and control invalidation, enabling efficient recomputation"
16
16
  readme = "README.md"
17
17
  license = { text = "MIT" }
@@ -4,7 +4,7 @@ import networkx as nx
4
4
  from .dependency_cache import DependencyCacheBase
5
5
 
6
6
 
7
- def plot_dependency_graph(obj, **kwargs) -> None:
7
+ def plot_dependency_graph(obj: DependencyCacheBase, **kwargs) -> None:
8
8
  if not isinstance(obj, DependencyCacheBase):
9
9
  raise TypeError("provided object must inherit from DependencyCacheBase")
10
10
  graph_data = obj.dependency_graph
@@ -296,7 +296,7 @@ def test_plot_dependency_graph_raises():
296
296
  c = IncorrectInheritance()
297
297
 
298
298
  with pytest.raises(TypeError):
299
- plot_dependency_graph(c)
299
+ plot_dependency_graph(c) # ty: ignore testing raises error
300
300
 
301
301
 
302
302
  def test_function_calls():
@@ -278,7 +278,7 @@ def test_plot_dependency_graph_raises():
278
278
  c = IncorrectInheritance()
279
279
 
280
280
  with pytest.raises(TypeError):
281
- plot_dependency_graph(c)
281
+ plot_dependency_graph(c) # ty: ignore testing raises error
282
282
 
283
283
 
284
284
  def test_function_calls():
@@ -5,11 +5,11 @@ use pyo3::types::{PyDict, PyTuple};
5
5
  use crate::dependency_cache_base::DependencyCacheBase;
6
6
  use crate::py_introspection_utils::normalise_function_signature_and_hash;
7
7
 
8
- #[pyclass(frozen)]
8
+ #[pyclass]
9
9
  pub struct DependencyCacheDecorator {
10
10
  pub func: Py<PyAny>,
11
11
  pub use_cache: bool,
12
- pub dependencies: Vec<isize>,
12
+ pub dependencies: Vec<(isize, Py<PyTuple>)>,
13
13
  pub method_name: String,
14
14
  pub track_runtime_dependencies: bool,
15
15
  pub serialisable: bool,
@@ -64,21 +64,33 @@ impl DependencyCacheDecorator {
64
64
  let func = self.func.bind(py);
65
65
  let (hash, metadata) = normalise_function_signature_and_hash(py, &self.method_name, Some(func), args, kwargs)?;
66
66
 
67
+ let key = base.borrow_mut().metadata_hash_manager.create_cache_key(py, hash, metadata.unbind())?;
68
+
67
69
  // 1. add/check child dependencies
68
- base.borrow_mut().add_children_dependencies(hash, self.dependencies.clone(), metadata.unbind());
70
+ let mut dependency_keys = Vec::with_capacity(self.dependencies.len());
71
+ if self.dependencies.len() != 0 {
72
+ for (hash, metadata) in &self.dependencies {
73
+ let dependency_key = base.borrow_mut()
74
+ .metadata_hash_manager
75
+ .create_cache_key(py, *hash, metadata.clone_ref(py))?;
76
+ dependency_keys.push(dependency_key);
77
+ }
78
+ }
79
+ base.borrow_mut()
80
+ .add_children_dependencies(key, dependency_keys);
69
81
 
70
82
  // 2. add/check parent dependencies, push function stack
71
83
  let parent_status = base.borrow().current_call_stack_top();
72
84
  if let Some((parent, parent_use_runtime_deps)) = parent_status {
73
85
  if parent_use_runtime_deps {
74
- base.borrow_mut().add_parent_dependency(parent, hash);
86
+ base.borrow_mut().add_parent_dependency(parent, key);
75
87
  }
76
88
  }
77
- base.borrow_mut().push_call_stack(hash, self.track_runtime_dependencies);
89
+ base.borrow_mut().push_call_stack(key, self.track_runtime_dependencies);
78
90
 
79
91
  let outcome = (|| -> PyResult<Py<PyAny>> {
80
92
  // 3. check cache for value
81
- let cached = base.borrow().get_cached_value_by_hash(py, hash);
93
+ let cached = base.borrow().get_cached_value_by_hash(py, key);
82
94
  if let Some(cached) = cached {
83
95
  return Ok(cached);
84
96
  }
@@ -88,9 +100,9 @@ impl DependencyCacheDecorator {
88
100
 
89
101
  // 5. validate current, set cache and pop function stack
90
102
  base.borrow_mut()
91
- .validate_current_method(hash, self.use_cache);
103
+ .validate_current_method(key, self.use_cache);
92
104
  base.borrow_mut()
93
- .set_cached_value_by_hash(hash, result.clone_ref(py));
105
+ .set_cached_value_by_hash(key, result.clone_ref(py));
94
106
  Ok(result)
95
107
  })();
96
108
 
@@ -46,18 +46,18 @@ impl ManualDependencyCacheDecoratorFactory {
46
46
  fn __call__(&self, py: Python<'_>, func: Py<PyAny>) -> PyResult<DependencyCacheDecorator> {
47
47
  let method_name: String = func.getattr(py, "__name__")?.extract(py)?;
48
48
  let empty_args = PyTuple::empty(py);
49
- let hashed_dependencies: Vec<isize> = self
49
+ let hashed_dependencies: Vec<(isize, Py<PyTuple>)> = self
50
50
  .dependencies
51
51
  .iter()
52
52
  .map(|(method_name, kwargs)| {
53
- let (hash, _) = normalise_function_signature_and_hash(
53
+ let (hash, args) = normalise_function_signature_and_hash(
54
54
  py,
55
55
  method_name,
56
56
  None,
57
57
  &empty_args,
58
58
  Some(kwargs.bind(py)),
59
59
  )?;
60
- Ok(hash)
60
+ Ok((hash, args.unbind()))
61
61
  })
62
62
  .collect::<PyResult<Vec<_>>>()?;
63
63
  if self.serialisable {
@@ -117,17 +117,17 @@ impl AutomagicDependencyCacheDecoratorFactory {
117
117
  }
118
118
  Some(deps) => deps,
119
119
  };
120
- let hashed_dependencies: Vec<isize> = dependencies
120
+ let hashed_dependencies: Vec<(isize, Py<PyTuple>)> = dependencies
121
121
  .iter()
122
122
  .map(|(method_name, kwargs)| {
123
- let (hash, _) = normalise_function_signature_and_hash(
123
+ let (hash, args) = normalise_function_signature_and_hash(
124
124
  py,
125
125
  method_name,
126
126
  None,
127
127
  &empty_args,
128
128
  Some(kwargs.bind(py)),
129
129
  )?;
130
- Ok(hash)
130
+ Ok((hash, args.unbind()))
131
131
  })
132
132
  .collect::<PyResult<Vec<_>>>()?;
133
133
  if self.serialisable {
@@ -10,30 +10,32 @@ use std::collections::{HashMap, HashSet};
10
10
  use crate::dependency_graph::{MethodDependencyGraph, ValidationState};
11
11
  use crate::py_introspection_utils::{normalise_function_signature_and_hash, validate_self_only_method};
12
12
  use crate::decorator::DependencyCacheDecorator;
13
+ use crate::metadata_hash_manager::{CacheKey, MetadataHashManager};
13
14
 
14
15
 
15
16
  #[pyclass(subclass)]
16
17
  pub struct DependencyCacheBase {
17
- pub cache: HashMap<isize, Py<PyAny>>,
18
- pub method_dependency_graph: MethodDependencyGraph<isize, Py<PyTuple>>,
19
- pub call_stack: Vec<(isize, bool)>,
18
+ pub cache: HashMap<CacheKey, Py<PyAny>>,
19
+ pub method_dependency_graph: MethodDependencyGraph<CacheKey>,
20
+ pub metadata_hash_manager: MetadataHashManager,
21
+ pub call_stack: Vec<(CacheKey, bool)>,
20
22
  }
21
23
 
22
24
  impl DependencyCacheBase {
23
25
 
24
- pub fn set_cached_value_by_hash(&mut self, hash: isize, value: Py<PyAny>) {
26
+ pub fn set_cached_value_by_hash(&mut self, hash: CacheKey, value: Py<PyAny>) {
25
27
  if !self.method_dependency_graph.is_valid(hash) {
26
28
  return ();
27
29
  }
28
30
  self.cache.insert(hash, value);
29
31
  }
30
32
 
31
- pub fn validate_current_method(&mut self, hash: isize, use_cache: bool) {
33
+ pub fn validate_current_method(&mut self, hash: CacheKey, use_cache: bool) {
32
34
  if !use_cache {
33
35
  self.method_dependency_graph.permanently_invalidate(hash);
34
36
  }
35
37
 
36
- let child_validation_states: Vec<isize> = self.method_dependency_graph.list_child_methods(&hash);
38
+ let child_validation_states: Vec<CacheKey> = self.method_dependency_graph.list_child_methods(&hash);
37
39
 
38
40
  let mut new_state = ValidationState::Valid;
39
41
 
@@ -61,11 +63,11 @@ impl DependencyCacheBase {
61
63
  }
62
64
  }
63
65
 
64
- pub fn current_call_stack_top(&self) -> Option<(isize, bool)> {
66
+ pub fn current_call_stack_top(&self) -> Option<(CacheKey, bool)> {
65
67
  self.call_stack.last().cloned()
66
68
  }
67
69
 
68
- pub fn push_call_stack(&mut self, hash: isize, add_parent_dependencies: bool) {
70
+ pub fn push_call_stack(&mut self, hash: CacheKey, add_parent_dependencies: bool) {
69
71
  self.call_stack.push((hash, add_parent_dependencies));
70
72
  }
71
73
 
@@ -73,28 +75,29 @@ impl DependencyCacheBase {
73
75
  self.call_stack.pop();
74
76
  }
75
77
 
76
- pub fn add_parent_dependency(&mut self, hash: isize, dependency: isize) {
78
+ pub fn add_parent_dependency(&mut self, hash: CacheKey, dependency: CacheKey) {
77
79
  self.method_dependency_graph
78
80
  .add_parent_dependency(hash, vec![dependency]);
79
81
  }
80
82
 
81
- pub fn add_children_dependencies(&mut self, hash: isize, dependency: Vec<isize>, metadata: Py<PyTuple>) {
83
+ pub fn add_children_dependencies(&mut self, hash: CacheKey, dependency: Vec<CacheKey>) {
82
84
  self.method_dependency_graph
83
- .add_children_dependency(hash, dependency, metadata);
85
+ .add_children_dependency(hash, dependency);
84
86
  }
85
87
 
86
- pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: isize) -> Option<Py<PyAny>> {
88
+ pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: CacheKey) -> Option<Py<PyAny>> {
87
89
  if self.method_dependency_graph.is_valid(hash) {
88
90
  return self.cache.get(&hash).map(|obj| obj.clone_ref(py));
89
91
  }
90
92
  return None;
91
93
  }
92
94
 
93
- fn create_hash(&self, py: Python<'_>, method_name: &String, kwargs: &Option<Py<PyDict>>) -> PyResult<isize> {
95
+ pub fn create_hash(&mut self, py: Python<'_>, method_name: &String, kwargs: &Option<Py<PyDict>>) -> PyResult<CacheKey> {
94
96
  let empty_args = PyTuple::empty(py);
95
97
  let kwargs_bound = kwargs.as_ref().map(|k| k.bind(py));
96
- let (hash, _) = normalise_function_signature_and_hash(py, &method_name, None, &empty_args, kwargs_bound)?;
97
- return Ok(hash);
98
+ let (hash, sig) = normalise_function_signature_and_hash(py, &method_name, None, &empty_args, kwargs_bound)?;
99
+ let key = self.metadata_hash_manager.create_cache_key(py, hash, sig.unbind());
100
+ return key;
98
101
  }
99
102
  }
100
103
 
@@ -106,12 +109,13 @@ impl DependencyCacheBase {
106
109
  return Self {
107
110
  cache: HashMap::new(),
108
111
  method_dependency_graph: MethodDependencyGraph::new(),
112
+ metadata_hash_manager: MetadataHashManager::new(),
109
113
  call_stack: Vec::new(),
110
114
  };
111
115
  }
112
116
 
113
117
  #[pyo3(signature = (method_name, **kwargs))]
114
- pub fn get_cached_value(&self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> PyResult<Option<Py<PyAny>>> {
118
+ pub fn get_cached_value(&mut self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> PyResult<Option<Py<PyAny>>> {
115
119
  let hash = self.create_hash(py, &method_name, &kwargs)?;
116
120
 
117
121
  if self.method_dependency_graph.is_valid(hash) {
@@ -121,7 +125,7 @@ impl DependencyCacheBase {
121
125
  }
122
126
 
123
127
  pub fn is_cached(
124
- &self,
128
+ &mut self,
125
129
  py: Python<'_>,
126
130
  method_name: String,
127
131
  kwargs: Option<Py<PyDict>>,
@@ -168,10 +172,9 @@ impl DependencyCacheBase {
168
172
  pub fn get_cached_values<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
169
173
  let dict = PyDict::new(py);
170
174
  for (hash, value) in &self.cache {
171
- let Some(meta) = self.method_dependency_graph.get_metadata(hash) else {
175
+ let Some(bound) = self.metadata_hash_manager.get_signature(py, hash) else {
172
176
  continue;
173
177
  };
174
- let bound = meta.bind(py);
175
178
 
176
179
  let func_name: String = bound.get_item(0)?.extract()?;
177
180
 
@@ -194,10 +197,9 @@ impl DependencyCacheBase {
194
197
  let dict = PyDict::new(py);
195
198
 
196
199
  for (child_hash, parent_hashes) in &self.method_dependency_graph.clone_graph() {
197
- let Some(child_meta) = self.method_dependency_graph.get_metadata(child_hash) else {
200
+ let Some(child_bound) = self.metadata_hash_manager.get_signature(py, child_hash) else {
198
201
  continue;
199
202
  };
200
- let child_bound = child_meta.bind(py);
201
203
 
202
204
  let func_name: String = child_bound.get_item(0)?.extract()?;
203
205
 
@@ -212,8 +214,7 @@ impl DependencyCacheBase {
212
214
 
213
215
  let mut parent_bounds = Vec::new();
214
216
  for parent_hash in parent_hashes {
215
- if let Some(parent_meta) = self.method_dependency_graph.get_metadata(parent_hash) {
216
- let bound = parent_meta.bind(py);
217
+ if let Some(bound) = self.metadata_hash_manager.get_signature(py, parent_hash) {
217
218
 
218
219
  let parent_name: String = bound.get_item(0)?.extract()?;
219
220
  let parent_args_item = bound.get_item(1)?;
@@ -239,10 +240,9 @@ impl DependencyCacheBase {
239
240
  pub fn get_validation_state<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
240
241
  let dict = PyDict::new(py);
241
242
  for (hash, state) in &self.method_dependency_graph.clone_state() {
242
- let Some(metadata) = self.method_dependency_graph.get_metadata(hash) else {
243
+ let Some(meta_bound) = self.metadata_hash_manager.get_signature(py, hash) else {
243
244
  continue;
244
245
  };
245
- let meta_bound = metadata.bind(py);
246
246
 
247
247
  let func_name: String = meta_bound.get_item(0)?.extract()?;
248
248
 
@@ -326,9 +326,8 @@ impl DependencyCacheBase {
326
326
  let class = slf.get_type();
327
327
 
328
328
  let load_method = |name: &str| -> PyResult<()> {
329
- let loaded_value = match data.get_item(name)? {
330
- Some(val) => val,
331
- None => return Ok(()),
329
+ let Some(loaded_value) = data.get_item(name)? else {
330
+ return Ok(());
332
331
  };
333
332
 
334
333
  let method_attr = class.getattr(name)?;
@@ -341,26 +340,25 @@ impl DependencyCacheBase {
341
340
  name
342
341
  ))
343
342
  })?;
343
+ // scope borrow to prevent already borrowed error
344
+ let underlying_func = {
345
+ let d = decorator.borrow();
346
+ if !d.serialisable {
347
+ return Err(PyValueError::new_err(format!(
348
+ "Method '{}' is not marked as serialisable",
349
+ name
350
+ )));
351
+ }
352
+ d.func.clone_ref(py)
353
+ };
344
354
 
345
- let decorator_ref = decorator.borrow();
346
-
347
-
348
- if !decorator_ref.serialisable {
349
- return Err(PyValueError::new_err(format!(
350
- "Method '{}' is not marked as serialisable",
351
- name
352
- )));
353
- }
354
-
355
- let underlying_func = decorator_ref.func.bind(py);
356
- validate_self_only_method(py, &underlying_func)?;
355
+ validate_self_only_method(py, underlying_func.bind(py))?;
357
356
 
358
357
  let _ = slf.call_method(name, (), None)?;
359
358
 
360
- let empty_args = PyTuple::empty(py);
361
- let (hash, _) = normalise_function_signature_and_hash(py, name, None, &empty_args, None)
362
- .map_err(|e| PyValueError::new_err(format!("Failed to hash '{}': {}", name, e)))?;
363
- slf.borrow_mut().cache.insert(hash, loaded_value.unbind());
359
+ let mut base = slf.borrow_mut();
360
+ let key = base.create_hash(py, &name.to_string(), &None)?;
361
+ base.cache.insert(key, loaded_value.unbind());
364
362
  Ok(())
365
363
  };
366
364
 
@@ -9,25 +9,19 @@ pub enum ValidationState {
9
9
  PermanentlyInvalid,
10
10
  }
11
11
 
12
- pub struct MethodDependencyGraph<T, M = ()> {
12
+ pub struct MethodDependencyGraph<T> {
13
13
  validation_state: HashMap<T, ValidationState>,
14
14
  dependency_graph: HashMap<T, HashSet<T>>, // maps child_name to set[parents_name], for ease of traversal
15
- metadata_map: HashMap<T, M>,
16
15
  }
17
16
 
18
- impl<T: Eq + Hash + Clone, M> MethodDependencyGraph<T, M> {
17
+ impl<T: Eq + Hash + Clone> MethodDependencyGraph<T> {
19
18
  pub fn new() -> Self {
20
19
  return MethodDependencyGraph {
21
20
  validation_state: HashMap::new(),
22
21
  dependency_graph: HashMap::new(),
23
- metadata_map: HashMap::new(),
24
22
  };
25
23
  }
26
24
 
27
- pub fn get_metadata(&self, method: &T) -> Option<&M> {
28
- return self.metadata_map.get(method);
29
- }
30
-
31
25
  pub fn get_method_state_as_enum(&self, method: &T) -> &ValidationState {
32
26
  return self.validation_state.get(method).unwrap_or(&ValidationState::PermanentlyInvalid);
33
27
  }
@@ -40,12 +34,11 @@ impl<T: Eq + Hash + Clone, M> MethodDependencyGraph<T, M> {
40
34
  .collect();
41
35
  }
42
36
 
43
- pub fn add_children_dependency(&mut self, method: T, dependencies: Vec<T>, metadata: M) -> () {
44
- if self.metadata_map.contains_key(&method) {
37
+ pub fn add_children_dependency(&mut self, method: T, dependencies: Vec<T>) -> () {
38
+ if self.validation_state.contains_key(&method) {
45
39
  return ();
46
40
  }
47
41
  self.validation_state.insert(method.clone(), ValidationState::Invalid);
48
- self.metadata_map.insert(method.clone(), metadata);
49
42
  self.dependency_graph.entry(method.clone()).or_default();
50
43
  for dependent_method in dependencies {
51
44
  self.dependency_graph
@@ -155,11 +148,6 @@ impl<T: Eq + Hash + Clone, M> MethodDependencyGraph<T, M> {
155
148
  .collect();
156
149
  }
157
150
 
158
- pub fn clone_metadata(&self) -> HashMap<T, M>
159
- where M: Clone {
160
- return self.metadata_map.clone();
161
- }
162
-
163
151
  pub fn invalidate_all(&mut self) {
164
152
  for state in self.validation_state.values_mut() {
165
153
  if *state == ValidationState::Valid {
@@ -176,9 +164,9 @@ mod tests {
176
164
  #[test]
177
165
  fn test_cache_state_add_one() {
178
166
  let mut dg = MethodDependencyGraph::new();
179
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
180
- dg.add_children_dependency("B".to_string(), vec![], ());
181
- dg.add_children_dependency("C".to_string(), vec![], ());
167
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
168
+ dg.add_children_dependency("B".to_string(), vec![]);
169
+ dg.add_children_dependency("C".to_string(), vec![]);
182
170
 
183
171
  let mut cache_state = HashMap::new();
184
172
  cache_state.insert("A".to_string(), ValidationState::Invalid);
@@ -190,13 +178,13 @@ mod tests {
190
178
  #[test]
191
179
  fn test_cache_state_add_many() {
192
180
  let mut dg = MethodDependencyGraph::new();
193
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
194
- dg.add_children_dependency("B".to_string(), vec!["D".to_string(), "E".to_string()], ());
195
- dg.add_children_dependency("C".to_string(), vec!["F".to_string(), "G".to_string()], ());
196
- dg.add_children_dependency("D".to_string(), vec![], ());
197
- dg.add_children_dependency("E".to_string(), vec![], ());
198
- dg.add_children_dependency("F".to_string(), vec![], ());
199
- dg.add_children_dependency("G".to_string(), vec![], ());
181
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
182
+ dg.add_children_dependency("B".to_string(), vec!["D".to_string(), "E".to_string()]);
183
+ dg.add_children_dependency("C".to_string(), vec!["F".to_string(), "G".to_string()]);
184
+ dg.add_children_dependency("D".to_string(), vec![]);
185
+ dg.add_children_dependency("E".to_string(), vec![]);
186
+ dg.add_children_dependency("F".to_string(), vec![]);
187
+ dg.add_children_dependency("G".to_string(), vec![]);
200
188
 
201
189
  let mut cache_state = HashMap::new();
202
190
  cache_state.insert("A".to_string(), ValidationState::Invalid);
@@ -212,7 +200,7 @@ mod tests {
212
200
  #[test]
213
201
  fn test_graph_state_add_one() {
214
202
  let mut dg = MethodDependencyGraph::new();
215
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
203
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
216
204
 
217
205
  let mut graph_state = HashMap::new();
218
206
  graph_state.insert("A".to_string(), HashSet::new());
@@ -224,9 +212,9 @@ mod tests {
224
212
  #[test]
225
213
  fn test_graph_state_add_many() {
226
214
  let mut dg = MethodDependencyGraph::new();
227
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
228
- dg.add_children_dependency("B".to_string(), vec!["D".to_string(), "E".to_string()], ());
229
- dg.add_children_dependency("C".to_string(), vec!["F".to_string(), "G".to_string()], ());
215
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
216
+ dg.add_children_dependency("B".to_string(), vec!["D".to_string(), "E".to_string()]);
217
+ dg.add_children_dependency("C".to_string(), vec!["F".to_string(), "G".to_string()]);
230
218
 
231
219
  let mut graph_state = HashMap::new();
232
220
  graph_state.insert("A".to_string(), HashSet::new());
@@ -242,9 +230,9 @@ mod tests {
242
230
  #[test]
243
231
  fn test_name_validation() {
244
232
  let mut dg = MethodDependencyGraph::new();
245
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
246
- dg.add_children_dependency("B".to_string(), vec![], ());
247
- dg.add_children_dependency("C".to_string(), vec![], ());
233
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
234
+ dg.add_children_dependency("B".to_string(), vec![]);
235
+ dg.add_children_dependency("C".to_string(), vec![]);
248
236
 
249
237
  assert!(!dg.is_valid("A".to_string()));
250
238
  assert!(!dg.is_valid("B".to_string()));
@@ -266,7 +254,7 @@ mod tests {
266
254
  #[test]
267
255
  fn test_name_invalidation() {
268
256
  let mut dg = MethodDependencyGraph::new();
269
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
257
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
270
258
  dg.validate("A".to_string());
271
259
  dg.validate("B".to_string());
272
260
  dg.validate("C".to_string());
@@ -283,10 +271,10 @@ mod tests {
283
271
  #[test]
284
272
  fn test_add_dependency_idempotency() {
285
273
  let mut dg = MethodDependencyGraph::new();
286
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
287
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
288
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
289
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
274
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
275
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
276
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
277
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
290
278
 
291
279
  let mut graph_state = HashMap::new();
292
280
  graph_state.insert("A".to_string(), HashSet::new());
@@ -298,9 +286,9 @@ mod tests {
298
286
  #[test]
299
287
  fn test_attempt_to_validate_permanently_invalid_state() {
300
288
  let mut dg = MethodDependencyGraph::new();
301
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
302
- dg.add_children_dependency("B".to_string(), vec![], ());
303
- dg.add_children_dependency("C".to_string(), vec![], ());
289
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
290
+ dg.add_children_dependency("B".to_string(), vec![]);
291
+ dg.add_children_dependency("C".to_string(), vec![]);
304
292
 
305
293
  dg.permanently_invalidate("B".to_string());
306
294
 
@@ -316,9 +304,9 @@ mod tests {
316
304
  #[test]
317
305
  fn test_attempt_to_invalidate_permanently_invalid_state() {
318
306
  let mut dg = MethodDependencyGraph::new();
319
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], ());
320
- dg.add_children_dependency("B".to_string(), vec![], ());
321
- dg.add_children_dependency("C".to_string(), vec![], ());
307
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
308
+ dg.add_children_dependency("B".to_string(), vec![]);
309
+ dg.add_children_dependency("C".to_string(), vec![]);
322
310
 
323
311
  dg.permanently_invalidate("B".to_string());
324
312
 
@@ -334,9 +322,9 @@ mod tests {
334
322
  #[test]
335
323
  fn test_clones_default() {
336
324
  let mut dg = MethodDependencyGraph::new();
337
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], "A".to_string());
338
- dg.add_children_dependency("B".to_string(), vec![], "B".to_string());
339
- dg.add_children_dependency("C".to_string(), vec![], "C".to_string());
325
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
326
+ dg.add_children_dependency("B".to_string(), vec![]);
327
+ dg.add_children_dependency("C".to_string(), vec![]);
340
328
 
341
329
  let mut cache_state = HashMap::new();
342
330
  cache_state.insert("A".to_string(), "invalid".to_string());
@@ -356,16 +344,14 @@ mod tests {
356
344
  metadata_store.insert("A".to_string(), "A".to_string());
357
345
  metadata_store.insert("B".to_string(), "B".to_string());
358
346
  metadata_store.insert("C".to_string(), "C".to_string());
359
-
360
- assert_eq!(dg.clone_metadata(), metadata_store);
361
347
  }
362
348
 
363
349
  #[test]
364
350
  fn test_clones_after_mutation() {
365
351
  let mut dg = MethodDependencyGraph::new();
366
- dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()], "A".to_string());
367
- dg.add_children_dependency("B".to_string(), vec![], "B".to_string());
368
- dg.add_children_dependency("C".to_string(), vec![], "C".to_string());
352
+ dg.add_children_dependency("A".to_string(), vec!["B".to_string(), "C".to_string()]);
353
+ dg.add_children_dependency("B".to_string(), vec![]);
354
+ dg.add_children_dependency("C".to_string(), vec![]);
369
355
  dg.validate("A".to_string());
370
356
  dg.permanently_invalidate("B".to_string());
371
357
 
@@ -376,7 +362,7 @@ mod tests {
376
362
 
377
363
  assert_eq!(dg.clone_state(), cache_state);
378
364
 
379
- dg.add_children_dependency("D".to_string(), vec![], "D".to_string());
365
+ dg.add_children_dependency("D".to_string(), vec![]);
380
366
  dg.add_parent_dependency("B".to_string(), vec!["D".to_string()]);
381
367
 
382
368
  let mut graph_state = HashMap::new();
@@ -3,6 +3,7 @@ mod dependency_graph;
3
3
  mod dependency_cache_base;
4
4
  mod decorator_factory;
5
5
  mod py_introspection_utils;
6
+ mod metadata_hash_manager;
6
7
 
7
8
  use pyo3::prelude::*;
8
9
 
@@ -0,0 +1,60 @@
1
+ use pyo3::prelude::*;
2
+ use pyo3::types::PyTuple;
3
+ use std::collections::HashMap;
4
+
5
+ pub type CacheKey = u64;
6
+
7
+ pub struct MetadataHashManager {
8
+ buckets: HashMap<isize, Vec<CacheKey>>,
9
+ signatures: HashMap<CacheKey, Py<PyTuple>>,
10
+ next_id: CacheKey,
11
+ }
12
+
13
+ impl MetadataHashManager {
14
+ pub fn new() -> Self {
15
+ Self { buckets: HashMap::new(), signatures: HashMap::new(), next_id: 0 }
16
+ }
17
+
18
+ pub fn get_cache_key(
19
+ &self,
20
+ py: Python<'_>,
21
+ hash: &isize,
22
+ sig: &Bound<'_, PyTuple>,
23
+ ) -> PyResult<Option<CacheKey>> {
24
+ let Some(bucket) = self.buckets.get(hash) else {
25
+ return Ok(None);
26
+ };
27
+ if bucket.len() == 1 {
28
+ let key = bucket[0];
29
+ let stored = self.signatures[&key].bind(py);
30
+ return Ok(stored.eq(sig)?.then_some(key));
31
+ }
32
+ for &key in bucket {
33
+ let stored = self.signatures[&key].bind(py);
34
+ if stored.eq(sig)? {
35
+ return Ok(Some(key));
36
+ }
37
+ }
38
+ Ok(None)
39
+ }
40
+
41
+ pub fn create_cache_key(
42
+ &mut self,
43
+ py: Python<'_>,
44
+ hash: isize,
45
+ sig: Py<PyTuple>,
46
+ ) -> PyResult<CacheKey> {
47
+ if let Some(key) = self.get_cache_key(py, &hash, sig.bind(py))? {
48
+ return Ok(key);
49
+ }
50
+ let key = self.next_id;
51
+ self.next_id += 1;
52
+ self.buckets.entry(hash.clone()).or_default().push(key);
53
+ self.signatures.insert(key, sig);
54
+ Ok(key)
55
+ }
56
+
57
+ pub fn get_signature<'py>(&self, py: Python<'py>, id: &CacheKey) -> Option<Bound<'py, PyTuple>> {
58
+ self.signatures.get(id).map(|s| s.bind(py).clone())
59
+ }
60
+ }
@@ -329,7 +329,7 @@ wheels = [
329
329
 
330
330
  [[package]]
331
331
  name = "dependency-cache"
332
- version = "0.3.0"
332
+ version = "0.4.0"
333
333
  source = { editable = "." }
334
334
  dependencies = [
335
335
  { name = "matplotlib", version = "3.7.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" },