forgetproof 0.2.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.
@@ -0,0 +1,283 @@
1
+ """A verified delete for mem0: `Memory.delete()` and `Memory.delete_all()`, followed by the engine, ending in receipts.
2
+
3
+ `forget_memory(memory, id)` reads the memory's text, lets mem0 delete it, then erases what the stores behind
4
+ that `Memory` still hold of it and returns one signed receipt per store. `forget_user` does the same around
5
+ `delete_all`, and `VerifiedMemory` wraps a `Memory` so its own `delete` and `delete_all` do it. This module
6
+ covers mem0's history database and a vector store on local disk: Qdrant local, or a Chroma persist directory.
7
+
8
+ What mem0 keeps after a delete. `Memory.delete(id)` removes the point from the vector store and appends a
9
+ DELETE row to `history.db` whose `old_memory` is the full text, next to the ADD and UPDATE rows that carry the
10
+ same text (`mem0_store.py` has the details). Qdrant local deletes its row and leaves the bytes in SQLite free
11
+ space. The engine removes both; this module only has to point it at the right files, with the memory's text
12
+ as the subject so the receipt can say whether that exact text is still anywhere in them.
13
+
14
+ Why the files are closed and reopened around the fix, rather than rewritten under the live client or queued.
15
+ A live `Memory` holds two things open: `SQLiteManager`'s connection to `history.db`, and a Qdrant local
16
+ client, which holds each collection's `storage.sqlite` and an exclusive lock on the directory, and which
17
+ keeps every point in memory. The engine refuses to rewrite a store another handle has open (`fix`'s open-file
18
+ check), and on Windows those handles also make the rename it uses to check impossible. Tested with mem0ai
19
+ 2.2.1 and qdrant-client 1.20 on Windows: while the `Memory` is alive, `forget()` on either store finds it open
20
+ and queues the request instead of fixing anything; after `memory.db.close()` and `memory.vector_store
21
+ .client.close()` nothing is held, both stores fix to a CLEAN receipt, and the `Memory` works again once its
22
+ two handles are recreated the way mem0's own `reset()` recreates them (`SQLiteManager(path)` and
23
+ `QdrantClient(path=...)`). So this module closes those two handles, runs the engine, and reopens them, with
24
+ the `Memory` unusable only for the duration of the call. The queue would have been the other safe route, but
25
+ it hands the caller a marker instead of a receipt and needs a second call on the next start; that is kept for
26
+ the one store that cannot be closed from inside a process, a Chroma persist directory, where chromadb keeps
27
+ the store's state in process memory for the life of the process and would write it back over the fix. For
28
+ Chroma the request is queued with `forget.queue()` and `forget.run_queued(path)` finishes it before the
29
+ application next opens the store.
30
+
31
+ No memory's text is ever printed, logged or stored by this module. The receipts carry counts and file hashes
32
+ only, as the engine's always do, and the result wraps them without adding anything from the memory.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import json
38
+ from collections.abc import Iterator
39
+ from contextlib import contextmanager
40
+ from dataclasses import asdict, dataclass
41
+ from pathlib import Path
42
+
43
+ from .. import forget as _forget
44
+ from ..scanner import UnsupportedStore, detect
45
+ from ..subject import subject as make_subject
46
+
47
+ VERDICTS = ("CLEAN", "RESIDUE_REMAINS", "UNVERIFIABLE", "QUEUED")
48
+ _LIST_LIMIT = 100_000 # get_all pages nothing; one call with a limit no personal store reaches
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Store:
53
+ """One place a `Memory` keeps data: what it is, where, and what this module can do about it.
54
+
55
+ `reach` is "fix" (closed, fixed and reopened in this call), "queue" (queued for `run_queued`, the
56
+ store stays open) or "none" (not on this machine's disk, or not a store the engine reads)."""
57
+
58
+ kind: str # history, qdrant, chroma, remote, unsupported
59
+ path: Path | None
60
+ reach: str
61
+ note: str
62
+
63
+
64
+ def _history_path(memory) -> Path | None:
65
+ path = getattr(getattr(memory, "config", None), "history_db_path", None)
66
+ if not path:
67
+ path = getattr(getattr(memory, "db", None), "db_path", None)
68
+ if not path or path == ":memory:":
69
+ return None
70
+ return Path(path)
71
+
72
+
73
+ def _qdrant_local_path(vector_store) -> str | None:
74
+ """The directory of a Qdrant client in local mode, or None. qdrant-client wraps `QdrantLocal` in
75
+ `QdrantClient._client` when it was given `path=`; a server client has a REST client there instead."""
76
+ client = getattr(vector_store, "client", None)
77
+ inner = getattr(client, "_client", None)
78
+ location = getattr(inner, "location", None)
79
+ if type(inner).__name__ == "QdrantLocal" and location and location != ":memory:":
80
+ return location
81
+ return None
82
+
83
+
84
+ def _chroma_persist_path(vector_store) -> str | None:
85
+ """The persist directory of mem0's Chroma wrapper, or None. The wrapper keeps the chromadb `Settings` it
86
+ built; a client the application passed in answers `get_settings()` itself."""
87
+ settings = getattr(vector_store, "settings", None)
88
+ if settings is None:
89
+ client = getattr(vector_store, "client", None)
90
+ get = getattr(client, "get_settings", None)
91
+ settings = get() if callable(get) else None
92
+ if settings is None or getattr(settings, "chroma_server_host", None) or not getattr(settings, "is_persistent", False):
93
+ return None
94
+ return getattr(settings, "persist_directory", None) or None
95
+
96
+
97
+ def stores_of(memory) -> list[Store]:
98
+ """The stores behind a `Memory`: its history database, then its vector store when that is on local disk.
99
+
100
+ A remote vector store (a Qdrant or Chroma server, Pinecone, pgvector, any cloud index) is listed with
101
+ reach "none": this module cannot see its disk. A local store the engine does not read (FAISS, say) is
102
+ listed the same way."""
103
+ stores: list[Store] = []
104
+ history = _history_path(memory)
105
+ if history is None:
106
+ stores.append(Store("history", None, "none", "mem0 keeps its history in memory only; nothing on disk to check"))
107
+ else:
108
+ stores.append(Store("history", history, "fix", "mem0's history database"))
109
+
110
+ vs = getattr(memory, "vector_store", None)
111
+ provider = getattr(getattr(getattr(memory, "config", None), "vector_store", None), "provider", None) or type(vs).__name__
112
+ qdrant = _qdrant_local_path(vs)
113
+ if qdrant:
114
+ stores.append(Store("qdrant", Path(qdrant), "fix", "Qdrant in local mode"))
115
+ return stores
116
+ chroma = _chroma_persist_path(vs)
117
+ if chroma:
118
+ stores.append(Store("chroma", Path(chroma), "queue", "a Chroma persist directory; queued, since chromadb keeps "
119
+ "the store in process memory until the application exits"))
120
+ return stores
121
+ local = getattr(vs, "path", None)
122
+ if local and Path(str(local)).exists():
123
+ try:
124
+ detect(local)
125
+ except UnsupportedStore:
126
+ stores.append(Store("unsupported", Path(str(local)), "none", f"{provider}: on this disk, but not a store the engine reads"))
127
+ return stores
128
+ stores.append(Store("unsupported", Path(str(local)), "fix", provider))
129
+ return stores
130
+ stores.append(Store("remote", None, "none", f"{provider}: not on this machine's disk; its deletions cannot be checked from here"))
131
+ return stores
132
+
133
+
134
+ @contextmanager
135
+ def _released(memory, stores: list[Store]) -> Iterator[None]:
136
+ """Close the handles the `Memory` holds on the stores about to be fixed; reopen them afterwards, even on error.
137
+
138
+ The history connection is recreated the way mem0's `reset()` recreates it. A Qdrant local client is
139
+ recreated with the same path, so it reloads the collections from the fixed files; the entity store, which
140
+ shares that client, is dropped so mem0 rebuilds it from the new client on first use."""
141
+ reopen = []
142
+ kinds = {s.kind for s in stores if s.reach == "fix"}
143
+ db = getattr(memory, "db", None)
144
+ if "history" in kinds and db is not None and hasattr(db, "close"):
145
+ path = getattr(db, "db_path", None) or str(_history_path(memory))
146
+ db.close()
147
+ reopen.append(lambda: setattr(memory, "db", type(db)(path)))
148
+ if "qdrant" in kinds:
149
+ vs = memory.vector_store
150
+ client = vs.client
151
+ location = _qdrant_local_path(vs)
152
+ client.close()
153
+
154
+ def reopen_qdrant() -> None:
155
+ vs.client = type(client)(path=location)
156
+ if getattr(memory, "_entity_store", None) is not None:
157
+ memory._entity_store = None
158
+
159
+ reopen.append(reopen_qdrant)
160
+ try:
161
+ yield
162
+ finally:
163
+ for step in reopen:
164
+ step()
165
+
166
+
167
+ def _texts_of(memory, memory_id: str) -> list[str]:
168
+ """Every text this memory has had: its current text from `get()`, earlier versions from `history()`."""
169
+ item = memory.get(memory_id)
170
+ if not item:
171
+ raise ValueError(f"memory {memory_id} not found")
172
+ texts = [item.get("memory") or ""]
173
+ for row in memory.history(memory_id) or []:
174
+ for key in ("old_memory", "new_memory"):
175
+ if row.get(key):
176
+ texts.append(row[key])
177
+ return [t for t in texts if t]
178
+
179
+
180
+ def _verify(memory, texts: list[str], receipt_path: Path | str | None, correlation_id: str | None) -> dict:
181
+ """Run the engine on every store behind `memory` with `texts` as the subject and assemble the result."""
182
+ subj = make_subject(texts)
183
+ stores = stores_of(memory)
184
+ receipts: list[dict] = []
185
+ queued: list[dict] = []
186
+ not_covered: list[str] = []
187
+ with _released(memory, stores):
188
+ for store in stores:
189
+ if store.reach == "fix":
190
+ outcome = _forget.forget(store.path, subj, correlation_id=correlation_id)
191
+ if isinstance(outcome, dict):
192
+ receipts.append(outcome)
193
+ else:
194
+ queued.append(asdict(outcome))
195
+ elif store.reach == "queue":
196
+ queued.append(asdict(_forget.queue(store.path, subj, correlation_id=correlation_id)))
197
+ else:
198
+ not_covered.append(store.note)
199
+ if any(r["verdict"] == "RESIDUE_REMAINS" for r in receipts):
200
+ verdict = "RESIDUE_REMAINS"
201
+ elif not_covered or any(r["verdict"] == "UNVERIFIABLE" for r in receipts):
202
+ verdict = "UNVERIFIABLE"
203
+ elif queued:
204
+ verdict = "QUEUED"
205
+ else:
206
+ verdict = "CLEAN"
207
+ result = {
208
+ "verdict": verdict,
209
+ "subject_values": subj.count,
210
+ "stores": [{"kind": s.kind, "path": str(s.path) if s.path else None, "reach": s.reach} for s in stores],
211
+ "receipts": receipts,
212
+ "queued": queued,
213
+ "not_covered": not_covered,
214
+ "correlation_id": correlation_id,
215
+ }
216
+ if receipt_path:
217
+ Path(receipt_path).write_text(json.dumps(result, indent=2), encoding="utf-8")
218
+ return result
219
+
220
+
221
+ def _forget_memory(memory, memory_id: str, receipt_path, correlation_id) -> tuple[object, dict]:
222
+ texts = _texts_of(memory, memory_id)
223
+ outcome = memory.delete(memory_id)
224
+ return outcome, _verify(memory, texts, receipt_path, correlation_id)
225
+
226
+
227
+ def _forget_all(memory, filters: dict[str, str], receipt_path, correlation_id) -> tuple[object, dict]:
228
+ listed = memory.get_all(filters=filters, top_k=_LIST_LIMIT)
229
+ items = listed.get("results", []) if isinstance(listed, dict) else list(listed or [])
230
+ if not items:
231
+ raise ValueError(f"no memories match {filters}; nothing to delete, so nothing to verify")
232
+ texts: list[str] = []
233
+ for item in items:
234
+ texts.extend(_texts_of(memory, item["id"]))
235
+ outcome = memory.delete_all(**filters)
236
+ return outcome, _verify(memory, texts, receipt_path, correlation_id)
237
+
238
+
239
+ def forget_memory(memory, memory_id: str, *, receipt_path: Path | str | None = None,
240
+ correlation_id: str | None = None) -> dict:
241
+ """Delete one memory through mem0, erase what its stores still hold of it, and return the receipts.
242
+
243
+ The subject is every text the memory has had: the current one and the earlier versions in its history.
244
+ The result is a dict: `verdict` (CLEAN, RESIDUE_REMAINS, UNVERIFIABLE or QUEUED, the worst across the
245
+ stores), `subject_values` (how many distinct texts; never the texts), `stores` (what was found behind
246
+ the `Memory` and what was done with each), `receipts` (one signed receipt per store fixed now, each
247
+ verifiable with `receipt.verify_signature`), `queued` (one marker per store queued for `run_queued`),
248
+ `not_covered` (one line per store this module cannot see) and the `correlation_id` given. With
249
+ `receipt_path` the same dict is also written there as JSON. Raises ValueError if the memory does
250
+ not exist; the `Memory` is left as it was.
251
+ """
252
+ return _forget_memory(memory, memory_id, receipt_path, correlation_id)[1]
253
+
254
+
255
+ def forget_user(memory, user_id: str, *, receipt_path: Path | str | None = None,
256
+ correlation_id: str | None = None) -> dict:
257
+ """Delete every memory of `user_id` through mem0's `delete_all`, erase what the stores still hold of
258
+ them, and return the receipts: the same result as `forget_memory`, with every memory's texts as the
259
+ subject. Raises ValueError when the user has no memories, since there is then nothing to verify."""
260
+ return _forget_all(memory, {"user_id": user_id}, receipt_path, correlation_id)[1]
261
+
262
+
263
+ class VerifiedMemory:
264
+ """A `Memory` whose `delete` and `delete_all` return `(mem0's result, receipts)`; everything else is the
265
+ wrapped `Memory`'s own. `receipts` is the dict `forget_memory` returns."""
266
+
267
+ def __init__(self, memory, *, correlation_id: str | None = None):
268
+ self.memory = memory
269
+ self.correlation_id = correlation_id
270
+
271
+ def __getattr__(self, name):
272
+ return getattr(self.memory, name)
273
+
274
+ def delete(self, memory_id: str, *, receipt_path: Path | str | None = None,
275
+ correlation_id: str | None = None) -> tuple[object, dict]:
276
+ return _forget_memory(self.memory, memory_id, receipt_path, correlation_id or self.correlation_id)
277
+
278
+ def delete_all(self, user_id: str | None = None, agent_id: str | None = None, run_id: str | None = None, *,
279
+ receipt_path: Path | str | None = None, correlation_id: str | None = None) -> tuple[object, dict]:
280
+ filters = {k: v for k, v in (("user_id", user_id), ("agent_id", agent_id), ("run_id", run_id)) if v}
281
+ if not filters:
282
+ raise ValueError("delete_all needs a user_id, agent_id or run_id")
283
+ return _forget_all(self.memory, filters, receipt_path, correlation_id or self.correlation_id)
@@ -0,0 +1,58 @@
1
+ """Where forgetproof keeps the secrets it generates for itself: the Ed25519 signing key, and the
2
+ key that encrypts a forget() request queued for later. By default that's a file under
3
+ FORGETPROOF_HOME with owner-only permissions, same as every release before this one.
4
+
5
+ Set FORGETPROOF_USE_KEYRING=1 to store them in the OS keychain instead — macOS Keychain, Windows
6
+ Credential Locker, the Secret Service on Linux — via the optional `keyring` package. This is
7
+ opt-in, never auto-detected: a keychain backend that needs an interactive unlock (most do, the
8
+ first time a new process touches them) would otherwise silently hang a non-interactive process the
9
+ first time it runs — a CI job or a backend service as much as a test suite. Decide to turn it on;
10
+ don't let a desktop session you happened to be running in decide it for you.
11
+
12
+ An existing file is never moved into the keychain automatically: if one is already there,
13
+ forgetproof keeps using it, so turning this on after the fact doesn't change which key a machine
14
+ signs with, or stop it from decrypting a queue entry a file key already encrypted.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ from collections.abc import Callable
21
+ from pathlib import Path
22
+
23
+ try:
24
+ import keyring
25
+ import keyring.errors
26
+ except ImportError:
27
+ keyring = None # the [keyring] extra isn't installed; the file fallback is what forgetproof always did
28
+
29
+ SERVICE = "forgetproof"
30
+
31
+
32
+ def use_keyring() -> bool:
33
+ return os.environ.get("FORGETPROOF_USE_KEYRING", "") == "1"
34
+
35
+
36
+ def get_or_create(name: str, path: Path, generate: Callable[[], bytes]) -> bytes:
37
+ """Return the secret kept at `path`, or under `name` in the OS keychain if
38
+ FORGETPROOF_USE_KEYRING=1 and `path` doesn't already hold one — creating it with
39
+ `generate()` on first use either way.
40
+ """
41
+ if path.exists():
42
+ return path.read_bytes()
43
+ if use_keyring() and keyring is not None:
44
+ try:
45
+ existing = keyring.get_password(SERVICE, name)
46
+ if existing is not None:
47
+ return bytes.fromhex(existing)
48
+ value = generate()
49
+ keyring.set_password(SERVICE, name, value.hex())
50
+ return value
51
+ except keyring.errors.KeyringError:
52
+ pass # no backend usable right now (e.g. no desktop session) — fall back to the file
53
+ value = generate()
54
+ path.parent.mkdir(parents=True, exist_ok=True)
55
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
56
+ with os.fdopen(fd, "wb") as f:
57
+ f.write(value)
58
+ return value
@@ -0,0 +1,191 @@
1
+ """LanceDB: an embedded vector database used by local-first agents and RAG tools.
2
+
3
+ A LanceDB database is a directory of tables, each a `<name>.lance` directory with immutable
4
+ fragment files under `data/`, a manifest per version under `_versions/`, and deletion vectors under
5
+ `_deletions/`. Rows are never changed in place: a delete writes a deletion vector that hides the
6
+ row, an update writes the new row to a new fragment and hides the old one. The hidden rows' bytes —
7
+ documents, payloads, embeddings — stay in the fragment files, and every earlier version of the
8
+ table stays readable, until the table is compacted and its old versions cleaned up. Neither happens
9
+ on its own.
10
+
11
+ Scanning reads the fragment and deletion files directly: rows hidden by deletion vectors are
12
+ counted from the deletion files, retained versions from the manifests, and personal data in the raw
13
+ fragment bytes is compared with what the table returns through LanceDB (when `lancedb` is
14
+ installed; without it the scan is reported incomplete, never clean). Fixing calls
15
+ `optimize(cleanup_older_than=0, delete_unverified=True)` on each table: compaction rewrites the live
16
+ rows into new fragments and the cleanup deletes the old fragments and manifests.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from datetime import timedelta
22
+ from pathlib import Path
23
+
24
+ from .pii import LivePii, find_pii, summarize
25
+ from .report import Finding, Report
26
+
27
+ GHOST_VECTORS = "embeddings can be inverted back to text (Ghost Vectors, arXiv:2606.18497)"
28
+
29
+
30
+ def is_table(d: Path) -> bool:
31
+ return d.is_dir() and d.suffix == ".lance" and (d / "_versions").is_dir()
32
+
33
+
34
+ def detect(target: Path) -> bool:
35
+ if not target.is_dir():
36
+ return False
37
+ if is_table(target):
38
+ return True
39
+ try:
40
+ return any(is_table(p) for p in target.iterdir() if not p.is_symlink())
41
+ except OSError:
42
+ return False
43
+
44
+
45
+ def tables(target: Path) -> list[Path]:
46
+ if is_table(target):
47
+ return [target]
48
+ return sorted(p for p in target.iterdir() if not p.is_symlink() and is_table(p))
49
+
50
+
51
+ def _lancedb():
52
+ try:
53
+ import lancedb
54
+ except ImportError:
55
+ return None
56
+ return lancedb
57
+
58
+
59
+ def _files(table: Path, sub: str) -> list[Path]:
60
+ d = table / sub
61
+ return sorted(p for p in d.iterdir() if p.is_file()) if d.is_dir() else []
62
+
63
+
64
+ def _deleted_rows(table: Path) -> int | None:
65
+ """Rows hidden by deletion vectors, counted from the `_deletions` files (Arrow IPC lists one row
66
+ id per row). A fragment's deletion file is rewritten whole at each version — named
67
+ `<fragment>-<version>-<id>` — so only the newest per fragment is counted, and the older ones are
68
+ themselves residue the old-versions finding covers. A bitmap-encoded file can't be counted
69
+ without Lance itself; None means unknown."""
70
+ files = _files(table, "_deletions")
71
+ if not files:
72
+ return 0
73
+ try:
74
+ import pyarrow.ipc as ipc
75
+ except ImportError:
76
+ return None
77
+ newest: dict[str, tuple[int, Path]] = {}
78
+ for f in files:
79
+ parts = f.stem.split("-")
80
+ try:
81
+ frag, version = parts[0], int(parts[1])
82
+ except (IndexError, ValueError):
83
+ frag, version = f.stem, 0
84
+ if frag not in newest or version > newest[frag][0]:
85
+ newest[frag] = (version, f)
86
+ total = 0
87
+ for _, f in newest.values():
88
+ if f.suffix != ".arrow":
89
+ return None
90
+ try:
91
+ with ipc.open_file(str(f)) as reader:
92
+ total += sum(reader.get_batch(i).num_rows for i in range(reader.num_record_batches))
93
+ except Exception:
94
+ return None
95
+ return total
96
+
97
+
98
+ def _live_values(table: Path) -> set[tuple[str, bytes]] | None:
99
+ lancedb = _lancedb()
100
+ if lancedb is None:
101
+ return None
102
+ import pyarrow as pa
103
+
104
+ db = lancedb.connect(str(table.parent))
105
+ t = db.open_table(table.stem)
106
+ found: set[tuple[str, bytes]] = set()
107
+ for batch in t.to_arrow().to_batches():
108
+ for i, field in enumerate(batch.schema):
109
+ if pa.types.is_string(field.type) or pa.types.is_large_string(field.type):
110
+ for v in batch.column(i).to_pylist():
111
+ if v:
112
+ found.update(find_pii(v.encode()))
113
+ elif pa.types.is_binary(field.type) or pa.types.is_large_binary(field.type):
114
+ for v in batch.column(i).to_pylist():
115
+ if v:
116
+ found.update(find_pii(v))
117
+ return found
118
+
119
+
120
+ def scan(target: Path, report: Report, show: bool = False) -> None:
121
+ report.stats["tables"] = len(tables(target))
122
+ for table in tables(target):
123
+ rel = table.name if table != target else table.name
124
+ raw: set[tuple[str, bytes]] = set()
125
+ for f in _files(table, "data") + _files(table, "_deletions"):
126
+ raw.update(find_pii(f.read_bytes()))
127
+ deleted = _deleted_rows(table)
128
+ versions = len([m for m in _files(table, "_versions") if m.suffix == ".manifest"])
129
+ live = _live_values(table)
130
+ if live is None:
131
+ report.incomplete = ("lancedb isn't installed, so live rows can't be told from deleted ones in the "
132
+ "fragment files; install forgetproof[lancedb]")
133
+ residue = set()
134
+ else:
135
+ residue = LivePii(live).not_live(raw)
136
+ if deleted:
137
+ pii, samples = summarize(residue, show)
138
+ report.findings.append(Finding(
139
+ check="lancedb.deleted_rows",
140
+ title="Deleted or replaced rows still stored in the table's fragment files — only hidden by a deletion vector",
141
+ location=f"{rel}/data",
142
+ records=deleted,
143
+ unit="rows",
144
+ why="a delete, and the old row of an update, write a deletion vector and leave the row's text and "
145
+ f"embedding in place; {GHOST_VECTORS}",
146
+ pii=pii,
147
+ samples=samples,
148
+ ))
149
+ elif residue:
150
+ pii, samples = summarize(residue, show)
151
+ report.findings.append(Finding(
152
+ check="lancedb.fragments",
153
+ title="Known-pattern values in fragment files that the table no longer returns",
154
+ location=f"{rel}/data",
155
+ records=len(residue),
156
+ unit="pattern matches",
157
+ why="rows replaced by an update, or hidden by a bitmap deletion vector, stay in their fragment file",
158
+ pii=pii,
159
+ samples=samples,
160
+ ))
161
+ if versions > 1:
162
+ report.findings.append(Finding(
163
+ check="lancedb.old_versions",
164
+ title="Earlier versions of the table are still readable",
165
+ location=f"{rel}/_versions",
166
+ records=versions - 1,
167
+ unit="versions",
168
+ why="every version's manifest, and the fragments it references, stay until cleanup_old_versions; "
169
+ "`checkout(version)` reads rows deleted or changed since",
170
+ ))
171
+
172
+
173
+ def plan(report: Report) -> list[str]:
174
+ return ["compact each table's fragments from its live rows (optimize), which drops hidden rows",
175
+ "delete every earlier version's manifest and the fragment files only they referenced"]
176
+
177
+
178
+ def fix(target: Path) -> list[str]:
179
+ lancedb = _lancedb()
180
+ if lancedb is None:
181
+ from .fixer import FixError
182
+
183
+ raise FixError("fixing a LanceDB store needs lancedb: pip install 'forgetproof[lancedb]'")
184
+ actions = []
185
+ for table in tables(target):
186
+ before = len([m for m in _files(table, "_versions") if m.suffix == ".manifest"])
187
+ db = lancedb.connect(str(table.parent))
188
+ t = db.open_table(table.stem)
189
+ t.optimize(cleanup_older_than=timedelta(0), delete_unverified=True)
190
+ actions.append(f"compacted {table.name} and removed {max(before - 1, 0)} old version(s)")
191
+ return actions