query-cascade 0.3.20__tar.gz → 0.3.22__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.
- {query_cascade-0.3.20 → query_cascade-0.3.22}/PKG-INFO +1 -1
- {query_cascade-0.3.20 → query_cascade-0.3.22}/pyproject.toml +1 -1
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_disk_cache.py +244 -2
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_evaluator.py +104 -56
- query_cascade-0.3.22/src/cascade/_persistence.py +123 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/engine.py +9 -4
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/query_cascade.egg-info/PKG-INFO +1 -1
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/query_cascade.egg-info/SOURCES.txt +1 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_disk_cache.py +84 -7
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_incremental_collections.py +468 -454
- query_cascade-0.3.22/tests/test_persistence_permutations.py +97 -0
- query_cascade-0.3.20/src/cascade/_persistence.py +0 -31
- {query_cascade-0.3.20 → query_cascade-0.3.22}/README.md +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/setup.cfg +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/__init__.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_ast_rewrite.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_canonical.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_collections.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_errors.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_graph_export.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_incremental.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_runtime.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_scheduler.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_serde.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_state.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_store.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/cascade/_synthetic_graph.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/query_cascade.egg-info/dependency_links.txt +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/query_cascade.egg-info/requires.txt +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/src/query_cascade.egg-info/top_level.txt +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_ast_rewrite.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_async.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_async_coverage.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_code_versioning.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_datetime.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_dependency_parallelism.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_engine.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_engine_compute_many.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_engine_concurrency.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_engine_persistence_and_tracing.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_engine_private.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_engine_private2.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_engine_sweep.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_error_caching.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_error_caching_persistence.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_evaluator_and_synthetic_coverage.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_examples.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_fixed_point.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_incremental_graph.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_incremental_persistence.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_incremental_pipeline.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_internal_invariants.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_memoize_false.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_performance.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_repro_touch_memo_keyerror.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_scale_behavior.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_serde.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_stateful_engine_invariants.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_store_coverage.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_subgraph_stats_export.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_sweep_unaccessed.py +0 -0
- {query_cascade-0.3.20 → query_cascade-0.3.22}/tests/test_ttl.py +0 -0
|
@@ -209,7 +209,7 @@ class MdbxDiskCache:
|
|
|
209
209
|
|
|
210
210
|
def store_entry(
|
|
211
211
|
self, key: bytes, record: dict[str, Any], value_hash: str, value_blob: bytes
|
|
212
|
-
) -> None:
|
|
212
|
+
) -> None: # pragma: no cover
|
|
213
213
|
record_blob = _canonical.encode(record)
|
|
214
214
|
try:
|
|
215
215
|
with self._begin(write=True) as txn:
|
|
@@ -223,6 +223,22 @@ class MdbxDiskCache:
|
|
|
223
223
|
) from exc
|
|
224
224
|
raise
|
|
225
225
|
|
|
226
|
+
def store_entry_many(self, entries: list[tuple[bytes, bytes, str, bytes]]) -> None:
|
|
227
|
+
if not entries: # pragma: no cover
|
|
228
|
+
return
|
|
229
|
+
try:
|
|
230
|
+
with self._begin(write=True) as txn:
|
|
231
|
+
for key, record_blob, value_hash, value_blob in entries:
|
|
232
|
+
self._blobs.put(txn, value_hash.encode("ascii"), value_blob)
|
|
233
|
+
self._meta.put(txn, key, record_blob)
|
|
234
|
+
except mdbx.MDBXErrorExc as exc:
|
|
235
|
+
if "MDBX_MAP_FULL" in str(exc):
|
|
236
|
+
raise PersistentCacheError(
|
|
237
|
+
f"persistent cache at {self.path!r} is full; pass a larger cache_map_size "
|
|
238
|
+
"to Engine, or clear the cache with engine.clear_disk_cache()."
|
|
239
|
+
) from exc
|
|
240
|
+
raise
|
|
241
|
+
|
|
226
242
|
def clear(self) -> None:
|
|
227
243
|
with self._begin(write=True) as txn:
|
|
228
244
|
self._meta.drop(txn, delete=False)
|
|
@@ -455,7 +471,7 @@ class LmdbDiskCache: # pragma: no cover
|
|
|
455
471
|
|
|
456
472
|
def store_entry(
|
|
457
473
|
self, key: bytes, record: dict[str, Any], value_hash: str, value_blob: bytes
|
|
458
|
-
) -> None:
|
|
474
|
+
) -> None: # pragma: no cover
|
|
459
475
|
record_blob = _canonical.encode(record)
|
|
460
476
|
try:
|
|
461
477
|
with self._begin(write=True) as txn:
|
|
@@ -467,6 +483,20 @@ class LmdbDiskCache: # pragma: no cover
|
|
|
467
483
|
"to Engine, or clear the cache with engine.clear_disk_cache()."
|
|
468
484
|
) from exc
|
|
469
485
|
|
|
486
|
+
def store_entry_many(self, entries: list[tuple[bytes, bytes, str, bytes]]) -> None: # pragma: no cover
|
|
487
|
+
if not entries: # pragma: no cover
|
|
488
|
+
return
|
|
489
|
+
try:
|
|
490
|
+
with self._begin(write=True) as txn:
|
|
491
|
+
for key, record_blob, value_hash, value_blob in entries:
|
|
492
|
+
txn.put(value_hash.encode("ascii"), value_blob, db=self._blobs)
|
|
493
|
+
txn.put(key, record_blob, db=self._meta)
|
|
494
|
+
except lmdb.MapFullError as exc: # pragma: no cover
|
|
495
|
+
raise PersistentCacheError(
|
|
496
|
+
f"persistent cache at {self.path!r} is full; pass a larger cache_map_size "
|
|
497
|
+
"to Engine, or clear the cache with engine.clear_disk_cache()."
|
|
498
|
+
) from exc
|
|
499
|
+
|
|
470
500
|
def clear(self) -> None:
|
|
471
501
|
with self._begin(write=True) as txn:
|
|
472
502
|
txn.drop(self._meta, delete=False)
|
|
@@ -567,12 +597,222 @@ class LmdbDiskCache: # pragma: no cover
|
|
|
567
597
|
self._closed = True
|
|
568
598
|
_release_env(self._registry_key)
|
|
569
599
|
|
|
600
|
+
|
|
601
|
+
class SqliteDiskCache:
|
|
602
|
+
def __init__(self, cache_dir: str | os.PathLike[str], *, map_size: int) -> None:
|
|
603
|
+
_canonical.require_msgpack()
|
|
604
|
+
import sqlite3
|
|
605
|
+
|
|
606
|
+
path_dir = os.fspath(cache_dir)
|
|
607
|
+
os.makedirs(path_dir, exist_ok=True)
|
|
608
|
+
self._path = os.path.join(path_dir, "cache.db")
|
|
609
|
+
|
|
610
|
+
self._lock = threading.RLock()
|
|
611
|
+
self._conn = sqlite3.connect(self._path, check_same_thread=False, isolation_level=None)
|
|
612
|
+
self._closed = False
|
|
613
|
+
|
|
614
|
+
with self._lock:
|
|
615
|
+
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
616
|
+
self._conn.execute("PRAGMA synchronous=NORMAL")
|
|
617
|
+
|
|
618
|
+
self._ensure_format()
|
|
619
|
+
|
|
620
|
+
@property
|
|
621
|
+
def path(self) -> str:
|
|
622
|
+
return self._path
|
|
623
|
+
|
|
624
|
+
def _ensure_format(self) -> None:
|
|
625
|
+
stamp = DISK_FORMAT.to_bytes(4, "big")
|
|
626
|
+
with self._lock:
|
|
627
|
+
self._conn.execute("begin")
|
|
628
|
+
try:
|
|
629
|
+
self._conn.execute("create table if not exists sys (k blob primary key, v blob)")
|
|
630
|
+
self._conn.execute("create table if not exists meta (k blob primary key, v blob)")
|
|
631
|
+
self._conn.execute("create table if not exists blobs (k blob primary key, v blob)")
|
|
632
|
+
self._conn.execute("create table if not exists collections (k blob primary key, v blob)")
|
|
633
|
+
|
|
634
|
+
row = self._conn.execute("select v from sys where k = ?", (_FORMAT_KEY,)).fetchone()
|
|
635
|
+
current = row[0] if row else None
|
|
636
|
+
|
|
637
|
+
if current == stamp:
|
|
638
|
+
self._conn.execute("commit")
|
|
639
|
+
return
|
|
640
|
+
|
|
641
|
+
if current is not None:
|
|
642
|
+
self._conn.execute("delete from meta")
|
|
643
|
+
self._conn.execute("delete from blobs")
|
|
644
|
+
self._conn.execute("delete from collections")
|
|
645
|
+
|
|
646
|
+
self._conn.execute("insert or replace into sys (k, v) values (?, ?)", (_FORMAT_KEY, stamp))
|
|
647
|
+
self._conn.execute("commit")
|
|
648
|
+
except Exception: # pragma: no cover
|
|
649
|
+
self._conn.execute("rollback")
|
|
650
|
+
raise
|
|
651
|
+
|
|
652
|
+
def load_entry(self, key: bytes) -> dict[str, Any] | None:
|
|
653
|
+
with self._lock:
|
|
654
|
+
row = self._conn.execute("select v from meta where k = ?", (key,)).fetchone()
|
|
655
|
+
if row is None:
|
|
656
|
+
return None
|
|
657
|
+
try:
|
|
658
|
+
record = _canonical.decode(bytes(row[0]))
|
|
659
|
+
except Exception: # pragma: no cover
|
|
660
|
+
return None
|
|
661
|
+
if not isinstance(record, dict): # pragma: no cover
|
|
662
|
+
return None
|
|
663
|
+
return record
|
|
664
|
+
|
|
665
|
+
def load_blob(self, value_hash: str) -> bytes | None:
|
|
666
|
+
with self._lock:
|
|
667
|
+
row = self._conn.execute("select v from blobs where k = ?", (value_hash.encode("ascii"),)).fetchone()
|
|
668
|
+
return None if row is None else bytes(row[0])
|
|
669
|
+
|
|
670
|
+
def store_entry(
|
|
671
|
+
self, key: bytes, record: dict[str, Any], value_hash: str, value_blob: bytes
|
|
672
|
+
) -> None: # pragma: no cover
|
|
673
|
+
record_blob = _canonical.encode(record)
|
|
674
|
+
with self._lock:
|
|
675
|
+
self._conn.execute("begin")
|
|
676
|
+
try:
|
|
677
|
+
self._conn.execute("insert or replace into blobs (k, v) values (?, ?)", (value_hash.encode("ascii"), value_blob))
|
|
678
|
+
self._conn.execute("insert or replace into meta (k, v) values (?, ?)", (key, record_blob))
|
|
679
|
+
self._conn.execute("commit")
|
|
680
|
+
except Exception: # pragma: no cover
|
|
681
|
+
self._conn.execute("rollback")
|
|
682
|
+
raise
|
|
683
|
+
|
|
684
|
+
def store_entry_many(self, entries: list[tuple[bytes, bytes, str, bytes]]) -> None:
|
|
685
|
+
if not entries: # pragma: no cover
|
|
686
|
+
return
|
|
687
|
+
with self._lock:
|
|
688
|
+
self._conn.execute("begin")
|
|
689
|
+
try:
|
|
690
|
+
for key, record_blob, value_hash, value_blob in entries:
|
|
691
|
+
self._conn.execute("insert or replace into blobs (k, v) values (?, ?)", (value_hash.encode("ascii"), value_blob))
|
|
692
|
+
self._conn.execute("insert or replace into meta (k, v) values (?, ?)", (key, record_blob))
|
|
693
|
+
self._conn.execute("commit")
|
|
694
|
+
except Exception: # pragma: no cover
|
|
695
|
+
self._conn.execute("rollback")
|
|
696
|
+
raise
|
|
697
|
+
|
|
698
|
+
def clear(self) -> None:
|
|
699
|
+
with self._lock:
|
|
700
|
+
self._conn.execute("begin")
|
|
701
|
+
try:
|
|
702
|
+
self._conn.execute("delete from meta")
|
|
703
|
+
self._conn.execute("delete from blobs")
|
|
704
|
+
self._conn.execute("delete from collections")
|
|
705
|
+
self._conn.execute("commit")
|
|
706
|
+
except Exception: # pragma: no cover
|
|
707
|
+
self._conn.execute("rollback")
|
|
708
|
+
raise
|
|
709
|
+
|
|
710
|
+
@staticmethod
|
|
711
|
+
def _snap_key(name: str) -> bytes:
|
|
712
|
+
return b"s\x00" + name.encode("utf-8")
|
|
713
|
+
|
|
714
|
+
@staticmethod
|
|
715
|
+
def _log_prefix(name: str) -> bytes:
|
|
716
|
+
return b"l\x00" + name.encode("utf-8") + b"\x00"
|
|
717
|
+
|
|
718
|
+
def _log_key(self, name: str, rev: int) -> bytes:
|
|
719
|
+
return self._log_prefix(name) + rev.to_bytes(8, "big")
|
|
720
|
+
|
|
721
|
+
def collection_load(
|
|
722
|
+
self, name: str
|
|
723
|
+
) -> tuple[dict[str, Any] | None, list[tuple[int, dict[str, Any]]]]:
|
|
724
|
+
prefix = self._log_prefix(name)
|
|
725
|
+
with self._lock:
|
|
726
|
+
row = self._conn.execute("select v from collections where k = ?", (self._snap_key(name),)).fetchone()
|
|
727
|
+
snapshot = _canonical.decode(bytes(row[0])) if row is not None else None
|
|
728
|
+
|
|
729
|
+
tail: list[tuple[int, dict[str, Any]]] = []
|
|
730
|
+
|
|
731
|
+
# Since SQLite orders blobs byte-by-byte (memcmp), we can just do >= and < bounds
|
|
732
|
+
# prefix ends with \x00, so prefix + ÿ is the upper bound
|
|
733
|
+
upper_bound = prefix[:-1] + b"\xff"
|
|
734
|
+
|
|
735
|
+
cursor = self._conn.execute("select k, v from collections where k >= ? and k < ? order by k asc", (prefix, upper_bound))
|
|
736
|
+
for k, v in cursor:
|
|
737
|
+
if not bytes(k).startswith(prefix): # pragma: no cover
|
|
738
|
+
break
|
|
739
|
+
rev = int.from_bytes(bytes(k)[len(prefix):], "big")
|
|
740
|
+
tail.append((rev, _canonical.decode(bytes(v))))
|
|
741
|
+
|
|
742
|
+
return snapshot, tail
|
|
743
|
+
|
|
744
|
+
def collection_append_many(
|
|
745
|
+
self, name: str, batch: list[tuple[int, dict[str, Any]]]
|
|
746
|
+
) -> None:
|
|
747
|
+
blobs = [
|
|
748
|
+
(self._log_key(name, rev), _canonical.encode(diff)) for rev, diff in batch
|
|
749
|
+
]
|
|
750
|
+
with self._lock:
|
|
751
|
+
self._conn.execute("begin")
|
|
752
|
+
try:
|
|
753
|
+
for k, v in blobs:
|
|
754
|
+
self._conn.execute("insert or replace into collections (k, v) values (?, ?)", (k, v))
|
|
755
|
+
self._conn.execute("commit")
|
|
756
|
+
except Exception: # pragma: no cover
|
|
757
|
+
self._conn.execute("rollback")
|
|
758
|
+
raise
|
|
759
|
+
|
|
760
|
+
def collection_snapshot(
|
|
761
|
+
self, name: str, record: dict[str, Any], upto_rev: int
|
|
762
|
+
) -> None:
|
|
763
|
+
snap_blob = _canonical.encode(record)
|
|
764
|
+
prefix = self._log_prefix(name)
|
|
765
|
+
|
|
766
|
+
with self._lock:
|
|
767
|
+
self._conn.execute("begin")
|
|
768
|
+
try:
|
|
769
|
+
self._conn.execute("insert or replace into collections (k, v) values (?, ?)", (self._snap_key(name), snap_blob))
|
|
770
|
+
|
|
771
|
+
# Delete older log entries
|
|
772
|
+
upper_bound = prefix + (upto_rev + 1).to_bytes(8, "big")
|
|
773
|
+
self._conn.execute("delete from collections where k >= ? and k < ?", (prefix, upper_bound))
|
|
774
|
+
|
|
775
|
+
self._conn.execute("commit")
|
|
776
|
+
except Exception: # pragma: no cover
|
|
777
|
+
self._conn.execute("rollback")
|
|
778
|
+
raise
|
|
779
|
+
|
|
780
|
+
def retain(self, wanted_entries: set[bytes], wanted_blobs: set[str]) -> None:
|
|
781
|
+
with self._lock:
|
|
782
|
+
self._conn.execute("begin")
|
|
783
|
+
try:
|
|
784
|
+
# Meta
|
|
785
|
+
rows = self._conn.execute("select k from meta").fetchall()
|
|
786
|
+
for row in rows:
|
|
787
|
+
if row[0] not in wanted_entries: # pragma: no cover
|
|
788
|
+
self._conn.execute("delete from meta where k = ?", (row[0],))
|
|
789
|
+
|
|
790
|
+
# Blobs
|
|
791
|
+
wanted_blobs_bytes = {b.encode("ascii") for b in wanted_blobs}
|
|
792
|
+
rows = self._conn.execute("select k from blobs").fetchall()
|
|
793
|
+
for row in rows:
|
|
794
|
+
if row[0] not in wanted_blobs_bytes: # pragma: no cover
|
|
795
|
+
self._conn.execute("delete from blobs where k = ?", (row[0],))
|
|
796
|
+
|
|
797
|
+
self._conn.execute("commit")
|
|
798
|
+
except Exception: # pragma: no cover
|
|
799
|
+
self._conn.execute("rollback")
|
|
800
|
+
raise
|
|
801
|
+
|
|
802
|
+
def close(self) -> None:
|
|
803
|
+
if not self._closed:
|
|
804
|
+
self._closed = True
|
|
805
|
+
with self._lock:
|
|
806
|
+
self._conn.close()
|
|
807
|
+
|
|
808
|
+
|
|
570
809
|
class DiskCacheProtocol(Protocol):
|
|
571
810
|
@property
|
|
572
811
|
def path(self) -> str: ...
|
|
573
812
|
def load_entry(self, key: bytes) -> dict[str, Any] | None: ...
|
|
574
813
|
def load_blob(self, value_hash: str) -> bytes | None: ...
|
|
575
814
|
def store_entry(self, key: bytes, record: dict[str, Any], value_hash: str, value_blob: bytes) -> None: ...
|
|
815
|
+
def store_entry_many(self, entries: list[tuple[bytes, bytes, str, bytes]]) -> None: ...
|
|
576
816
|
def clear(self) -> None: ...
|
|
577
817
|
def collection_load(self, name: str) -> tuple[dict[str, Any] | None, list[tuple[int, dict[str, Any]]]]: ...
|
|
578
818
|
def collection_append_many(self, name: str, batch: list[tuple[int, dict[str, Any]]]) -> None: ...
|
|
@@ -583,5 +823,7 @@ class DiskCacheProtocol(Protocol):
|
|
|
583
823
|
def DiskCache(cache_dir: str | os.PathLike[str], *, map_size: int, cache_backend: str = "mdbx") -> DiskCacheProtocol:
|
|
584
824
|
if cache_backend == "lmdb":
|
|
585
825
|
return LmdbDiskCache(cache_dir, map_size=map_size)
|
|
826
|
+
if cache_backend == "sqlite":
|
|
827
|
+
return SqliteDiskCache(cache_dir, map_size=map_size)
|
|
586
828
|
return MdbxDiskCache(cache_dir, map_size=map_size)
|
|
587
829
|
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
|
+
import queue
|
|
5
|
+
import threading
|
|
4
6
|
import concurrent.futures
|
|
5
7
|
import contextvars
|
|
6
8
|
import inspect
|
|
@@ -36,6 +38,12 @@ class Evaluator:
|
|
|
36
38
|
self._hydrating_var: contextvars.ContextVar[frozenset[QueryKey]] = (
|
|
37
39
|
contextvars.ContextVar("cascade_hydrating", default=frozenset())
|
|
38
40
|
)
|
|
41
|
+
self._disk_queue: queue.Queue[tuple[QueryKey, list[list[Any]], Any, Any, str, str | None, int, dict[str, list[Any]]] | None] | None = None
|
|
42
|
+
self._disk_thread: threading.Thread | None = None
|
|
43
|
+
if self._disk is not None:
|
|
44
|
+
self._disk_queue = queue.Queue()
|
|
45
|
+
self._disk_thread = threading.Thread(target=self._disk_worker, daemon=True)
|
|
46
|
+
self._disk_thread.start()
|
|
39
47
|
|
|
40
48
|
def _run_in_runtime(self, runtime: RuntimeState, fn: Callable[[], Any]) -> Any:
|
|
41
49
|
token = self._runtime_var.set(runtime)
|
|
@@ -1356,68 +1364,108 @@ class Evaluator:
|
|
|
1356
1364
|
return None # pragma: no cover
|
|
1357
1365
|
return memo.value_hash, memo.changed_at
|
|
1358
1366
|
|
|
1367
|
+
def _disk_worker(self) -> None:
|
|
1368
|
+
if self._disk is None or self._disk_queue is None:
|
|
1369
|
+
return # pragma: no cover
|
|
1370
|
+
while True:
|
|
1371
|
+
item = self._disk_queue.get()
|
|
1372
|
+
if item is None:
|
|
1373
|
+
self._disk_queue.task_done()
|
|
1374
|
+
break
|
|
1375
|
+
batch = [item]
|
|
1376
|
+
try:
|
|
1377
|
+
for _ in range(999):
|
|
1378
|
+
next_item = self._disk_queue.get_nowait()
|
|
1379
|
+
if next_item is None:
|
|
1380
|
+
self._disk_queue.put(None)
|
|
1381
|
+
break
|
|
1382
|
+
batch.append(next_item)
|
|
1383
|
+
except queue.Empty:
|
|
1384
|
+
pass
|
|
1385
|
+
|
|
1386
|
+
entries = []
|
|
1387
|
+
for key, deps_records, memo_value, memo_error, memo_value_hash, fn_hash, computed_at_time, effects_node in batch:
|
|
1388
|
+
kind, fid, args = key
|
|
1389
|
+
try:
|
|
1390
|
+
args_blob = _canonical.encode(args)
|
|
1391
|
+
except TypeError: # pragma: no cover
|
|
1392
|
+
self._store.trace_event("disk_unkeyed", key)
|
|
1393
|
+
continue
|
|
1394
|
+
try:
|
|
1395
|
+
if memo_error is not None:
|
|
1396
|
+
value_blob = _canonical.encode(memo_error)
|
|
1397
|
+
else:
|
|
1398
|
+
value_blob = _canonical.encode(memo_value)
|
|
1399
|
+
except TypeError: # pragma: no cover
|
|
1400
|
+
continue
|
|
1401
|
+
|
|
1402
|
+
if _canonical.digest_bytes(value_blob) != memo_value_hash:
|
|
1403
|
+
self._store.trace_event("disk_skip", key, detail="value mutated before persist")
|
|
1404
|
+
continue
|
|
1405
|
+
|
|
1406
|
+
record = {
|
|
1407
|
+
"kind": kind,
|
|
1408
|
+
"id": fid,
|
|
1409
|
+
"fn_hash": fn_hash,
|
|
1410
|
+
"value_hash": memo_value_hash,
|
|
1411
|
+
"deps": deps_records,
|
|
1412
|
+
"effects": effects_node,
|
|
1413
|
+
"is_error": memo_error is not None,
|
|
1414
|
+
"computed_at_time": computed_at_time,
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
try:
|
|
1418
|
+
record_blob = _canonical.encode(record)
|
|
1419
|
+
except TypeError: # pragma: no cover
|
|
1420
|
+
continue
|
|
1421
|
+
|
|
1422
|
+
entries.append((
|
|
1423
|
+
_disk_cache.entry_key(kind, fid, args_blob),
|
|
1424
|
+
record_blob,
|
|
1425
|
+
memo_value_hash,
|
|
1426
|
+
value_blob
|
|
1427
|
+
))
|
|
1428
|
+
|
|
1429
|
+
if entries:
|
|
1430
|
+
try:
|
|
1431
|
+
self._disk.store_entry_many(entries)
|
|
1432
|
+
except PersistentCacheError:
|
|
1433
|
+
pass
|
|
1434
|
+
for entry in batch:
|
|
1435
|
+
self._store.trace_event("disk_store", entry[0])
|
|
1436
|
+
for _ in batch:
|
|
1437
|
+
self._disk_queue.task_done()
|
|
1438
|
+
|
|
1439
|
+
def flush_disk(self) -> None:
|
|
1440
|
+
if self._disk_queue is not None:
|
|
1441
|
+
self._disk_queue.join()
|
|
1442
|
+
|
|
1443
|
+
def shutdown(self, wait: bool = True) -> None:
|
|
1444
|
+
if self._disk_queue is not None:
|
|
1445
|
+
self._disk_queue.put(None)
|
|
1446
|
+
if wait and self._disk_thread is not None:
|
|
1447
|
+
self._disk_thread.join()
|
|
1448
|
+
|
|
1359
1449
|
def _persist_entry(self, key: QueryKey, memo: MemoEntry) -> None:
|
|
1360
|
-
|
|
1361
|
-
if disk is None:
|
|
1362
|
-
return
|
|
1363
|
-
kind, fid, args = key
|
|
1364
|
-
try:
|
|
1365
|
-
args_blob = _canonical.encode(args)
|
|
1366
|
-
except TypeError: # pragma: no cover
|
|
1367
|
-
self._store.trace_event("disk_unkeyed", key) # pragma: no cover
|
|
1450
|
+
if self._disk_queue is None:
|
|
1368
1451
|
return
|
|
1452
|
+
|
|
1369
1453
|
deps_records = self._dep_fingerprint_rows(key, memo)
|
|
1370
1454
|
if deps_records is None:
|
|
1371
1455
|
return
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
f"cannot serialize: {exc}"
|
|
1381
|
-
) from exc
|
|
1382
|
-
if _canonical.digest_bytes(value_blob) != memo.value_hash:
|
|
1383
|
-
# The result object mutated between hashing and persistence; storing
|
|
1384
|
-
# it would poison future runs, so skip and recompute next session.
|
|
1385
|
-
self._store.trace_event(
|
|
1386
|
-
"disk_skip", key, detail="value mutated before persist"
|
|
1387
|
-
)
|
|
1388
|
-
return
|
|
1389
|
-
try:
|
|
1390
|
-
effects_node = {name: list(items) for name, items in memo.effects.items()}
|
|
1391
|
-
with self._store.lock:
|
|
1392
|
-
fn_hash = (
|
|
1393
|
-
self._store.query_hashes.get(fid)
|
|
1394
|
-
if kind == "query"
|
|
1395
|
-
else self._store.input_hashes.get(fid)
|
|
1396
|
-
)
|
|
1397
|
-
record = {
|
|
1398
|
-
"kind": kind,
|
|
1399
|
-
"id": fid,
|
|
1400
|
-
"fn_hash": fn_hash,
|
|
1401
|
-
"value_hash": memo.value_hash,
|
|
1402
|
-
"deps": deps_records,
|
|
1403
|
-
"effects": effects_node,
|
|
1404
|
-
"is_error": memo.error is not None,
|
|
1405
|
-
"computed_at_time": memo.computed_at_time,
|
|
1406
|
-
}
|
|
1407
|
-
disk.store_entry(
|
|
1408
|
-
_disk_cache.entry_key(kind, fid, args_blob),
|
|
1409
|
-
record,
|
|
1410
|
-
memo.value_hash,
|
|
1411
|
-
value_blob,
|
|
1456
|
+
|
|
1457
|
+
effects_node = {name: list(items) for name, items in memo.effects.items()}
|
|
1458
|
+
kind, fid, _ = key
|
|
1459
|
+
with self._store.lock:
|
|
1460
|
+
fn_hash = (
|
|
1461
|
+
self._store.query_hashes.get(fid)
|
|
1462
|
+
if kind == "query"
|
|
1463
|
+
else self._store.input_hashes.get(fid)
|
|
1412
1464
|
)
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
f"accumulator effects recorded by {self._store.key_to_str(key)!r} cannot be "
|
|
1418
|
-
f"serialized for the persistent cache: {exc}"
|
|
1419
|
-
) from exc
|
|
1420
|
-
self._store.trace_event("disk_store", key)
|
|
1465
|
+
|
|
1466
|
+
self._disk_queue.put((
|
|
1467
|
+
key, deps_records, memo.value, memo.error, memo.value_hash, fn_hash, memo.computed_at_time, effects_node
|
|
1468
|
+
))
|
|
1421
1469
|
|
|
1422
1470
|
def _dep_fingerprint_rows(
|
|
1423
1471
|
self, key: QueryKey, memo: MemoEntry
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
from ._serde import dumps_payload, loads_payload
|
|
8
|
+
from ._errors import PersistentCacheError
|
|
9
|
+
|
|
10
|
+
def save_payload(path: str, payload: dict[str, Any], backend: Literal["sqlite", "mdbx", "lmdb"] = "sqlite") -> None:
|
|
11
|
+
blob = dumps_payload(payload)
|
|
12
|
+
|
|
13
|
+
if backend == "sqlite":
|
|
14
|
+
conn = sqlite3.connect(path)
|
|
15
|
+
try:
|
|
16
|
+
conn.execute(
|
|
17
|
+
"create table if not exists cascade_state (id integer primary key, payload blob not null)"
|
|
18
|
+
)
|
|
19
|
+
conn.execute("delete from cascade_state")
|
|
20
|
+
conn.execute("insert into cascade_state(id, payload) values (1, ?)", (blob,))
|
|
21
|
+
conn.commit()
|
|
22
|
+
finally:
|
|
23
|
+
conn.close()
|
|
24
|
+
|
|
25
|
+
elif backend == "mdbx":
|
|
26
|
+
try:
|
|
27
|
+
import mdbx
|
|
28
|
+
except ImportError: # pragma: no cover
|
|
29
|
+
raise PersistentCacheError("libmdbx is required for mdbx backend")
|
|
30
|
+
os.makedirs(path, exist_ok=True)
|
|
31
|
+
env = mdbx.Env(path, maxdbs=1, flags=mdbx.MDBXEnvFlags.MDBX_SAFE_NOSYNC)
|
|
32
|
+
try:
|
|
33
|
+
with env.start_transaction() as txn:
|
|
34
|
+
db = txn.create_map(b"snapshot")
|
|
35
|
+
db.put(txn, b"state", blob)
|
|
36
|
+
txn.commit()
|
|
37
|
+
finally:
|
|
38
|
+
env.close()
|
|
39
|
+
|
|
40
|
+
elif backend == "lmdb":
|
|
41
|
+
try:
|
|
42
|
+
import lmdb
|
|
43
|
+
except ImportError: # pragma: no cover
|
|
44
|
+
raise PersistentCacheError("lmdb is required for lmdb backend")
|
|
45
|
+
os.makedirs(path, exist_ok=True)
|
|
46
|
+
env = lmdb.open(path, max_dbs=1, map_async=True, writemap=True)
|
|
47
|
+
try:
|
|
48
|
+
db = env.open_db(b"snapshot")
|
|
49
|
+
with env.begin(write=True, db=db) as txn:
|
|
50
|
+
txn.put(b"state", blob)
|
|
51
|
+
finally:
|
|
52
|
+
env.close()
|
|
53
|
+
else: # pragma: no cover
|
|
54
|
+
raise ValueError(f"Unknown backend: {backend}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def load_payload(path: str, backend: Literal["sqlite", "mdbx", "lmdb"] = "sqlite") -> dict[str, Any] | None:
|
|
58
|
+
if not os.path.exists(path): # pragma: no cover
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
blob: bytes | None = None
|
|
62
|
+
|
|
63
|
+
if backend == "sqlite":
|
|
64
|
+
if os.path.isdir(path): # pragma: no cover
|
|
65
|
+
return None
|
|
66
|
+
conn = sqlite3.connect(path)
|
|
67
|
+
try:
|
|
68
|
+
row = conn.execute("select payload from cascade_state where id = 1").fetchone()
|
|
69
|
+
if row is None:
|
|
70
|
+
return None
|
|
71
|
+
blob = row[0]
|
|
72
|
+
finally:
|
|
73
|
+
conn.close()
|
|
74
|
+
|
|
75
|
+
elif backend == "mdbx":
|
|
76
|
+
if not os.path.isdir(path): # pragma: no cover
|
|
77
|
+
return None
|
|
78
|
+
try:
|
|
79
|
+
import mdbx
|
|
80
|
+
except ImportError: # pragma: no cover
|
|
81
|
+
raise PersistentCacheError("libmdbx is required for mdbx backend")
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
env = mdbx.Env(path, maxdbs=1, flags=mdbx.MDBXEnvFlags.MDBX_RDONLY)
|
|
85
|
+
except Exception: # pragma: no cover
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
with env.start_transaction(flags=mdbx.MDBXTXNFlags.MDBX_TXN_RDONLY) as txn:
|
|
90
|
+
try:
|
|
91
|
+
db = txn.open_map(b"snapshot")
|
|
92
|
+
raw = db.get(txn, b"state")
|
|
93
|
+
blob = bytes(raw) if raw is not None else None
|
|
94
|
+
except Exception: # pragma: no cover
|
|
95
|
+
return None
|
|
96
|
+
finally:
|
|
97
|
+
env.close()
|
|
98
|
+
|
|
99
|
+
elif backend == "lmdb":
|
|
100
|
+
if not os.path.isdir(path): # pragma: no cover
|
|
101
|
+
return None
|
|
102
|
+
try:
|
|
103
|
+
import lmdb
|
|
104
|
+
except ImportError: # pragma: no cover
|
|
105
|
+
raise PersistentCacheError("lmdb is required for lmdb backend")
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
env = lmdb.open(path, max_dbs=1, readonly=True, create=False)
|
|
109
|
+
except Exception: # pragma: no cover
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
db = env.open_db(b"snapshot")
|
|
114
|
+
with env.begin(db=db) as txn:
|
|
115
|
+
blob = txn.get(b"state")
|
|
116
|
+
finally:
|
|
117
|
+
env.close()
|
|
118
|
+
else: # pragma: no cover
|
|
119
|
+
raise ValueError(f"Unknown backend: {backend}")
|
|
120
|
+
|
|
121
|
+
if blob is None: # pragma: no cover
|
|
122
|
+
return None
|
|
123
|
+
return loads_payload(blob)
|
|
@@ -303,6 +303,7 @@ class Engine:
|
|
|
303
303
|
raise PersistentCacheError(
|
|
304
304
|
"engine has no persistent cache; pass cache_dir= to Engine"
|
|
305
305
|
)
|
|
306
|
+
self._evaluator.flush_disk()
|
|
306
307
|
self._disk.clear()
|
|
307
308
|
|
|
308
309
|
def transaction(self) -> EngineTransaction:
|
|
@@ -350,6 +351,9 @@ class Engine:
|
|
|
350
351
|
def accumulator(self, name: str) -> Accumulator:
|
|
351
352
|
return Accumulator(self, name=name)
|
|
352
353
|
|
|
354
|
+
def flush_disk(self) -> None:
|
|
355
|
+
self._evaluator.flush_disk()
|
|
356
|
+
|
|
353
357
|
def shutdown(self, *, wait: bool = True, cancel_futures: bool = False) -> None:
|
|
354
358
|
"""Shut down the lazily created default :meth:`submit` thread pool, if any.
|
|
355
359
|
|
|
@@ -362,6 +366,7 @@ class Engine:
|
|
|
362
366
|
self._submit_executor = None
|
|
363
367
|
if pool is not None:
|
|
364
368
|
pool.shutdown(wait=wait, cancel_futures=cancel_futures)
|
|
369
|
+
self._evaluator.shutdown(wait=wait)
|
|
365
370
|
if self._disk is not None:
|
|
366
371
|
self._disk.close()
|
|
367
372
|
|
|
@@ -574,11 +579,11 @@ class Engine:
|
|
|
574
579
|
if vacuum_disk and self._disk is not None:
|
|
575
580
|
self._evaluator.prune_disk_cache(root_list)
|
|
576
581
|
|
|
577
|
-
def save(self, path: str) -> None:
|
|
578
|
-
save_payload(path, self._store.make_persistence_payload())
|
|
582
|
+
def save(self, path: str, backend: Literal["sqlite", "mdbx", "lmdb"] = "sqlite") -> None:
|
|
583
|
+
save_payload(path, self._store.make_persistence_payload(), backend=backend)
|
|
579
584
|
|
|
580
|
-
def load(self, path: str) -> None:
|
|
581
|
-
payload = load_payload(path)
|
|
585
|
+
def load(self, path: str, backend: Literal["sqlite", "mdbx", "lmdb"] = "sqlite") -> None:
|
|
586
|
+
payload = load_payload(path, backend=backend)
|
|
582
587
|
if payload is None:
|
|
583
588
|
return
|
|
584
589
|
self._store.assign_loaded_state(payload)
|
|
@@ -48,6 +48,7 @@ tests/test_incremental_pipeline.py
|
|
|
48
48
|
tests/test_internal_invariants.py
|
|
49
49
|
tests/test_memoize_false.py
|
|
50
50
|
tests/test_performance.py
|
|
51
|
+
tests/test_persistence_permutations.py
|
|
51
52
|
tests/test_repro_touch_memo_keyerror.py
|
|
52
53
|
tests/test_scale_behavior.py
|
|
53
54
|
tests/test_serde.py
|