-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
3849 lines (3242 loc) · 128 KB
/
Copy pathcache.py
File metadata and controls
3849 lines (3242 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Cache infrastructure primitives and graph-level helpers for TNFR.
This module consolidates structural cache helpers that previously lived in
legacy helper modules and are now exposed under :mod:`tnfr.utils`. The
functions exposed here are responsible for maintaining deterministic node
digests, scoped graph caches guarded by locks, and version counters that keep
edge artifacts in sync with ΔNFR driven updates.
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
import pickle
import sys
import threading
import time
import weakref
from collections import defaultdict
from collections.abc import (
Callable,
Hashable,
Iterable,
Iterator,
Mapping,
MutableMapping,
)
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import field
from functools import lru_cache, wraps
from time import perf_counter
from typing import Any, Generic, TypeVar, cast
import networkx as nx
from ..compat.dataclass import dataclass
from ..errors import TNFRSecurityError, TNFRSecurityWarning, TNFRValueError
from ..locking import get_lock
from ..security.crypto import create_hmac_signer, create_hmac_validator
from ..types import CacheLevel
from ..types import CacheStats as CacheStatistics
from ..types import GraphLike, NodeId, TimingContext, TNFRGraph
from .cache_layers import (
CacheLayer,
MappingCacheLayer,
RedisCacheLayer,
ShelveCacheLayer,
create_secure_redis_layer,
create_secure_shelve_layer,
)
from .graph import get_graph, mark_dnfr_prep_dirty
from .unified_cache import UnifiedLRUCache
K = TypeVar("K", bound=Hashable)
V = TypeVar("V")
T = TypeVar("T")
SecurityError = TNFRSecurityError
SecurityWarning = TNFRSecurityWarning
__all__ = (
"CacheLayer",
"CacheManager",
"CacheCapacityConfig",
"CacheStatistics",
"InstrumentedLRUCache",
"ManagedLRUCache",
"MappingCacheLayer",
"RedisCacheLayer",
"ShelveCacheLayer",
"SecurityError",
"SecurityWarning",
"create_hmac_signer",
"create_hmac_validator",
"create_secure_shelve_layer",
"create_secure_redis_layer",
"prune_lock_mapping",
"EdgeCacheManager",
"NODE_SET_CHECKSUM_KEY",
"cached_node_list",
"cached_nodes_and_A",
"clear_node_repr_cache",
"edge_version_cache",
"edge_version_update",
"ensure_node_index_map",
"ensure_node_offset_map",
"stable_node_offsets",
"get_graph_version",
"increment_edge_version",
"increment_graph_version",
"node_set_checksum",
"stable_json",
"configure_graph_cache_limits",
"DNFR_PREP_STATE_KEY",
"GRAPH_RUNTIME_CACHE_KEYS",
"DnfrPrepState",
"build_cache_manager",
"configure_global_cache_layers",
"reset_global_cache_manager",
"_GRAPH_CACHE_LAYERS_KEY",
"_SeedHashCache",
"ScopedCounterCache",
"DnfrCache",
"new_dnfr_cache",
# Hierarchical cache classes (moved from caching/)
"CacheLevel",
"CacheEntry",
"TNFRHierarchicalCache",
# Cache decorators (moved from caching/decorators.py)
"cache_tnfr_computation",
"invalidate_function_cache",
"get_global_cache",
"set_global_cache",
"reset_global_cache",
# Invalidation tracking (moved from caching/invalidation.py)
"GraphChangeTracker",
"track_node_property_update",
# Persistence (moved from caching/persistence.py)
"PersistentTNFRCache",
)
# Environment variable to control security warnings for pickle deserialization
_TNFR_ALLOW_UNSIGNED_PICKLE = "TNFR_ALLOW_UNSIGNED_PICKLE"
@dataclass(frozen=True)
class CacheCapacityConfig:
"""Configuration snapshot for cache capacity policies."""
default_capacity: int | None
overrides: dict[str, int | None]
@dataclass
class DnfrCache:
idx: dict[Any, int]
theta: list[float]
epi: list[float]
vf: list[float]
cos_theta: list[float]
sin_theta: list[float]
neighbor_x: list[float]
neighbor_y: list[float]
neighbor_epi_sum: list[float]
neighbor_vf_sum: list[float]
neighbor_count: list[float]
neighbor_deg_sum: list[float] | None
th_bar: list[float] | None = None
epi_bar: list[float] | None = None
vf_bar: list[float] | None = None
deg_bar: list[float] | None = None
degs: dict[Any, float] | None = None
deg_list: list[float] | None = None
theta_np: Any | None = None
epi_np: Any | None = None
vf_np: Any | None = None
cos_theta_np: Any | None = None
sin_theta_np: Any | None = None
deg_array: Any | None = None
edge_src: Any | None = None
edge_dst: Any | None = None
checksum: Any | None = None
neighbor_x_np: Any | None = None
neighbor_y_np: Any | None = None
neighbor_epi_sum_np: Any | None = None
neighbor_vf_sum_np: Any | None = None
neighbor_count_np: Any | None = None
neighbor_deg_sum_np: Any | None = None
th_bar_np: Any | None = None
epi_bar_np: Any | None = None
vf_bar_np: Any | None = None
deg_bar_np: Any | None = None
grad_phase_np: Any | None = None
grad_epi_np: Any | None = None
grad_vf_np: Any | None = None
grad_topo_np: Any | None = None
grad_total_np: Any | None = None
dense_components_np: Any | None = None
dense_accum_np: Any | None = None
dense_degree_np: Any | None = None
neighbor_accum_np: Any | None = None
neighbor_inv_count_np: Any | None = None
neighbor_cos_avg_np: Any | None = None
neighbor_sin_avg_np: Any | None = None
neighbor_mean_tmp_np: Any | None = None
neighbor_mean_length_np: Any | None = None
edge_signature: Any | None = None
neighbor_accum_signature: Any | None = None
neighbor_edge_values_np: Any | None = None
def new_dnfr_cache() -> DnfrCache:
"""Return an empty :class:`DnfrCache` prepared for ΔNFR orchestration."""
return DnfrCache(
idx={},
theta=[],
epi=[],
vf=[],
cos_theta=[],
sin_theta=[],
neighbor_x=[],
neighbor_y=[],
neighbor_epi_sum=[],
neighbor_vf_sum=[],
neighbor_count=[],
neighbor_deg_sum=[],
)
@dataclass
class _CacheMetrics:
hits: int = 0
misses: int = 0
evictions: int = 0
total_time: float = 0.0
timings: int = 0
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
def snapshot(self) -> CacheStatistics:
return CacheStatistics(
hits=self.hits,
misses=self.misses,
evictions=self.evictions,
total_time=self.total_time,
timings=self.timings,
)
@dataclass
class _CacheEntry:
factory: Callable[[], Any]
lock: threading.Lock
reset: Callable[[Any], Any] | None = None
encoder: Callable[[Any], Any] | None = None
decoder: Callable[[Any], Any] | None = None
class CacheManager:
"""Coordinate named caches guarded by per-entry locks."""
_MISSING = object()
def __init__(
self,
storage: MutableMapping[str, Any] | None = None,
*,
default_capacity: int | None = None,
overrides: Mapping[str, int | None] | None = None,
layers: Iterable[CacheLayer] | None = None,
) -> None:
mapping_layer = MappingCacheLayer(storage)
extra_layers: tuple[CacheLayer, ...]
if layers is None:
extra_layers = ()
else:
extra_layers = tuple(layers)
for layer in extra_layers:
if not isinstance(
layer, CacheLayer
): # pragma: no cover - defensive typing
raise TypeError(f"unsupported cache layer type: {type(layer)!r}")
self._layers: tuple[CacheLayer, ...] = (mapping_layer, *extra_layers)
self._storage_layer = mapping_layer
self._storage: MutableMapping[str, Any] = mapping_layer.storage
self._entries: dict[str, _CacheEntry] = {}
self._registry_lock = threading.RLock()
self._default_capacity = self._normalise_capacity(default_capacity)
self._capacity_overrides: dict[str, int | None] = {}
self._metrics: dict[str, _CacheMetrics] = {}
self._metrics_publishers: list[Callable[[str, CacheStatistics], None]] = []
if overrides:
self.configure(overrides=overrides)
@staticmethod
def _normalise_capacity(value: int | None) -> int | None:
if value is None:
return None
size = int(value)
if size < 0:
raise TNFRValueError(
"capacity must be non-negative or None",
context={"capacity": value},
)
return size
def register(
self,
name: str,
factory: Callable[[], Any],
*,
lock_factory: Callable[[], threading.Lock | threading.RLock] | None = None,
reset: Callable[[Any], Any] | None = None,
create: bool = True,
encoder: Callable[[Any], Any] | None = None,
decoder: Callable[[Any], Any] | None = None,
) -> None:
"""Register `
ame`` with ``factory`` and optional lifecycle hooks."""
if lock_factory is None:
lock_factory = threading.RLock
with self._registry_lock:
entry = self._entries.get(name)
if entry is None:
entry = _CacheEntry(
factory=factory,
lock=lock_factory(),
reset=reset,
encoder=encoder,
decoder=decoder,
)
self._entries[name] = entry
else:
# Update hooks when re-registering the same cache name.
entry.factory = factory
entry.reset = reset
entry.encoder = encoder
entry.decoder = decoder
self._ensure_metrics(name)
if create:
self.get(name)
def configure(
self,
*,
default_capacity: int | None | object = _MISSING,
overrides: Mapping[str, int | None] | None = None,
replace_overrides: bool = False,
) -> None:
"""Update the cache capacity policy shared by registered entries."""
with self._registry_lock:
if default_capacity is not self._MISSING:
self._default_capacity = self._normalise_capacity(
default_capacity if default_capacity is not None else None
)
if overrides is not None:
if replace_overrides:
self._capacity_overrides.clear()
for key, value in overrides.items():
self._capacity_overrides[key] = self._normalise_capacity(value)
def configure_from_mapping(self, config: Mapping[str, Any]) -> None:
"""Load configuration produced by :meth:`export_config`."""
default = config.get("default_capacity", self._MISSING)
overrides = config.get("overrides")
overrides_mapping: Mapping[str, int | None] | None
overrides_mapping = overrides if isinstance(overrides, Mapping) else None
self.configure(default_capacity=default, overrides=overrides_mapping)
def export_config(self) -> CacheCapacityConfig:
"""Return a copy of the current capacity configuration."""
with self._registry_lock:
return CacheCapacityConfig(
default_capacity=self._default_capacity,
overrides=dict(self._capacity_overrides),
)
def get_capacity(
self,
name: str,
*,
requested: int | None = None,
fallback: int | None = None,
use_default: bool = True,
) -> int | None:
"""Return capacity for `
ame`` considering overrides and defaults."""
with self._registry_lock:
override = self._capacity_overrides.get(name, self._MISSING)
default = self._default_capacity
if override is not self._MISSING:
return override
values: tuple[int | None, ...]
if use_default:
values = (requested, default, fallback)
else:
values = (requested, fallback)
for value in values:
if value is self._MISSING:
continue
normalised = self._normalise_capacity(value)
if normalised is not None:
return normalised
return None
def has_override(self, name: str) -> bool:
"""Return ``True`` if `
ame`` has an explicit capacity override."""
with self._registry_lock:
return name in self._capacity_overrides
def get_lock(self, name: str) -> threading.Lock | threading.RLock:
"""Return the lock guarding cache `
ame`` for external coordination."""
entry = self._entries.get(name)
if entry is None:
raise KeyError(name)
return entry.lock
def names(self) -> Iterator[str]:
"""Iterate over registered cache names."""
with self._registry_lock:
return iter(tuple(self._entries))
def get(self, name: str, *, create: bool = True) -> Any:
"""Return cache `
ame`` creating it on demand when ``create`` is true."""
entry = self._entries.get(name)
if entry is None:
raise KeyError(name)
with entry.lock:
value = self._load_from_layers(name, entry)
if create and value is None:
value = entry.factory()
self._persist_layers(name, entry, value)
return value
def peek(self, name: str) -> Any:
"""Return cache `
ame`` without creating a missing entry."""
entry = self._entries.get(name)
if entry is None:
raise KeyError(name)
with entry.lock:
return self._load_from_layers(name, entry)
def store(self, name: str, value: Any) -> None:
"""Replace the stored value for cache `
ame`` with ``value``."""
entry = self._entries.get(name)
if entry is None:
raise KeyError(name)
with entry.lock:
self._persist_layers(name, entry, value)
def update(
self,
name: str,
updater: Callable[[Any], Any],
*,
create: bool = True,
) -> Any:
"""Apply ``updater`` to cache `
ame`` storing the resulting value."""
entry = self._entries.get(name)
if entry is None:
raise KeyError(name)
with entry.lock:
current = self._load_from_layers(name, entry)
if create and current is None:
current = entry.factory()
new_value = updater(current)
self._persist_layers(name, entry, new_value)
return new_value
def clear(self, name: str | None = None) -> None:
"""Reset caches either selectively or for every registered name."""
if name is not None:
names = (name,)
else:
with self._registry_lock:
names = tuple(self._entries)
for cache_name in names:
entry = self._entries.get(cache_name)
if entry is None:
continue
with entry.lock:
current = self._load_from_layers(cache_name, entry)
new_value = None
if entry.reset is not None:
try:
new_value = entry.reset(current)
except Exception: # pragma: no cover - defensive logging
_logger.exception("cache reset failed for %s", cache_name)
if new_value is None:
try:
new_value = entry.factory()
except Exception:
self._delete_from_layers(cache_name)
continue
self._persist_layers(cache_name, entry, new_value)
# ------------------------------------------------------------------
# Layer orchestration helpers
def _encode_value(self, entry: _CacheEntry, value: Any) -> Any:
encoder = entry.encoder
if encoder is None:
return value
return encoder(value)
def _decode_value(self, entry: _CacheEntry, payload: Any) -> Any:
decoder = entry.decoder
if decoder is None:
return payload
return decoder(payload)
def _store_layer(
self, name: str, entry: _CacheEntry, value: Any, *, layer_index: int
) -> None:
layer = self._layers[layer_index]
if layer_index == 0:
payload = value
else:
try:
payload = self._encode_value(entry, value)
except Exception: # pragma: no cover - defensive logging
_logger.exception("cache encoding failed for %s", name)
return
try:
layer.store(name, payload)
except Exception: # pragma: no cover - defensive logging
_logger.exception(
"cache layer store failed for %s on %s", name, layer.__class__.__name__
)
def _persist_layers(self, name: str, entry: _CacheEntry, value: Any) -> None:
for index in range(len(self._layers)):
self._store_layer(name, entry, value, layer_index=index)
def _delete_from_layers(self, name: str) -> None:
for layer in self._layers:
try:
layer.delete(name)
except KeyError:
continue
except Exception: # pragma: no cover - defensive logging
_logger.exception(
"cache layer delete failed for %s on %s",
name,
layer.__class__.__name__,
)
def _load_from_layers(self, name: str, entry: _CacheEntry) -> Any:
# Primary in-memory layer first for fast-path lookups.
try:
value = self._layers[0].load(name)
except KeyError:
value = None
except Exception: # pragma: no cover - defensive logging
_logger.exception(
"cache layer load failed for %s on %s",
name,
self._layers[0].__class__.__name__,
)
value = None
if value is not None:
return value
# Fall back to slower layers and hydrate preceding caches on success.
for index in range(1, len(self._layers)):
layer = self._layers[index]
try:
payload = layer.load(name)
except KeyError:
continue
except Exception: # pragma: no cover - defensive logging
_logger.exception(
"cache layer load failed for %s on %s",
name,
layer.__class__.__name__,
)
continue
try:
value = self._decode_value(entry, payload)
except Exception: # pragma: no cover - defensive logging
_logger.exception("cache decoding failed for %s", name)
continue
if value is None:
continue
for prev_index in range(index):
self._store_layer(name, entry, value, layer_index=prev_index)
return value
return None
# ------------------------------------------------------------------
# Metrics helpers
def _ensure_metrics(self, name: str) -> _CacheMetrics:
metrics = self._metrics.get(name)
if metrics is None:
with self._registry_lock:
metrics = self._metrics.get(name)
if metrics is None:
metrics = _CacheMetrics()
self._metrics[name] = metrics
return metrics
def increment_hit(
self,
name: str,
*,
amount: int = 1,
duration: float | None = None,
) -> None:
"""Increase cache hit counters for `
ame`` (optionally logging latency)."""
metrics = self._ensure_metrics(name)
with metrics.lock:
metrics.hits += int(amount)
if duration is not None:
metrics.total_time += float(duration)
metrics.timings += 1
def increment_miss(
self,
name: str,
*,
amount: int = 1,
duration: float | None = None,
) -> None:
"""Increase cache miss counters for `
ame`` (optionally logging latency)."""
metrics = self._ensure_metrics(name)
with metrics.lock:
metrics.misses += int(amount)
if duration is not None:
metrics.total_time += float(duration)
metrics.timings += 1
def increment_eviction(self, name: str, *, amount: int = 1) -> None:
"""Increase eviction count for cache `
ame``."""
metrics = self._ensure_metrics(name)
with metrics.lock:
metrics.evictions += int(amount)
def record_timing(self, name: str, duration: float) -> None:
"""Accumulate ``duration`` into latency telemetry for `
ame``."""
metrics = self._ensure_metrics(name)
with metrics.lock:
metrics.total_time += float(duration)
metrics.timings += 1
@contextmanager
def timer(self, name: str) -> TimingContext:
"""Context manager recording execution time for `
ame``."""
start = perf_counter()
try:
yield
finally:
self.record_timing(name, perf_counter() - start)
def get_metrics(self, name: str) -> CacheStatistics:
"""Return a snapshot of telemetry collected for cache `
ame``."""
metrics = self._metrics.get(name)
if metrics is None:
return CacheStatistics()
with metrics.lock:
return metrics.snapshot()
def iter_metrics(self) -> Iterator[tuple[str, CacheStatistics]]:
"""Yield ``(name, stats)`` pairs for every cache with telemetry."""
with self._registry_lock:
items = tuple(self._metrics.items())
for name, metrics in items:
with metrics.lock:
yield name, metrics.snapshot()
def aggregate_metrics(self) -> CacheStatistics:
"""Return aggregated telemetry statistics across all caches."""
aggregate = CacheStatistics()
for _, stats in self.iter_metrics():
aggregate = aggregate.merge(stats)
return aggregate
def register_metrics_publisher(
self, publisher: Callable[[str, CacheStatistics], None]
) -> None:
"""Register ``publisher`` to receive metrics snapshots on demand."""
with self._registry_lock:
self._metrics_publishers.append(publisher)
def publish_metrics(
self,
*,
publisher: Callable[[str, CacheStatistics], None] | None = None,
) -> None:
"""Send cached telemetry to ``publisher`` or all registered publishers."""
if publisher is None:
with self._registry_lock:
publishers = tuple(self._metrics_publishers)
else:
publishers = (publisher,)
if not publishers:
return
snapshot = tuple(self.iter_metrics())
for emit in publishers:
for name, stats in snapshot:
try:
emit(name, stats)
except Exception: # pragma: no cover - defensive logging
_logger.exception("Cache metrics publisher failed for %s", name)
def log_metrics(self, logger: logging.Logger, *, level: int = logging.INFO) -> None:
"""Emit cache metrics using ``logger`` for telemetry hooks."""
for name, stats in self.iter_metrics():
logger.log(
level,
"cache=%s hits=%d misses=%d evictions=%d timings=%d total_time=%.6f",
name,
stats.hits,
stats.misses,
stats.evictions,
stats.timings,
stats.total_time,
)
try:
from .init import get_logger as _get_logger
except ImportError: # pragma: no cover - circular bootstrap fallback
def _get_logger(name: str) -> logging.Logger:
return logging.getLogger(name)
_logger = _get_logger(__name__)
get_logger = _get_logger
def prune_lock_mapping(
cache: Mapping[K, Any] | MutableMapping[K, Any] | None,
locks: MutableMapping[K, Any] | None,
) -> None:
"""Drop lock entries not present in ``cache``."""
if locks is None:
return
if cache is None:
cache_keys: set[K] = set()
else:
cache_keys = set(cache.keys())
for key in list(locks.keys()):
if key not in cache_keys:
locks.pop(key, None)
# Compatibility names share the maintained LRU implementation.
InstrumentedLRUCache = UnifiedLRUCache
ManagedLRUCache = UnifiedLRUCache
@dataclass
class _SeedCacheState:
"""Container tracking the state for :class:`_SeedHashCache`."""
cache: InstrumentedLRUCache[tuple[int, int], int] | None
maxsize: int
@dataclass
class _CounterState(Generic[K]):
"""State bundle used by :class:`ScopedCounterCache`."""
cache: InstrumentedLRUCache[K, int]
locks: dict[K, threading.RLock]
max_entries: int
# Key used to store the node set checksum in a graph's ``graph`` attribute.
NODE_SET_CHECKSUM_KEY = "_node_set_checksum_cache"
logger = _logger
# Helper to avoid importing ``tnfr.utils.init`` at module import time and keep
# circular dependencies at bay while still reusing the canonical numpy loader.
def _require_numpy():
from ..mathematics.unified_numerical import np
return np
# Graph key storing per-graph layer configuration overrides.
_GRAPH_CACHE_LAYERS_KEY = "_tnfr_cache_layers"
# Process-wide configuration for shared cache layers (Shelve/Redis).
_GLOBAL_CACHE_LAYER_CONFIG: dict[str, dict[str, Any]] = {}
_GLOBAL_CACHE_LOCK = threading.RLock()
_GLOBAL_CACHE_MANAGER: CacheManager | None = None
# Keys of cache entries dependent on the edge version. Any change to the edge
# set requires these to be dropped to avoid stale data.
EDGE_VERSION_CACHE_KEYS = ("_trig_version",)
def get_graph_version(graph: Any, key: str, default: int = 0) -> int:
"""Return integer version stored in ``graph`` under ``key``."""
return int(graph.get(key, default))
def increment_graph_version(graph: Any, key: str) -> int:
"""Increment and store a version counter in ``graph`` under ``key``."""
version = get_graph_version(graph, key) + 1
graph[key] = version
return version
def stable_json(obj: Any) -> str:
"""Return a JSON string with deterministic ordering for ``obj``."""
from .io import json_dumps
return json_dumps(
obj,
sort_keys=True,
ensure_ascii=False,
to_bytes=False,
)
def _compute_node_repr_digest(obj: Any) -> tuple[str, bytes]:
"""Serialize one label without using node equality as a cache identity."""
try:
repr_ = stable_json(obj)
except TypeError:
repr_ = repr(obj)
digest = hashlib.blake2b(repr_.encode("utf-8"), digest_size=16).digest()
return repr_, digest
class _NodeIdentityKey:
"""Keep a label alive while its bounded digest entry uses object identity."""
__slots__ = ("node",)
def __init__(self, node: Any) -> None:
self.node = node
def __hash__(self) -> int:
return id(self.node)
def __eq__(self, other: object) -> bool:
return isinstance(other, _NodeIdentityKey) and self.node is other.node
@lru_cache(maxsize=1024, typed=True)
def _cached_node_repr_digest(key: _NodeIdentityKey) -> tuple[str, bytes]:
return _compute_node_repr_digest(key.node)
def _node_repr_digest(obj: Any) -> tuple[str, bytes]:
"""Return a stable digest cached for the actual node object.
Identity is only an in-process cache key; it never enters serialization or
digest bytes. Keeping the object in a bounded key prevents id reuse while
separating equal labels with different nested types or representations.
"""
return _cached_node_repr_digest(_NodeIdentityKey(obj))
# Preserve the existing functools cache diagnostics and uncached entry point.
_node_repr_digest.cache_info = _cached_node_repr_digest.cache_info # type: ignore[attr-defined]
_node_repr_digest.cache_clear = _cached_node_repr_digest.cache_clear # type: ignore[attr-defined]
_node_repr_digest.cache_parameters = _cached_node_repr_digest.cache_parameters # type: ignore[attr-defined]
_node_repr_digest.__wrapped__ = _compute_node_repr_digest # type: ignore[attr-defined]
def clear_node_repr_cache() -> None:
"""Clear cached node representations used for checksums."""
_cached_node_repr_digest.cache_clear()
def configure_global_cache_layers(
*,
shelve: Mapping[str, Any] | None = None,
redis: Mapping[str, Any] | None = None,
replace: bool = False,
) -> None:
"""Update process-wide cache layer configuration.
Parameters mirror the per-layer specifications accepted via graph metadata.
Passing ``replace=True`` clears previous settings before applying new ones.
Providing ``None`` for a layer while ``replace`` is true removes that layer
from the configuration.
"""
global _GLOBAL_CACHE_MANAGER
with _GLOBAL_CACHE_LOCK:
manager = _GLOBAL_CACHE_MANAGER
_GLOBAL_CACHE_MANAGER = None
if replace:
_GLOBAL_CACHE_LAYER_CONFIG.clear()
if shelve is not None:
_GLOBAL_CACHE_LAYER_CONFIG["shelve"] = dict(shelve)
elif replace:
_GLOBAL_CACHE_LAYER_CONFIG.pop("shelve", None)
if redis is not None:
_GLOBAL_CACHE_LAYER_CONFIG["redis"] = dict(redis)
elif replace:
_GLOBAL_CACHE_LAYER_CONFIG.pop("redis", None)
_close_cache_layers(manager)
def _resolve_layer_config(
graph: MutableMapping[str, Any] | None,
) -> dict[str, dict[str, Any]]:
resolved: dict[str, dict[str, Any]] = {}
with _GLOBAL_CACHE_LOCK:
for name, spec in _GLOBAL_CACHE_LAYER_CONFIG.items():
resolved[name] = dict(spec)
if graph is not None:
overrides = graph.get(_GRAPH_CACHE_LAYERS_KEY)
if isinstance(overrides, Mapping):
for name in ("shelve", "redis"):
layer_spec = overrides.get(name)
if isinstance(layer_spec, Mapping):
resolved[name] = dict(layer_spec)
elif layer_spec is None:
resolved.pop(name, None)
return resolved
def _build_shelve_layer(spec: Mapping[str, Any]) -> ShelveCacheLayer | None:
path = spec.get("path")
if not path:
return None
flag = spec.get("flag", "c")
protocol = spec.get("protocol")
writeback = bool(spec.get("writeback", False))
try:
proto_arg = None if protocol is None else int(protocol)
except (TypeError, ValueError):
logger.warning("Invalid shelve protocol %r; falling back to default", protocol)
proto_arg = None
try:
return ShelveCacheLayer(
str(path),
flag=str(flag),
protocol=proto_arg,
writeback=writeback,
)
except Exception: # pragma: no cover - defensive logging
logger.exception("Failed to initialise ShelveCacheLayer for path %r", path)
return None
def _build_redis_layer(spec: Mapping[str, Any]) -> RedisCacheLayer | None:
enabled = spec.get("enabled", True)
if not enabled:
return None
namespace = spec.get("namespace")
client = spec.get("client")
if client is None:
factory = spec.get("client_factory")
if callable(factory):
try:
client = factory()
except Exception: # pragma: no cover - defensive logging
logger.exception("Redis cache client factory failed")
return None
else:
kwargs = spec.get("client_kwargs")
if isinstance(kwargs, Mapping):
try: # pragma: no cover - optional dependency
import redis # type: ignore
except Exception: # pragma: no cover - defensive logging
logger.exception(
"redis-py is required to build the configured Redis client"
)
return None
try:
client = redis.Redis(**dict(kwargs))
except Exception: # pragma: no cover - defensive logging
logger.exception(
"Failed to initialise redis client with %r", kwargs
)