kipp-memory 0.1.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.
kipp/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Entity-based persistent memory for AI agents."""
kipp/backup.py ADDED
@@ -0,0 +1,155 @@
1
+ """Snapshot every Qdrant collection to local disk (#38).
2
+
3
+ ``kipp export`` covers only the shared domain's entities, so it is not a
4
+ backup. This takes a native Qdrant snapshot of EVERY collection, downloads it,
5
+ verifies it against the checksum Qdrant reports, and deletes the server-side
6
+ copy (``/qdrant/snapshots`` is not on the data volume, so leftovers pile up in
7
+ the container's writable layer).
8
+
9
+ A run writes into ``<dest>/.partial-<stamp>/`` and is renamed to
10
+ ``<dest>/<stamp>/`` only once every collection verified, so a directory named
11
+ like a stamp is always a complete backup. ``manifest.json`` records each
12
+ collection's exact point count and sha256 at backup time.
13
+
14
+ Same disk as the data: this covers a bad migration, a buggy repair or an
15
+ accidental delete — not drive failure.
16
+
17
+ Restore one collection (replaces it; Qdrant reads the file from the upload):
18
+ curl -X POST "$QDRANT_URL/collections/<name>/snapshots/upload?priority=snapshot" \\
19
+ -H "api-key: $QDRANT_API_KEY" -F snapshot=@<dest>/<stamp>/<name>.snapshot
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ import os
27
+ import re
28
+ import shutil
29
+ import time
30
+ from dataclasses import dataclass, field
31
+ from datetime import datetime
32
+ from pathlib import Path
33
+ from typing import Protocol
34
+
35
+ import httpx
36
+
37
+ STAMP_RE = re.compile(r"^\d{8}T\d{6}Z$")
38
+ PARTIAL_PREFIX = ".partial-"
39
+ DEFAULT_KEEP = 7 # ~150 MB each; a week of nightly rollback
40
+ CHUNK = 1 << 20
41
+ STALE_PARTIAL_SECONDS = 24 * 3600
42
+
43
+
44
+ class SnapshotClient(Protocol):
45
+ """The slice of ``QdrantClient`` a backup needs."""
46
+
47
+ def get_collections(self): ...
48
+ def count(self, collection_name: str, exact: bool = True): ...
49
+ def create_snapshot(self, collection_name: str, wait: bool = True): ...
50
+ def delete_snapshot(self, collection_name: str, snapshot_name: str, wait: bool = True): ...
51
+
52
+
53
+ @dataclass
54
+ class BackupResult:
55
+ path: Path
56
+ collections: dict[str, dict] = field(default_factory=dict) # name -> manifest entry
57
+ pruned: list[Path] = field(default_factory=list)
58
+
59
+
60
+ def backup_all(
61
+ client: SnapshotClient,
62
+ http: httpx.Client,
63
+ dest: Path,
64
+ now: datetime,
65
+ keep: int = DEFAULT_KEEP,
66
+ ) -> BackupResult:
67
+ """Snapshot every collection into ``dest/<stamp>/``, then prune to ``keep``.
68
+
69
+ ``http`` must target the same Qdrant as ``client`` (base_url + api-key
70
+ header); snapshots are downloaded through it because qdrant-client's
71
+ generated download call decodes the binary body as text.
72
+ """
73
+ if keep < 1:
74
+ raise ValueError(f"keep must be >= 1, got {keep}")
75
+ stamp = now.strftime("%Y%m%dT%H%M%SZ")
76
+ final = dest / stamp
77
+ if final.exists():
78
+ raise FileExistsError(f"backup already exists: {final}")
79
+ partial = dest / f"{PARTIAL_PREFIX}{stamp}"
80
+ dest.mkdir(parents=True, exist_ok=True)
81
+ partial.mkdir(mode=0o700)
82
+
83
+ result = BackupResult(path=final)
84
+ try:
85
+ names = sorted(c.name for c in client.get_collections().collections)
86
+ for name in names:
87
+ points = client.count(name, exact=True).count
88
+ snap = client.create_snapshot(name, wait=True)
89
+ if snap is None:
90
+ raise RuntimeError(f"Qdrant returned no snapshot for {name}")
91
+ try:
92
+ digest, size = _download(http, name, snap.name, partial / f"{name}.snapshot")
93
+ finally:
94
+ client.delete_snapshot(name, snap.name, wait=True)
95
+ if snap.checksum and digest != snap.checksum:
96
+ raise RuntimeError(
97
+ f"{name}: downloaded sha256 {digest} != Qdrant's {snap.checksum}"
98
+ )
99
+ result.collections[name] = {"points": points, "bytes": size, "sha256": digest}
100
+ _write_private(partial / "manifest.json", json.dumps(
101
+ {"created": now.isoformat(), "collections": result.collections}, indent=2,
102
+ ).encode())
103
+ partial.rename(final)
104
+ except BaseException:
105
+ shutil.rmtree(partial, ignore_errors=True)
106
+ raise
107
+ result.pruned = prune(dest, keep)
108
+ return result
109
+
110
+
111
+ def _download(http: httpx.Client, collection: str, snapshot: str, path: Path) -> tuple[str, int]:
112
+ sha, size = hashlib.sha256(), 0
113
+ with http.stream("GET", f"/collections/{collection}/snapshots/{snapshot}") as resp:
114
+ resp.raise_for_status()
115
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
116
+ with os.fdopen(fd, "wb") as fh:
117
+ for chunk in resp.iter_bytes(CHUNK):
118
+ fh.write(chunk)
119
+ sha.update(chunk)
120
+ size += len(chunk)
121
+ if size == 0:
122
+ raise RuntimeError(f"{collection}: empty snapshot download")
123
+ return sha.hexdigest(), size
124
+
125
+
126
+ def _write_private(path: Path, data: bytes) -> None:
127
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
128
+ with os.fdopen(fd, "wb") as fh:
129
+ fh.write(data)
130
+
131
+
132
+ def prune(dest: Path, keep: int) -> list[Path]:
133
+ """Delete all but the newest ``keep`` complete backups, plus stale partials.
134
+
135
+ Only directories this module names are touched: ``<stamp>`` and
136
+ ``.partial-<stamp>``. Stamps sort chronologically as strings. A partial is
137
+ left by a killed run (SIGKILL skips the cleanup); it is removed once it
138
+ is a day old, so a concurrent run's in-flight directory is never touched.
139
+ """
140
+ removed: list[Path] = []
141
+ complete = sorted(p for p in dest.iterdir() if p.is_dir() and STAMP_RE.match(p.name))
142
+ for old in complete[:-keep]:
143
+ shutil.rmtree(old)
144
+ removed.append(old)
145
+ cutoff = time.time() - STALE_PARTIAL_SECONDS
146
+ for p in dest.iterdir():
147
+ if (
148
+ p.is_dir()
149
+ and p.name.startswith(PARTIAL_PREFIX)
150
+ and STAMP_RE.match(p.name[len(PARTIAL_PREFIX):])
151
+ and p.stat().st_mtime < cutoff # never a run still in flight
152
+ ):
153
+ shutil.rmtree(p)
154
+ removed.append(p)
155
+ return removed