dependency-cache 0.3.0__tar.gz → 0.4.1__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.1}/Cargo.toml +2 -0
  2. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/PKG-INFO +3 -3
  3. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/README.md +2 -2
  4. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/pyproject.toml +1 -1
  5. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/dependency_cache/plot_dependency_graph.py +1 -1
  6. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/test_python.py +1 -1
  7. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/test_python_automagic.py +1 -1
  8. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/src/decorator.rs +22 -10
  9. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/src/decorator_factory.rs +6 -6
  10. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/src/dependency_cache_base.rs +76 -70
  11. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/src/dependency_graph.rs +39 -53
  12. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/src/lib.rs +1 -0
  13. dependency_cache-0.4.1/src/metadata_hash_manager.rs +67 -0
  14. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/src/py_introspection_utils.rs +1 -1
  15. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/uv.lock +1 -1
  16. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/.github/workflows/CI.yml +0 -0
  17. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/.github/workflows/Test.yml +0 -0
  18. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/.gitignore +0 -0
  19. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/Cargo.lock +0 -0
  20. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/LICENSE +0 -0
  21. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/dependency_cache/__init__.py +0 -0
  22. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/dependency_cache/dependency_cache.pyi +0 -0
  23. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/automagic_dependency_example.py +0 -0
  24. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/example.py +0 -0
  25. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/inheritance_example.py +0 -0
  26. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/manual_dependency_example.py +0 -0
  27. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/runtime_dependencies_example.py +0 -0
  28. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/runtime_function_calls_example.py +0 -0
  29. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/static_function_calls_example.py +0 -0
  30. {dependency_cache-0.3.0 → dependency_cache-0.4.1}/python/examples/use_cache_example.py +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.1
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.1"
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,
@@ -18,7 +18,7 @@ pub struct DependencyCacheDecorator {
18
18
  #[pymethods]
19
19
  impl DependencyCacheDecorator {
20
20
  fn __set__(&self, _obj: Py<PyAny>, _value: Py<PyAny>) -> PyResult<()> {
21
- return Err(PyTypeError::new_err("cannot assign to decorated method"));
21
+ return Err(PyTypeError::new_err("Cannot assign to decorated method"));
22
22
  }
23
23
 
24
24
  fn __get__(
@@ -57,28 +57,40 @@ impl DependencyCacheDecorator {
57
57
  let instance = args.get_item(0)?;
58
58
  let base = instance.cast::<DependencyCacheBase>().map_err(|_| {
59
59
  PyTypeError::new_err(
60
- "the decorated method's class must inherit from DependencyCacheBase",
60
+ "The decorated method's class must inherit from DependencyCacheBase",
61
61
  )
62
62
  })?;
63
63
 
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.try_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.is_empty() {
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_key(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_key(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>) {
25
- if !self.method_dependency_graph.is_valid(hash) {
26
+ pub fn set_cached_value_by_key(&mut self, key: CacheKey, value: Py<PyAny>) {
27
+ if !self.method_dependency_graph.is_valid(key) {
26
28
  return ();
27
29
  }
28
- self.cache.insert(hash, value);
30
+ self.cache.insert(key, 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, key: CacheKey, use_cache: bool) {
32
34
  if !use_cache {
33
- self.method_dependency_graph.permanently_invalidate(hash);
35
+ self.method_dependency_graph.permanently_invalidate(key);
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(&key);
37
39
 
38
40
  let mut new_state = ValidationState::Valid;
39
41
 
@@ -50,51 +52,60 @@ impl DependencyCacheBase {
50
52
 
51
53
  match new_state {
52
54
  ValidationState::PermanentlyInvalid => {
53
- self.method_dependency_graph.permanently_invalidate(hash);
55
+ self.method_dependency_graph.permanently_invalidate(key);
54
56
  }
55
57
  ValidationState::Invalid => {
56
- self.method_dependency_graph.temporarily_invalidate(hash);
58
+ self.method_dependency_graph.temporarily_invalidate(key);
57
59
  }
58
60
  ValidationState::Valid => {
59
- self.method_dependency_graph.validate(hash);
61
+ self.method_dependency_graph.validate(key);
60
62
  }
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) {
69
- self.call_stack.push((hash, add_parent_dependencies));
70
+ pub fn push_call_stack(&mut self, key: CacheKey, add_parent_dependencies: bool) {
71
+ self.call_stack.push((key, add_parent_dependencies));
70
72
  }
71
73
 
72
74
  pub fn pop_call_stack(&mut self) {
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, key: CacheKey, dependency: CacheKey) {
77
79
  self.method_dependency_graph
78
- .add_parent_dependency(hash, vec![dependency]);
80
+ .add_parent_dependency(key, 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, key: CacheKey, dependency: Vec<CacheKey>) {
82
84
  self.method_dependency_graph
83
- .add_children_dependency(hash, dependency, metadata);
85
+ .add_children_dependency(key, dependency);
84
86
  }
85
87
 
86
- pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: isize) -> Option<Py<PyAny>> {
87
- if self.method_dependency_graph.is_valid(hash) {
88
- return self.cache.get(&hash).map(|obj| obj.clone_ref(py));
88
+ pub fn get_cached_value_by_key(&self, py: Python<'_>, key: CacheKey) -> Option<Py<PyAny>> {
89
+ if self.method_dependency_graph.is_valid(key) {
90
+ return self.cache.get(&key).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_key(&mut self, py: Python<'_>, method_name: &str, 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;
101
+ }
102
+
103
+ pub fn get_key(&mut self, py: Python<'_>, method_name: &str, kwargs: &Option<Py<PyDict>>) -> PyResult<CacheKey> {
104
+ let empty_args = PyTuple::empty(py);
105
+ let kwargs_bound = kwargs.as_ref().map(|k| k.bind(py));
106
+ let (hash, sig) = normalise_function_signature_and_hash(py, method_name, None, &empty_args, kwargs_bound)?;
107
+ let key = self.metadata_hash_manager.get_cache_key(py, &hash, &sig);
108
+ return key;
98
109
  }
99
110
  }
100
111
 
@@ -106,43 +117,44 @@ impl DependencyCacheBase {
106
117
  return Self {
107
118
  cache: HashMap::new(),
108
119
  method_dependency_graph: MethodDependencyGraph::new(),
120
+ metadata_hash_manager: MetadataHashManager::new(),
109
121
  call_stack: Vec::new(),
110
122
  };
111
123
  }
112
124
 
113
125
  #[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>>> {
115
- let hash = self.create_hash(py, &method_name, &kwargs)?;
126
+ pub fn get_cached_value(&mut self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> PyResult<Option<Py<PyAny>>> {
127
+ let key = self.get_key(py, &method_name, &kwargs)?;
116
128
 
117
- if self.method_dependency_graph.is_valid(hash) {
118
- return Ok(self.cache.get(&hash).map(|obj| obj.clone_ref(py)));
129
+ if self.method_dependency_graph.is_valid(key) {
130
+ return Ok(self.cache.get(&key).map(|obj| obj.clone_ref(py)));
119
131
  }
120
132
  return Ok(None);
121
133
  }
122
134
 
123
135
  pub fn is_cached(
124
- &self,
136
+ &mut self,
125
137
  py: Python<'_>,
126
138
  method_name: String,
127
139
  kwargs: Option<Py<PyDict>>,
128
140
  ) -> PyResult<bool> {
129
- let hash = self.create_hash(py, &method_name, &kwargs)?;
130
- Ok(self.method_dependency_graph.is_valid(hash) && self.cache.contains_key(&hash))
141
+ let key = self.get_key(py, &method_name, &kwargs)?;
142
+ Ok(self.method_dependency_graph.is_valid(key) && self.cache.contains_key(&key))
131
143
  }
132
144
 
133
145
 
134
146
  #[pyo3(signature = (method_name, value, **kwargs))]
135
147
  pub fn update_cached_value(&mut self, py: Python<'_>, method_name: String, value: Py<PyAny>, kwargs: Option<Py<PyDict>>) -> PyResult<()> {
136
- let hash = self.create_hash(py, &method_name, &kwargs)?;
148
+ let key = self.get_key(py, &method_name, &kwargs)?;
137
149
 
138
- let Some(v) = self.cache.get_mut(&hash) else {
150
+ let Some(v) = self.cache.get_mut(&key) else {
139
151
  return Err(PyKeyError::new_err(format!(
140
152
  "Cannot update cached value for '{method_name}'"
141
153
  )));
142
154
  };
143
155
  *v = value;
144
- self.method_dependency_graph.temporarily_invalidate(hash);
145
- self.method_dependency_graph.validate(hash);
156
+ self.method_dependency_graph.temporarily_invalidate(key);
157
+ self.method_dependency_graph.validate(key);
146
158
  return Ok(());
147
159
  }
148
160
 
@@ -153,25 +165,24 @@ impl DependencyCacheBase {
153
165
 
154
166
  #[pyo3(signature = (method_name, **kwargs))]
155
167
  pub fn clear_cached_value(&mut self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> PyResult<()> {
156
- let hash = self.create_hash(py, &method_name, &kwargs)?;
168
+ let key = self.get_key(py, &method_name, &kwargs)?;
157
169
 
158
- if self.cache.remove(&hash).is_none() {
170
+ if self.cache.remove(&key).is_none() {
159
171
  return Err(PyKeyError::new_err(format!(
160
172
  "Cannot clear cached value for '{method_name}'"
161
173
  )));
162
174
  }
163
- self.method_dependency_graph.temporarily_invalidate(hash);
175
+ self.method_dependency_graph.temporarily_invalidate(key);
164
176
  Ok(())
165
177
  }
166
178
 
167
179
  #[getter]
168
180
  pub fn get_cached_values<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
169
181
  let dict = PyDict::new(py);
170
- for (hash, value) in &self.cache {
171
- let Some(meta) = self.method_dependency_graph.get_metadata(hash) else {
182
+ for (key, value) in &self.cache {
183
+ let Some(bound) = self.metadata_hash_manager.get_signature(py, key) else {
172
184
  continue;
173
185
  };
174
- let bound = meta.bind(py);
175
186
 
176
187
  let func_name: String = bound.get_item(0)?.extract()?;
177
188
 
@@ -193,11 +204,10 @@ impl DependencyCacheBase {
193
204
  pub fn get_dependency_graph<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
194
205
  let dict = PyDict::new(py);
195
206
 
196
- 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 {
207
+ for (child_key, parent_keys) in &self.method_dependency_graph.clone_graph() {
208
+ let Some(child_bound) = self.metadata_hash_manager.get_signature(py, child_key) else {
198
209
  continue;
199
210
  };
200
- let child_bound = child_meta.bind(py);
201
211
 
202
212
  let func_name: String = child_bound.get_item(0)?.extract()?;
203
213
 
@@ -211,9 +221,8 @@ impl DependencyCacheBase {
211
221
  };
212
222
 
213
223
  let mut parent_bounds = Vec::new();
214
- 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);
224
+ for parent_key in parent_keys {
225
+ if let Some(bound) = self.metadata_hash_manager.get_signature(py, parent_key) {
217
226
 
218
227
  let parent_name: String = bound.get_item(0)?.extract()?;
219
228
  let parent_args_item = bound.get_item(1)?;
@@ -238,11 +247,10 @@ impl DependencyCacheBase {
238
247
  #[getter]
239
248
  pub fn get_validation_state<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
240
249
  let dict = PyDict::new(py);
241
- for (hash, state) in &self.method_dependency_graph.clone_state() {
242
- let Some(metadata) = self.method_dependency_graph.get_metadata(hash) else {
250
+ for (key, state) in &self.method_dependency_graph.clone_state() {
251
+ let Some(meta_bound) = self.metadata_hash_manager.get_signature(py, key) else {
243
252
  continue;
244
253
  };
245
- let meta_bound = metadata.bind(py);
246
254
 
247
255
  let func_name: String = meta_bound.get_item(0)?.extract()?;
248
256
 
@@ -326,9 +334,8 @@ impl DependencyCacheBase {
326
334
  let class = slf.get_type();
327
335
 
328
336
  let load_method = |name: &str| -> PyResult<()> {
329
- let loaded_value = match data.get_item(name)? {
330
- Some(val) => val,
331
- None => return Ok(()),
337
+ let Some(loaded_value) = data.get_item(name)? else {
338
+ return Ok(());
332
339
  };
333
340
 
334
341
  let method_attr = class.getattr(name)?;
@@ -341,26 +348,25 @@ impl DependencyCacheBase {
341
348
  name
342
349
  ))
343
350
  })?;
351
+ // scope borrow to prevent already borrowed error
352
+ let underlying_func = {
353
+ let d = decorator.borrow();
354
+ if !d.serialisable {
355
+ return Err(PyValueError::new_err(format!(
356
+ "Method '{}' is not marked as serialisable",
357
+ name
358
+ )));
359
+ }
360
+ d.func.clone_ref(py)
361
+ };
344
362
 
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)?;
363
+ validate_self_only_method(py, underlying_func.bind(py))?;
357
364
 
358
365
  let _ = slf.call_method(name, (), None)?;
359
366
 
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());
367
+ let mut base = slf.borrow_mut();
368
+ let key = base.create_key(py, name, &None)?;
369
+ base.cache.insert(key, loaded_value.unbind());
364
370
  Ok(())
365
371
  };
366
372
 
@@ -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,67 @@
1
+ use pyo3::prelude::*;
2
+ use pyo3::types::PyTuple;
3
+ use pyo3::exceptions::PyKeyError;
4
+
5
+ use std::collections::HashMap;
6
+
7
+ pub type CacheKey = u64;
8
+
9
+ pub struct MetadataHashManager {
10
+ buckets: HashMap<isize, Vec<CacheKey>>,
11
+ signatures: HashMap<CacheKey, Py<PyTuple>>,
12
+ next_id: CacheKey,
13
+ }
14
+
15
+ impl MetadataHashManager {
16
+ pub fn new() -> Self {
17
+ Self { buckets: HashMap::new(), signatures: HashMap::new(), next_id: 0 }
18
+ }
19
+
20
+ fn find_cache_key(
21
+ &self,
22
+ py: Python<'_>,
23
+ hash: &isize,
24
+ sig: &Bound<'_, PyTuple>,
25
+ ) -> PyResult<Option<CacheKey>> {
26
+ let Some(bucket) = self.buckets.get(hash) else {
27
+ return Ok(None);
28
+ };
29
+ for &key in bucket {
30
+ let stored_signature = self.signatures[&key].bind(py);
31
+ if stored_signature.eq(sig)? {
32
+ return Ok(Some(key));
33
+ }
34
+ }
35
+ Ok(None)
36
+ }
37
+
38
+ pub fn get_cache_key(
39
+ &self,
40
+ py: Python<'_>,
41
+ hash: &isize,
42
+ sig: &Bound<'_, PyTuple>,
43
+ ) -> PyResult<CacheKey> {
44
+ self.find_cache_key(py, hash, sig)?
45
+ .ok_or_else(|| PyKeyError::new_err("No cache key found for provided signature"))
46
+ }
47
+
48
+ pub fn create_cache_key(
49
+ &mut self,
50
+ py: Python<'_>,
51
+ hash: isize,
52
+ sig: Py<PyTuple>,
53
+ ) -> PyResult<CacheKey> {
54
+ if let Some(key) = self.find_cache_key(py, &hash, sig.bind(py))? {
55
+ return Ok(key);
56
+ }
57
+ let key = self.next_id;
58
+ self.next_id += 1;
59
+ self.buckets.entry(hash).or_default().push(key);
60
+ self.signatures.insert(key, sig);
61
+ Ok(key)
62
+ }
63
+
64
+ pub fn get_signature<'py>(&self, py: Python<'py>, id: &CacheKey) -> Option<Bound<'py, PyTuple>> {
65
+ self.signatures.get(id).map(|s| s.bind(py).clone())
66
+ }
67
+ }
@@ -182,7 +182,7 @@ pub fn ast_inspect_method_dependencies(py: Python<'_>, python_func: &Py<PyAny>)
182
182
  let ast_module = PyModule::import(py, "ast")?;
183
183
  let ast_tree = ast_module
184
184
  .call_method1("parse", (function_string_clean,))
185
- .map_err(|e| PyValueError::new_err(format!("failed to parse source: {e}")))?;
185
+ .map_err(|e| PyValueError::new_err(format!("Failed to parse source: {e}")))?;
186
186
 
187
187
  let ast_function = ast_module.getattr("FunctionDef")?;
188
188
  let ast_async_function = ast_module.getattr("AsyncFunctionDef")?;
@@ -329,7 +329,7 @@ wheels = [
329
329
 
330
330
  [[package]]
331
331
  name = "dependency-cache"
332
- version = "0.3.0"
332
+ version = "0.4.1"
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'" },