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.
- forgetproof/__init__.py +3 -0
- forgetproof/__main__.py +5 -0
- forgetproof/_chroma_rebuild.py +197 -0
- forgetproof/agent.py +342 -0
- forgetproof/cli.py +582 -0
- forgetproof/copies.py +155 -0
- forgetproof/desktop/__init__.py +1 -0
- forgetproof/desktop/__main__.py +26 -0
- forgetproof/desktop/api.py +549 -0
- forgetproof/desktop/app.py +59 -0
- forgetproof/desktop/schedule.py +161 -0
- forgetproof/desktop/ui/index.html +298 -0
- forgetproof/discovery.py +357 -0
- forgetproof/erase_live.py +180 -0
- forgetproof/files_store.py +69 -0
- forgetproof/fixer.py +274 -0
- forgetproof/forget.py +264 -0
- forgetproof/forgetme.py +270 -0
- forgetproof/hnsw.py +132 -0
- forgetproof/integrations/__init__.py +9 -0
- forgetproof/integrations/mem0.py +283 -0
- forgetproof/keystore.py +58 -0
- forgetproof/lance_store.py +191 -0
- forgetproof/mcp_server.py +541 -0
- forgetproof/mem0_store.py +189 -0
- forgetproof/pii.py +160 -0
- forgetproof/postgres.py +334 -0
- forgetproof/py.typed +0 -0
- forgetproof/qdrant_store.py +69 -0
- forgetproof/receipt.py +135 -0
- forgetproof/remembered.py +257 -0
- forgetproof/report.py +59 -0
- forgetproof/safety.py +105 -0
- forgetproof/scanner.py +288 -0
- forgetproof/sqlite_pages.py +245 -0
- forgetproof/sqlite_residue.py +226 -0
- forgetproof/subject.py +81 -0
- forgetproof-0.2.0.dist-info/METADATA +397 -0
- forgetproof-0.2.0.dist-info/RECORD +42 -0
- forgetproof-0.2.0.dist-info/WHEEL +4 -0
- forgetproof-0.2.0.dist-info/entry_points.txt +3 -0
- forgetproof-0.2.0.dist-info/licenses/LICENSE +21 -0
forgetproof/forgetme.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""ForgetMe v1, the wire format: what the engine gives a host that speaks it.
|
|
2
|
+
|
|
3
|
+
ForgetMe is the button and flow a person and their personal agent use to make "forget this" really
|
|
4
|
+
happen and show what happened; ForgetProof is the engine behind it. This module is the engine's side
|
|
5
|
+
of the ForgetMe v1 wire contract (docs/extension.md): the namespace and outcome vocabulary, the
|
|
6
|
+
portable receipt (`forget-me-receipt/1`, a signed projection of an erasure that carries no host path,
|
|
7
|
+
no filename, no raw value, no cross-service identifier and no value hash), its verification, and the
|
|
8
|
+
discovery helpers a client uses to go from a Company's `/.well-known/poppy.json` to its endpoint and
|
|
9
|
+
its signing keys.
|
|
10
|
+
|
|
11
|
+
A host does not need this module to implement the contract; the spec and the schemas in
|
|
12
|
+
`schemas/forget-me/v1/` are enough. It exists so the demo's two parties, Pim and the reference
|
|
13
|
+
Company, share one implementation of the parts that must agree byte for byte: canonical JSON, the
|
|
14
|
+
signature, the outcome order.
|
|
15
|
+
|
|
16
|
+
ForgetMe is a third-party extension proposal targeting Poppy 1.0, the Personal Agent Protocol. It is
|
|
17
|
+
not approved, adopted or reviewed by anyone. The namespace `stellarminds.ai/forget-me`, version "1",
|
|
18
|
+
is provisional.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import hashlib
|
|
24
|
+
import re
|
|
25
|
+
from datetime import datetime, timezone
|
|
26
|
+
from typing import Any
|
|
27
|
+
from urllib.parse import urljoin, urlsplit
|
|
28
|
+
|
|
29
|
+
from cryptography.exceptions import InvalidSignature
|
|
30
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
|
31
|
+
|
|
32
|
+
from . import receipt as receipt_mod
|
|
33
|
+
|
|
34
|
+
NAMESPACE = "stellarminds.ai/forget-me"
|
|
35
|
+
VERSION = "1"
|
|
36
|
+
RECEIPT_FORMAT = "forget-me-receipt/1"
|
|
37
|
+
STATUS = "third-party proposal targeting Poppy 1.0; not approved, adopted or reviewed by anyone"
|
|
38
|
+
|
|
39
|
+
# The outcome vocabulary, worst first. The overall outcome of an operation is the worst of its holders:
|
|
40
|
+
# one clean store never overrides an outstanding one.
|
|
41
|
+
OUTCOMES = ("error", "bytes-still-found", "queued", "unsupported", "intentionally-retained", "inspected-and-clear")
|
|
42
|
+
SETTLED = ("inspected-and-clear", "intentionally-retained")
|
|
43
|
+
SCOPES = ("item", "account")
|
|
44
|
+
CHOICES = ("keep", "delete")
|
|
45
|
+
STATES = ("accepted", "running", "done", "error")
|
|
46
|
+
RETENTIONS = ("persistent", "none", "unknown")
|
|
47
|
+
|
|
48
|
+
# The verdict words receipts have always used, so a reader of 0.2 receipts recognises them. A portable
|
|
49
|
+
# receipt's `verdict` follows from its `outcome`; the outcome is the finer statement.
|
|
50
|
+
VERDICT_OF = {
|
|
51
|
+
"inspected-and-clear": "CLEAN",
|
|
52
|
+
"intentionally-retained": "RESIDUE_REMAINS",
|
|
53
|
+
"bytes-still-found": "RESIDUE_REMAINS",
|
|
54
|
+
"queued": "UNVERIFIABLE",
|
|
55
|
+
"unsupported": "UNVERIFIABLE",
|
|
56
|
+
"error": "UNVERIFIABLE",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
# Size bounds (docs/extension.md, "Size bounds"). Servers refuse more; clients send less.
|
|
60
|
+
MAX_BODY_BYTES = 16 * 1024
|
|
61
|
+
IDEMPOTENCY_KEY = (8, 128)
|
|
62
|
+
MAX_EXCEPTIONS = 64
|
|
63
|
+
MAX_LABEL = 200
|
|
64
|
+
MAX_TEXT = 2000
|
|
65
|
+
MAX_HOLDERS = 32
|
|
66
|
+
|
|
67
|
+
REFERENCE = re.compile(r"^fmr_[A-Za-z0-9_-]{16,48}$")
|
|
68
|
+
OPERATION = re.compile(r"^fmo_[A-Za-z0-9_-]{16,48}$")
|
|
69
|
+
IDEMPOTENCY = re.compile(r"^[\x21-\x7e]{8,128}$") # printable ASCII, no spaces
|
|
70
|
+
HOLDER_NAME = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
|
|
71
|
+
|
|
72
|
+
# What a portable receipt may say it did. Plain sentences, none of them naming a file, a path or a value.
|
|
73
|
+
ACTIONS = (
|
|
74
|
+
"record deleted through the holder's own API, by id",
|
|
75
|
+
"derived items removed",
|
|
76
|
+
"derived items rebuilt without the withdrawn record",
|
|
77
|
+
"active retrieval of the record stopped",
|
|
78
|
+
"residue the deletion left behind erased",
|
|
79
|
+
"every byte of the holder scanned for the exact text afterwards",
|
|
80
|
+
"exact text searched for in the holder",
|
|
81
|
+
"scanned again after a restart; nothing erased again",
|
|
82
|
+
"deletion requested through the holder's API and acknowledged",
|
|
83
|
+
"record kept, as the person chose",
|
|
84
|
+
"record kept under a retention the preview disclosed",
|
|
85
|
+
"restore attempted through the holder's own path and refused",
|
|
86
|
+
"nothing done: the holder was not reachable",
|
|
87
|
+
"nothing done: the request lost its authority before this step ran",
|
|
88
|
+
"nothing done: the holder could not be inspected from here",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def now() -> str:
|
|
93
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def worst(outcomes) -> str:
|
|
97
|
+
"""The worst outcome of a list, or `unsupported` for an empty one."""
|
|
98
|
+
best = None
|
|
99
|
+
for o in outcomes:
|
|
100
|
+
if o not in OUTCOMES:
|
|
101
|
+
raise ValueError(f"not a ForgetMe outcome: {o!r}")
|
|
102
|
+
if best is None or OUTCOMES.index(o) < OUTCOMES.index(best):
|
|
103
|
+
best = o
|
|
104
|
+
return best or "unsupported"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def counts(holders: list[dict]) -> dict[str, int]:
|
|
108
|
+
"""`{outcome: n}` for the holder rows of an outcome, in vocabulary order, zeros omitted."""
|
|
109
|
+
return {o: n for o in OUTCOMES if (n := sum(1 for h in holders if h.get("outcome") == o))}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# --- the portable receipt -------------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
def _digest(source: dict | None) -> dict | None:
|
|
115
|
+
if not source:
|
|
116
|
+
return None
|
|
117
|
+
return {"format": source.get("format", "unknown"), "digest": hashlib.sha256(receipt_mod.canonical(source)).hexdigest()}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def issue(*, issuer: str, operation: str, holder: str, kind: str, scope: str, outcome: str, actions: list[str],
|
|
121
|
+
before: dict, after: dict, coverage: dict, subject_values: int, key: Ed25519PrivateKey,
|
|
122
|
+
retrieval_stopped_at: str | None = None, physical_cleanup_at: str | None = None,
|
|
123
|
+
restore: dict | None = None, retained_until: str | None = None, source_receipt: dict | None = None,
|
|
124
|
+
issued_at: str | None = None) -> dict:
|
|
125
|
+
"""Sign a portable receipt for one holder of one operation.
|
|
126
|
+
|
|
127
|
+
Everything here is a count, a timestamp, a vocabulary word or a plain sentence from ACTIONS. The
|
|
128
|
+
caller is responsible for not passing a path, a filename, a value or a value hash in `coverage`
|
|
129
|
+
or anywhere else; `check_portable()` rejects the obvious cases. `source_receipt`, if given, is the
|
|
130
|
+
host's own full receipt (for example a forgetproof-receipt/0.2 with file hashes); only its format
|
|
131
|
+
and SHA-256 digest go into the portable one, so the host can match them up later without
|
|
132
|
+
publishing its paths.
|
|
133
|
+
"""
|
|
134
|
+
if outcome not in OUTCOMES:
|
|
135
|
+
raise ValueError(f"outcome must be one of {OUTCOMES}")
|
|
136
|
+
if scope not in SCOPES:
|
|
137
|
+
raise ValueError(f"scope must be one of {SCOPES}")
|
|
138
|
+
if not HOLDER_NAME.match(holder):
|
|
139
|
+
raise ValueError("holder must be a short lower-case name")
|
|
140
|
+
if not OPERATION.match(operation):
|
|
141
|
+
raise ValueError("operation must be an fmo_ id")
|
|
142
|
+
for a in actions:
|
|
143
|
+
if a not in ACTIONS:
|
|
144
|
+
raise ValueError(f"not a portable action: {a!r}")
|
|
145
|
+
body = {
|
|
146
|
+
"format": RECEIPT_FORMAT,
|
|
147
|
+
"namespace": NAMESPACE,
|
|
148
|
+
"version": VERSION,
|
|
149
|
+
"issuer": issuer,
|
|
150
|
+
"issued_at": issued_at or now(),
|
|
151
|
+
"operation": operation,
|
|
152
|
+
"holder": holder,
|
|
153
|
+
"kind": kind,
|
|
154
|
+
"scope": scope,
|
|
155
|
+
"outcome": outcome,
|
|
156
|
+
"verdict": VERDICT_OF[outcome],
|
|
157
|
+
"coverage": {"inspected": bool(coverage.get("inspected", False)),
|
|
158
|
+
"checks": sorted(coverage.get("checks", [])),
|
|
159
|
+
"scope": coverage.get("scope", "the person's records and their residue"),
|
|
160
|
+
"limits": list(coverage.get("limits", []))},
|
|
161
|
+
"before": {"residue": int(before.get("residue", 0)),
|
|
162
|
+
"exact_text_in_your_records": bool(before.get("exact_text_in_your_records", False))},
|
|
163
|
+
"after": {"residue": int(after.get("residue", 0)),
|
|
164
|
+
"exact_text_in_your_records": bool(after.get("exact_text_in_your_records", False))},
|
|
165
|
+
"actions": list(actions),
|
|
166
|
+
"subject_values": int(subject_values),
|
|
167
|
+
"retrieval_stopped_at": retrieval_stopped_at,
|
|
168
|
+
"physical_cleanup_at": physical_cleanup_at,
|
|
169
|
+
"restore": restore or {"coverage": "unsupported"},
|
|
170
|
+
"retained_until": retained_until,
|
|
171
|
+
"source_receipt": _digest(source_receipt),
|
|
172
|
+
"public_key": receipt_mod.public_key_b64(key),
|
|
173
|
+
}
|
|
174
|
+
check_portable(body)
|
|
175
|
+
body["signature"] = receipt_mod._b64(key.sign(receipt_mod.canonical(body)))
|
|
176
|
+
return body
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
_PATHISH = re.compile(r"(^|[\s(])(/[A-Za-z0-9._-]+){2,}|[A-Za-z]:\\|\\\\|\.(db|sqlite3?|jsonl?|bin|pem)\b", re.IGNORECASE)
|
|
180
|
+
_EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
|
|
181
|
+
_HEXHASH = re.compile(r"\b[0-9a-f]{40,}\b")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def check_portable(body: dict, forbidden_values=()) -> None:
|
|
185
|
+
"""Refuse a portable receipt that carries what it must not: a path, a filename, an email address, a
|
|
186
|
+
long hex digest outside `source_receipt`, or any of `forbidden_values` (the subject's exact values)."""
|
|
187
|
+
|
|
188
|
+
def walk(x: Any, where: str) -> None:
|
|
189
|
+
if isinstance(x, dict):
|
|
190
|
+
for k, v in x.items():
|
|
191
|
+
walk(v, f"{where}.{k}")
|
|
192
|
+
elif isinstance(x, list):
|
|
193
|
+
for i, v in enumerate(x):
|
|
194
|
+
walk(v, f"{where}[{i}]")
|
|
195
|
+
elif isinstance(x, str):
|
|
196
|
+
if where.startswith("$.source_receipt") or where in ("$.public_key", "$.signature"):
|
|
197
|
+
return
|
|
198
|
+
if _PATHISH.search(x):
|
|
199
|
+
raise ValueError(f"portable receipt {where} looks like a path or filename: {x!r}")
|
|
200
|
+
if _EMAIL.search(x):
|
|
201
|
+
raise ValueError(f"portable receipt {where} contains an email address")
|
|
202
|
+
if _HEXHASH.search(x):
|
|
203
|
+
raise ValueError(f"portable receipt {where} contains a long hex digest")
|
|
204
|
+
for v in forbidden_values:
|
|
205
|
+
if v and v.lower() in x.lower():
|
|
206
|
+
raise ValueError(f"portable receipt {where} contains a subject value")
|
|
207
|
+
|
|
208
|
+
walk(body, "$")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def verify(rec: dict, keys=None) -> None:
|
|
212
|
+
"""Raise ValueError unless `rec` is a portable receipt signed by one of `keys` (base64url public
|
|
213
|
+
keys or 32-hex fingerprints; None skips the key check, as `receipt.verify_signature` does)."""
|
|
214
|
+
if rec.get("format") != RECEIPT_FORMAT:
|
|
215
|
+
raise ValueError(f"not a {RECEIPT_FORMAT} receipt")
|
|
216
|
+
if rec.get("namespace") != NAMESPACE or rec.get("version") != VERSION:
|
|
217
|
+
raise ValueError("the receipt's namespace or version is not ForgetMe v1")
|
|
218
|
+
if rec.get("outcome") not in OUTCOMES or rec.get("verdict") != VERDICT_OF[rec["outcome"]]:
|
|
219
|
+
raise ValueError("the receipt's outcome and verdict don't agree")
|
|
220
|
+
pub_b64 = rec.get("public_key", "")
|
|
221
|
+
if keys is not None:
|
|
222
|
+
wanted = [keys] if isinstance(keys, str) else list(keys)
|
|
223
|
+
fp = receipt_mod.fingerprint(pub_b64)
|
|
224
|
+
if pub_b64 not in wanted and fp not in wanted:
|
|
225
|
+
raise ValueError("the receipt was signed by a key the issuer doesn't publish")
|
|
226
|
+
body = {k: v for k, v in rec.items() if k != "signature"}
|
|
227
|
+
try:
|
|
228
|
+
pub = Ed25519PublicKey.from_public_bytes(receipt_mod._unb64(pub_b64))
|
|
229
|
+
pub.verify(receipt_mod._unb64(rec.get("signature", "")), receipt_mod.canonical(body))
|
|
230
|
+
except (InvalidSignature, ValueError, TypeError):
|
|
231
|
+
raise ValueError("signature does not match: the receipt was altered or the key is wrong") from None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# --- discovery --------------------------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
def discovery_fragment(endpoint: str) -> dict:
|
|
237
|
+
"""The fragment a Company merges into its `/.well-known/poppy.json`."""
|
|
238
|
+
return {"extensions": {NAMESPACE: [{"version": VERSION, "endpoint": endpoint}]}}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def routes(endpoint: str) -> dict[str, str]:
|
|
242
|
+
"""Every route, derived from the advertised endpoint and nothing else."""
|
|
243
|
+
base = endpoint.rstrip("/")
|
|
244
|
+
return {"index": base, "preview": f"{base}/preview", "submit": f"{base}/submit",
|
|
245
|
+
"operation": f"{base}/operations/{{id}}", "evidence": f"{base}/operations/{{id}}/evidence"}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def endpoint_from_poppy(doc: dict, origin: str) -> str | None:
|
|
249
|
+
"""The v1 endpoint a `poppy.json` advertises, as an absolute URL on the document's origin, or None
|
|
250
|
+
when the Company doesn't list ForgetMe v1 (an unsupported Company is an observation, never a receipt)."""
|
|
251
|
+
ext = doc.get("extensions") if isinstance(doc, dict) else None
|
|
252
|
+
entries = ext.get(NAMESPACE) if isinstance(ext, dict) else None
|
|
253
|
+
if not isinstance(entries, list):
|
|
254
|
+
return None
|
|
255
|
+
for e in entries:
|
|
256
|
+
if isinstance(e, dict) and e.get("version") == VERSION and isinstance(e.get("endpoint"), str):
|
|
257
|
+
url = urljoin(origin.rstrip("/") + "/", e["endpoint"])
|
|
258
|
+
parts = urlsplit(url)
|
|
259
|
+
if parts.scheme in ("http", "https") and parts.netloc:
|
|
260
|
+
return url.rstrip("/")
|
|
261
|
+
return None
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def keys_of(index: dict) -> list[str]:
|
|
265
|
+
"""The public keys a ForgetMe index publishes (`keys[].public_key`)."""
|
|
266
|
+
out = []
|
|
267
|
+
for k in index.get("keys", []) if isinstance(index, dict) else []:
|
|
268
|
+
if isinstance(k, dict) and isinstance(k.get("public_key"), str):
|
|
269
|
+
out.append(k["public_key"])
|
|
270
|
+
return out
|
forgetproof/hnsw.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Read and sanitize hnswlib index files as persisted by Chroma, without loading the index.
|
|
2
|
+
|
|
3
|
+
Two ways these files hold data they shouldn't:
|
|
4
|
+
|
|
5
|
+
1. Deletion only sets a flag on the element; the vector bytes stay in data_level0.bin
|
|
6
|
+
until the index is rebuilt.
|
|
7
|
+
2. Chroma's hnswlib fork allocates its buffers with malloc (never zeroed) and persists
|
|
8
|
+
them. Slots past cur_element_count were never written by the index, so on disk they
|
|
9
|
+
hold whatever that memory held before: often other collections' documents. hnswlib
|
|
10
|
+
zeroes each data_level0 slot when it is first used, so those below the count are clean.
|
|
11
|
+
length.bin holds each vector's norm, but only cosine indexes (normalize=true) ever write
|
|
12
|
+
it or read it back. For l2 and ip every byte of length.bin is leftover memory.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import mmap
|
|
18
|
+
import re
|
|
19
|
+
import struct
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from .pii import find_pii
|
|
24
|
+
|
|
25
|
+
# offsetLevel0, max_elements, cur_element_count, size_data_per_element,
|
|
26
|
+
# label_offset, offsetData, maxlevel, enterpoint_node, maxM, maxM0, M
|
|
27
|
+
_HEADER = struct.Struct("<QQQQQQiIQQQ")
|
|
28
|
+
_DELETE_MARK = 0x01 # hnswlib marks deletion in byte 2 of the level-0 link list header
|
|
29
|
+
_LENGTH_ENTRY = 4 # one float per element
|
|
30
|
+
# Leftover memory is usually allocator pointers; text runs this long are data.
|
|
31
|
+
_TEXT_RUN = re.compile(rb"[\x20-\x7e]{8,}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class HnswIndex:
|
|
36
|
+
path: Path
|
|
37
|
+
vectors: int # elements physically stored on disk
|
|
38
|
+
deleted: int # of which flagged deleted (bytes still present)
|
|
39
|
+
element_size: int
|
|
40
|
+
normalized: bool = True # cosine: length.bin holds real norms below the count
|
|
41
|
+
leaked_bytes: int = 0 # non-zero bytes in never-used capacity slots (zeroed by fix)
|
|
42
|
+
leaked_text: int = 0 # printable text fragments among them — i.e. actual data
|
|
43
|
+
leaked_pii: set[tuple[str, bytes]] = field(default_factory=set)
|
|
44
|
+
|
|
45
|
+
def unused_regions(self) -> list[tuple[Path, int]]:
|
|
46
|
+
"""(file, offset) pairs from which everything to EOF is unused capacity."""
|
|
47
|
+
return [
|
|
48
|
+
(self.path / "data_level0.bin", self.vectors * self.element_size),
|
|
49
|
+
(self.path / "length.bin", self.vectors * _LENGTH_ENTRY if self.normalized else 0),
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parse(header: bytes, data_len: int) -> tuple[int, int] | None:
|
|
54
|
+
# Chroma's fork prefixes a 4-byte format version; upstream hnswlib does not.
|
|
55
|
+
for prefix in (4, 0):
|
|
56
|
+
if len(header) < prefix + _HEADER.size:
|
|
57
|
+
continue
|
|
58
|
+
_, max_el, count, size, label_off, data_off, *_ = _HEADER.unpack_from(header, prefix)
|
|
59
|
+
if 0 < size < 1 << 24 and label_off + 8 <= size and data_off < size and count <= max(max_el, 1) * 2 and count * size <= data_len:
|
|
60
|
+
return count, size
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
_CHUNK = 8 << 20
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _scan_tail(path: Path, offset: int, index: HnswIndex) -> None:
|
|
68
|
+
"""Look at everything from offset to EOF in chunks, so huge indexes don't need huge memory."""
|
|
69
|
+
overlap = 256 # long enough for any PII value straddling a chunk boundary
|
|
70
|
+
with path.open("rb") as f:
|
|
71
|
+
f.seek(offset)
|
|
72
|
+
carry = b""
|
|
73
|
+
open_run = False # a text run touched the end of the last window and may continue
|
|
74
|
+
while chunk := f.read(_CHUNK):
|
|
75
|
+
nonzero = len(chunk) - chunk.count(0)
|
|
76
|
+
index.leaked_bytes += nonzero
|
|
77
|
+
window = carry + chunk
|
|
78
|
+
if nonzero or open_run:
|
|
79
|
+
open_run = False
|
|
80
|
+
for m in _TEXT_RUN.finditer(window):
|
|
81
|
+
if m.end() < len(carry):
|
|
82
|
+
continue # counted with the previous window
|
|
83
|
+
if m.end() == len(window):
|
|
84
|
+
open_run = True # count it once we see where it ends
|
|
85
|
+
else:
|
|
86
|
+
index.leaked_text += 1
|
|
87
|
+
index.leaked_pii.update(find_pii(window))
|
|
88
|
+
carry = window[-overlap:]
|
|
89
|
+
index.leaked_text += open_run
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def read_index(segment_dir: Path, normalized: bool = True) -> HnswIndex | None:
|
|
93
|
+
"""normalized: whether the index is cosine. When unsure, pass True: it only protects more bytes."""
|
|
94
|
+
header_path = segment_dir / "header.bin"
|
|
95
|
+
data_path = segment_dir / "data_level0.bin"
|
|
96
|
+
if not header_path.exists() or not data_path.exists():
|
|
97
|
+
return None
|
|
98
|
+
data_len = data_path.stat().st_size
|
|
99
|
+
parsed = _parse(header_path.read_bytes(), data_len)
|
|
100
|
+
if parsed is None:
|
|
101
|
+
raise ValueError(f"unrecognized HNSW header in {header_path}")
|
|
102
|
+
count, size = parsed
|
|
103
|
+
deleted = 0
|
|
104
|
+
if count:
|
|
105
|
+
with data_path.open("rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
|
|
106
|
+
deleted = sum(1 for i in range(count) if mm[i * size + 2] & _DELETE_MARK)
|
|
107
|
+
index = HnswIndex(segment_dir, count, deleted, size, normalized)
|
|
108
|
+
for path, offset in index.unused_regions():
|
|
109
|
+
if path.exists() and path.stat().st_size > offset:
|
|
110
|
+
_scan_tail(path, offset, index)
|
|
111
|
+
return index
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def zero_unused(index: HnswIndex) -> int:
|
|
115
|
+
"""Overwrite never-used capacity slots with zeros, in place, keeping file sizes."""
|
|
116
|
+
zeroed = 0
|
|
117
|
+
for path, offset in index.unused_regions():
|
|
118
|
+
if not path.exists():
|
|
119
|
+
continue
|
|
120
|
+
size = path.stat().st_size
|
|
121
|
+
if size <= offset:
|
|
122
|
+
continue
|
|
123
|
+
with path.open("r+b") as f:
|
|
124
|
+
f.seek(offset)
|
|
125
|
+
remaining = size - offset
|
|
126
|
+
while remaining:
|
|
127
|
+
n = min(remaining, 1 << 20)
|
|
128
|
+
f.write(b"\x00" * n)
|
|
129
|
+
remaining -= n
|
|
130
|
+
f.flush()
|
|
131
|
+
zeroed += size - offset
|
|
132
|
+
return zeroed
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Hooks into the memory layers agents are built on, so a delete there is verified and receipted here.
|
|
2
|
+
|
|
3
|
+
An agent that adopts a protocol is rare; an agent that uses a memory library is the norm. Each module in this
|
|
4
|
+
package wraps one library's own delete call: it reads what is about to be deleted, lets the library delete
|
|
5
|
+
it, then runs the engine on the files the library keeps and returns signed receipts with counts only.
|
|
6
|
+
`mem0` is first (`forgetproof.integrations.mem0`). Nothing here imports the library at module level, so the
|
|
7
|
+
package installs without any of them; each module's functions take the library's own object as their first
|
|
8
|
+
argument.
|
|
9
|
+
"""
|