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/scanner.py ADDED
@@ -0,0 +1,288 @@
1
+ """Scan an agent memory store for data that was deleted but is still on disk."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import mmap
7
+ from collections.abc import Iterable, Iterator
8
+ from pathlib import Path
9
+
10
+ from . import files_store, hnsw, lance_store, mem0_store, postgres, qdrant_store
11
+ from ._chroma_rebuild import JOURNAL, TMP_PREFIX
12
+ from .pii import find_pii, summarize
13
+ from .report import CanaryResult, Finding, Report
14
+ from .safety import store_files
15
+ from .sqlite_residue import connect_ro, is_sqlite, live_pii, slack_finding
16
+
17
+ GHOST_VECTORS = "embeddings can be inverted back to text (Ghost Vectors, arXiv:2606.18497)"
18
+
19
+ # Chroma's embeddings_queue operation codes
20
+ _ADD, _UPDATE, _UPSERT = 0, 1, 2
21
+
22
+ # Every kind `detect` can return, in the words the CLI and the apps use for it.
23
+ KINDS = {
24
+ "chroma": "Chroma",
25
+ "sqlite": "SQLite",
26
+ "postgres": "Postgres",
27
+ "mem0": "mem0",
28
+ "qdrant": "Qdrant (local)",
29
+ "lancedb": "LanceDB",
30
+ "files": "text files",
31
+ }
32
+
33
+
34
+ class UnsupportedStore(Exception):
35
+ pass
36
+
37
+
38
+ def detect(target: Path | str) -> str:
39
+ """Which kind of store is at `target`. Directory stores are told apart by their marker files,
40
+ so a mem0 directory holding a Qdrant subdirectory is one mem0 store, not two."""
41
+ if postgres.is_postgres(target):
42
+ return "postgres"
43
+ target = Path(target)
44
+ if target.is_dir():
45
+ if (target / "chroma.sqlite3").exists():
46
+ return "chroma"
47
+ if mem0_store.detect(target):
48
+ return "mem0"
49
+ if qdrant_store.detect(target):
50
+ return "qdrant"
51
+ if lance_store.detect(target):
52
+ return "lancedb"
53
+ if files_store.detect(target):
54
+ return "files"
55
+ elif target.is_file():
56
+ if is_sqlite(target):
57
+ return "mem0" if mem0_store.detect(target) else "sqlite"
58
+ if files_store.detect(target):
59
+ return "files"
60
+ raise UnsupportedStore(
61
+ f"{target}: not a supported store. Give a Chroma persist directory (contains chroma.sqlite3), "
62
+ "a mem0 directory (history.db), a Qdrant local directory (meta.json), a LanceDB directory (*.lance), "
63
+ "a SQLite file, a markdown/JSONL file or directory, or a postgresql:// URL."
64
+ )
65
+
66
+
67
+ def _spaces_in(value) -> Iterator[str]:
68
+ """Every hnsw "space" setting anywhere in a stored collection configuration."""
69
+ if isinstance(value, dict):
70
+ if value.get("space") in ("l2", "ip", "cosine"):
71
+ yield value["space"]
72
+ for v in value.values():
73
+ yield from _spaces_in(v)
74
+ elif isinstance(value, list):
75
+ for v in value:
76
+ yield from _spaces_in(v)
77
+
78
+
79
+ def normalized_segments(conn) -> dict[str, bool]:
80
+ """segment id -> whether its HNSW index may be cosine (normalized), which decides whether
81
+ length.bin holds real data. Chroma has stored the space as collection metadata (hnsw:space),
82
+ in config_json_str and in schema_str, and they can disagree: 0.x keeps a default "l2" in its
83
+ config and applies the metadata on top. So an index counts as l2/ip only when every setting
84
+ found says l2 or ip; otherwise it's treated as cosine, which only makes fix zero less."""
85
+ columns = {r[1] for r in conn.execute("pragma table_info(collections)")}
86
+ configs = [c for c in ("config_json_str", "schema_str") if c in columns]
87
+ found: dict[str, set[str]] = {}
88
+ for row in conn.execute(f"select id{''.join(', ' + c for c in configs)} from collections"):
89
+ spaces = found.setdefault(row[0], set())
90
+ for raw in row[1:]:
91
+ try:
92
+ spaces.update(_spaces_in(json.loads(raw or "{}")))
93
+ except ValueError:
94
+ spaces.add("unknown")
95
+ for coll, value in conn.execute("select collection_id, str_value from collection_metadata where key = 'hnsw:space'"):
96
+ found.setdefault(coll, set()).add(value)
97
+
98
+ def normalized(coll: str) -> bool:
99
+ spaces = found.get(coll, set())
100
+ return not spaces or not spaces <= {"l2", "ip"}
101
+
102
+ return {sid: normalized(coll) for sid, coll in conn.execute("select id, collection from segments")}
103
+
104
+
105
+ def _sqlite_slack_finding(db: Path, target: Path, show: bool = False) -> Finding | None:
106
+ return slack_finding(db, str(db.relative_to(target)) if db != target else db.name, show)
107
+
108
+
109
+ def _scan_chroma(target: Path, report: Report, show: bool = False) -> None:
110
+ db = target / "chroma.sqlite3"
111
+ conn = connect_ro(db)
112
+ try:
113
+ segments = {sid: (scope, coll) for sid, scope, coll in conn.execute("select id, scope, collection from segments")}
114
+ collections = dict(conn.execute("select id, name from collections"))
115
+ meta_seg = {coll: sid for sid, (scope, coll) in segments.items() if scope == "METADATA"}
116
+ normalized = normalized_segments(conn)
117
+ # Chroma < 1.0 stored seq_id as 8 big-endian bytes.
118
+ max_seq = {seg: int.from_bytes(seq, "big") if isinstance(seq, bytes) else seq
119
+ for seg, seq in conn.execute("select segment_id, seq_id from max_seq_id")}
120
+
121
+ live: dict[str, set[str]] = {c: set() for c in collections}
122
+ for seg_id, emb_id in conn.execute("select segment_id, embedding_id from embeddings"):
123
+ coll = segments.get(seg_id, (None, None))[1]
124
+ if coll in live:
125
+ live[coll].add(emb_id)
126
+
127
+ def applied_seq(coll: str) -> int:
128
+ return max_seq.get(meta_seg.get(coll), -1)
129
+
130
+ # The newest applied write for each record: any earlier write is an old version.
131
+ newest: dict[tuple[str, str], int] = {}
132
+ for seq_id, topic, emb_id in conn.execute("select seq_id, topic, id from embeddings_queue"):
133
+ coll = topic.rsplit("/", 1)[-1]
134
+ if coll in collections and seq_id <= applied_seq(coll):
135
+ key = (coll, emb_id)
136
+ newest[key] = max(newest.get(key, seq_id), seq_id)
137
+
138
+ retained_ids: set[tuple[str, str]] = set()
139
+ retained_vectors = overwritten = 0
140
+ retained_pii: set[tuple[str, bytes]] = set()
141
+ rows = conn.execute("select seq_id, operation, topic, id, vector, metadata from embeddings_queue")
142
+ for seq_id, op, topic, emb_id, vector, metadata in rows:
143
+ if op not in (_ADD, _UPDATE, _UPSERT):
144
+ continue
145
+ coll = topic.rsplit("/", 1)[-1]
146
+ if coll in collections:
147
+ if seq_id > applied_seq(coll):
148
+ continue # not yet applied to the index: still the record's current content
149
+ if emb_id in live[coll]:
150
+ overwritten += seq_id < newest[(coll, emb_id)]
151
+ continue
152
+ retained_ids.add((coll, emb_id))
153
+ retained_vectors += vector is not None
154
+ if metadata:
155
+ retained_pii.update(find_pii(metadata.encode() if isinstance(metadata, str) else metadata))
156
+
157
+ unfinished = sorted(n for n in collections.values() if n.startswith(TMP_PREFIX))
158
+ if (target / JOURNAL).exists() or unfinished:
159
+ report.warnings.append("a previous `forgetproof fix` was interrupted; run fix again to finish it"
160
+ + (f" (temporary collections: {', '.join(unfinished)})" if unfinished else ""))
161
+ report.stats["collections"] = len(collections)
162
+ report.stats["live_records"] = sum(len(v) for v in live.values())
163
+ finally:
164
+ conn.close()
165
+
166
+ if retained_ids:
167
+ pii, samples = summarize(retained_pii, show)
168
+ report.findings.append(Finding(
169
+ check="chroma.write_log",
170
+ title="Deleted records still readable in Chroma's write log (embeddings_queue table)",
171
+ location="chroma.sqlite3",
172
+ records=len(retained_ids),
173
+ why=f"a plain SQL query returns their full text and {retained_vectors} embeddings",
174
+ pii=pii,
175
+ samples=samples,
176
+ ))
177
+ if overwritten:
178
+ report.findings.append(Finding(
179
+ check="chroma.write_log_overwritten",
180
+ title="Old versions of updated records still readable in Chroma's write log",
181
+ location="chroma.sqlite3",
182
+ records=overwritten,
183
+ unit="old versions",
184
+ why="update() and upsert() keep the previous text and embedding; a memory your agent corrected "
185
+ "is still on disk as it was",
186
+ ))
187
+
188
+ tombstoned = orphaned_vectors = leaked_text = 0
189
+ orphan_dirs: list[str] = []
190
+ leaked_dirs: list[str] = []
191
+ leaked_pii: set[tuple[str, bytes]] = set()
192
+ for sub in sorted(p for p in target.iterdir() if p.is_dir()):
193
+ index = hnsw.read_index(sub, normalized.get(sub.name, True))
194
+ if index is None:
195
+ continue
196
+ if sub.name not in segments:
197
+ orphan_dirs.append(sub.name)
198
+ orphaned_vectors += index.vectors
199
+ continue
200
+ tombstoned += index.deleted
201
+ if index.leaked_text or index.leaked_pii:
202
+ leaked_dirs.append(sub.name)
203
+ leaked_text += index.leaked_text
204
+ leaked_pii |= index.leaked_pii
205
+ live = live_pii(db)
206
+ leaked_pii = live.not_live(leaked_pii)
207
+ if leaked_pii:
208
+ pii, samples = summarize(leaked_pii, show)
209
+ report.findings.append(Finding(
210
+ check="chroma.uninitialized_index_memory",
211
+ title="Known-pattern values in leftover process memory written into vector index files",
212
+ location=", ".join(d[:8] + "…/data_level0.bin, length.bin" for d in leaked_dirs),
213
+ records=len(leaked_pii),
214
+ unit="pattern matches",
215
+ why="Chroma persists never-used index capacity without zeroing it; it can contain other "
216
+ "collections' documents, including deleted ones",
217
+ pii=pii,
218
+ samples=samples,
219
+ ))
220
+ elif leaked_text:
221
+ report.warnings.append(
222
+ f"{leaked_text} text fragments of leftover process memory in unused index capacity "
223
+ f"({len(leaked_dirs)} index(es)); none matches a known pattern (email, phone, card, SSN, API key). "
224
+ "Chroma writes this without zeroing it; `fix` zeroes it, and canaries check it for specific values."
225
+ )
226
+ if tombstoned:
227
+ report.findings.append(Finding(
228
+ check="chroma.hnsw_tombstones",
229
+ title="Deleted vectors still stored in the HNSW index — only flagged as deleted",
230
+ location="<segment>/data_level0.bin",
231
+ records=tombstoned,
232
+ unit="vectors",
233
+ why=GHOST_VECTORS,
234
+ ))
235
+ if orphan_dirs:
236
+ report.findings.append(Finding(
237
+ check="chroma.orphaned_index",
238
+ title=f"Index files left behind by {len(orphan_dirs)} deleted collection(s)",
239
+ location=", ".join(d[:8] + "…" for d in orphan_dirs),
240
+ records=orphaned_vectors,
241
+ unit="vectors",
242
+ why=f"delete_collection removed the rows but not these vectors; {GHOST_VECTORS}",
243
+ ))
244
+
245
+ slack = _sqlite_slack_finding(db, target, show)
246
+ if slack:
247
+ report.findings.append(slack)
248
+
249
+
250
+ def check_canaries(target: Path, canaries: Iterable[str]) -> list[CanaryResult]:
251
+ """Look for specific values you deleted (e.g. a user's email) anywhere in the store's files."""
252
+ canaries = [c for c in canaries if c]
253
+ hits: list[list[str]] = [[] for _ in canaries]
254
+ needles = [{c.encode(), c.lower().encode()} for c in canaries]
255
+ for f in store_files(target):
256
+ if f.stat().st_size == 0:
257
+ continue
258
+ with f.open("rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm:
259
+ for i, wanted in enumerate(needles):
260
+ if any(mm.find(n) != -1 for n in wanted):
261
+ hits[i].append(f.relative_to(target).as_posix() if target.is_dir() else f.name)
262
+ return [CanaryResult(i, found) for i, found in enumerate(hits, 1)]
263
+
264
+
265
+ def scan(target: Path | str, canaries: Iterable[str] = (), show: bool = False) -> Report:
266
+ """Scan a store. `show` is owner mode: samples come back unredacted, for a store the person
267
+ owns on their own machine. It never applies to a Postgres scan."""
268
+ if postgres.is_postgres(target):
269
+ return postgres.scan(str(target), list(canaries))
270
+ target = Path(target).resolve()
271
+ store = detect(target)
272
+ report = Report(target=str(target), store=store)
273
+ if store == "chroma":
274
+ _scan_chroma(target, report, show)
275
+ elif store == "mem0":
276
+ mem0_store.scan(target, report, show)
277
+ elif store == "qdrant":
278
+ qdrant_store.scan(target, report, show)
279
+ elif store == "lancedb":
280
+ lance_store.scan(target, report, show)
281
+ elif store == "files":
282
+ files_store.scan(target, report, show)
283
+ else:
284
+ slack = _sqlite_slack_finding(target, target, show=show)
285
+ if slack:
286
+ report.findings.append(slack)
287
+ report.canaries = check_canaries(target, canaries)
288
+ return report
@@ -0,0 +1,245 @@
1
+ """Tell a SQLite file's live cells from its free space by parsing its pages.
2
+
3
+ SQL shows what a database holds; the file holds more. A deleted row's bytes stay in the free block
4
+ that replaced its cell, in the unallocated gap of a page that was compacted or split, and on
5
+ freelist pages, until a VACUUM rewrites the file (secure_delete is off in most builds). An update
6
+ leaves the previous version the same way. This module walks the b-trees from their roots and the
7
+ freelist from the header, follows overflow chains, and returns two lists: every live cell's payload
8
+ bytes, and every region no live cell covers. Text in the second list that the first does not
9
+ explain is residue, whatever it says: a name, an address, a pickled payload, a dropped table's
10
+ schema. No pattern decides it.
11
+
12
+ The write-ahead log is read as SQLite reads it: the newest committed frame of a page replaces that
13
+ page in the main file. Everything else the log still holds is free space of its own kind, and its
14
+ whole image goes in the second list: older frames of the same page, frames from before the last
15
+ checkpoint reset, frames of an uncommitted transaction, and the main file's copy of a page the log
16
+ has replaced. A rollback journal is treated the same way.
17
+
18
+ Format: https://www.sqlite.org/fileformat2.html
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import mmap
24
+ import struct
25
+ from collections.abc import Iterable
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+
29
+ MAGIC = b"SQLite format 3\x00"
30
+ _WAL_MAGIC = (0x377F0682, 0x377F0683)
31
+ _LEAF_TABLE, _INTERIOR_TABLE, _LEAF_INDEX, _INTERIOR_INDEX = 0x0D, 0x05, 0x0A, 0x02
32
+ _BTREE = {_LEAF_TABLE, _INTERIOR_TABLE, _LEAF_INDEX, _INTERIOR_INDEX}
33
+ _WAL_HEADER, _FRAME_HEADER = 32, 24
34
+
35
+
36
+ @dataclass
37
+ class Layout:
38
+ page_size: int
39
+ pages: int
40
+ live: list[bytes] = field(default_factory=list) # every live cell's payload: local part plus overflow
41
+ slack: list[tuple[str, bytes]] = field(default_factory=list) # (where, bytes) that no live cell covers
42
+ unreadable: list[str] = field(default_factory=list) # pages or cells the parser could not follow
43
+
44
+
45
+ def _u16(b, i: int) -> int:
46
+ return struct.unpack_from(">H", b, i)[0]
47
+
48
+
49
+ def _u32(b, i: int) -> int:
50
+ return struct.unpack_from(">I", b, i)[0]
51
+
52
+
53
+ def _varint(b: bytes, i: int) -> tuple[int, int]:
54
+ """SQLite's big-endian varint: up to eight 7-bit bytes, a ninth byte carries all eight bits."""
55
+ v = 0
56
+ for n in range(8):
57
+ c = b[i + n]
58
+ v = (v << 7) | (c & 0x7F)
59
+ if not c & 0x80:
60
+ return v, i + n + 1
61
+ return (v << 8) | b[i + 8], i + 9
62
+
63
+
64
+ class _Pages:
65
+ """The database as SQLite sees it: the main file with the log's newest committed frames on top."""
66
+
67
+ def __init__(self, main, path: Path):
68
+ self.main = main
69
+ ps = _u16(main, 16)
70
+ self.page_size = 65536 if ps == 1 else ps
71
+ self.usable = self.page_size - main[20]
72
+ self.pages = len(main) // self.page_size
73
+ if _u32(main, 24) == _u32(main, 92) and _u32(main, 28):
74
+ self.pages = min(self.pages, _u32(main, 28))
75
+ self.overlay: dict[int, bytes] = {}
76
+ self.stale: list[tuple[str, bytes]] = []
77
+ self._read_wal(path.with_name(path.name + "-wal"))
78
+ journal = path.with_name(path.name + "-journal")
79
+ if journal.exists() and journal.stat().st_size:
80
+ self.stale.append(("-journal", journal.read_bytes()))
81
+
82
+ def page(self, n: int) -> bytes:
83
+ if n in self.overlay:
84
+ return self.overlay[n]
85
+ start = (n - 1) * self.page_size
86
+ return bytes(self.main[start:start + self.page_size])
87
+
88
+ def _read_wal(self, wal: Path) -> None:
89
+ if not wal.exists() or wal.stat().st_size < _WAL_HEADER:
90
+ return
91
+ data = wal.read_bytes()
92
+ magic, _, page_size, _, salt1, salt2 = struct.unpack_from(">IIIIII", data, 0)
93
+ if magic not in _WAL_MAGIC or page_size != self.page_size:
94
+ self.stale.append(("-wal", data)) # not a log for this file as it is; still bytes on disk
95
+ return
96
+ frame = _FRAME_HEADER + self.page_size
97
+ committed: dict[int, bytes] = {}
98
+ pending: dict[int, bytes] = {}
99
+ size_after = 0
100
+ for off in range(_WAL_HEADER, len(data) - frame + 1, frame):
101
+ pgno, commit, s1, s2 = struct.unpack_from(">IIII", data, off)
102
+ image = data[off + _FRAME_HEADER:off + frame]
103
+ if (s1, s2) != (salt1, salt2) or pgno == 0:
104
+ self.stale.append(("-wal (frame from before the last checkpoint)", image))
105
+ continue
106
+ if pgno in pending:
107
+ self.stale.append(("-wal (superseded frame)", pending.pop(pgno)))
108
+ pending[pgno] = image
109
+ if commit:
110
+ for p, img in pending.items():
111
+ if p in committed:
112
+ self.stale.append(("-wal (superseded frame)", committed[p]))
113
+ committed[p] = img
114
+ pending = {}
115
+ size_after = commit
116
+ for image in pending.values():
117
+ self.stale.append(("-wal (uncommitted frame)", image))
118
+ self.overlay = committed
119
+ if size_after:
120
+ self.pages = size_after
121
+ for p in committed:
122
+ if p <= len(self.main) // self.page_size:
123
+ start = (p - 1) * self.page_size
124
+ self.stale.append((f"page {p} (main file copy replaced by -wal)", bytes(self.main[start:start + self.page_size])))
125
+
126
+
127
+ def layout(path: Path, roots: Iterable[int] = ()) -> Layout:
128
+ """Walk the file. `roots` are the b-tree root pages from sqlite_master; page 1 is always one."""
129
+ with path.open("rb") as f:
130
+ size = f.seek(0, 2)
131
+ if size < 100:
132
+ return Layout(0, 0)
133
+ with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
134
+ return _layout(_Pages(mm, path), roots)
135
+
136
+
137
+ def _layout(pg: _Pages, roots: Iterable[int]) -> Layout:
138
+ out = Layout(pg.page_size, pg.pages)
139
+ usable = pg.usable
140
+ first = pg.page(1)
141
+ if not first or len(first) < 100:
142
+ return out
143
+
144
+ # The freelist: trunk pages chain from the header; each lists leaf pages. Every byte of a leaf
145
+ # page, and everything past the leaf array on a trunk page, is what it held before it was freed.
146
+ free: set[int] = set()
147
+ trunk, count, hops = _u32(first, 32), _u32(first, 36), 0
148
+ while 1 < trunk <= pg.pages and trunk not in free and hops <= count:
149
+ hops += 1
150
+ free.add(trunk)
151
+ p = pg.page(trunk)
152
+ nxt, k = _u32(p, 0), min(_u32(p, 4), (usable - 8) // 4)
153
+ out.slack.append((f"page {trunk} (freelist trunk)", p[8 + 4 * k:usable]))
154
+ for i in range(k):
155
+ leaf = _u32(p, 8 + 4 * i)
156
+ if 1 < leaf <= pg.pages and leaf not in free:
157
+ free.add(leaf)
158
+ out.slack.append((f"page {leaf} (freelist)", pg.page(leaf)[:usable]))
159
+ trunk = nxt
160
+
161
+ # Pointer-map pages (auto_vacuum) and the lock-byte page hold neither cells nor free space.
162
+ skip: set[int] = set()
163
+ if _u32(first, 52):
164
+ skip.update(range(2, pg.pages + 1, usable // 5 + 1))
165
+ lock = (1 << 30) // pg.page_size + 1
166
+ if lock <= pg.pages:
167
+ skip.add(lock)
168
+
169
+ reached: set[int] = set()
170
+ # (page, whether it belongs to the schema tree rooted at page 1): a replaced CREATE statement is not a record
171
+ stack = [(1, True), *((r, False) for r in roots if 1 < r <= pg.pages)]
172
+ while stack:
173
+ n, schema = stack.pop()
174
+ if n in reached or n in free or n in skip or not 1 <= n <= pg.pages:
175
+ continue
176
+ reached.add(n)
177
+ p = pg.page(n)
178
+ hdr = 100 if n == 1 else 0
179
+ kind = p[hdr] if len(p) > hdr else None
180
+ tag = ", schema" if schema else ""
181
+ if kind not in _BTREE:
182
+ out.unreadable.append(f"page {n}")
183
+ out.slack.append((f"page {n} (unrecognized{tag})", p[hdr:usable]))
184
+ continue
185
+ interior = kind in (_INTERIOR_TABLE, _INTERIOR_INDEX)
186
+ ncells, content = _u16(p, hdr + 3), _u16(p, hdr + 5) or 65536
187
+ ptrs = hdr + (12 if interior else 8)
188
+ out.slack.append((f"page {n} (unallocated{tag})", p[ptrs + 2 * ncells:min(content, usable)]))
189
+ fb, seen = _u16(p, hdr + 1), set()
190
+ while fb and fb not in seen and fb + 4 <= usable:
191
+ seen.add(fb)
192
+ nxt, size = _u16(p, fb), _u16(p, fb + 2)
193
+ out.slack.append((f"page {n} (free block{tag})", p[fb + 4:min(fb + size, usable)]))
194
+ fb = nxt
195
+ if interior:
196
+ stack.append((_u32(p, hdr + 8), schema))
197
+ for i in range(ncells):
198
+ off = _u16(p, ptrs + 2 * i)
199
+ if off >= usable:
200
+ out.unreadable.append(f"page {n} cell {i}")
201
+ continue
202
+ try:
203
+ _cell(pg, p, off, kind, schema, stack, reached, out)
204
+ except (IndexError, struct.error):
205
+ out.unreadable.append(f"page {n} cell {i}")
206
+
207
+ for n in range(1, pg.pages + 1):
208
+ if n not in reached and n not in free and n not in skip:
209
+ out.slack.append((f"page {n} (unreferenced)", pg.page(n)[:usable]))
210
+ out.slack.extend(pg.stale)
211
+ return out
212
+
213
+
214
+ def _cell(pg: _Pages, p: bytes, off: int, kind: int, schema: bool, stack: list, reached: set[int], out: Layout) -> None:
215
+ usable = pg.usable
216
+ if kind == _INTERIOR_TABLE:
217
+ stack.append((_u32(p, off), schema))
218
+ return
219
+ if kind == _INTERIOR_INDEX:
220
+ stack.append((_u32(p, off), schema))
221
+ off += 4
222
+ size, off = _varint(p, off)
223
+ if kind == _LEAF_TABLE:
224
+ _, off = _varint(p, off)
225
+ # How much of the payload is on this page, and how much spills to overflow pages (fileformat2 §1.6).
226
+ x = usable - 35 if kind == _LEAF_TABLE else (usable - 12) * 64 // 255 - 23
227
+ m = (usable - 12) * 32 // 255 - 23
228
+ if size <= x:
229
+ local = size
230
+ else:
231
+ k = m + (size - m) % (usable - 4)
232
+ local = k if k <= x else m
233
+ payload = p[off:off + local]
234
+ if local < size:
235
+ nxt, remaining = _u32(p, off + local), size - local
236
+ while 1 < nxt <= pg.pages and remaining > 0 and nxt not in reached:
237
+ reached.add(nxt)
238
+ op = pg.page(nxt)
239
+ take = min(remaining, usable - 4)
240
+ payload += op[4:4 + take]
241
+ remaining -= take
242
+ if remaining == 0:
243
+ out.slack.append((f"page {nxt} (overflow tail{', schema' if schema else ''})", op[4 + take:usable]))
244
+ nxt = _u32(op, 0)
245
+ out.live.append(payload)