python-wrap 0.2.1__py3-none-any.whl → 0.4.0__py3-none-any.whl

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 (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/caching.py CHANGED
@@ -9,8 +9,9 @@ import contextvars
9
9
  import datetime
10
10
  import functools
11
11
  import inspect
12
+ import random
12
13
  import threading
13
- import time
14
+ import uuid
14
15
  import weakref
15
16
  from collections import OrderedDict
16
17
  from collections.abc import Awaitable, Callable, Coroutine, Hashable
@@ -26,7 +27,8 @@ from typing import (
26
27
  runtime_checkable,
27
28
  )
28
29
 
29
- from python_wrap import _core
30
+ from python_wrap import _core, _fork
31
+ from python_wrap._runtime import digest, stable_digest
30
32
 
31
33
  __all__ = [
32
34
  "CacheInfo",
@@ -34,9 +36,11 @@ __all__ = [
34
36
  "CachedProperty",
35
37
  "Memoized",
36
38
  "Once",
39
+ "ainvalidate_tags",
37
40
  "cache",
38
41
  "cached_property",
39
42
  "invalidate",
43
+ "invalidate_tags",
40
44
  "memoize",
41
45
  "once",
42
46
  ]
@@ -56,7 +60,7 @@ class CacheInfo(NamedTuple):
56
60
  hits: int
57
61
  misses: int
58
62
  maxsize: int | None
59
- currsize: int
63
+ currsize: int | None
60
64
 
61
65
 
62
66
  class Memoized(Protocol[P, R_co]):
@@ -114,7 +118,7 @@ class Memoized(Protocol[P, R_co]):
114
118
  """
115
119
 
116
120
  def cache_parameters(self) -> dict[str, Any]:
117
- """The options: ``maxsize``, ``ttl``, ``typed``, ``cache_exceptions``, ``exception_ttl``."""
121
+ """Return configuration, including TTL, key behavior and result-copy isolation."""
118
122
 
119
123
 
120
124
  class _MemoizedOnClass(Memoized[P, R_co], Protocol[P, P2, R_co]):
@@ -396,10 +400,7 @@ def _fast_arity(func: Callable[..., Any], typed: bool, key: Callable[..., Hashab
396
400
  # (equal to ``expires`` unless ``stale_ttl`` is set).
397
401
  _EXPIRED: Any = ()
398
402
 
399
- # Deadlines in entries given to a custom `CacheStore` are Unix-epoch seconds, so processes
400
- # sharing one store agree on them. They are still read through ``_core.monotonic()`` (plus
401
- # this constant offset) so ``fake_clock`` drives them too.
402
- _WALL_OFFSET = time.time() - time.monotonic()
403
+ # External-store deadlines use the live Unix wall clock; fake_clock patches it too.
403
404
 
404
405
 
405
406
  @runtime_checkable
@@ -414,6 +415,10 @@ class CacheStore(Protocol):
414
415
  * ``delete(key)`` removes the entry and returns True if there was one.
415
416
  * ``clear()`` removes every entry.
416
417
  * ``__len__()`` is the number of stored entries (``cache_info().currsize``).
418
+ Network adapters may additionally expose ``size() -> int | None``; memoize uses
419
+ that method when present. Return None for an unknown count rather than scanning
420
+ a remote database on every stats read. ``__len__`` must still return a nonnegative
421
+ integer for normal Python compatibility.
417
422
 
418
423
  Contract:
419
424
 
@@ -522,6 +527,100 @@ class _LocalStore:
522
527
  return (ttl_evicted << 32) | lru_evicted
523
528
 
524
529
 
530
+ # -- cache tags: one version token per tag; entries record the tokens they were written under
531
+ _TAG_PREFIX = "python-wrap:tag:"
532
+ _local_tags: dict[str, str] = {}
533
+ _MAX_LOCAL_TAGS = 10_000
534
+ # Bumped when _local_tags is cleared, so every entry written before reads as stale
535
+ # (never as fresh, which a plain eviction could cause).
536
+ _tag_epoch = [0]
537
+ # Weak on purpose: a client nothing else holds can no longer write through a store, so
538
+ # it needs no invalidation. A strong registry kept every client alive for the whole
539
+ # process, and one closed client made invalidate_tags fail for every tag.
540
+ _tag_clients: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
541
+ _async_tag_clients: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
542
+ _tag_store_owners: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
543
+ _async_tag_store_owners: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary()
544
+ _tag_registry_lock = threading.RLock()
545
+
546
+
547
+ def _register_tag_client(
548
+ registry: weakref.WeakValueDictionary[int, Any],
549
+ owner_registry: weakref.WeakValueDictionary[int, Any],
550
+ client: Any,
551
+ owner: Any,
552
+ ) -> None:
553
+ try:
554
+ with _tag_registry_lock:
555
+ registry[id(client)] = client
556
+ except TypeError:
557
+ # Track the store instead when a compatible client disallows weak references.
558
+ # The memoized wrapper owns that store and it owns the client.
559
+ with _tag_registry_lock:
560
+ owner_registry[id(owner)] = owner
561
+
562
+
563
+ def _tag_client_targets(
564
+ registry: weakref.WeakValueDictionary[int, Any],
565
+ owner_registry: weakref.WeakValueDictionary[int, Any],
566
+ client: Any,
567
+ ) -> list[Any]:
568
+ with _tag_registry_lock:
569
+ targets = dict(registry.items())
570
+ owners = list(owner_registry.values())
571
+ for owner in owners:
572
+ target = getattr(owner, "client", None)
573
+ if target is not None:
574
+ targets[id(target)] = target
575
+ if client is not None:
576
+ targets[id(client)] = client
577
+ return list(targets.values())
578
+
579
+
580
+ def _decode(value: Any) -> str:
581
+ return value.decode() if isinstance(value, bytes) else str(value or "")
582
+
583
+
584
+ def _tag_versions(names: list[str], client: Any) -> dict[str, str] | None:
585
+ """Current token per tag (from Redis when shared); None if the store cannot answer."""
586
+ if client is None:
587
+ return {n: f"{_tag_epoch[0]}:{_local_tags.get(n, '')}" for n in names}
588
+ try:
589
+ return {n: _decode(client.get(_TAG_PREFIX + digest(n))) for n in names}
590
+ except Exception: # an unknown version must read as a miss, never as a hit
591
+ return None
592
+
593
+
594
+ def _remember_local(name: str, token: str) -> None:
595
+ if len(_local_tags) >= _MAX_LOCAL_TAGS and name not in _local_tags:
596
+ _local_tags.clear() # tag names may come from data: bound the memory
597
+ _tag_epoch[0] += 1
598
+ _local_tags[name] = token
599
+
600
+
601
+ def invalidate_tags(*names: str, client: Any = None) -> None:
602
+ """Make every cached entry written with one of these tags miss on its next read.
603
+
604
+ Each tag gets a new version token: in this process, and in Redis through every
605
+ sync client used by a ``memoize(tags=..., store=RedisStore(...))`` here (and
606
+ ``client`` when given). One write per tag, no scan. Async clients: `ainvalidate_tags`.
607
+ """
608
+ for name in names:
609
+ token = uuid.uuid4().hex
610
+ _remember_local(name, token)
611
+ for target in _tag_client_targets(_tag_clients, _tag_store_owners, client):
612
+ target.set(_TAG_PREFIX + digest(name), token)
613
+
614
+
615
+ async def ainvalidate_tags(*names: str, client: Any = None) -> None:
616
+ """`invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore)."""
617
+ for name in names:
618
+ token = uuid.uuid4().hex
619
+ _remember_local(name, token)
620
+ for target in _tag_client_targets(_async_tag_clients, _async_tag_store_owners, client):
621
+ await target.set(_TAG_PREFIX + digest(name), token)
622
+
623
+
525
624
  @overload
526
625
  def memoize(func: Callable[P, R], /) -> Memoized[P, R]: ...
527
626
  @overload
@@ -538,7 +637,14 @@ def memoize(
538
637
  exception_ttl: float | datetime.timedelta | None = None,
539
638
  store: CacheStore | None = None,
540
639
  per_instance: bool = False,
640
+ singleflight: bool = False,
641
+ copy_result: bool = False,
541
642
  logger: _core.LoggerLike = None,
643
+ lock: Any = None,
644
+ lock_ttl: float = 30,
645
+ lock_wait: float = 5,
646
+ tags: Callable[..., Any] | None = None,
647
+ ttl_jitter: float = 0.0,
542
648
  ) -> Callable[[Callable[P, R]], Memoized[P, R]]: ...
543
649
  def memoize(
544
650
  func: Callable[..., Any] | None = None,
@@ -553,7 +659,14 @@ def memoize(
553
659
  exception_ttl: float | datetime.timedelta | None = None,
554
660
  store: CacheStore | None = None,
555
661
  per_instance: bool = False,
662
+ singleflight: bool = False,
663
+ copy_result: bool = False,
556
664
  logger: _core.LoggerLike = None,
665
+ lock: Any = None,
666
+ lock_ttl: float = 30,
667
+ lock_wait: float = 5,
668
+ tags: Callable[..., Any] | None = None,
669
+ ttl_jitter: float = 0.0,
557
670
  ) -> Any:
558
671
  """Cache a function's results per argument values.
559
672
 
@@ -567,9 +680,10 @@ def memoize(
567
680
  keeps growing; raise a fresh exception from a ``except`` clause if that matters).
568
681
  The cache is guarded by a lock. For sync functions two threads that miss on the same
569
682
  key at the same time may both compute the value (the function itself is never called
570
- under the lock); the last result stored wins. For ``async def`` functions the awaited
571
- result is cached and concurrent awaits of the same missing key share a single
572
- in-flight task per event loop, so it runs once.
683
+ under the lock); the last result stored wins -- pass ``singleflight=True`` to make the
684
+ other threads wait for the first one's outcome instead. For ``async def`` functions
685
+ the awaited result is cached and concurrent awaits of the same missing key share a
686
+ single in-flight task per event loop, so it runs once.
573
687
 
574
688
  Stale-while-revalidate: with ``stale_ttl`` an entry older than ``ttl`` is *stale* but
575
689
  still served, immediately, for ``stale_ttl`` more seconds; the call that finds it
@@ -586,7 +700,16 @@ def memoize(
586
700
  its own cache, found by identity through a weak reference, so instances stay
587
701
  collectable (their entries go with them) and need not be hashable. They must be
588
702
  weak-referenceable (a ``__slots__`` class must list ``'__weakref__'``), and a cached
589
- result that references its instance keeps it alive.
703
+ result that references its instance keeps it alive. `python_wrap.doctor` flags a
704
+ method cache keyed on ``self`` with no ``maxsize``, ``ttl`` or ``store`` (PW011).
705
+
706
+ Mutable results are shared by reference by default. Set ``copy_result=True`` to
707
+ deepcopy a private snapshot on write and return an independent deepcopy to each
708
+ caller (including concurrent async miss waiters and ``cache_get``). The first
709
+ caller cannot mutate the cache, and mutations to an externally retained original
710
+ result cannot alter the snapshot. Copies follow Python's ``deepcopy`` protocol;
711
+ unsupported values raise TypeError rather than falling back to a shared object.
712
+ Cached exceptions are never copied. Copying occurs outside the cache lock.
590
713
 
591
714
  The wrapper has ``cache_clear()``, ``cache_info()`` (a `CacheInfo`),
592
715
  ``cache_delete(*args, **kwargs)``, ``cache_contains(*args, **kwargs)``,
@@ -620,7 +743,25 @@ def memoize(
620
743
  store: A `CacheStore` to keep entries in instead of the built-in LRU dict.
621
744
  per_instance: For methods: one cache per instance, held through a weak
622
745
  reference, keyed by the arguments after ``self``.
746
+ singleflight: Sync functions: concurrent misses on the same key (in different
747
+ threads) run the function once; the other threads wait and get the same
748
+ result, or the same exception. A call that shares another thread's computation
749
+ counts as a hit. A re-entrant call on the computing thread computes directly.
750
+ ``async def`` functions already behave this way, so it changes nothing there.
751
+ copy_result: Deepcopy successful values on write and on delivery. False keeps
752
+ the existing shared-reference behavior. Does not apply while caching is disabled.
623
753
  logger: Logger (or name) for failed background refreshes.
754
+ lock: A lease backend (`RedisLock`, `AsyncRedisLock`, ...) shared by every
755
+ process. On a miss one process holds a lease on the cache key and computes;
756
+ the others wait up to ``lock_wait`` seconds, read the store again, and
757
+ compute only if the entry is still absent. Stale refreshes take the same
758
+ lease without waiting, so one process refreshes. Needs ``store``.
759
+ lock_ttl: Seconds the stampede lease lives (renewed while computing).
760
+ lock_wait: Seconds a process waits for another's computation.
761
+ tags: ``tags(*args, **kwargs)`` returning tag names for the entry; see
762
+ `invalidate_tags`. Each tag costs one store read per hit.
763
+ ttl_jitter: Shorten each entry's ttl by a random share up to this (0 to 1), so
764
+ entries written together do not expire together.
624
765
 
625
766
  Returns:
626
767
  The wrapped function, or a decorator when called with options.
@@ -632,7 +773,8 @@ def memoize(
632
773
  `CacheStore`, ``store`` combined with ``maxsize`` or ``per_instance``, or
633
774
  ``per_instance`` on a function without parameters. At call time, for an
634
775
  unhashable argument (see above) or, with ``per_instance``, an instance that
635
- cannot be weakly referenced.
776
+ cannot be weakly referenced. Also if copy_result is not bool or a result
777
+ cannot be deep-copied with copy_result=True (original error is chained).
636
778
 
637
779
  Example:
638
780
  >>> @memoize(maxsize=128, ttl=60)
@@ -643,6 +785,23 @@ def memoize(
643
785
  >>> square.cache_info().hits
644
786
  1
645
787
  """
788
+ if not isinstance(copy_result, bool):
789
+ raise TypeError("copy_result must be bool")
790
+ if not isinstance(singleflight, bool):
791
+ raise TypeError("singleflight must be bool")
792
+ copier: Callable[[Any], Any] | None = None
793
+ if copy_result:
794
+ from copy import deepcopy
795
+
796
+ copier = deepcopy
797
+ if lock is not None and store is None:
798
+ raise ValueError("lock= coordinates processes through a shared store; pass store=")
799
+ if not 0 <= ttl_jitter < 1:
800
+ raise ValueError("ttl_jitter must be in [0, 1)")
801
+ lock_backend = lock # the name `lock` is reused below for the cache's own mutex
802
+ tag_client = getattr(store, "client", None) if tags is not None else None
803
+ if tag_client is not None:
804
+ _register_tag_client(_tag_clients, _tag_store_owners, tag_client, store)
646
805
  if maxsize is not None and maxsize < 1:
647
806
  raise ValueError("maxsize must be a positive integer or None")
648
807
  if store is not None:
@@ -677,7 +836,7 @@ def memoize(
677
836
  else:
678
837
 
679
838
  def now() -> float:
680
- return _core.monotonic() + _WALL_OFFSET
839
+ return _core.wall_time()
681
840
 
682
841
  def decorate(f: Callable[..., Any]) -> Any:
683
842
  build_key = _make_key_builder(f, typed, key, skip_first=per_instance)
@@ -685,6 +844,19 @@ def memoize(
685
844
  if per_instance and fast_n == 0:
686
845
  raise TypeError("per_instance=True needs a method (a function taking self)")
687
846
  name = _core.qualname(f)
847
+
848
+ def isolate(value: Any) -> Any:
849
+ # Never copy while holding a cache lock: user __deepcopy__ methods may
850
+ # inspect cache_info(), invalidate entries, or call other cached functions.
851
+ if copier is None:
852
+ return value
853
+ try:
854
+ return copier(value)
855
+ except Exception as exc:
856
+ raise TypeError(
857
+ f"memoize(copy_result=True) could not deepcopy the result of {name}"
858
+ ) from exc
859
+
688
860
  main: Any = _LocalStore(maxsize, expiring) if builtin else store
689
861
  # per_instance: id(instance) -> (weak reference, that instance's store)
690
862
  instances: dict[int, tuple[weakref.ref[Any], _LocalStore]] = {}
@@ -693,8 +865,10 @@ def memoize(
693
865
  asyncio.AbstractEventLoop, dict[Hashable, asyncio.Future[Any]]
694
866
  ] = weakref.WeakKeyDictionary()
695
867
  refreshing: set[Hashable] = set() # sync keys being refreshed in a thread
868
+ # singleflight, sync: key -> (future of the computing thread's outcome, its thread id)
869
+ sync_flights: dict[Hashable, tuple[concurrent.futures.Future[Any], int]] = {}
696
870
  background: set[asyncio.Future[Any]] = set() # strong refs to refresh tasks
697
- lock = threading.Lock()
871
+ lock = _fork.ForkSafeLock()
698
872
  guard: Any = lock if builtin else contextlib.nullcontext()
699
873
  hits = misses = gen = 0
700
874
 
@@ -760,13 +934,23 @@ def memoize(
760
934
  continue
761
935
  return [b for ref, b in slots if ref() is not None]
762
936
 
937
+ def outdated(entry: Any) -> bool:
938
+ """A tagged entry whose tags were invalidated after it was written."""
939
+ if len(entry) < 5 or not entry[4]:
940
+ return False
941
+ return bool(_tag_versions(list(entry[4]), tag_client) != entry[4])
942
+
943
+ def snapshot_tags(args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
944
+ # Read before computing: an invalidation during the call leaves it stale.
945
+ return None if tags is None else _tag_versions(list(tags(*args, **kwargs)), tag_client)
946
+
763
947
  def fetch(b: Any, k: Hashable) -> Any:
764
948
  # Caller holds ``guard``.
765
949
  entry = b.get(k)
766
950
  if entry is None:
767
951
  return None
768
952
  expires = entry[1]
769
- if expires is not None and now() >= expires:
953
+ if (expires is not None and now() >= expires) or (tags is not None and outdated(entry)):
770
954
  b.delete(k)
771
955
  return _EXPIRED
772
956
  if lru:
@@ -779,26 +963,33 @@ def memoize(
779
963
  def report_expired() -> None:
780
964
  _core.emit("cache.evicted", name, reason="ttl")
781
965
 
782
- def save(b: Any, k: Hashable, value: Any, g: int, is_exc: bool = False) -> None:
966
+ def save(
967
+ b: Any, k: Hashable, value: Any, g: int, is_exc: bool = False, tv: Any = None
968
+ ) -> Any:
783
969
  if is_exc:
784
970
  seconds = exc_ttl_s
785
971
  elif ttl_fn is not None:
786
972
  seconds = ttl_fn(value)
787
- if seconds is not None and seconds <= 0:
788
- return # not worth storing
789
973
  else:
790
974
  seconds = ttl_s
975
+ if ttl_jitter and seconds:
976
+ seconds *= 1 - random.random() * ttl_jitter # nosec B311 - not security
977
+ snapshot = isolate(value) if copy_result and not is_exc else value
978
+ if not is_exc and seconds is not None and seconds <= 0:
979
+ return snapshot # not stored, but async waiters still need a private outcome
791
980
  keep = seconds
792
981
  if seconds is not None and stale_s is not None and not is_exc:
793
982
  keep = seconds + stale_s
794
983
  evicted = 0
795
984
  with guard:
796
985
  if g != gen:
797
- return # cache_clear() ran while computing
986
+ return snapshot # cache_clear() ran while computing
798
987
  t = now()
799
988
  fresh = None if seconds is None else t + seconds
800
989
  expires = None if keep is None else t + keep
801
- entry = (value, expires, is_exc, fresh)
990
+ entry: tuple[Any, ...] = (snapshot, expires, is_exc, fresh)
991
+ if tags is not None:
992
+ entry = (*entry, tv)
802
993
  if builtin:
803
994
  evicted = b.put(k, entry)
804
995
  else:
@@ -808,6 +999,63 @@ def memoize(
808
999
  report_expired()
809
1000
  for _ in range(evicted & 0xFFFFFFFF):
810
1001
  _core.emit("cache.evicted", name, reason="lru")
1002
+ return snapshot
1003
+
1004
+ def lease_for(k: Hashable, wait: bool) -> Any:
1005
+ from python_wrap.coordination import Lease
1006
+
1007
+ return Lease(
1008
+ f"memo:{digest(name)}:{stable_digest(k)}",
1009
+ backend=lock_backend,
1010
+ ttl=lock_ttl,
1011
+ wait=wait,
1012
+ timeout=lock_wait if wait else None,
1013
+ )
1014
+
1015
+ def cached_outcome(b: Any, k: Hashable) -> tuple[bool, Any]:
1016
+ with guard:
1017
+ entry = fetch(b, k)
1018
+ if not entry:
1019
+ return False, None
1020
+ if entry[2]:
1021
+ raise entry[0]
1022
+ return True, entry[0]
1023
+
1024
+ def once_across_processes(b: Any, k: Hashable, run: Callable[[], Any]) -> Any:
1025
+ """Run ``run()`` (returns ``(snapshot, result)``) unless another process did."""
1026
+ from python_wrap.coordination import AlreadyRunning
1027
+
1028
+ lease = lease_for(k, True)
1029
+ try:
1030
+ lease.__enter__()
1031
+ except AlreadyRunning:
1032
+ lease = None # waited lock_wait: use its result if it landed, else compute
1033
+ try:
1034
+ found, value = cached_outcome(b, k)
1035
+ return (value, value) if found else run()
1036
+ finally:
1037
+ if lease is not None:
1038
+ with contextlib.suppress(Exception):
1039
+ lease.__exit__(None, None, None)
1040
+
1041
+ async def aonce_across_processes(
1042
+ b: Any, k: Hashable, run: Callable[[], Awaitable[Any]]
1043
+ ) -> Any:
1044
+ """Async `once_across_processes`; ``run()`` returns the saved result."""
1045
+ from python_wrap.coordination import AlreadyRunning
1046
+
1047
+ lease = lease_for(k, True)
1048
+ try:
1049
+ await lease.__aenter__()
1050
+ except AlreadyRunning:
1051
+ lease = None
1052
+ try:
1053
+ found, value = cached_outcome(b, k)
1054
+ return value if found else await run()
1055
+ finally:
1056
+ if lease is not None:
1057
+ with contextlib.suppress(Exception):
1058
+ await lease.__aexit__(None, None, None)
811
1059
 
812
1060
  def refresh_failed(exc: BaseException) -> None:
813
1061
  _core.get_logger(logger).warning(
@@ -828,11 +1076,25 @@ def memoize(
828
1076
  g = gen
829
1077
 
830
1078
  def run() -> None:
1079
+ from python_wrap.coordination import AlreadyRunning
1080
+
1081
+ lease = None
831
1082
  try:
832
- save(b, k, f(*args, **kwargs), g)
1083
+ if lock_backend is not None:
1084
+ lease = lease_for(k, False)
1085
+ try:
1086
+ lease.__enter__()
1087
+ except AlreadyRunning:
1088
+ lease = None
1089
+ return # another process is refreshing this key
1090
+ tv = snapshot_tags(args, kwargs)
1091
+ save(b, k, f(*args, **kwargs), g, tv=tv)
833
1092
  except Exception as exc:
834
1093
  refresh_failed(exc)
835
1094
  finally:
1095
+ if lease is not None:
1096
+ with contextlib.suppress(Exception):
1097
+ lease.__exit__(None, None, None)
836
1098
  with lock:
837
1099
  refreshing.discard(rk)
838
1100
 
@@ -864,14 +1126,31 @@ def memoize(
864
1126
  g = gen
865
1127
  shared_fut = loop_inflight[rk] = _shared_future()
866
1128
 
1129
+ async def refresh() -> Any:
1130
+ tv = snapshot_tags(args, kwargs)
1131
+ return save(b, k, await f(*args, **kwargs), g, tv=tv)
1132
+
867
1133
  async def run() -> Any:
1134
+ from python_wrap.coordination import AlreadyRunning
1135
+
868
1136
  try:
869
- result = await f(*args, **kwargs)
870
- save(b, k, result, g)
1137
+ if lock_backend is None:
1138
+ return await refresh()
1139
+ lease = lease_for(k, False)
1140
+ try:
1141
+ await lease.__aenter__()
1142
+ except AlreadyRunning: # another process refreshes: keep the stale value
1143
+ with guard:
1144
+ entry = b.get(k)
1145
+ return None if entry is None else entry[0]
1146
+ try:
1147
+ return await refresh()
1148
+ finally:
1149
+ with contextlib.suppress(Exception):
1150
+ await lease.__aexit__(None, None, None)
871
1151
  except Exception as exc:
872
1152
  refresh_failed(exc)
873
1153
  raise
874
- return result
875
1154
 
876
1155
  def done(_t: asyncio.Future[Any] | None) -> None:
877
1156
  with lock:
@@ -898,6 +1177,7 @@ def memoize(
898
1177
 
899
1178
  def cache_info() -> CacheInfo:
900
1179
  expired = 0
1180
+ size: int | None = 0
901
1181
  with lock:
902
1182
  if per_instance:
903
1183
  buckets = live_buckets()
@@ -909,7 +1189,8 @@ def memoize(
909
1189
  size = len(main)
910
1190
  info = (hits, misses)
911
1191
  if not builtin:
912
- size = len(main)
1192
+ size_fn = getattr(main, "size", None)
1193
+ size = size_fn() if callable(size_fn) else len(main)
913
1194
  if _core.listeners:
914
1195
  for _ in range(expired):
915
1196
  report_expired()
@@ -943,7 +1224,7 @@ def memoize(
943
1224
  raise KeyError("no cached entry for these arguments")
944
1225
  if entry[2]:
945
1226
  raise entry[0]
946
- return entry[0]
1227
+ return isolate(entry[0]) if copy_result else entry[0]
947
1228
 
948
1229
  def cache_parameters() -> dict[str, Any]:
949
1230
  return {
@@ -955,6 +1236,9 @@ def memoize(
955
1236
  "exception_ttl": exc_ttl_s,
956
1237
  "store": store,
957
1238
  "per_instance": per_instance,
1239
+ "key": key,
1240
+ "singleflight": singleflight,
1241
+ "copy_result": copy_result,
958
1242
  }
959
1243
 
960
1244
  data: Any = main.data if builtin else None
@@ -966,13 +1250,83 @@ def memoize(
966
1250
  if entry is None:
967
1251
  return None
968
1252
  expires = entry[1]
969
- if expires is not None and _core.monotonic() >= expires:
1253
+ if (expires is not None and _core.monotonic() >= expires) or (
1254
+ tags is not None and outdated(entry)
1255
+ ):
970
1256
  del data[k]
971
1257
  return _EXPIRED
972
1258
  if lru:
973
1259
  data.move_to_end(k)
974
1260
  return entry
975
1261
 
1262
+ def sync_miss(
1263
+ b: Any, k: Hashable, args: tuple[Any, ...], kwargs: dict[str, Any], g: int
1264
+ ) -> Any:
1265
+ # The sync miss path: compute and store; with singleflight=True only one
1266
+ # thread per key computes while the others wait for its outcome.
1267
+ nonlocal hits, misses
1268
+
1269
+ def run() -> tuple[Any, Any]:
1270
+ tv = snapshot_tags(args, kwargs)
1271
+ try:
1272
+ result = f(*args, **kwargs)
1273
+ except exc_types as exc:
1274
+ save(b, k, exc, g, True, tv)
1275
+ raise
1276
+ return save(b, k, result, g, tv=tv), result
1277
+
1278
+ def compute() -> tuple[Any, Any]:
1279
+ if lock_backend is None:
1280
+ return run()
1281
+ return once_across_processes(b, k, run) # type: ignore[no-any-return]
1282
+
1283
+ if not singleflight:
1284
+ snapshot, result = compute()
1285
+ return isolate(snapshot) if copy_result else result
1286
+ rk = (id(b), k) if per_instance else k
1287
+ me = threading.get_ident()
1288
+ with lock:
1289
+ flight = sync_flights.get(rk)
1290
+ if flight is None:
1291
+ future: concurrent.futures.Future[Any] = concurrent.futures.Future()
1292
+ sync_flights[rk] = (future, me)
1293
+ else:
1294
+ shared, owner = flight
1295
+ if flight is not None:
1296
+ if owner == me:
1297
+ # Re-entrant call on the computing thread: waiting for our own
1298
+ # result would deadlock, so compute directly.
1299
+ snapshot, result = compute()
1300
+ return isolate(snapshot) if copy_result else result
1301
+ snapshot = shared.result()
1302
+ with lock: # it shared another thread's computation: a hit, not a miss
1303
+ hits += 1
1304
+ misses -= 1
1305
+ if _core.listeners:
1306
+ _core.emit("cache.hit", name)
1307
+ return isolate(snapshot) if copy_result else snapshot
1308
+ try:
1309
+ # Another thread may have finished this key between our lookup and now.
1310
+ with guard:
1311
+ cached = fetch(b, k)
1312
+ if cached:
1313
+ if cached[2]:
1314
+ raise cached[0]
1315
+ snapshot = result = cached[0]
1316
+ else:
1317
+ snapshot, result = compute()
1318
+ except BaseException as exc:
1319
+ with lock:
1320
+ if sync_flights.get(rk, (None,))[0] is future:
1321
+ del sync_flights[rk]
1322
+ future.set_exception(exc)
1323
+ raise
1324
+ with lock:
1325
+ if sync_flights.get(rk, (None,))[0] is future:
1326
+ del sync_flights[rk]
1327
+ future.set_result(snapshot)
1328
+ return isolate(snapshot) if copy_result else result
1329
+
976
1330
  async def amiss(b: Any, k: Hashable, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
977
1331
  # The async miss path: share one in-flight task per key and event loop.
978
1332
  nonlocal hits, misses
@@ -991,15 +1345,20 @@ def memoize(
991
1345
  shared = True
992
1346
  if not shared:
993
1347
 
994
- async def run() -> Any:
1348
+ async def compute() -> Any:
1349
+ tv = snapshot_tags(args, kwargs)
995
1350
  try:
996
1351
  result = await f(*args, **kwargs)
997
1352
  except exc_types as exc:
998
1353
  if not isinstance(exc, asyncio.CancelledError):
999
- save(b, k, exc, g, True)
1354
+ save(b, k, exc, g, True, tv)
1000
1355
  raise
1001
- save(b, k, result, g)
1002
- return result
1356
+ return save(b, k, result, g, tv=tv)
1357
+
1358
+ async def run() -> Any:
1359
+ if lock_backend is None:
1360
+ return await compute()
1361
+ return await aonce_across_processes(b, k, compute)
1003
1362
 
1004
1363
  def done(_t: asyncio.Future[Any] | None) -> None:
1005
1364
  with lock:
@@ -1010,7 +1369,8 @@ def memoize(
1010
1369
  if _core.listeners:
1011
1370
  _core.emit("cache.hit" if shared else "cache.miss", name)
1012
1371
  # one cancelled caller must not cancel the shared computation
1013
- return await _await_shared(shared_fut)
1372
+ outcome = await _await_shared(shared_fut)
1373
+ return isolate(outcome) if copy_result else outcome
1014
1374
 
1015
1375
  if _core.is_async(f) and builtin and not per_instance:
1016
1376
 
@@ -1040,7 +1400,7 @@ def memoize(
1040
1400
  refresh_in_task(main, k, args, kwargs)
1041
1401
  if entry[2]:
1042
1402
  raise entry[0]
1043
- return entry[0]
1403
+ return isolate(entry[0]) if copy_result else entry[0]
1044
1404
  if _core.listeners and entry is not None:
1045
1405
  report_expired()
1046
1406
  return await amiss(main, k, args, kwargs)
@@ -1066,7 +1426,7 @@ def memoize(
1066
1426
  refresh_in_task(b, k, args, kwargs)
1067
1427
  if entry[2]:
1068
1428
  raise entry[0]
1069
- return entry[0]
1429
+ return isolate(entry[0]) if copy_result else entry[0]
1070
1430
  if _core.listeners and entry is not None:
1071
1431
  report_expired()
1072
1432
  return await amiss(b, k, args, kwargs)
@@ -1113,18 +1473,12 @@ def memoize(
1113
1473
  refresh_in_thread(main, k, args, kwargs)
1114
1474
  if entry[2]:
1115
1475
  raise entry[0]
1116
- return entry[0]
1476
+ return isolate(entry[0]) if copy_result else entry[0]
1117
1477
  if _core.listeners:
1118
1478
  if entry is not None:
1119
1479
  report_expired()
1120
1480
  _core.emit("cache.miss", name)
1121
- try:
1122
- result = f(*args, **kwargs)
1123
- except exc_types as exc:
1124
- save(main, k, exc, g, True)
1125
- raise
1126
- save(main, k, result, g)
1127
- return result
1481
+ return sync_miss(main, k, args, kwargs, g)
1128
1482
 
1129
1483
  else:
1130
1484
 
@@ -1150,24 +1504,32 @@ def memoize(
1150
1504
  refresh_in_thread(b, k, args, kwargs)
1151
1505
  if entry[2]:
1152
1506
  raise entry[0]
1153
- return entry[0]
1507
+ return isolate(entry[0]) if copy_result else entry[0]
1154
1508
  if _core.listeners:
1155
1509
  if entry is not None:
1156
1510
  report_expired()
1157
1511
  _core.emit("cache.miss", name)
1158
- try:
1159
- result = f(*args, **kwargs)
1160
- except exc_types as exc:
1161
- save(b, k, exc, g, True)
1162
- raise
1163
- save(b, k, result, g)
1164
- return result
1512
+ return sync_miss(b, k, args, kwargs, g)
1165
1513
 
1166
1514
  wrapper.cache_clear = cache_clear
1167
1515
  wrapper.cache_info = cache_info
1168
1516
  wrapper.cache_delete = cache_delete
1169
1517
  wrapper.cache_contains = cache_contains
1170
1518
  wrapper.cache_get = cache_get
1519
+
1520
+ def reset_after_fork() -> None:
1521
+ nonlocal hits, misses, gen
1522
+ if builtin:
1523
+ main.clear()
1524
+ instances.clear()
1525
+ inflight.clear()
1526
+ refreshing.clear()
1527
+ sync_flights.clear()
1528
+ background.clear()
1529
+ hits = misses = 0
1530
+ gen += 1
1531
+
1532
+ wrapper.__dict__["_fork_reset"] = _fork.register_reset(reset_after_fork)
1171
1533
  wrapper.cache_parameters = cache_parameters
1172
1534
  return wrapper
1173
1535
 
@@ -1266,7 +1628,7 @@ def once(func: Callable[..., Any] | None = None, /) -> Any:
1266
1628
  """
1267
1629
 
1268
1630
  def decorate(f: Callable[..., Any]) -> Any:
1269
- lock = threading.RLock()
1631
+ lock = _fork.ForkSafeRLock()
1270
1632
  # "flight" is the run in progress (shared by every thread and event loop).
1271
1633
  state: dict[str, Any] = {"done": False, "result": None, "gen": 0, "flight": None}
1272
1634
 
@@ -1338,6 +1700,7 @@ def once(func: Callable[..., Any] | None = None, /) -> Any:
1338
1700
  state.update(done=False, result=None, gen=state["gen"] + 1, flight=None)
1339
1701
  wrapper.called = False
1340
1702
 
1703
+ wrapper.__dict__["_fork_reset"] = _fork.register_reset(reset)
1341
1704
  wrapper.reset = reset
1342
1705
  return wrapper
1343
1706
 
@@ -1361,24 +1724,30 @@ class _PropState:
1361
1724
  pickles as an empty state so locks never end up in a pickle.
1362
1725
  """
1363
1726
 
1364
- __slots__ = ("entries", "gens", "locks", "owner_id", "tasks")
1727
+ __slots__ = ("__weakref__", "entries", "gens", "locks", "owner_id", "tasks")
1365
1728
 
1366
1729
  def __init__(self, owner_id: int) -> None:
1367
1730
  self.owner_id = owner_id
1368
1731
  self.entries: dict[str, tuple[Any, float | None]] = {}
1369
- self.locks: dict[str, threading.RLock] = {}
1732
+ self.locks: dict[str, _fork.ForkSafeRLock] = {}
1370
1733
  self.gens: dict[str, int] = {}
1371
1734
  self.tasks: weakref.WeakKeyDictionary[
1372
1735
  asyncio.AbstractEventLoop, dict[str, asyncio.Future[Any]]
1373
1736
  ] = weakref.WeakKeyDictionary()
1737
+ _fork.register(self)
1738
+
1739
+ def _reset_after_fork(self) -> None:
1740
+ self.entries.clear()
1741
+ self.tasks.clear()
1742
+ self.gens.clear()
1374
1743
 
1375
1744
  def __reduce__(self) -> tuple[Callable[[], _PropState], tuple[()]]:
1376
1745
  return (_new_state, ())
1377
1746
 
1378
- def lock_for(self, name: str) -> threading.RLock:
1747
+ def lock_for(self, name: str) -> _fork.ForkSafeRLock:
1379
1748
  lock = self.locks.get(name)
1380
1749
  if lock is None:
1381
- lock = self.locks.setdefault(name, threading.RLock()) # atomic: one winner
1750
+ lock = self.locks.setdefault(name, _fork.ForkSafeRLock()) # atomic: one winner
1382
1751
  return lock
1383
1752
 
1384
1753
  def drop(self, name: str) -> bool: