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,189 @@
1
+ """mem0 (mem0ai): the memory layer many personal agents are built on.
2
+
3
+ mem0 keeps the memories themselves in a vector store (Qdrant local by default, under the same
4
+ directory or wherever the app pointed it) and a *history* of every change in `history.db`, a
5
+ SQLite file with one row per event: ADD, UPDATE and DELETE, each carrying the text before and
6
+ after. A delete in mem0 removes the vector and appends a DELETE row whose `old_memory` is the full
7
+ text of what was just deleted — and leaves the ADD and UPDATE rows that carry the same text.
8
+ So after `memory.delete(id)` the memory is unreachable through `memory.get()` and `search()`, and
9
+ readable in full with one SQL query. An update keeps the previous text in the UPDATE row's
10
+ `old_memory` the same way.
11
+
12
+ That is retained by design, not an artefact of free space, so it's reported as its own finding
13
+ (`mem0.history_deleted`, `mem0.history_versions`) separately from `sqlite.slack`, and `fix`
14
+ removes it explicitly: every history row of a deleted memory is deleted, the `old_memory` of an
15
+ UPDATE row for a live memory is blanked, and the file is vacuumed with secure_delete on. After
16
+ that, `memory.history(id)` for a deleted memory returns nothing — which is the point.
17
+
18
+ A mem0 directory that also holds a Qdrant local store (the default layout is `<dir>/history.db`
19
+ plus `<dir>/qdrant/` when the app set `path`) is scanned and fixed as one store, with the Qdrant
20
+ findings located under their subdirectory.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import sqlite3
26
+ from pathlib import Path
27
+
28
+ from . import qdrant_store
29
+ from .pii import find_pii, summarize
30
+ from .report import Finding, Report
31
+ from .sqlite_residue import connect_ro, is_sqlite, slack_finding, table_columns, vacuum
32
+
33
+ HISTORY = "history.db"
34
+ _HISTORY_COLUMNS = {"memory_id", "old_memory", "new_memory", "event"}
35
+
36
+
37
+ def is_history_db(path: Path) -> bool:
38
+ if not path.is_file() or not is_sqlite(path):
39
+ return False
40
+ try:
41
+ conn = connect_ro(path)
42
+ except sqlite3.Error:
43
+ return False
44
+ try:
45
+ return _HISTORY_COLUMNS <= set(table_columns(conn).get("history", []))
46
+ except sqlite3.Error:
47
+ return False
48
+ finally:
49
+ conn.close()
50
+
51
+
52
+ def detect(target: Path) -> bool:
53
+ """A mem0 directory (holds history.db) or the history.db file itself."""
54
+ if target.is_dir():
55
+ return is_history_db(target / HISTORY)
56
+ return is_history_db(target)
57
+
58
+
59
+ def history_db(target: Path) -> Path:
60
+ return target / HISTORY if target.is_dir() else target
61
+
62
+
63
+ def qdrant_dirs(target: Path) -> list[Path]:
64
+ if not target.is_dir():
65
+ return []
66
+ return sorted(p for p in target.iterdir() if p.is_dir() and not p.is_symlink() and qdrant_store.detect(p))
67
+
68
+
69
+ def _rows(conn: sqlite3.Connection) -> list[tuple]:
70
+ """(rowid, memory_id, EVENT, old_memory, new_memory) in the order mem0 wrote them."""
71
+ return conn.execute("select rowid, memory_id, upper(coalesce(event, '')), old_memory, new_memory from history "
72
+ "order by rowid").fetchall()
73
+
74
+
75
+ def _deleted_ids(rows) -> set[str]:
76
+ return {mid for _, mid, ev, _, _ in rows if ev == "DELETE"}
77
+
78
+
79
+ def _stale_versions(rows, deleted: set[str]) -> list[tuple[int, str]]:
80
+ """(rowid, text) for every text in a live memory's history that isn't its current text: the
81
+ `old_memory` of any row, and the `new_memory` of every row but the newest. mem0 keeps the original
82
+ ADD row when a memory is updated, so the first version survives there as well as in the UPDATE row."""
83
+ newest: dict[str, int] = {}
84
+ current: dict[str, str | None] = {}
85
+ for rowid, mid, ev, old, new in rows:
86
+ if mid in deleted:
87
+ continue
88
+ newest[mid] = rowid
89
+ current[mid] = new
90
+ stale = []
91
+ for rowid, mid, ev, old, new in rows:
92
+ if mid in deleted:
93
+ continue
94
+ if old and old != current.get(mid):
95
+ stale.append((rowid, old))
96
+ if new and rowid != newest[mid] and new != current.get(mid):
97
+ stale.append((rowid, new))
98
+ return stale
99
+
100
+
101
+ def scan(target: Path, report: Report, show: bool = False) -> None:
102
+ db = history_db(target)
103
+ where = HISTORY if target.is_dir() else db.name
104
+ conn = connect_ro(db)
105
+ try:
106
+ rows = _rows(conn)
107
+ finally:
108
+ conn.close()
109
+ deleted = _deleted_ids(rows)
110
+ deleted_rows = [(old, new) for _, mid, _, old, new in rows if mid in deleted]
111
+ version_rows = [text for _, text in _stale_versions(rows, deleted)]
112
+ all_ids = {mid for _, mid, *_ in rows}
113
+ report.stats["memories"] = len(all_ids - deleted)
114
+ report.stats["deleted_memories"] = len(deleted)
115
+
116
+ if deleted_rows:
117
+ texts = [t for pair in deleted_rows for t in pair if t]
118
+ pii, samples = summarize((kv for t in texts for kv in find_pii(t.encode())), show)
119
+ report.findings.append(Finding(
120
+ check="mem0.history_deleted",
121
+ title="Deleted memories still readable in full in mem0's history table",
122
+ location=where,
123
+ records=len(deleted_rows),
124
+ unit="history rows",
125
+ why="mem0 appends a DELETE row carrying the memory's text and keeps its ADD/UPDATE rows; "
126
+ "`select old_memory from history` returns everything the user asked it to forget",
127
+ pii=pii,
128
+ samples=samples,
129
+ ))
130
+ if version_rows:
131
+ pii, samples = summarize((kv for t in version_rows for kv in find_pii(t.encode())), show)
132
+ report.findings.append(Finding(
133
+ check="mem0.history_versions",
134
+ title="Previous versions of corrected memories kept in mem0's history table",
135
+ location=where,
136
+ records=len(version_rows),
137
+ unit="old versions",
138
+ why="the UPDATE row keeps the text as it was before the correction, and the original ADD row keeps it too",
139
+ pii=pii,
140
+ samples=samples,
141
+ ))
142
+ slack = slack_finding(db, where, show)
143
+ if slack:
144
+ report.findings.append(slack)
145
+ for sub in qdrant_dirs(target):
146
+ qdrant_store.scan(sub, report, show=show, prefix=sub.name + "/")
147
+
148
+
149
+ def plan(report: Report) -> list[str]:
150
+ checks = {f.check for f in report.findings}
151
+ steps = []
152
+ if "mem0.history_deleted" in checks:
153
+ steps.append("delete every history row of a memory that has a DELETE event")
154
+ if "mem0.history_versions" in checks:
155
+ steps.append("blank every earlier version's text in the history of memories that are still live "
156
+ "(the current text and the event rows stay)")
157
+ steps.append(f"VACUUM {HISTORY} with secure_delete on")
158
+ if any(f.location.endswith("storage.sqlite") for f in report.findings):
159
+ steps.append("VACUUM each Qdrant collection's storage.sqlite with secure_delete on")
160
+ return steps
161
+
162
+
163
+ def fix(target: Path) -> list[str]:
164
+ db = history_db(target)
165
+ conn = sqlite3.connect(db)
166
+ try:
167
+ conn.execute("pragma secure_delete=on")
168
+ rows = _rows(conn)
169
+ deleted = _deleted_ids(rows)
170
+ removed = blanked = 0
171
+ if deleted:
172
+ for mid in deleted:
173
+ removed += conn.execute("delete from history where memory_id = ?", (mid,)).rowcount
174
+ for rowid, text in _stale_versions(rows, deleted):
175
+ blanked += conn.execute("update history set old_memory = NULL where rowid = ? and old_memory = ?", (rowid, text)).rowcount
176
+ blanked += conn.execute("update history set new_memory = NULL where rowid = ? and new_memory = ?", (rowid, text)).rowcount
177
+ conn.commit()
178
+ finally:
179
+ conn.close()
180
+ actions = []
181
+ if removed:
182
+ actions.append(f"deleted {removed} history row(s) of {len(deleted)} deleted memor{'y' if len(deleted) == 1 else 'ies'}")
183
+ if blanked:
184
+ actions.append(f"blanked {blanked} earlier version(s) in the history of live memories")
185
+ vacuum(db)
186
+ actions.append(f"vacuumed {HISTORY} (secure_delete on)")
187
+ for sub in qdrant_dirs(target):
188
+ actions += [f"{sub.name}/{a}" for a in qdrant_store.fix(sub)]
189
+ return actions
forgetproof/pii.py ADDED
@@ -0,0 +1,160 @@
1
+ """Pattern matchers for a few kinds of value (email, North American phone, US SSN, card numbers that
2
+ pass Luhn, common API key formats) in raw bytes, plus redaction for display.
3
+
4
+ These annotate findings and are the only content check for stores where free space cannot be told
5
+ from live cells structurally: Postgres table files, LanceDB fragments and Chroma's leaked index
6
+ memory. They do not define what counts as residue in SQLite, and they are not a personal-data
7
+ detector: a name or a street address matches nothing here. To check for a specific value, name it
8
+ as a canary or a subject.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections import Counter
15
+ from collections.abc import Iterable, Iterator
16
+
17
+ # Patterns run over bytes so they work on raw database pages, not just decoded text.
18
+ PATTERNS: dict[str, re.Pattern[bytes]] = {
19
+ "email": re.compile(rb"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}"),
20
+ "phone": re.compile(rb"(?<![\d-])(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]\d{3}[ .-]\d{4}(?![\d-])"),
21
+ "ssn": re.compile(rb"(?<![\d-])\d{3}-\d{2}-\d{4}(?![\d-])"),
22
+ # Grouped like a printed card number; bare digit runs in binary pages are mostly noise.
23
+ "card": re.compile(rb"(?<![0-9A-Za-z])\d{4}(?:[ -]\d{4}){2}[ -]\d{1,7}(?![0-9A-Za-z-])"),
24
+ "api_key": re.compile(
25
+ rb"(?:sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36}|xox[baprs]-[A-Za-z0-9-]{10,})"
26
+ ),
27
+ }
28
+
29
+
30
+ # Raw database pages put values next to unrelated bytes, so `user@example.com` followed by a stray
31
+ # letter reads as `user@example.comC`. When the last label isn't a known TLD but starts with one, cut
32
+ # it back. Covers the TLDs most addresses use; others are left as matched.
33
+ _COMMON_TLDS = frozenset(
34
+ b"com org net edu gov mil int io ai co dev app me us uk de fr nl es it ca au in jp cn br ru ch se no "
35
+ b"dk fi pl be at ie nz sg hk kr tw mx ar za il tr pt gr cz hu ro info biz xyz tech cloud online site".split()
36
+ )
37
+
38
+
39
+ def _trim_email(value: bytes) -> bytes:
40
+ head, _, tld = value.rpartition(b".")
41
+ if tld.lower() in _COMMON_TLDS:
42
+ return value
43
+ for n in range(len(tld) - 1, 1, -1):
44
+ if tld[:n].lower() in _COMMON_TLDS:
45
+ return head + b"." + tld[:n]
46
+ return value
47
+
48
+
49
+ def _luhn(digits: str) -> bool:
50
+ total = 0
51
+ for i, ch in enumerate(reversed(digits)):
52
+ d = int(ch)
53
+ if i % 2 == 1:
54
+ d *= 2
55
+ if d > 9:
56
+ d -= 9
57
+ total += d
58
+ return total % 10 == 0
59
+
60
+
61
+ def find_pii(data: bytes) -> Iterator[tuple[str, bytes]]:
62
+ """Yield (kind, value) for every match in data."""
63
+ for kind, pattern in PATTERNS.items():
64
+ for m in pattern.finditer(data):
65
+ value = m.group(0)
66
+ if kind == "email":
67
+ value = _trim_email(value)
68
+ if kind == "card":
69
+ digits = re.sub(rb"\D", b"", value).decode()
70
+ if not (13 <= len(digits) <= 19 and _luhn(digits)):
71
+ continue
72
+ yield kind, value
73
+
74
+
75
+ def pii_set(chunks: Iterable[bytes]) -> set[tuple[str, bytes]]:
76
+ found: set[tuple[str, bytes]] = set()
77
+ for chunk in chunks:
78
+ found.update(find_pii(chunk))
79
+ return found
80
+
81
+
82
+ MAX_SAMPLES = 5
83
+
84
+
85
+ def summarize(values: Iterable[tuple[str, bytes]], show: bool = False) -> tuple[dict[str, int], list[str]]:
86
+ """Counts per kind, and a few samples: redacted unless `show` (owner mode, for a store the
87
+ person owns on their own machine)."""
88
+ values = sorted(set(values))
89
+ counts = Counter(kind for kind, _ in values)
90
+ samples = [f"{kind}: {v.decode('utf-8', 'replace') if show else redact(kind, v)}" for kind, v in values[:MAX_SAMPLES]]
91
+ return dict(counts), samples
92
+
93
+
94
+ def redact(kind: str, value: bytes) -> str:
95
+ """Show enough to recognise a value in a screenshot, not enough to leak it."""
96
+ text = value.decode("utf-8", "replace")
97
+ if kind == "email":
98
+ local, _, domain = text.partition("@")
99
+ shown = local[0] + "*" * max(len(local) - 2, 1) + (local[-1] if len(local) > 1 else "")
100
+ return f"{shown}@{domain}"
101
+ if kind in ("phone", "ssn", "card"):
102
+ digits = re.sub(r"\D", "", text)
103
+ return "*" * (len(digits) - 4) + digits[-4:]
104
+ if kind == "text":
105
+ return f"{text[:4]}… ({len(text)} chars)"
106
+ return text[:6] + "…"
107
+
108
+
109
+ def _explained_by_live(kind: str, value: bytes, live: set[tuple[str, bytes]], locals_: set[bytes], domains: set[bytes]) -> bool:
110
+ """Raw pages pack values next to unrelated bytes, so a pattern can run into a neighbour
111
+ (`a@b.comX`, `Xa@b.com`). A raw match is live if it contains a live value of its kind."""
112
+ if (kind, value) in live:
113
+ return True
114
+ if kind == "email":
115
+ local, _, domain = value.partition(b"@")
116
+ heads = [domain[:i] for i in range(len(domain), 0, -1) if domain[:i] in domains]
117
+ tails = [local[i:] for i in range(len(local)) if local[i:] in locals_]
118
+ return any(("email", t + b"@" + h) in live for t in tails for h in heads)
119
+ n = len(value)
120
+ return any((kind, value[a:b]) in live for a in range(n) for b in range(n, a, -1))
121
+
122
+
123
+ class LivePii:
124
+ """Pattern matches still reachable through the store's API, for deciding whether a raw match is live."""
125
+
126
+ def __init__(self, values: set[tuple[str, bytes]]):
127
+ self.values = values
128
+ emails = [v for k, v in values if k == "email"]
129
+ self._locals = {v.partition(b"@")[0] for v in emails}
130
+ self._domains = {v.partition(b"@")[2] for v in emails}
131
+
132
+ def not_live(self, found: set[tuple[str, bytes]]) -> set[tuple[str, bytes]]:
133
+ return {(k, v) for k, v in found if not _explained_by_live(k, v, self.values, self._locals, self._domains)}
134
+
135
+
136
+ class ByteScanner:
137
+ """Find pattern matches and canary values in a stream of chunks, including values split across chunks."""
138
+
139
+ OVERLAP = 512
140
+
141
+ def __init__(self, canaries: list[str] = ()):
142
+ self.pii: set[tuple[str, bytes]] = set()
143
+ self._needles = [{c.encode(), c.lower().encode()} for c in canaries]
144
+ self.canary_hits: list[bool] = [False] * len(self._needles)
145
+
146
+ def feed(self, chunks: Iterable[bytes]) -> bool:
147
+ """Scan one file's chunks. Returns True if any canary was seen in it."""
148
+ seen = [False] * len(self._needles)
149
+ carry = b""
150
+ for chunk in chunks:
151
+ window = carry + chunk
152
+ if window.count(0) != len(window):
153
+ self.pii.update(find_pii(window))
154
+ for i, needles in enumerate(self._needles):
155
+ seen[i] = seen[i] or any(n in window for n in needles)
156
+ carry = window[-self.OVERLAP:]
157
+ for i, s in enumerate(seen):
158
+ self.canary_hits[i] |= s
159
+ self.last_seen = seen
160
+ return any(seen)
@@ -0,0 +1,334 @@
1
+ """Postgres + pgvector: find deleted rows that are still in the table files, and erase them.
2
+
3
+ What a DELETE or UPDATE leaves behind in Postgres:
4
+
5
+ - The old row version stays in the table's pages as a dead tuple until VACUUM.
6
+ - Plain VACUUM (and autovacuum) frees that space but does not overwrite it, so the bytes
7
+ stay readable in the table files until new rows happen to land on them.
8
+ - The same goes for TOAST storage (long values) and for index entries.
9
+ - The write-ahead log (WAL) records the row as it was written. It is shared by every database on
10
+ the server and recycled rather than wiped, so it is checked for canaries and reported as a warning.
11
+ - Recent changes may exist only in shared memory and the WAL until a checkpoint, so the scan
12
+ runs CHECKPOINT first (it flushes pages; it changes no data).
13
+
14
+ VACUUM FULL rewrites the table, its TOAST data and its indexes into new files holding only
15
+ live rows. Switching WAL segments and checkpointing lets Postgres recycle old WAL.
16
+
17
+ Reading the files needs superuser or the pg_read_server_files role, because we read them
18
+ through SQL (pg_read_binary_file) and never need filesystem access to the server.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ from collections.abc import Iterator
25
+ from dataclasses import dataclass
26
+
27
+ from .pii import ByteScanner, LivePii, find_pii
28
+ from .report import CanaryResult, Finding, Report
29
+
30
+ CHUNK = 8 << 20
31
+ LOCK_TIMEOUT = "15s" # how long VACUUM FULL waits for the app to release a table
32
+ VECTOR_TYPES = ("vector", "halfvec", "sparsevec")
33
+
34
+
35
+ class PostgresError(Exception):
36
+ pass
37
+
38
+
39
+ def is_postgres(target) -> bool:
40
+ return str(target).startswith(("postgres://", "postgresql://"))
41
+
42
+
43
+ def _psycopg():
44
+ try:
45
+ import psycopg
46
+ except ImportError:
47
+ raise PostgresError("Postgres support needs psycopg: pip install 'forgetproof[postgres]'") from None
48
+ return psycopg
49
+
50
+
51
+ def display(dsn: str) -> str:
52
+ """The connection string without its password, safe to print and to put in receipts."""
53
+ psycopg = _psycopg()
54
+ info = psycopg.conninfo.conninfo_to_dict(dsn)
55
+ info.pop("password", None)
56
+ host = info.get("host", "")
57
+ where = f"{info.get('user', '')}@{host}" if "/" not in host else f"{info.get('user', '')}@(socket)"
58
+ return f"postgresql://{where}{':' + str(info['port']) if info.get('port') else ''}/{info.get('dbname', '')}"
59
+
60
+
61
+ def connect(dsn: str):
62
+ psycopg = _psycopg()
63
+ try:
64
+ return psycopg.connect(dsn, autocommit=True)
65
+ except psycopg.Error as e:
66
+ raise PostgresError(f"could not connect to {display(dsn)}: {str(e).strip()}") from None
67
+
68
+
69
+ def _quote(schema: str, table: str) -> str:
70
+ return '"' + schema.replace('"', '""') + '"."' + table.replace('"', '""') + '"'
71
+
72
+
73
+ @dataclass
74
+ class Table:
75
+ oid: int
76
+ schema: str
77
+ name: str
78
+
79
+ @property
80
+ def sql(self) -> str:
81
+ return _quote(self.schema, self.name)
82
+
83
+ @property
84
+ def label(self) -> str:
85
+ return f"{self.schema}.{self.name}"
86
+
87
+
88
+ def vector_tables(conn) -> list[Table]:
89
+ """User tables with at least one pgvector column: where agent memories live."""
90
+ rows = conn.execute(
91
+ """
92
+ select distinct c.oid, n.nspname, c.relname
93
+ from pg_attribute a
94
+ join pg_class c on c.oid = a.attrelid
95
+ join pg_namespace n on n.oid = c.relnamespace
96
+ join pg_type t on t.oid = a.atttypid
97
+ where t.typname = any(%s) and c.relkind in ('r', 'p', 'm') and a.attnum > 0 and not a.attisdropped
98
+ and n.nspname not in ('pg_catalog', 'information_schema')
99
+ order by n.nspname, c.relname
100
+ """,
101
+ (list(VECTOR_TYPES),),
102
+ ).fetchall()
103
+ return [Table(*r) for r in rows]
104
+
105
+
106
+ def can_read_files(conn) -> bool:
107
+ try:
108
+ conn.execute("select pg_read_binary_file('PG_VERSION', 0, 1)").fetchone()
109
+ return True
110
+ except Exception:
111
+ return False
112
+
113
+
114
+ def _relations(conn, table: Table) -> list[tuple[str, int]]:
115
+ """(label, oid) of the table, its TOAST table and every index on either."""
116
+ rows = conn.execute(
117
+ """
118
+ select 'heap', c.oid from pg_class c where c.oid = %(t)s
119
+ union all
120
+ select 'toast', c.reltoastrelid from pg_class c where c.oid = %(t)s and c.reltoastrelid <> 0
121
+ union all
122
+ select 'index ' || i.indexrelid::regclass::text, i.indexrelid from pg_index i
123
+ where i.indrelid = %(t)s
124
+ or i.indrelid = (select reltoastrelid from pg_class where oid = %(t)s)
125
+ """,
126
+ {"t": table.oid},
127
+ ).fetchall()
128
+ return [(label, oid) for label, oid in rows]
129
+
130
+
131
+ def _files(conn, oid: int) -> list[tuple[str, int]]:
132
+ """A relation's data files: the main fork split into 1 GB segments (path, path.1, ...)."""
133
+ base = conn.execute("select pg_relation_filepath(%s)", (oid,)).fetchone()[0]
134
+ if base is None:
135
+ return []
136
+ out = []
137
+ for n in range(10_000):
138
+ path = base if n == 0 else f"{base}.{n}"
139
+ row = conn.execute("select size from pg_stat_file(%s, true)", (path,)).fetchone()
140
+ if row is None or row[0] is None:
141
+ break
142
+ out.append((path, row[0]))
143
+ return out
144
+
145
+
146
+ def _wal_files(conn) -> list[tuple[str, int]]:
147
+ return [(f"pg_wal/{name}", size) for name, size in conn.execute("select name, size from pg_ls_waldir() order by name")]
148
+
149
+
150
+ def _read(conn, path: str, size: int) -> Iterator[bytes]:
151
+ for offset in range(0, size, CHUNK):
152
+ row = conn.execute("select pg_read_binary_file(%s, %s, %s, true)", (path, offset, min(CHUNK, size - offset))).fetchone()
153
+ if row is None or row[0] is None:
154
+ return # file went away (e.g. WAL recycled) while we read it
155
+ yield bytes(row[0])
156
+
157
+
158
+ def _live(conn, tables: list[Table]) -> tuple[LivePii, int]:
159
+ """Pattern matches in every live row, read as text; and the live row count."""
160
+ values: set[tuple[str, bytes]] = set()
161
+ rows = 0
162
+ for t in tables:
163
+ with conn.cursor(name="forgetproof_live") as cur: # server-side: big tables stream
164
+ # Explicit transaction: a named cursor needs one, and autocommit is on.
165
+ with conn.transaction():
166
+ cur.execute(f"select t::text from {t.sql} t")
167
+ for (text,) in cur:
168
+ rows += 1
169
+ values.update(find_pii(text.encode()))
170
+ return LivePii(values), rows
171
+
172
+
173
+ def scan(dsn: str, canaries: list[str]) -> Report:
174
+ conn = connect(dsn)
175
+ try:
176
+ return _scan(conn, display(dsn), canaries)
177
+ finally:
178
+ conn.close()
179
+
180
+
181
+ def _scan(conn, target: str, canaries: list[str]) -> Report:
182
+ report = Report(target=target, store="postgres")
183
+ tables = vector_tables(conn)
184
+ live, rows = _live(conn, tables)
185
+ report.stats = {"tables": len(tables), "live_records": rows}
186
+ if not tables:
187
+ report.warnings.append("no tables with a pgvector column (vector, halfvec, sparsevec) in this database")
188
+
189
+ if not can_read_files(conn):
190
+ report.incomplete = (
191
+ "this role can't read table files, so bytes left after VACUUM can't be checked. Connect as a "
192
+ "superuser or a role with pg_read_server_files for a full scan."
193
+ )
194
+ dead = conn.execute(
195
+ "select relid, n_dead_tup from pg_stat_user_tables where relid = any(%s)", ([t.oid for t in tables],)
196
+ ).fetchall()
197
+ n_dead = sum(n for _, n in dead)
198
+ if n_dead:
199
+ report.findings.append(Finding(
200
+ check="pg.dead_tuples",
201
+ title="Deleted or overwritten rows not yet vacuumed (Postgres statistics estimate)",
202
+ location=", ".join(t.label for t in tables),
203
+ records=n_dead,
204
+ unit="row versions",
205
+ why="a DELETE or UPDATE only marks the old row version dead; it stays in the table files",
206
+ ))
207
+ report.canaries = [CanaryResult(i, ["(not checked: no file access)"]) for i in range(1, len(canaries) + 1)]
208
+ return report
209
+
210
+ # Changed pages sit in shared memory until a checkpoint writes them out; flush them so the
211
+ # files show what Postgres holds. A checkpoint writes no new data and changes no rows.
212
+ try:
213
+ conn.execute("checkpoint")
214
+ except Exception:
215
+ report.warnings.append(
216
+ "couldn't CHECKPOINT (needs superuser or pg_checkpoint), so very recent changes may not be in "
217
+ "the table files yet; they are in the WAL, which is also scanned"
218
+ )
219
+ canaries = [c for c in canaries if c]
220
+ found_in: list[list[str]] = [[] for _ in canaries]
221
+ table_scan = ByteScanner(canaries)
222
+ locations = []
223
+ for t in tables:
224
+ for label, oid in _relations(conn, t):
225
+ for path, size in _files(conn, oid):
226
+ table_scan.feed(_read(conn, path, size))
227
+ for i, seen in enumerate(table_scan.last_seen):
228
+ if seen:
229
+ found_in[i].append(f"{t.label} ({label}) {path}")
230
+ locations.append(t.label)
231
+ # The WAL is shared by every database on the server, so its pattern matches can't be compared
232
+ # with this database's live rows. Only canaries, which name one specific value, are checked there.
233
+ wal_hits: list[list[str]] = [[] for _ in canaries]
234
+ if canaries:
235
+ wal_scan = ByteScanner(canaries)
236
+ for path, size in _wal_files(conn):
237
+ wal_scan.feed(_read(conn, path, size))
238
+ for i, seen in enumerate(wal_scan.last_seen):
239
+ if seen:
240
+ wal_hits[i].append(path)
241
+ for i, paths in enumerate(wal_hits, 1):
242
+ if paths:
243
+ report.warnings.append(
244
+ f"canary #{i} is still in the write-ahead log ({', '.join(paths)}). Postgres recycles WAL rather "
245
+ "than wiping it, so it can stay until the segment is reused; backups and replicas may also hold it"
246
+ )
247
+
248
+ from .pii import summarize # shared formatting
249
+
250
+ residue = live.not_live(table_scan.pii)
251
+ if residue:
252
+ pii, samples = summarize(residue)
253
+ report.findings.append(Finding(
254
+ check="pg.table_residue",
255
+ title="Deleted or overwritten rows' known-pattern values still in table files",
256
+ location=", ".join(locations),
257
+ records=len(residue),
258
+ unit="pattern matches",
259
+ why="DELETE and UPDATE leave the old row in the page; VACUUM frees the space but doesn't "
260
+ "overwrite it. Anyone who can read the files or a disk image can recover it",
261
+ pii=pii,
262
+ samples=samples,
263
+ ))
264
+ report.canaries = [CanaryResult(i, found) for i, found in enumerate(found_in, 1)]
265
+ return report
266
+
267
+
268
+ def plan(report: Report) -> list[str]:
269
+ tables = report.stats.get("tables", 0)
270
+ return [
271
+ f"VACUUM FULL the {tables} table(s) with a pgvector column: rewrites each table, its TOAST data and "
272
+ "its indexes with live rows only. Each table is locked (reads and writes wait) while it is rewritten.",
273
+ "switch WAL segments and CHECKPOINT twice, so Postgres can recycle WAL that recorded the deleted rows",
274
+ ]
275
+
276
+
277
+ def fix(dsn: str) -> list[str]:
278
+ conn = connect(dsn)
279
+ psycopg = _psycopg()
280
+ try:
281
+ tables = vector_tables(conn)
282
+ not_owned = [r[0] for r in conn.execute(
283
+ """
284
+ select c.oid::regclass::text from pg_class c
285
+ where c.oid = any(%s)
286
+ and not pg_has_role(current_user, c.relowner, 'USAGE')
287
+ and not (select rolsuper from pg_roles where rolname = current_user)
288
+ """,
289
+ ([t.oid for t in tables],),
290
+ )]
291
+ if not_owned:
292
+ raise PostgresError(
293
+ f"VACUUM FULL needs the table owner or a superuser; this role doesn't own: {', '.join(not_owned)}"
294
+ )
295
+ conn.execute(f"set lock_timeout = '{LOCK_TIMEOUT}'")
296
+ actions = []
297
+ for t in tables:
298
+ try:
299
+ conn.execute(f"vacuum (full, analyze) {t.sql}")
300
+ except psycopg.errors.LockNotAvailable:
301
+ raise PostgresError(
302
+ f"{t.label} is in use (couldn't lock it within {LOCK_TIMEOUT}). Stop the app's writes and run fix again; "
303
+ f"tables already rewritten: {', '.join(a.split()[1] for a in actions) or 'none'}"
304
+ ) from None
305
+ actions.append(f"rewrote {t.label} (VACUUM FULL)")
306
+ try:
307
+ for _ in range(2):
308
+ conn.execute("select pg_switch_wal()")
309
+ conn.execute("checkpoint")
310
+ actions.append("switched WAL segments and checkpointed")
311
+ except psycopg.Error as e:
312
+ actions.append(f"could not rotate WAL ({str(e).strip().splitlines()[0]}); deleted rows may stay in it until Postgres recycles it")
313
+ return actions
314
+ finally:
315
+ conn.close()
316
+
317
+
318
+ def fingerprints(dsn: str) -> dict[str, str]:
319
+ """SHA-256 of each scanned relation file, for receipts. Empty without file access."""
320
+ conn = connect(dsn)
321
+ try:
322
+ if not can_read_files(conn):
323
+ return {}
324
+ out = {}
325
+ for t in vector_tables(conn):
326
+ for label, oid in _relations(conn, t):
327
+ for path, size in _files(conn, oid):
328
+ h = hashlib.sha256()
329
+ for chunk in _read(conn, path, size):
330
+ h.update(chunk)
331
+ out[f"{t.label} ({label}) {path}"] = h.hexdigest()
332
+ return out
333
+ finally:
334
+ conn.close()
forgetproof/py.typed ADDED
File without changes