coldmemory 0.3.6__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,3553 @@
1
+ """Disk-backed SQLite + mmap index for ColdMemory.
2
+
3
+ Pure Python stdlib only. Moves postings, note postings, impact-ordered ceilings,
4
+ section metadata/norms, char-trigram OOV lookup, note metadata, bundle graph, and
5
+ LinkGraph tables out of Python RAM into an owner-only (0o600) SQLite + mmap pair.
6
+ """
7
+
8
+ from collections import Counter, OrderedDict, defaultdict
9
+ from collections.abc import Mapping, Sequence
10
+ from concurrent.futures import ProcessPoolExecutor
11
+ from contextlib import contextmanager
12
+ from array import array
13
+ from bisect import bisect_left
14
+ from pathlib import Path
15
+ from urllib.parse import quote as _uri_quote
16
+ import copy
17
+ import datetime
18
+ import errno
19
+ import fcntl
20
+ import hashlib
21
+ import heapq
22
+ import json
23
+ import math
24
+ import mmap
25
+ import multiprocessing
26
+ import os
27
+ import posixpath
28
+ import re
29
+ import shutil
30
+ import sqlite3
31
+ import stat
32
+ import struct
33
+ import tempfile
34
+ import threading
35
+ import time
36
+ import zlib
37
+
38
+ from .ingest import (
39
+ PARALLEL_READS,
40
+ PARSER,
41
+ STALE,
42
+ Note,
43
+ Refused,
44
+ Source,
45
+ StaleNoteRead,
46
+ _NOTION_ID,
47
+ _candidates,
48
+ _named,
49
+ _signature,
50
+ _state,
51
+ check_rel,
52
+ frontmatter,
53
+ parse_note,
54
+ read_bytes,
55
+ )
56
+ from .redact import MARK, scrub
57
+
58
+ SCHEMA_VERSION = 1
59
+ BIN_MAGIC = b"CMIDX001"
60
+ BIN_HEADER_FMT = "<8s16sQQQQQQQQQQQQ"
61
+ BIN_HEADER_SIZE = struct.calcsize(BIN_HEADER_FMT)
62
+ DOC_META_STRIDE = 6 # (note_id, begin, end, size, heading_off, heading_len) as uint32
63
+ NOTE_LRU_SIZE = 32
64
+ LINES_LRU_SIZE = 64
65
+ LINES_LRU_MAX_BYTES = 4 * 1024 * 1024
66
+ STREAM_THRESHOLD = 2000
67
+ RUN_FLUSH_NOTES = 8192
68
+ _REQUIRED_TABLES = (
69
+ "meta",
70
+ "terms",
71
+ "trigrams",
72
+ "notes",
73
+ "lg_names",
74
+ "lg_members",
75
+ "lg_labels",
76
+ "bundle_graph",
77
+ "gone",
78
+ )
79
+ _REQUIRED_TABLE_PROBES = (
80
+ "SELECT k, v FROM meta LIMIT 1",
81
+ "SELECT term, df, sec_off, note_df, note_off, ceil_cnt, ceil_off, ceil_max FROM terms LIMIT 1",
82
+ "SELECT first_char, term_len, trigram, terms_blob FROM trigrams LIMIT 1",
83
+ "SELECT note_id, key, source_idx, rel, sha256, mtime_ns, ctime_ns, size, ino, title, body_start, line_count, status, date, dangling, meta_blob FROM notes LIMIT 1",
84
+ "SELECT phrase, note_ids FROM lg_names LIMIT 1",
85
+ "SELECT phrase, note_ids FROM lg_members LIMIT 1",
86
+ "SELECT note_id, phrases_blob FROM lg_labels LIMIT 1",
87
+ "SELECT key, entry_blob FROM bundle_graph LIMIT 1",
88
+ "SELECT key, path, mtime_ns, ctime_ns, size, ino FROM gone LIMIT 1",
89
+ )
90
+ _REQUIRED_META_KEYS = (
91
+ "schema_version",
92
+ "pair_id",
93
+ "parser_hash",
94
+ "bundle_id",
95
+ "bundle_revision",
96
+ "bundle_version",
97
+ "sources_json",
98
+ "n_notes",
99
+ "n_docs",
100
+ "n_terms",
101
+ "n_note_terms",
102
+ "average",
103
+ "avg_note",
104
+ "lg_max_name",
105
+ "walked_at",
106
+ "has_bundle_graph",
107
+ "n_bundle_graph",
108
+ )
109
+ _CODE_DIR = Path(__file__).parent
110
+ INDEX_CODE_HASH = hashlib.sha256(
111
+ b"".join(
112
+ (_CODE_DIR / name).read_bytes()
113
+ for name in ("disk_index.py", "verifier.py", "multihop_retriever.py")
114
+ )
115
+ + PARSER.encode()
116
+ ).hexdigest()[:32]
117
+ _CODE_TAG = INDEX_CODE_HASH[:8]
118
+
119
+ _WORDS = re.compile(r"\w+")
120
+
121
+
122
+ class IndexInvalid(ValueError):
123
+ """Raised when an on-disk index is missing, corrupt, incompatible, or tampered."""
124
+
125
+
126
+ def _words(text):
127
+ return _WORDS.findall(text.casefold())
128
+
129
+
130
+ def _align8(value):
131
+ return (value + 7) & ~7
132
+
133
+
134
+ def _compress_blob(raw):
135
+ if len(raw) >= 96:
136
+ comp = zlib.compress(raw, level=1)
137
+ if len(comp) + 1 < len(raw):
138
+ return b"\x01" + comp
139
+ return b"\x00" + raw
140
+
141
+
142
+ def _decompress_blob(blob):
143
+ if not isinstance(blob, (bytes, bytearray, memoryview)):
144
+ raise IndexInvalid("corrupt blob storage type in SQLite index")
145
+ if not blob:
146
+ return b""
147
+ tag = blob[0]
148
+ if tag == 0:
149
+ return blob[1:]
150
+ if tag == 1:
151
+ try:
152
+ return zlib.decompress(blob[1:])
153
+ except zlib.error as exc:
154
+ raise IndexInvalid(f"corrupt compressed blob: {exc}") from exc
155
+ raise IndexInvalid("corrupt compressed blob")
156
+
157
+
158
+ def _decode_utf8(raw):
159
+ if not isinstance(raw, (bytes, bytearray, memoryview)):
160
+ raise IndexInvalid("corrupt UTF-8 blob storage type")
161
+ try:
162
+ return bytes(raw).decode("utf-8")
163
+ except UnicodeDecodeError as exc:
164
+ raise IndexInvalid(f"corrupt UTF-8 blob: {exc}") from exc
165
+
166
+
167
+ def _decode_json_blob(blob, *, compressed=True):
168
+ if not isinstance(blob, (bytes, bytearray, memoryview)):
169
+ raise IndexInvalid("corrupt JSON blob storage type in SQLite index")
170
+ raw = _decompress_blob(blob) if compressed else blob
171
+ try:
172
+ return json.loads(_decode_utf8(raw))
173
+ except (json.JSONDecodeError, ValueError, TypeError) as exc:
174
+ raise IndexInvalid(f"corrupt JSON metadata blob: {exc}") from exc
175
+
176
+
177
+ def _canonical_rel_key(source_kind, rel):
178
+ """Match pre-PR ingest._candidates(source) ordering exactly for tie-breaking parity."""
179
+ if source_kind == "repo":
180
+ return (rel,)
181
+ parts = rel.split("/")
182
+ return tuple((1, p) for p in parts[:-1]) + ((0, parts[-1]),)
183
+
184
+
185
+ def _verify_owner_dir(path):
186
+ """Verify path is an existing owner-only (0700) real directory without following symlinks."""
187
+ try:
188
+ fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
189
+ except OSError as error:
190
+ raise Refused("index directory must be an owner-only directory") from error
191
+ try:
192
+ info = os.fstat(fd)
193
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or (info.st_mode & 0o077):
194
+ raise Refused("index directory must be an owner-only directory")
195
+ finally:
196
+ os.close(fd)
197
+
198
+
199
+ def _open_owner_file(path):
200
+ """Open an existing regular file without following symlinks and verify uid and exact 0600 mode."""
201
+ try:
202
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
203
+ except FileNotFoundError:
204
+ raise
205
+ except OSError as error:
206
+ raise Refused("disk index must be an owner-only regular file") from error
207
+ try:
208
+ info = os.fstat(fd)
209
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600:
210
+ raise Refused("disk index must be an owner-only 0600 regular file")
211
+ except BaseException:
212
+ os.close(fd)
213
+ raise
214
+ return fd, info
215
+
216
+
217
+ @contextmanager
218
+ def _publish_lock(folder, *, shared=False):
219
+ """Coordinate pair publication (LOCK_EX) and opening (LOCK_SH) so readers never see a mixed pair."""
220
+ lock_path = Path(folder) / ".publish.lock"
221
+ try:
222
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
223
+ except OSError as exc:
224
+ if shared and exc.errno in (errno.EROFS, errno.EACCES):
225
+ try:
226
+ fd = os.open(lock_path, os.O_RDONLY | os.O_NOFOLLOW)
227
+ except FileNotFoundError:
228
+ yield
229
+ return
230
+ else:
231
+ raise
232
+ try:
233
+ info = os.fstat(fd)
234
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600:
235
+ raise Refused("index publish lock must be an owner-only 0600 regular file")
236
+ fcntl.flock(fd, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
237
+ try:
238
+ yield
239
+ finally:
240
+ fcntl.flock(fd, fcntl.LOCK_UN)
241
+ finally:
242
+ os.close(fd)
243
+
244
+
245
+ def _ensure_owner_dir(path):
246
+ """Create or verify an owner-only (0700) directory without traversing symlinks for its leaf."""
247
+ path = Path(path)
248
+ if not path.exists() and not path.is_symlink():
249
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
250
+ _verify_owner_dir(path)
251
+ return path
252
+
253
+
254
+ def _fsync_file(path):
255
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
256
+ try:
257
+ os.fsync(fd)
258
+ finally:
259
+ os.close(fd)
260
+
261
+
262
+ def _fsync_dir(path):
263
+ try:
264
+ fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
265
+ except OSError:
266
+ return
267
+ try:
268
+ os.fsync(fd)
269
+ finally:
270
+ os.close(fd)
271
+
272
+
273
+ def resolve_index_dir(bundle):
274
+ """Resolve the cache directory for a bundle's disk index. Returns (Path, is_temp)."""
275
+ env_dir = os.environ.get("COLDMEMORY_INDEX_CACHE", "").strip()
276
+ if env_dir:
277
+ candidate = Path(env_dir).expanduser()
278
+ else:
279
+ note_cache = os.environ.get("COLDMEMORY_NOTE_CACHE", "").strip()
280
+ if note_cache:
281
+ candidate = Path(note_cache).expanduser().parent / "index"
282
+ else:
283
+ candidate = bundle.path.parent.parent / ".coldmemory-index"
284
+ try:
285
+ if len(str(candidate)) > 400:
286
+ raise OSError(errno.ENAMETOOLONG, "index path exceeds SQLite limit")
287
+ return _ensure_owner_dir(candidate), False
288
+ except (OSError, Refused):
289
+ return Path(tempfile.mkdtemp(prefix="coldmemory-idx-")), True
290
+
291
+
292
+ def _bundle_home_tag(bundle_home):
293
+ return hashlib.sha256(str(Path(bundle_home).resolve()).encode("utf-8")).hexdigest()[:12]
294
+
295
+
296
+ def _rev_tag(revision):
297
+ return re.sub(r"[^A-Za-z0-9]", "", str(revision))[:12] or "0"
298
+
299
+
300
+ def index_fingerprint(bundle):
301
+ """Stable identifier for one bundle revision, source list, and parser/index code."""
302
+ payload = json.dumps(
303
+ [
304
+ SCHEMA_VERSION,
305
+ INDEX_CODE_HASH,
306
+ bundle.id,
307
+ bundle.revision,
308
+ bundle.manifest["version"],
309
+ sorted((s.kind, s.label, s.root) for s in bundle.sources),
310
+ ],
311
+ separators=(",", ":"),
312
+ ).encode()
313
+ return hashlib.sha256(payload).hexdigest()[:20]
314
+
315
+
316
+ def index_paths(folder, bundle):
317
+ tag = _bundle_home_tag(bundle.path.parent)
318
+ rev = _rev_tag(bundle.revision)
319
+ fp = index_fingerprint(bundle)
320
+ return (
321
+ folder / f"idx-{tag}-{rev}-{_CODE_TAG}-{fp}.sqlite",
322
+ folder / f"idx-{tag}-{rev}-{_CODE_TAG}-{fp}.bin",
323
+ )
324
+
325
+
326
+ def _live_revisions_for_bundle(bundle_path):
327
+ """Return set of active/previous revision tags from bundle current.json if readable."""
328
+ try:
329
+ home = Path(bundle_path).parent
330
+ state = json.loads((home / "current.json").read_bytes())
331
+ if not isinstance(state, dict):
332
+ return None
333
+ return {_rev_tag(r) for r in state.values() if r}
334
+ except (OSError, ValueError, TypeError, AttributeError):
335
+ return None
336
+
337
+
338
+ def _prune_stale_indexes(folder, bundle_home, *, keep_names=(), keep_rev_tags=None, current_rev_tag=None):
339
+ """Remove obsolete index pairs for `bundle_home` in `folder` without touching other stores.
340
+
341
+ Prunes:
342
+ - Any pair whose revision is no longer in `keep_rev_tags` (when `keep_rev_tags` is available).
343
+ - Any pair for `bundle_home` built with a stale code fingerprint (`code_tag != _CODE_TAG` or legacy format),
344
+ since upgraded code refuses to open it anyway, preventing multi-GB cache accumulation across upgrades.
345
+ - Any older pair for `current_rev_tag` not in `keep_names`.
346
+ """
347
+ prefix = f"idx-{_bundle_home_tag(bundle_home)}-"
348
+ keep = set(keep_names)
349
+ try:
350
+ entries = list(Path(folder).iterdir())
351
+ except OSError:
352
+ return
353
+ for p in entries:
354
+ name = p.name
355
+ if name in keep or not name.startswith(prefix):
356
+ continue
357
+ if name.endswith(".sqlite"):
358
+ stem = name[: -len(".sqlite")]
359
+ elif name.endswith(".bin"):
360
+ stem = name[: -len(".bin")]
361
+ else:
362
+ continue
363
+ rest = stem[len(prefix) :]
364
+ parts = rest.split("-")
365
+ rev_part = parts[0]
366
+ code_part = parts[1] if len(parts) >= 3 else None
367
+ stale_code = code_part != _CODE_TAG
368
+ stale_current = current_rev_tag is not None and rev_part == current_rev_tag
369
+ stale_rev = keep_rev_tags is not None and rev_part not in keep_rev_tags
370
+ if not (stale_code or stale_current or stale_rev):
371
+ continue
372
+ try:
373
+ p.unlink()
374
+ except OSError:
375
+ pass
376
+
377
+
378
+ def prune_bundle_indexes(home, pruned_revisions):
379
+ """Remove cached disk-index pairs belonging to pruned bundle revisions of `home`."""
380
+ if not pruned_revisions:
381
+ return
382
+ home = Path(home)
383
+ prefix = f"idx-{_bundle_home_tag(home)}-"
384
+ pruned_tags = {_rev_tag(r) for r in pruned_revisions}
385
+ dirs = []
386
+ env_dir = os.environ.get("COLDMEMORY_INDEX_CACHE", "").strip()
387
+ if env_dir:
388
+ dirs.append(Path(env_dir).expanduser())
389
+ note_cache = os.environ.get("COLDMEMORY_NOTE_CACHE", "").strip()
390
+ if note_cache:
391
+ dirs.append(Path(note_cache).expanduser().parent / "index")
392
+ dirs.append(home.parent / ".coldmemory-index")
393
+ seen_dirs = set()
394
+ for folder in dirs:
395
+ try:
396
+ key = str(folder)
397
+ if key in seen_dirs or not folder.is_dir():
398
+ continue
399
+ seen_dirs.add(key)
400
+ _verify_owner_dir(folder)
401
+ with _publish_lock(folder):
402
+ for p in folder.iterdir():
403
+ name = p.name
404
+ if not name.startswith(prefix) or not (name.endswith(".sqlite") or name.endswith(".bin")):
405
+ continue
406
+ rev_part = name[len(prefix) :].split("-", 1)[0]
407
+ if rev_part in pruned_tags:
408
+ try:
409
+ p.unlink()
410
+ except OSError:
411
+ pass
412
+ except (OSError, Refused):
413
+ continue
414
+
415
+
416
+ class LazyNote(Note):
417
+ """Note metadata backed by DiskIndex; loads lines lazily through a bounded LRU cache."""
418
+
419
+ def __init__(self, *args, line_count=0, line_loader=None, **kwargs):
420
+ self._cached_lines = None
421
+ self._line_loader = line_loader
422
+ self._line_count = line_count
423
+ super().__init__(*args, **kwargs)
424
+
425
+ @property
426
+ def lines(self):
427
+ if self._cached_lines is not None:
428
+ return self._cached_lines
429
+ if self._line_loader is not None:
430
+ return self._line_loader(self)
431
+ return []
432
+
433
+ @lines.setter
434
+ def lines(self, value):
435
+ self._cached_lines = value
436
+
437
+ @property
438
+ def line_count(self):
439
+ return self._line_count
440
+
441
+
442
+ class NoteLinesCache:
443
+ """Bounded LRU cache (item count + byte budget) for lazily reading scrubbed note lines.
444
+
445
+ Verifies file SHA-256 on every disk read (cache miss); Engine._reread() independently
446
+ re-verifies live disk bytes for every cited note before returning a response.
447
+ """
448
+
449
+ def __init__(self, maxsize=LINES_LRU_SIZE, max_bytes=LINES_LRU_MAX_BYTES):
450
+ self.maxsize = max(1, int(maxsize))
451
+ self.max_bytes = max(1024, int(max_bytes))
452
+ self._lock = threading.RLock()
453
+ self._cache = OrderedDict() # (root, rel, sha256) -> (note_key, lines, est_bytes)
454
+ self._key_map = {} # note.key -> cache_key
455
+ self._total_bytes = 0
456
+
457
+ def get(self, note):
458
+ cache_key = (note.source.root, note.rel, note.sha256)
459
+ with self._lock:
460
+ cached = self._cache.get(cache_key)
461
+ if cached is not None:
462
+ self._cache.move_to_end(cache_key)
463
+ return cached[1]
464
+ try:
465
+ data, _ = read_bytes(note.source.root, note.rel)
466
+ except (OSError, Refused):
467
+ raise StaleNoteRead(note.key) from None
468
+ if hashlib.sha256(data).hexdigest() != note.sha256:
469
+ raise StaleNoteRead(note.key)
470
+ lines = scrub(data.decode("utf-8-sig", "replace").replace("\r\n", "\n")).split("\n")
471
+ est_bytes = len(data) + len(lines) * 64 + 256
472
+ if est_bytes > self.max_bytes:
473
+ return lines
474
+ with self._lock:
475
+ old = self._cache.pop(cache_key, None)
476
+ if old is not None:
477
+ self._total_bytes -= old[2]
478
+ prev_ck = self._key_map.get(note.key)
479
+ if prev_ck is not None and prev_ck != cache_key:
480
+ prev_old = self._cache.pop(prev_ck, None)
481
+ if prev_old is not None:
482
+ self._total_bytes -= prev_old[2]
483
+ self._cache[cache_key] = (note.key, lines, est_bytes)
484
+ self._total_bytes += est_bytes
485
+ self._key_map[note.key] = cache_key
486
+ while self._cache and (len(self._cache) > self.maxsize or self._total_bytes > self.max_bytes):
487
+ ev_ck, (ev_key, _, ev_bytes) = self._cache.popitem(last=False)
488
+ self._total_bytes -= ev_bytes
489
+ if self._key_map.get(ev_key) == ev_ck:
490
+ self._key_map.pop(ev_key, None)
491
+ return lines
492
+
493
+ def invalidate(self, key):
494
+ with self._lock:
495
+ ck = self._key_map.pop(key, None)
496
+ if ck is not None:
497
+ old = self._cache.pop(ck, None)
498
+ if old is not None:
499
+ self._total_bytes -= old[2]
500
+
501
+ def clear(self):
502
+ with self._lock:
503
+ self._cache.clear()
504
+ self._key_map.clear()
505
+ self._total_bytes = 0
506
+
507
+ def __len__(self):
508
+ with self._lock:
509
+ return len(self._cache)
510
+
511
+
512
+ # ---- Read-only Mapping / Sequence views backed by DiskIndex ----
513
+
514
+
515
+ class _PostingsView(Mapping):
516
+ def __init__(self, index):
517
+ self._index = index
518
+
519
+ def __contains__(self, term):
520
+ row = self._index.term_row(term)
521
+ return row is not None and row[0] > 0
522
+
523
+ def __getitem__(self, term):
524
+ row = self._index.term_row(term)
525
+ if row is None or row[0] == 0:
526
+ raise KeyError(term)
527
+ df, sec_off = row[0], row[1]
528
+ return self._index._uint32_pair(sec_off, df)
529
+
530
+ def __len__(self):
531
+ return self._index.n_terms
532
+
533
+ def __iter__(self):
534
+ return self._index.iter_terms()
535
+
536
+
537
+ class _NotePostingsView(Mapping):
538
+ def __init__(self, index):
539
+ self._index = index
540
+
541
+ def __contains__(self, term):
542
+ row = self._index.term_row(term)
543
+ return row is not None and row[2] > 0
544
+
545
+ def __getitem__(self, term):
546
+ row = self._index.term_row(term)
547
+ if row is None or row[2] == 0:
548
+ raise KeyError(term)
549
+ note_df, note_off = row[2], row[3]
550
+ return self._index._uint32_pair(note_off, note_df)
551
+
552
+ def __len__(self):
553
+ return self._index.n_note_terms
554
+
555
+ def __iter__(self):
556
+ return self._index.iter_note_terms()
557
+
558
+
559
+ class _CeilingsView(Mapping):
560
+ def __init__(self, index):
561
+ self._index = index
562
+
563
+ def __contains__(self, term):
564
+ row = self._index.term_row(term)
565
+ return row is not None and row[4] > 0
566
+
567
+ def __getitem__(self, term):
568
+ row = self._index.term_row(term)
569
+ if row is None or row[4] == 0:
570
+ raise KeyError(term)
571
+ ceil_cnt, ceil_off = row[4], row[5]
572
+ return self._index._uint32_float64_pair(ceil_off, ceil_cnt)
573
+
574
+ def __len__(self):
575
+ return self._index.n_terms
576
+
577
+ def __iter__(self):
578
+ return self._index.iter_terms()
579
+
580
+
581
+ class _DocsView(Sequence):
582
+ def __init__(self, index):
583
+ self._index = index
584
+
585
+ def __len__(self):
586
+ return self._index.n_docs
587
+
588
+ def __getitem__(self, idx):
589
+ if isinstance(idx, slice):
590
+ return [self[i] for i in range(*idx.indices(self._index.n_docs))]
591
+ if idx < 0:
592
+ idx += self._index.n_docs
593
+ if idx < 0 or idx >= self._index.n_docs:
594
+ raise IndexError(idx)
595
+ return self._index.get_doc(idx)
596
+
597
+
598
+ class _KeysView(Sequence):
599
+ def __init__(self, index):
600
+ self._index = index
601
+
602
+ def __len__(self):
603
+ return self._index.n_notes
604
+
605
+ def __getitem__(self, idx):
606
+ if isinstance(idx, slice):
607
+ return [self[i] for i in range(*idx.indices(self._index.n_notes))]
608
+ if idx < 0:
609
+ idx += self._index.n_notes
610
+ if idx < 0 or idx >= self._index.n_notes:
611
+ raise IndexError(idx)
612
+ return self._index.get_key(idx)
613
+
614
+ def __iter__(self):
615
+ return self._index.iter_keys()
616
+
617
+
618
+ class _KeyIndexView(Mapping):
619
+ def __init__(self, index):
620
+ self._index = index
621
+
622
+ def __contains__(self, key):
623
+ return self._index.get_note_id(key) is not None
624
+
625
+ def __getitem__(self, key):
626
+ nid = self._index.get_note_id(key)
627
+ if nid is None:
628
+ raise KeyError(key)
629
+ return nid
630
+
631
+ def get(self, key, default=None):
632
+ nid = self._index.get_note_id(key)
633
+ return default if nid is None else nid
634
+
635
+ def __len__(self):
636
+ return self._index.n_notes
637
+
638
+ def __iter__(self):
639
+ return self._index.iter_keys()
640
+
641
+
642
+ class _SpansView(Mapping):
643
+ def __init__(self, index):
644
+ self._index = index
645
+
646
+ def __contains__(self, key):
647
+ return self._index.get_note_id(key) is not None
648
+
649
+ def __getitem__(self, key):
650
+ nid = self._index.get_note_id(key)
651
+ if nid is None:
652
+ raise KeyError(key)
653
+ return self._index.get_span_by_id(nid)
654
+
655
+ def __len__(self):
656
+ return self._index.n_notes
657
+
658
+ def __iter__(self):
659
+ return self._index.iter_keys()
660
+
661
+
662
+ class _IndexedView(Mapping):
663
+ def __init__(self, index):
664
+ self._index = index
665
+
666
+ def __contains__(self, key):
667
+ return self._index.get_sha256(key) is not None
668
+
669
+ def __getitem__(self, key):
670
+ sha = self._index.get_sha256(key)
671
+ if sha is None:
672
+ raise KeyError(key)
673
+ return sha
674
+
675
+ def get(self, key, default=None):
676
+ sha = self._index.get_sha256(key)
677
+ return default if sha is None else sha
678
+
679
+ def __len__(self):
680
+ return self._index.n_notes
681
+
682
+ def __iter__(self):
683
+ return self._index.iter_keys()
684
+
685
+
686
+ class _BundleGraphView(Mapping):
687
+ def __init__(self, index):
688
+ self._index = index
689
+
690
+ def __contains__(self, key):
691
+ return self._index.has_bundle_graph_key(key)
692
+
693
+ def __getitem__(self, key):
694
+ entry = self._index.get_bundle_graph_entry(key)
695
+ if entry is None:
696
+ raise KeyError(key)
697
+ return entry
698
+
699
+ def get(self, key, default=None):
700
+ entry = self._index.get_bundle_graph_entry(key)
701
+ return default if entry is None else entry
702
+
703
+ def __len__(self):
704
+ return self._index.n_bundle_graph
705
+
706
+ def __iter__(self):
707
+ return self._index.iter_bundle_graph_keys()
708
+
709
+
710
+ class DiskNotesView(Mapping):
711
+ """Mapping view over live notes: DiskIndex base minus _removed plus _overrides."""
712
+
713
+ def __init__(
714
+ self,
715
+ index,
716
+ removed,
717
+ overrides,
718
+ extra_superseded=None,
719
+ drop_superseded=None,
720
+ links_overrides=None,
721
+ extra_backlinks=None,
722
+ drop_backlinks=None,
723
+ ):
724
+ self._index = index
725
+ self._removed = removed
726
+ self._overrides = overrides
727
+ self._extra_superseded = extra_superseded or {}
728
+ self._drop_superseded = drop_superseded or {}
729
+ self._links_overrides = links_overrides or {}
730
+ self._extra_backlinks = extra_backlinks or {}
731
+ self._drop_backlinks = drop_backlinks or {}
732
+
733
+ def __contains__(self, key):
734
+ if key in self._overrides:
735
+ return True
736
+ if key in self._removed:
737
+ return False
738
+ return self._index.has_note(key)
739
+
740
+ def _override_note(self, key):
741
+ note = self._overrides[key]
742
+ extra = self._extra_superseded.get(key)
743
+ links_ov = self._links_overrides.get(key)
744
+ extra_bl = self._extra_backlinks.get(key)
745
+ drop_bl = self._drop_backlinks.get(key)
746
+ has_removed = bool(self._removed) and (
747
+ any(k in self._removed for k in note.superseded_by)
748
+ or any(k in self._removed for k in note.links)
749
+ or any(k in self._removed for k in note.backlinks)
750
+ )
751
+ if not extra and links_ov is None and not extra_bl and not drop_bl and not has_removed:
752
+ return note
753
+ sup = [k for k in note.superseded_by if k not in self._removed]
754
+ if extra:
755
+ sup = sorted(set(sup) | set(extra))
756
+ links = list(links_ov) if links_ov is not None else [k for k in note.links if k not in self._removed]
757
+ bl = [k for k in note.backlinks if k not in self._removed and (not drop_bl or k not in drop_bl)]
758
+ if extra_bl:
759
+ bl = sorted(set(bl) | set(extra_bl))
760
+ if sup == note.superseded_by and links == note.links and bl == note.backlinks:
761
+ return note
762
+ cloned = copy.copy(note)
763
+ cloned.superseded_by = sup
764
+ cloned.links = links
765
+ cloned.backlinks = bl
766
+ return cloned
767
+
768
+ def __getitem__(self, key):
769
+ if key in self._overrides:
770
+ return self._override_note(key)
771
+ if key in self._removed:
772
+ raise KeyError(key)
773
+ return self._index.get_note(
774
+ key,
775
+ removed=self._removed,
776
+ extra_superseded=self._extra_superseded.get(key),
777
+ drop_superseded=self._drop_superseded.get(key),
778
+ links_override=self._links_overrides.get(key),
779
+ extra_backlinks=self._extra_backlinks.get(key),
780
+ drop_backlinks=self._drop_backlinks.get(key),
781
+ )
782
+
783
+ def get(self, key, default=None):
784
+ if key in self._overrides:
785
+ return self._override_note(key)
786
+ if key in self._removed:
787
+ return default
788
+ if not self._index.has_note(key):
789
+ return default
790
+ return self._index.get_note(
791
+ key,
792
+ removed=self._removed,
793
+ extra_superseded=self._extra_superseded.get(key),
794
+ drop_superseded=self._drop_superseded.get(key),
795
+ links_override=self._links_overrides.get(key),
796
+ extra_backlinks=self._extra_backlinks.get(key),
797
+ drop_backlinks=self._drop_backlinks.get(key),
798
+ )
799
+
800
+ def __len__(self):
801
+ extra = sum(1 for k in self._overrides if not self._index.has_note(k) or k in self._removed)
802
+ removed_in_idx = sum(1 for k in self._removed if k not in self._overrides and self._index.has_note(k))
803
+ return self._index.n_notes - removed_in_idx + extra
804
+
805
+ def __iter__(self):
806
+ for key in self._index.iter_keys():
807
+ if key in self._overrides:
808
+ yield key
809
+ elif key not in self._removed:
810
+ yield key
811
+ for key in self._overrides:
812
+ if not self._index.has_note(key):
813
+ yield key
814
+
815
+
816
+ class DiskIndex:
817
+ """Read-only handle to a verified (sqlite, bin) on-disk index pair."""
818
+
819
+ def __init__(
820
+ self,
821
+ sqlite_path,
822
+ bin_path,
823
+ con,
824
+ mm,
825
+ header,
826
+ meta,
827
+ sources,
828
+ *,
829
+ temp_dir=None,
830
+ sql_id=None,
831
+ bin_id=None,
832
+ ):
833
+ self.sqlite_path = Path(sqlite_path)
834
+ self.bin_path = Path(bin_path)
835
+ self._sql_id = sql_id
836
+ self._bin_id = bin_id
837
+ self._con = con
838
+ self._mm = mm
839
+ self._mv = memoryview(mm)
840
+ self._lock = threading.RLock()
841
+ self._closed = False
842
+ self._temp_dir = Path(temp_dir) if temp_dir else None
843
+
844
+ (
845
+ _magic,
846
+ self.pair_id,
847
+ self.n_notes,
848
+ self.n_docs,
849
+ norm_off,
850
+ note_norm_off,
851
+ spans_off,
852
+ doc_meta_off,
853
+ headings_off,
854
+ headings_len,
855
+ postings_off,
856
+ postings_len,
857
+ _total_bytes,
858
+ date_ord_off,
859
+ ) = header
860
+
861
+ self.meta = meta
862
+ self.sources = list(sources)
863
+ self.average = float(meta["average"])
864
+ self.avg_note = float(meta["avg_note"])
865
+ self.min_date_ord = int(meta["min_date_ord"]) if meta.get("min_date_ord") else None
866
+ self.max_date_ord = int(meta["max_date_ord"]) if meta.get("max_date_ord") else None
867
+ self.max_date_str = meta.get("max_date_str") or None
868
+ self.lg_max_name = int(meta.get("lg_max_name", "0"))
869
+ self.walked_at = float(meta.get("walked_at", "0"))
870
+ self.n_terms = int(meta.get("n_terms", "0"))
871
+ self.n_note_terms = int(meta.get("n_note_terms", "0"))
872
+ self.has_bundle_graph = meta.get("has_bundle_graph") == "1"
873
+ self.n_bundle_graph = int(meta.get("n_bundle_graph", "0"))
874
+ self.bundle_version = int(meta["bundle_version"])
875
+ self._initial_gone = None
876
+
877
+ self.norm = self._mv[norm_off : norm_off + 8 * self.n_docs].cast("d") if self.n_docs else memoryview(array("d"))
878
+ self.note_norm = (
879
+ self._mv[note_norm_off : note_norm_off + 8 * self.n_notes].cast("d")
880
+ if self.n_notes
881
+ else memoryview(array("d"))
882
+ )
883
+ self._spans = self._mv[spans_off : spans_off + 4 * (self.n_notes + 1)].cast("I")
884
+ self.date_ords = (
885
+ self._mv[date_ord_off : date_ord_off + 4 * self.n_notes].cast("I")
886
+ if self.n_notes
887
+ else memoryview(array("I"))
888
+ )
889
+ self._doc_meta = (
890
+ self._mv[doc_meta_off : doc_meta_off + 24 * self.n_docs].cast("I")
891
+ if self.n_docs
892
+ else memoryview(array("I"))
893
+ )
894
+ self._postings_off = postings_off
895
+ self._postings_len = postings_len
896
+ self._total_bytes = _total_bytes
897
+ self._headings = self._mv[headings_off : headings_off + headings_len]
898
+ self._postings = self._mv[postings_off : postings_off + postings_len]
899
+
900
+ self.lines_cache = NoteLinesCache(LINES_LRU_SIZE)
901
+ self._note_lru = OrderedDict() # key -> LazyNote (unfiltered base)
902
+ self._term_lru = OrderedDict() # term -> row tuple or None
903
+ self._key_id_lru = OrderedDict() # key -> (note_id, sha256)
904
+ self._id_key_lru = OrderedDict() # note_id -> key
905
+
906
+ self.postings = _PostingsView(self)
907
+ self.note_postings = _NotePostingsView(self)
908
+ self.ceilings = _CeilingsView(self)
909
+ self.docs = _DocsView(self)
910
+ self.keys = _KeysView(self)
911
+ self.key_index = _KeyIndexView(self)
912
+ self.spans = _SpansView(self)
913
+ self.indexed = _IndexedView(self)
914
+ self.bundle_graph = _BundleGraphView(self)
915
+
916
+ @classmethod
917
+ def open(cls, sqlite_path, bin_path, bundle, *, temp_dir=None):
918
+ """Open and rigorously validate an existing (sqlite, bin) index pair."""
919
+ sqlite_path, bin_path = Path(sqlite_path), Path(bin_path)
920
+ sql_fd = -1
921
+ bin_fd = -1
922
+ mm = None
923
+ con = None
924
+ try:
925
+ with _publish_lock(sqlite_path.parent, shared=True):
926
+ sql_fd, sql_info = _open_owner_file(sqlite_path)
927
+ bin_fd, bin_info = _open_owner_file(bin_path)
928
+ if bin_info.st_size < BIN_HEADER_SIZE:
929
+ raise IndexInvalid("binary index is truncated")
930
+ mm = mmap.mmap(bin_fd, 0, access=mmap.ACCESS_READ)
931
+ if hasattr(mm, "madvise") and hasattr(mmap, "MADV_RANDOM"):
932
+ try:
933
+ mm.madvise(mmap.MADV_RANDOM)
934
+ except OSError:
935
+ pass
936
+ os.close(bin_fd)
937
+ bin_fd = -1
938
+
939
+ header = struct.unpack(BIN_HEADER_FMT, mm[:BIN_HEADER_SIZE])
940
+ (
941
+ magic,
942
+ pair_id,
943
+ n_notes,
944
+ n_docs,
945
+ norm_off,
946
+ note_norm_off,
947
+ spans_off,
948
+ doc_meta_off,
949
+ headings_off,
950
+ headings_len,
951
+ postings_off,
952
+ postings_len,
953
+ total_bytes,
954
+ date_ord_off,
955
+ ) = header
956
+ if magic != BIN_MAGIC:
957
+ raise IndexInvalid("binary index magic mismatch")
958
+ if total_bytes != bin_info.st_size:
959
+ raise IndexInvalid("binary index size mismatch")
960
+ for off, size in (
961
+ (norm_off, 8 * n_docs),
962
+ (note_norm_off, 8 * n_notes),
963
+ (spans_off, 4 * (n_notes + 1)),
964
+ (date_ord_off, 4 * n_notes),
965
+ (doc_meta_off, 24 * n_docs),
966
+ (headings_off, headings_len),
967
+ (postings_off, postings_len),
968
+ ):
969
+ if off < BIN_HEADER_SIZE or off + size > total_bytes or (off & 7) != 0:
970
+ raise IndexInvalid("binary index section bounds invalid")
971
+
972
+ con = sqlite3.connect(
973
+ f"file:{_uri_quote(str(sqlite_path), safe='/')}?mode=ro&immutable=1",
974
+ uri=True,
975
+ check_same_thread=False,
976
+ )
977
+ # Force SQLite to open the underlying file descriptor while holding the shared lock
978
+ con.execute("SELECT name FROM sqlite_master WHERE type = 'table' LIMIT 1").fetchone()
979
+ after_sql = os.lstat(sqlite_path)
980
+ after_bin = os.lstat(bin_path)
981
+ os.close(sql_fd)
982
+ sql_fd = -1
983
+ if (after_sql.st_dev, after_sql.st_ino) != (sql_info.st_dev, sql_info.st_ino) or (
984
+ after_bin.st_dev,
985
+ after_bin.st_ino,
986
+ ) != (bin_info.st_dev, bin_info.st_ino):
987
+ raise Refused("disk index file changed during open")
988
+
989
+ con.execute("PRAGMA cache_size = -1500")
990
+ con.execute("PRAGMA temp_store = MEMORY")
991
+ existing_tables = {
992
+ row[0]
993
+ for row in con.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall()
994
+ }
995
+ missing_tables = [t for t in _REQUIRED_TABLES if t not in existing_tables]
996
+ if missing_tables:
997
+ raise IndexInvalid(f"disk index missing required tables: {', '.join(missing_tables)}")
998
+ for probe in _REQUIRED_TABLE_PROBES:
999
+ con.execute(probe).fetchone()
1000
+ meta = dict(con.execute("SELECT k, v FROM meta").fetchall())
1001
+ if any(k not in meta for k in _REQUIRED_META_KEYS):
1002
+ raise IndexInvalid("disk index missing required metadata")
1003
+ if meta["schema_version"] != str(SCHEMA_VERSION):
1004
+ raise IndexInvalid("index schema version mismatch")
1005
+ if meta["pair_id"] != pair_id.hex():
1006
+ raise IndexInvalid("sqlite/bin pair_id mismatch")
1007
+ if meta["parser_hash"] != INDEX_CODE_HASH:
1008
+ raise IndexInvalid("parser/index code hash mismatch")
1009
+ if meta["bundle_id"] != bundle.id or meta["bundle_revision"] != bundle.revision:
1010
+ raise IndexInvalid("bundle revision mismatch")
1011
+ if meta["bundle_version"] != str(bundle.manifest["version"]):
1012
+ raise IndexInvalid("bundle version mismatch")
1013
+ expected_sources = json.dumps(
1014
+ [(s.kind, s.label, s.root) for s in bundle.sources], separators=(",", ":")
1015
+ )
1016
+ if meta["sources_json"] != expected_sources:
1017
+ raise IndexInvalid("bundle sources mismatch")
1018
+ if int(meta["n_notes"]) != n_notes or int(meta["n_docs"]) != n_docs:
1019
+ raise IndexInvalid("note/doc count mismatch")
1020
+ actual_notes_count = con.execute("SELECT COUNT(*) FROM notes").fetchone()[0]
1021
+ if actual_notes_count != n_notes:
1022
+ raise IndexInvalid("notes table row count mismatch")
1023
+ if int(meta.get("n_terms", "0")) <= 50_000:
1024
+ bad_term = con.execute(
1025
+ "SELECT 1 FROM terms WHERE "
1026
+ "typeof(df) != 'integer' OR typeof(sec_off) != 'integer' "
1027
+ "OR typeof(note_df) != 'integer' OR typeof(note_off) != 'integer' "
1028
+ "OR typeof(ceil_cnt) != 'integer' OR typeof(ceil_off) != 'integer' "
1029
+ "OR typeof(ceil_max) NOT IN ('integer', 'real') OR abs(ceil_max) > 1e300 "
1030
+ "OR df < 0 OR sec_off < 0 OR sec_off + 8 * df > ? "
1031
+ "OR note_df < 0 OR note_off < 0 OR (note_df > 0 AND note_off + 8 * note_df > ?) "
1032
+ "OR ceil_cnt < 0 OR ceil_off < 0 OR (ceil_cnt > 0 AND ((ceil_off & 7) != 0 OR ceil_off + 12 * ceil_cnt > ?)) "
1033
+ "LIMIT 1",
1034
+ (postings_len, postings_len, postings_len),
1035
+ ).fetchone()
1036
+ if bad_term is not None:
1037
+ raise IndexInvalid("corrupt posting offset or count in terms table")
1038
+
1039
+ # Cryptographically authenticate cached bundle_graph (and v2 signed notes) against manifest["files"]["graph.json"]
1040
+ expected_graph_sha = bundle.manifest.get("files", {}).get("graph.json")
1041
+ is_signed_v2 = bundle.manifest["version"] == 2
1042
+ if is_signed_v2 and not expected_graph_sha:
1043
+ raise IndexInvalid("signed bundle missing graph.json digest")
1044
+ if expected_graph_sha is not None and (is_signed_v2 or meta.get("has_bundle_graph") == "1"):
1045
+ if meta.get("has_bundle_graph") != "1":
1046
+ raise IndexInvalid("disk index missing authenticated bundle_graph")
1047
+ h = hashlib.sha256()
1048
+ h.update(b"{")
1049
+ first = True
1050
+ bg_count = 0
1051
+ matched_notes = 0
1052
+ cur = con.execute(
1053
+ "SELECT g.key, g.entry_blob, n.sha256 "
1054
+ "FROM bundle_graph g LEFT JOIN notes n ON n.key = g.key "
1055
+ "ORDER BY g.key"
1056
+ )
1057
+ while True:
1058
+ batch = cur.fetchmany(4096)
1059
+ if not batch:
1060
+ break
1061
+ for k, blob, n_sha in batch:
1062
+ if not isinstance(blob, bytes):
1063
+ raise IndexInvalid("corrupt bundle_graph blob storage type")
1064
+ if first:
1065
+ first = False
1066
+ else:
1067
+ h.update(b",")
1068
+ h.update(json.dumps(k, ensure_ascii=False, allow_nan=False).encode("utf-8"))
1069
+ h.update(b":")
1070
+ h.update(blob)
1071
+ bg_count += 1
1072
+ if is_signed_v2 and n_sha is not None:
1073
+ matched_notes += 1
1074
+ needle = b'"sha256":"' + n_sha.encode("utf-8") + b'"'
1075
+ if blob.count(b'"sha256":') == 1:
1076
+ if needle not in blob:
1077
+ raise IndexInvalid("cached note sha256 disagrees with signed graph")
1078
+ else:
1079
+ entry_obj = _decode_json_blob(blob, compressed=False)
1080
+ if not isinstance(entry_obj, dict) or entry_obj.get("sha256") != n_sha:
1081
+ raise IndexInvalid("cached note sha256 disagrees with signed graph")
1082
+ h.update(b"}")
1083
+ if h.hexdigest() != expected_graph_sha:
1084
+ raise IndexInvalid("cached bundle_graph digest does not match manifest graph.json")
1085
+ if bg_count != int(meta["n_bundle_graph"]):
1086
+ raise IndexInvalid("bundle_graph count mismatch")
1087
+ if is_signed_v2 and matched_notes != n_notes:
1088
+ raise IndexInvalid("cached notes table contains unsigned entries")
1089
+
1090
+ # Read full `gone` table inside DiskIndex.open() so any damaged page converts to IndexInvalid
1091
+ gone_rows = con.execute("SELECT key, path, mtime_ns, ctime_ns, size, ino FROM gone").fetchall()
1092
+ initial_gone = {
1093
+ k: (path, None if mt is None else (mt, ct, sz, ino))
1094
+ for k, path, mt, ct, sz, ino in gone_rows
1095
+ }
1096
+
1097
+ obj = cls(
1098
+ sqlite_path,
1099
+ bin_path,
1100
+ con,
1101
+ mm,
1102
+ header,
1103
+ meta,
1104
+ bundle.sources,
1105
+ temp_dir=temp_dir,
1106
+ sql_id=(sql_info.st_dev, sql_info.st_ino),
1107
+ bin_id=(bin_info.st_dev, bin_info.st_ino),
1108
+ )
1109
+ obj._initial_gone = initial_gone
1110
+ return obj
1111
+ except (sqlite3.Error, struct.error, ValueError, KeyError, OSError) as error:
1112
+ if con is not None:
1113
+ try:
1114
+ con.close()
1115
+ except Exception:
1116
+ pass
1117
+ if mm is not None:
1118
+ try:
1119
+ mm.close()
1120
+ except Exception:
1121
+ pass
1122
+ if sql_fd >= 0:
1123
+ os.close(sql_fd)
1124
+ if bin_fd >= 0:
1125
+ os.close(bin_fd)
1126
+ if isinstance(error, (Refused, IndexInvalid)):
1127
+ raise
1128
+ raise IndexInvalid(f"corrupt disk index: {error}") from error
1129
+
1130
+ def close(self):
1131
+ with self._lock:
1132
+ if self._closed:
1133
+ return
1134
+ self._closed = True
1135
+ self.lines_cache.clear()
1136
+ self._note_lru.clear()
1137
+ self._term_lru.clear()
1138
+ self._key_id_lru.clear()
1139
+ self._id_key_lru.clear()
1140
+ for mv in (
1141
+ self.norm,
1142
+ self.note_norm,
1143
+ self._spans,
1144
+ self.date_ords,
1145
+ self._doc_meta,
1146
+ self._headings,
1147
+ self._postings,
1148
+ self._mv,
1149
+ ):
1150
+ try:
1151
+ mv.release()
1152
+ except Exception:
1153
+ pass
1154
+ try:
1155
+ self._mm.close()
1156
+ except Exception:
1157
+ pass
1158
+ try:
1159
+ self._con.close()
1160
+ except Exception:
1161
+ pass
1162
+ if self._temp_dir is not None:
1163
+ shutil.rmtree(self._temp_dir, ignore_errors=True)
1164
+ self._temp_dir = None
1165
+
1166
+ def __del__(self):
1167
+ try:
1168
+ self.close()
1169
+ except Exception:
1170
+ pass
1171
+
1172
+ def invalidate_lines(self, key):
1173
+ self.lines_cache.invalidate(key)
1174
+
1175
+ def trim_mmap(self):
1176
+ """Release mmapped index PTEs from process VmRSS while keeping hot pages in the OS page cache."""
1177
+ if self._closed or self._total_bytes < 16 * 1024 * 1024:
1178
+ return
1179
+ if not (hasattr(self._mm, "madvise") and hasattr(mmap, "MADV_DONTNEED")):
1180
+ return
1181
+ try:
1182
+ self._mm.madvise(mmap.MADV_DONTNEED, 0, self._total_bytes)
1183
+ except OSError:
1184
+ pass
1185
+
1186
+ # ---- Low-level mmap array slices ----
1187
+
1188
+ @staticmethod
1189
+ def _validate_term_row(row):
1190
+ if row is None:
1191
+ return None
1192
+ df, sec_off, note_df, note_off, ceil_cnt, ceil_off, ceil_max = row
1193
+ if (
1194
+ type(df) is not int
1195
+ or type(sec_off) is not int
1196
+ or type(note_df) is not int
1197
+ or type(note_off) is not int
1198
+ or type(ceil_cnt) is not int
1199
+ or type(ceil_off) is not int
1200
+ or isinstance(ceil_max, bool)
1201
+ or not isinstance(ceil_max, (int, float))
1202
+ or not math.isfinite(ceil_max)
1203
+ ):
1204
+ raise IndexInvalid("corrupt term row field types in terms table")
1205
+ return row
1206
+
1207
+ def _uint32_pair(self, off, count):
1208
+ if type(off) is not int or type(count) is not int:
1209
+ raise IndexInvalid("non-integer posting offset or count")
1210
+ if count < 0 or off < 0:
1211
+ raise IndexInvalid("negative posting offset or count")
1212
+ if count == 0:
1213
+ empty = memoryview(array("I"))
1214
+ return empty, empty
1215
+ nbytes = 4 * count
1216
+ if off + 2 * nbytes > self._postings_len:
1217
+ raise IndexInvalid("posting slice out of bounds")
1218
+ a = self._postings[off : off + nbytes].cast("I")
1219
+ b = self._postings[off + nbytes : off + 2 * nbytes].cast("I")
1220
+ return a, b
1221
+
1222
+ def _uint32_float64_pair(self, off, count):
1223
+ """Return (note_ids: memoryview['I'], shares: memoryview['d']) stored as [float64[count], uint32[count]]."""
1224
+ if type(off) is not int or type(count) is not int:
1225
+ raise IndexInvalid("non-integer ceiling offset or count")
1226
+ if count < 0 or off < 0:
1227
+ raise IndexInvalid("negative ceiling offset or count")
1228
+ if count == 0:
1229
+ return memoryview(array("I")), memoryview(array("d"))
1230
+ dbytes = 8 * count
1231
+ if (off & 7) != 0 or off + dbytes + 4 * count > self._postings_len:
1232
+ raise IndexInvalid("ceiling slice out of bounds")
1233
+ shares = self._postings[off : off + dbytes].cast("d")
1234
+ ids = self._postings[off + dbytes : off + dbytes + 4 * count].cast("I")
1235
+ return ids, shares
1236
+
1237
+ # ---- Term & posting lookups ----
1238
+
1239
+ def term_row(self, term):
1240
+ with self._lock:
1241
+ if term in self._term_lru:
1242
+ val = self._term_lru[term]
1243
+ self._term_lru.move_to_end(term)
1244
+ return val
1245
+ row = self._validate_term_row(
1246
+ self._con.execute(
1247
+ "SELECT df, sec_off, note_df, note_off, ceil_cnt, ceil_off, ceil_max "
1248
+ "FROM terms WHERE term = ?",
1249
+ (term,),
1250
+ ).fetchone()
1251
+ )
1252
+ self._term_lru[term] = row
1253
+ if len(self._term_lru) > 512:
1254
+ self._term_lru.popitem(last=False)
1255
+ return row
1256
+
1257
+ def batch_term_rows(self, term_list):
1258
+ if not term_list:
1259
+ return {}
1260
+ out = {}
1261
+ missing = []
1262
+ with self._lock:
1263
+ for t in term_list:
1264
+ if t in self._term_lru:
1265
+ val = self._term_lru[t]
1266
+ self._term_lru.move_to_end(t)
1267
+ if val is not None:
1268
+ out[t] = val
1269
+ else:
1270
+ missing.append(t)
1271
+ found = {}
1272
+ for start in range(0, len(missing), 900):
1273
+ chunk = missing[start : start + 900]
1274
+ placeholders = ",".join("?" * len(chunk))
1275
+ rows = self._con.execute(
1276
+ f"SELECT term, df, sec_off, note_df, note_off, ceil_cnt, ceil_off, ceil_max "
1277
+ f"FROM terms WHERE term IN ({placeholders})",
1278
+ chunk,
1279
+ ).fetchall()
1280
+ found.update((r[0], self._validate_term_row(r[1:])) for r in rows)
1281
+ for t in missing:
1282
+ val = found.get(t)
1283
+ self._term_lru[t] = val
1284
+ if val is not None:
1285
+ out[t] = val
1286
+ while len(self._term_lru) > 512:
1287
+ self._term_lru.popitem(last=False)
1288
+ return out
1289
+
1290
+ def ceiling_blocks(self, term):
1291
+ row = self.term_row(term)
1292
+ if row is None or row[4] == 0:
1293
+ return None
1294
+ ceil_cnt, ceil_off, ceil_max = row[4], row[5], row[6]
1295
+ n_ids, shares = self._uint32_float64_pair(ceil_off, ceil_cnt)
1296
+ return n_ids, shares, ceil_max
1297
+
1298
+ def term_df(self, term):
1299
+ row = self.term_row(term)
1300
+ return row[0] if row is not None else 0
1301
+
1302
+ def term_note_df(self, term):
1303
+ row = self.term_row(term)
1304
+ return row[2] if row is not None else 0
1305
+
1306
+ def iter_terms(self):
1307
+ with self._lock:
1308
+ rows = self._con.execute("SELECT term FROM terms WHERE df > 0").fetchall()
1309
+ for (t,) in rows:
1310
+ yield t
1311
+
1312
+ def iter_note_terms(self):
1313
+ with self._lock:
1314
+ rows = self._con.execute("SELECT term FROM terms WHERE note_df > 0").fetchall()
1315
+ for (t,) in rows:
1316
+ yield t
1317
+
1318
+ # ---- Fuzzy OOV trigram lookup ----
1319
+
1320
+ def fuzzy_candidates(self, oov_term):
1321
+ """Return Counter({vocab_term: shared_trigram_count}) matching first_char & len within 1."""
1322
+ length = len(oov_term)
1323
+ if length < 6 or not oov_term.isalpha():
1324
+ return Counter()
1325
+ first_char = oov_term[0]
1326
+ q_trigrams = [oov_term[i : i + 3] for i in range(length - 2)]
1327
+ uniq = list(dict.fromkeys(q_trigrams))
1328
+ tri_mult = Counter(q_trigrams)
1329
+ placeholders = ",".join("?" * len(uniq))
1330
+ with self._lock:
1331
+ rows = self._con.execute(
1332
+ f"SELECT trigram, terms_blob FROM trigrams "
1333
+ f"WHERE first_char = ? AND term_len BETWEEN ? AND ? AND trigram IN ({placeholders})",
1334
+ (first_char, length - 1, length + 1, *uniq),
1335
+ ).fetchall()
1336
+ cand_hits = Counter()
1337
+ for tri, blob in rows:
1338
+ mult = tri_mult[tri]
1339
+ raw = _decode_utf8(_decompress_blob(blob))
1340
+ if not raw:
1341
+ continue
1342
+ for vocab in raw.split("\n"):
1343
+ cand_hits[vocab] += mult
1344
+ return cand_hits
1345
+
1346
+ # ---- Doc / section / note lookups ----
1347
+
1348
+ def _decode_heading(self, h_off, h_len):
1349
+ if not h_len:
1350
+ return ""
1351
+ if h_off + h_len > len(self._headings):
1352
+ raise IndexInvalid("heading slice out of bounds")
1353
+ return _decode_utf8(bytes(self._headings[h_off : h_off + h_len]))
1354
+
1355
+ def get_doc(self, doc_idx):
1356
+ if not (0 <= doc_idx < self.n_docs):
1357
+ raise IndexInvalid(f"corrupt doc_idx: {doc_idx}")
1358
+ base = doc_idx * DOC_META_STRIDE
1359
+ note_id = self._doc_meta[base]
1360
+ begin = self._doc_meta[base + 1]
1361
+ end = self._doc_meta[base + 2]
1362
+ size = self._doc_meta[base + 3]
1363
+ h_off = self._doc_meta[base + 4]
1364
+ h_len = self._doc_meta[base + 5]
1365
+ key, line_count = self._note_key_and_lines(note_id)
1366
+ if begin >= end or end > line_count:
1367
+ raise IndexInvalid(f"corrupt section bounds for doc_idx {doc_idx}")
1368
+ heading = self._decode_heading(h_off, h_len)
1369
+ return key, (begin, heading, end), size
1370
+
1371
+ def get_doc_section(self, doc_idx):
1372
+ if not (0 <= doc_idx < self.n_docs):
1373
+ raise IndexInvalid(f"corrupt doc_idx: {doc_idx}")
1374
+ base = doc_idx * DOC_META_STRIDE
1375
+ note_id = self._doc_meta[base]
1376
+ begin = self._doc_meta[base + 1]
1377
+ end = self._doc_meta[base + 2]
1378
+ h_off = self._doc_meta[base + 4]
1379
+ h_len = self._doc_meta[base + 5]
1380
+ _, line_count = self._note_key_and_lines(note_id)
1381
+ if begin >= end or end > line_count:
1382
+ raise IndexInvalid(f"corrupt section metadata for doc_idx {doc_idx}")
1383
+ heading = self._decode_heading(h_off, h_len)
1384
+ return (begin, heading, end)
1385
+
1386
+ def get_span_by_id(self, note_id):
1387
+ if not (0 <= note_id < self.n_notes):
1388
+ raise IndexInvalid(f"corrupt note_id: {note_id}")
1389
+ start = self._spans[note_id]
1390
+ stop = self._spans[note_id + 1]
1391
+ if start > stop or stop > self.n_docs:
1392
+ raise IndexInvalid(f"corrupt span bounds for note_id {note_id}")
1393
+ return range(start, stop)
1394
+
1395
+ def _sections_for_note_id(self, note_id, line_count=None):
1396
+ if not (0 <= note_id < self.n_notes):
1397
+ raise IndexInvalid(f"corrupt note_id: {note_id}")
1398
+ start = self._spans[note_id]
1399
+ stop = self._spans[note_id + 1]
1400
+ if start > stop or stop > self.n_docs:
1401
+ raise IndexInvalid(f"corrupt span bounds for note_id {note_id}")
1402
+ out = []
1403
+ for doc_idx in range(start, stop):
1404
+ base = doc_idx * DOC_META_STRIDE
1405
+ begin = self._doc_meta[base + 1]
1406
+ end = self._doc_meta[base + 2]
1407
+ if begin >= end or (line_count is not None and end > line_count):
1408
+ raise IndexInvalid(f"corrupt section line bounds for doc_idx {doc_idx}")
1409
+ h_off = self._doc_meta[base + 4]
1410
+ h_len = self._doc_meta[base + 5]
1411
+ heading = self._decode_heading(h_off, h_len)
1412
+ out.append((begin, heading, end))
1413
+ return out
1414
+
1415
+ def _note_key_and_lines(self, note_id):
1416
+ if not (0 <= note_id < self.n_notes):
1417
+ raise IndexInvalid(f"corrupt note_id: {note_id}")
1418
+ with self._lock:
1419
+ pair = self._id_key_lru.get(note_id)
1420
+ if pair is not None:
1421
+ self._id_key_lru.move_to_end(note_id)
1422
+ return pair
1423
+ row = self._con.execute(
1424
+ "SELECT key, line_count FROM notes WHERE note_id = ?", (note_id,)
1425
+ ).fetchone()
1426
+ if row is None:
1427
+ raise IndexInvalid(f"missing note_id in notes table: {note_id}")
1428
+ k, lc = row
1429
+ if not isinstance(k, str) or type(lc) is not int or lc < 0:
1430
+ raise IndexInvalid(f"corrupt key or line_count for note_id: {note_id}")
1431
+ pair = (k, lc)
1432
+ self._id_key_lru[note_id] = pair
1433
+ if len(self._id_key_lru) > 1024:
1434
+ self._id_key_lru.popitem(last=False)
1435
+ return pair
1436
+
1437
+ def get_key(self, note_id):
1438
+ return self._note_key_and_lines(note_id)[0]
1439
+
1440
+ def prioritize_keys(self, keys, query_terms, overrides=None, *, max_lookup=256, check_two_hop=False):
1441
+ """Order `keys` so notes matching `query_terms` in mmap note_postings (or in `overrides`) come first.
1442
+
1443
+ When `check_two_hop=True` and `len(keys) > 24` (hub root with many intermediary links), also boosts
1444
+ intermediaries whose outgoing links match `query_terms` so a 2-hop answer is never starved by the
1445
+ first-hop visit budget. Uses only SQLite/mmap (zero disk reads, zero corpus.has() calls).
1446
+ """
1447
+ if not keys or not query_terms:
1448
+ return keys
1449
+ term_list = [t for t in query_terms if t]
1450
+ if not term_list:
1451
+ return keys
1452
+ t_rows = self.batch_term_rows(term_list)
1453
+ posting_views = []
1454
+ for t in term_list:
1455
+ row = t_rows.get(t)
1456
+ if row is not None and row[2] > 0:
1457
+ nids, _ = self._uint32_pair(row[3], row[2])
1458
+ posting_views.append(nids)
1459
+ if not posting_views and not overrides:
1460
+ return keys
1461
+
1462
+ def _nid_hits(nid):
1463
+ hits = 0
1464
+ for nids in posting_views:
1465
+ idx = bisect_left(nids, nid)
1466
+ if idx < len(nids) and nids[idx] == nid:
1467
+ hits += 1
1468
+ return hits
1469
+
1470
+ ov = overrides or ()
1471
+ scores = {}
1472
+ if len(keys) <= max_lookup:
1473
+ key_to_id = {}
1474
+ intermediary_links = {}
1475
+ want_two_hop = check_two_hop and len(keys) > 24 and len(keys) <= 256 and bool(posting_views)
1476
+ with self._lock:
1477
+ for start in range(0, len(keys), 900):
1478
+ chunk = keys[start : start + 900]
1479
+ ph = ",".join("?" * len(chunk))
1480
+ if want_two_hop:
1481
+ for k, nid, mblob in self._con.execute(
1482
+ f"SELECT key, note_id, meta_blob FROM notes WHERE key IN ({ph})", chunk
1483
+ ).fetchall():
1484
+ key_to_id[k] = nid
1485
+ meta = _decode_json_blob(mblob, compressed=True)
1486
+ if isinstance(meta, list) and len(meta) == 8 and meta[2]:
1487
+ intermediary_links[k] = meta[2]
1488
+ else:
1489
+ for k, nid in self._con.execute(
1490
+ f"SELECT key, note_id FROM notes WHERE key IN ({ph})", chunk
1491
+ ).fetchall():
1492
+ key_to_id[k] = nid
1493
+ for k in keys:
1494
+ if k in ov:
1495
+ scores[k] = (len(posting_views) + 1) * 100
1496
+ continue
1497
+ nid = key_to_id.get(k)
1498
+ if nid is None:
1499
+ continue
1500
+ hits = _nid_hits(nid)
1501
+ if hits:
1502
+ scores[k] = hits * 100
1503
+ if want_two_hop and intermediary_links:
1504
+ # Resolve 2nd-hop targets (capped at 1024 unique keys) and boost intermediaries linking to matches
1505
+ hop2_keys = []
1506
+ seen_h2 = set()
1507
+ for dsts in intermediary_links.values():
1508
+ for dst in dsts:
1509
+ if dst not in seen_h2:
1510
+ seen_h2.add(dst)
1511
+ hop2_keys.append(dst)
1512
+ if len(hop2_keys) >= 1024:
1513
+ break
1514
+ if len(hop2_keys) >= 1024:
1515
+ break
1516
+ hop2_ids = {}
1517
+ with self._lock:
1518
+ for start in range(0, len(hop2_keys), 900):
1519
+ chunk = hop2_keys[start : start + 900]
1520
+ ph = ",".join("?" * len(chunk))
1521
+ for dk, dnid in self._con.execute(
1522
+ f"SELECT key, note_id FROM notes WHERE key IN ({ph})", chunk
1523
+ ).fetchall():
1524
+ hop2_ids[dk] = dnid
1525
+ hop2_match = {dk for dk, dnid in hop2_ids.items() if _nid_hits(dnid) > 0} | (
1526
+ set(ov) & seen_h2
1527
+ )
1528
+ if hop2_match:
1529
+ for k, dsts in intermediary_links.items():
1530
+ if k not in scores and any(dst in hop2_match for dst in dsts):
1531
+ scores[k] = 10
1532
+ else:
1533
+ # Huge hub stream (e.g. thousands of backlinks): intersect from small posting lists + overrides
1534
+ key_set = set(keys)
1535
+ for k in ov:
1536
+ if k in key_set:
1537
+ scores[k] = (len(posting_views) + 1) * 100
1538
+ nid_hits = Counter()
1539
+ budget = 4096
1540
+ for nids in sorted(posting_views, key=len):
1541
+ if len(nids) > budget:
1542
+ continue
1543
+ budget -= len(nids)
1544
+ for nid in nids:
1545
+ nid_hits[nid] += 1
1546
+ if nid_hits:
1547
+ with self._lock:
1548
+ id_to_key = self._batch_keys_locked(list(nid_hits.keys()))
1549
+ for nid, cnt in nid_hits.items():
1550
+ k = id_to_key[nid]
1551
+ if k in key_set and k not in scores:
1552
+ scores[k] = cnt * 100
1553
+
1554
+ if not scores:
1555
+ return keys
1556
+ return [
1557
+ k
1558
+ for _, _, k in sorted(
1559
+ ((scores.get(k, 0), -idx, k) for idx, k in enumerate(keys)),
1560
+ reverse=True,
1561
+ )
1562
+ ]
1563
+
1564
+ def _key_meta(self, key):
1565
+ with self._lock:
1566
+ if key in self._key_id_lru:
1567
+ val = self._key_id_lru[key]
1568
+ self._key_id_lru.move_to_end(key)
1569
+ return val
1570
+ row = self._con.execute("SELECT note_id, sha256 FROM notes WHERE key = ?", (key,)).fetchone()
1571
+ self._key_id_lru[key] = row
1572
+ if len(self._key_id_lru) > 1024:
1573
+ self._key_id_lru.popitem(last=False)
1574
+ return row
1575
+
1576
+ def get_note_id(self, key):
1577
+ row = self._key_meta(key)
1578
+ return row[0] if row is not None else None
1579
+
1580
+ def get_sha256(self, key):
1581
+ row = self._key_meta(key)
1582
+ return row[1] if row is not None else None
1583
+
1584
+ def has_note(self, key):
1585
+ return self._key_meta(key) is not None
1586
+
1587
+ def get_note_date(self, note_id):
1588
+ with self._lock:
1589
+ row = self._con.execute("SELECT date FROM notes WHERE note_id = ?", (note_id,)).fetchone()
1590
+ return row[0] if row else ""
1591
+
1592
+ def _resolve_target_exact(self, src_label, src_rel, src_key, target, *, removed=frozenset()):
1593
+ """Mirror Corpus._link() resolution over live SQLite notes to validate a supersession edge."""
1594
+ kind, value = target
1595
+ if kind == "path":
1596
+ norm = posixpath.normpath(posixpath.join(posixpath.dirname(src_rel), value.partition("#")[0]))
1597
+ cand = f"{src_label}/{norm}"
1598
+ return cand if cand not in removed and self.has_note(cand) else None
1599
+ name = value.lower().removesuffix(".md")
1600
+ local, everywhere = set(), set()
1601
+ with self._lock:
1602
+ rows = self._con.execute("SELECT key, source_idx, rel, title, meta_blob FROM notes").fetchall()
1603
+ for k, s_idx, r, title, mblob in rows:
1604
+ if k in removed:
1605
+ continue
1606
+ if type(s_idx) is not int or not (0 <= s_idx < len(self.sources)):
1607
+ raise IndexInvalid(f"corrupt source_idx in notes table: {s_idx!r}")
1608
+ label = self.sources[s_idx].label
1609
+ path = posixpath.splitext(r)[0]
1610
+ base = posixpath.basename(path)
1611
+ names = {path.lower(), base.lower(), _NOTION_ID.sub("", base).lower(), (title or "").lower()}
1612
+ m = _decode_json_blob(mblob, compressed=True)
1613
+ if not isinstance(m, list) or len(m) != 8 or not isinstance(m[1], list) or not all(isinstance(a, str) for a in m[1]):
1614
+ raise IndexInvalid("corrupt note metadata tuple")
1615
+ names.update(a.lower() for a in m[1])
1616
+ if name in names:
1617
+ everywhere.add(k)
1618
+ if label == src_label:
1619
+ local.add(k)
1620
+ found = local if local else (everywhere if len(everywhere) == 1 else set())
1621
+ here = posixpath.dirname(src_key)
1622
+ return min(found, key=lambda k: (posixpath.dirname(k) != here, k.count("/"), k), default=None)
1623
+
1624
+ @staticmethod
1625
+ def _validate_meta_tuple(parsed_meta):
1626
+ if not isinstance(parsed_meta, list) or len(parsed_meta) != 8:
1627
+ raise IndexInvalid("corrupt note metadata tuple")
1628
+ for idx in range(5):
1629
+ field = parsed_meta[idx]
1630
+ if not isinstance(field, list) or not all(isinstance(item, str) for item in field):
1631
+ raise IndexInvalid(f"corrupt note metadata list field {idx}")
1632
+ for idx in range(5, 8):
1633
+ field = parsed_meta[idx]
1634
+ if not isinstance(field, list) or not all(
1635
+ isinstance(pair, (list, tuple)) and len(pair) == 2
1636
+ and isinstance(pair[0], str) and isinstance(pair[1], str)
1637
+ for pair in field
1638
+ ):
1639
+ raise IndexInvalid(f"corrupt note metadata rel field {idx}")
1640
+ return parsed_meta
1641
+
1642
+ def _verify_signed_raw_rels(self, source, rel, expected_sha, *, expected_raw_newer=None, expected_raw_older=None):
1643
+ """Verify cached raw_newer/raw_older declarations using the real note parser (frontmatter + body)."""
1644
+ try:
1645
+ data, sig = read_bytes(source.root, rel)
1646
+ except (OSError, Refused):
1647
+ raise StaleNoteRead(f"{source.label}/{rel}") from None
1648
+ if hashlib.sha256(data).hexdigest() != expected_sha:
1649
+ raise StaleNoteRead(f"{source.label}/{rel}")
1650
+ parsed = parse_note(source, rel, data, sig)
1651
+ if expected_raw_newer is not None:
1652
+ if [tuple(t) for t in expected_raw_newer] != parsed.raw_newer:
1653
+ raise IndexInvalid(f"cached raw_newer disagrees with signed file for {source.label}/{rel}")
1654
+ if expected_raw_older is not None:
1655
+ if [tuple(t) for t in expected_raw_older] != parsed.raw_older:
1656
+ raise IndexInvalid(f"cached raw_older disagrees with signed file for {source.label}/{rel}")
1657
+ return parsed
1658
+
1659
+ def _signed_note_loc(self, key):
1660
+ """Return (source, rel, sha256, raw_newer, raw_older) for a note in the SQLite table."""
1661
+ with self._lock:
1662
+ row = self._con.execute(
1663
+ "SELECT source_idx, rel, sha256, meta_blob FROM notes WHERE key = ?",
1664
+ (key,),
1665
+ ).fetchone()
1666
+ if row is None:
1667
+ raise IndexInvalid(f"missing note referenced by supersession edge: {key}")
1668
+ s_idx, rel, sha, mblob = row
1669
+ if type(s_idx) is not int or not (0 <= s_idx < len(self.sources)):
1670
+ raise IndexInvalid(f"corrupt source_idx in notes table: {s_idx}")
1671
+ meta = self._validate_meta_tuple(_decode_json_blob(mblob, compressed=True))
1672
+ return self.sources[s_idx], rel, sha, meta[6], meta[7]
1673
+
1674
+ def get_note(
1675
+ self,
1676
+ key,
1677
+ *,
1678
+ removed=frozenset(),
1679
+ extra_superseded=None,
1680
+ drop_superseded=None,
1681
+ links_override=None,
1682
+ extra_backlinks=None,
1683
+ drop_backlinks=None,
1684
+ ):
1685
+ with self._lock:
1686
+ base = self._note_lru.get(key)
1687
+ if base is not None:
1688
+ self._note_lru.move_to_end(key)
1689
+ else:
1690
+ row = self._con.execute(
1691
+ "SELECT note_id, source_idx, rel, sha256, mtime_ns, ctime_ns, size, ino, "
1692
+ "title, body_start, line_count, status, date, dangling, meta_blob "
1693
+ "FROM notes WHERE key = ?",
1694
+ (key,),
1695
+ ).fetchone()
1696
+ if row is None:
1697
+ raise KeyError(key)
1698
+ (
1699
+ note_id,
1700
+ source_idx,
1701
+ rel,
1702
+ sha256,
1703
+ mtime_ns,
1704
+ ctime_ns,
1705
+ size,
1706
+ ino,
1707
+ title,
1708
+ body_start,
1709
+ line_count,
1710
+ status,
1711
+ date,
1712
+ dangling,
1713
+ meta_blob,
1714
+ ) = row
1715
+ if type(source_idx) is not int or not (0 <= source_idx < len(self.sources)):
1716
+ raise IndexInvalid(f"corrupt source_idx in notes table: {source_idx}")
1717
+ if type(note_id) is not int or not (0 <= note_id < self.n_notes):
1718
+ raise IndexInvalid(f"corrupt note_id in notes table: {note_id}")
1719
+ if type(line_count) is not int or line_count < 0:
1720
+ raise IndexInvalid(f"corrupt line_count in notes table: {line_count}")
1721
+ if type(body_start) is not int or body_start < 0 or type(dangling) is not int or dangling < 0:
1722
+ raise IndexInvalid(f"corrupt note integer field for {key}")
1723
+ parsed_meta = self._validate_meta_tuple(_decode_json_blob(meta_blob, compressed=True))
1724
+ tags, aliases, links, backlinks, superseded_by, raw_links, raw_newer, raw_older = parsed_meta
1725
+ skip_lru_cache = False
1726
+ if self.bundle_version == 2:
1727
+ pinned = self.get_bundle_graph_entry(key)
1728
+ if not isinstance(pinned, dict):
1729
+ raise IndexInvalid(f"missing signed bundle_graph entry for {key}")
1730
+ if pinned.get("sha256") != sha256:
1731
+ raise IndexInvalid(f"cached note sha256 disagrees with signed graph for {key}")
1732
+ if pinned.get("status", "") != status:
1733
+ raise IndexInvalid(f"cached note status disagrees with signed graph for {key}")
1734
+ expected_sup = sorted(k for k in pinned.get("superseded_by", ()) if self.has_note(k))
1735
+ if any(k not in superseded_by for k in expected_sup):
1736
+ raise IndexInvalid(f"cached note missing signed superseded_by edge for {key}")
1737
+ live_removed = set(removed)
1738
+ if drop_superseded:
1739
+ live_removed.update(drop_superseded)
1740
+ extra_sup_edges = [k for k in superseded_by if k not in expected_sup]
1741
+ live_extra_sup = [k for k in extra_sup_edges if k not in live_removed]
1742
+ if len(live_extra_sup) != len(extra_sup_edges):
1743
+ skip_lru_cache = True
1744
+ if live_extra_sup:
1745
+ if self.n_notes == self.n_bundle_graph:
1746
+ raise IndexInvalid(f"cached note has extra superseded_by edge not in signed graph for {key}")
1747
+ # Partial vault at build time: parse both signed endpoints and prove the exact resolver target
1748
+ key_parsed = self._verify_signed_raw_rels(
1749
+ self.sources[source_idx], rel, sha256, expected_raw_newer=raw_newer
1750
+ )
1751
+ for sup_k in live_extra_sup:
1752
+ sup_pinned = self.get_bundle_graph_entry(sup_k)
1753
+ if not isinstance(sup_pinned, dict):
1754
+ raise IndexInvalid(f"unsigned superseded_by target {sup_k} for {key}")
1755
+ s_src, s_rel, s_sha, _, s_raw_older = self._signed_note_loc(sup_k)
1756
+ if s_sha != sup_pinned.get("sha256"):
1757
+ raise IndexInvalid(f"cached sha256 mismatch for superseding note {sup_k}")
1758
+ sup_parsed = self._verify_signed_raw_rels(
1759
+ s_src, s_rel, s_sha, expected_raw_older=s_raw_older
1760
+ )
1761
+ fwd_match = any(
1762
+ self._resolve_target_exact(
1763
+ self.sources[source_idx].label, rel, key, t, removed=live_removed
1764
+ ) == sup_k
1765
+ for t in key_parsed.raw_newer
1766
+ )
1767
+ rev_match = any(
1768
+ self._resolve_target_exact(
1769
+ s_src.label, s_rel, sup_k, t, removed=live_removed
1770
+ ) == key
1771
+ for t in sup_parsed.raw_older
1772
+ )
1773
+ if not (fwd_match or rev_match):
1774
+ raise IndexInvalid(
1775
+ f"cached extra superseded_by edge {key} -> {sup_k} not declared in signed files"
1776
+ )
1777
+ if self.n_notes == self.n_bundle_graph:
1778
+ if sorted(links) != sorted(pinned.get("links", ())):
1779
+ raise IndexInvalid(f"cached note links disagree with signed graph for {key}")
1780
+ if sorted(backlinks) != sorted(pinned.get("backlinks", ())):
1781
+ raise IndexInvalid(f"cached note backlinks disagree with signed graph for {key}")
1782
+ if not expected_sup and status not in STALE and raw_newer:
1783
+ # Prevent fake raw_newer injection in SQLite from suppressing a current signed note
1784
+ self._verify_signed_raw_rels(
1785
+ self.sources[source_idx], rel, sha256, expected_raw_newer=raw_newer
1786
+ )
1787
+ sections = self._sections_for_note_id(note_id, line_count=line_count)
1788
+ base = LazyNote(
1789
+ key=key,
1790
+ source=self.sources[source_idx],
1791
+ rel=rel,
1792
+ sha256=sha256,
1793
+ signature=(mtime_ns, ctime_ns, size, ino),
1794
+ lines=None,
1795
+ title=title,
1796
+ body_start=body_start,
1797
+ sections=sections,
1798
+ tags=tags,
1799
+ aliases=aliases,
1800
+ status=status,
1801
+ raw_links=[tuple(t) for t in raw_links],
1802
+ raw_newer=[tuple(t) for t in raw_newer],
1803
+ raw_older=[tuple(t) for t in raw_older],
1804
+ links=links,
1805
+ backlinks=backlinks,
1806
+ superseded_by=superseded_by,
1807
+ dangling=dangling,
1808
+ date=date,
1809
+ line_count=line_count,
1810
+ line_loader=self.lines_cache.get,
1811
+ )
1812
+ if not skip_lru_cache:
1813
+ self._note_lru[key] = base
1814
+ if len(self._note_lru) > NOTE_LRU_SIZE:
1815
+ self._note_lru.popitem(last=False)
1816
+ has_removed = bool(removed) and (
1817
+ any(k in removed for k in base.links)
1818
+ or any(k in removed for k in base.backlinks)
1819
+ or any(k in removed for k in base.superseded_by)
1820
+ )
1821
+ has_delta = (
1822
+ bool(extra_superseded)
1823
+ or bool(drop_superseded)
1824
+ or links_override is not None
1825
+ or bool(extra_backlinks)
1826
+ or bool(drop_backlinks)
1827
+ )
1828
+ if not has_removed and not has_delta:
1829
+ return base
1830
+ sup = [
1831
+ k
1832
+ for k in base.superseded_by
1833
+ if k not in removed and (not drop_superseded or k not in drop_superseded)
1834
+ ]
1835
+ if extra_superseded:
1836
+ sup = sorted(set(sup) | set(extra_superseded))
1837
+ links = (
1838
+ list(links_override)
1839
+ if links_override is not None
1840
+ else [k for k in base.links if k not in removed]
1841
+ )
1842
+ backlinks = [
1843
+ k
1844
+ for k in base.backlinks
1845
+ if k not in removed and (not drop_backlinks or k not in drop_backlinks)
1846
+ ]
1847
+ if extra_backlinks:
1848
+ backlinks = sorted(set(backlinks) | set(extra_backlinks))
1849
+ return LazyNote(
1850
+ key=base.key,
1851
+ source=base.source,
1852
+ rel=base.rel,
1853
+ sha256=base.sha256,
1854
+ signature=base.signature,
1855
+ lines=None,
1856
+ title=base.title,
1857
+ body_start=base.body_start,
1858
+ sections=base.sections,
1859
+ tags=base.tags,
1860
+ aliases=base.aliases,
1861
+ status=base.status,
1862
+ raw_links=base.raw_links,
1863
+ raw_newer=base.raw_newer,
1864
+ raw_older=base.raw_older,
1865
+ links=links,
1866
+ backlinks=backlinks,
1867
+ superseded_by=sup,
1868
+ dangling=base.dangling,
1869
+ date=base.date,
1870
+ line_count=base.line_count,
1871
+ line_loader=self.lines_cache.get,
1872
+ )
1873
+
1874
+ def resolve_live_edges(self, live_keys, overrides, removed):
1875
+ """Resolve live supersession and wikilink edges after edits, additions, or deletions before rebuild.
1876
+
1877
+ Matches Corpus._link() resolution over the live note set so deletions, renames, and
1878
+ new notes update both supersession targets and ordinary wikilinks/backlinks immediately.
1879
+ Returns (extra_superseded, drop_superseded, links_overrides, extra_backlinks, drop_backlinks).
1880
+ """
1881
+ if not overrides and not removed:
1882
+ return {}, {}, {}, {}, {}
1883
+ prev_disk = {}
1884
+ for k in overrides:
1885
+ if self.has_note(k):
1886
+ prev_disk[k] = self.get_note(k)
1887
+ name_changed = any(
1888
+ k not in prev_disk
1889
+ or overrides[k].title != prev_disk[k].title
1890
+ or overrides[k].aliases != prev_disk[k].aliases
1891
+ for k in overrides
1892
+ )
1893
+ need_resolve = (
1894
+ bool(removed)
1895
+ or name_changed
1896
+ or any(n.raw_links or n.raw_older or n.raw_newer for n in overrides.values())
1897
+ or any(d.raw_links or d.raw_older or d.raw_newer for d in prev_disk.values())
1898
+ )
1899
+ extra_superseded = defaultdict(set)
1900
+ drop_superseded = defaultdict(set)
1901
+ links_overrides = {}
1902
+ extra_backlinks = defaultdict(set)
1903
+ drop_backlinks = defaultdict(set)
1904
+ if not need_resolve:
1905
+ for k, old in prev_disk.items():
1906
+ for sup in old.superseded_by:
1907
+ if sup in live_keys and sup not in overrides:
1908
+ extra_superseded[k].add(sup)
1909
+ for bl in old.backlinks:
1910
+ if bl in live_keys and bl not in overrides:
1911
+ extra_backlinks[k].add(bl)
1912
+ return dict(extra_superseded), {}, {}, dict(extra_backlinks), {}
1913
+
1914
+ local = defaultdict(set)
1915
+ everywhere = defaultdict(set)
1916
+ for k, note in overrides.items():
1917
+ path = posixpath.splitext(note.rel)[0]
1918
+ names = {path, posixpath.basename(path), _NOTION_ID.sub("", posixpath.basename(path)), note.title, *note.aliases}
1919
+ for name in names:
1920
+ low = name.lower()
1921
+ local[(note.source.label, low)].add(k)
1922
+ everywhere[low].add(k)
1923
+ disk_rels = []
1924
+ disk_base_sup = {}
1925
+ disk_link_candidates = []
1926
+ signed_pinned_sup = {}
1927
+ signed_meta_by_key = {}
1928
+ with self._lock:
1929
+ if self.bundle_version == 2:
1930
+ cur = self._con.execute(
1931
+ "SELECT n.key, n.source_idx, n.rel, n.sha256, n.title, n.dangling, n.meta_blob, g.entry_blob "
1932
+ "FROM notes n LEFT JOIN bundle_graph g ON g.key = n.key"
1933
+ )
1934
+ else:
1935
+ cur = self._con.execute(
1936
+ "SELECT key, source_idx, rel, sha256, title, dangling, meta_blob, NULL FROM notes"
1937
+ )
1938
+ while True:
1939
+ batch = cur.fetchmany(2048)
1940
+ if not batch:
1941
+ break
1942
+ for k, s_idx, rel, sha, title, dangling, meta_blob, g_blob in batch:
1943
+ if k in removed or k in overrides:
1944
+ continue
1945
+ if type(s_idx) is not int or not (0 <= s_idx < len(self.sources)):
1946
+ raise IndexInvalid(f"corrupt source_idx in notes table: {s_idx}")
1947
+ parsed_meta = self._validate_meta_tuple(_decode_json_blob(meta_blob, compressed=True))
1948
+ aliases = parsed_meta[1]
1949
+ base_links = parsed_meta[2]
1950
+ base_sup = parsed_meta[4]
1951
+ d_raw_links = parsed_meta[5]
1952
+ d_raw_newer = parsed_meta[6]
1953
+ d_raw_older = parsed_meta[7]
1954
+ src_label = self.sources[s_idx].label
1955
+ path = posixpath.splitext(rel)[0]
1956
+ names = {path, posixpath.basename(path), _NOTION_ID.sub("", posixpath.basename(path)), title, *aliases}
1957
+ for name in names:
1958
+ low = name.lower()
1959
+ local[(src_label, low)].add(k)
1960
+ everywhere[low].add(k)
1961
+ if self.bundle_version == 2:
1962
+ if g_blob is None:
1963
+ raise IndexInvalid(f"missing signed bundle_graph entry for {k}")
1964
+ pinned_obj = _decode_json_blob(g_blob, compressed=False)
1965
+ if not isinstance(pinned_obj, dict) or pinned_obj.get("sha256") != sha:
1966
+ raise IndexInvalid(f"signed bundle_graph mismatch for {k}")
1967
+ p_sup = set(pinned_obj.get("superseded_by", ()))
1968
+ signed_pinned_sup[k] = p_sup
1969
+ signed_meta_by_key[k] = (self.sources[s_idx], rel, sha, d_raw_newer, d_raw_older)
1970
+ if self.n_notes == self.n_bundle_graph:
1971
+ if any(s not in p_sup for s in base_sup):
1972
+ raise IndexInvalid(f"cached base superseded_by has extra edge for {k}")
1973
+ for s in p_sup:
1974
+ if s in live_keys and s not in base_sup:
1975
+ extra_superseded[k].add(s)
1976
+ if base_sup:
1977
+ disk_base_sup[k] = base_sup
1978
+ if d_raw_older or d_raw_newer:
1979
+ disk_rels.append((k, src_label, rel, d_raw_older, d_raw_newer))
1980
+ if d_raw_links and (name_changed or dangling > 0 or any(t in removed for t in base_links)):
1981
+ disk_link_candidates.append((k, src_label, rel, base_links, d_raw_links))
1982
+
1983
+ def resolve(src_label, rel, key, target):
1984
+ kind, value = target
1985
+ if kind == "path":
1986
+ value = posixpath.normpath(posixpath.join(posixpath.dirname(rel), value.partition("#")[0]))
1987
+ dst = f"{src_label}/{value}"
1988
+ return dst if dst in live_keys else None
1989
+ name = value.lower().removesuffix(".md")
1990
+ found = local[(src_label, name)]
1991
+ if not found and len(everywhere[name]) == 1:
1992
+ found = everywhere[name]
1993
+ here = posixpath.dirname(key)
1994
+ return min(found, key=lambda cand: (posixpath.dirname(cand) != here, cand.count("/"), cand), default=None)
1995
+
1996
+ # Compute exact live supersession targets from all unchanged disk notes
1997
+ live_older = {}
1998
+ live_newer = {}
1999
+ verified_signed_keys = set()
2000
+ for dk, d_src, d_rel, d_raw_older, d_raw_newer in disk_rels:
2001
+ older_set = {dst for dst in (resolve(d_src, d_rel, dk, t) for t in d_raw_older) if dst and dst != dk}
2002
+ newer_set = {dst for dst in (resolve(d_src, d_rel, dk, t) for t in d_raw_newer) if dst and dst != dk}
2003
+ if self.bundle_version == 2:
2004
+ # Never trust unauthenticated SQLite raw_older/raw_newer to inject edges absent from signed graph
2005
+ extra_older = [dst for dst in older_set if dk not in signed_pinned_sup.get(dst, ())]
2006
+ extra_newer = [dst for dst in newer_set if dst not in signed_pinned_sup.get(dk, ())]
2007
+ if (extra_older or extra_newer) and dk not in verified_signed_keys:
2008
+ s_src, s_rel, s_sha, s_rn, s_ro = signed_meta_by_key[dk]
2009
+ self._verify_signed_raw_rels(
2010
+ s_src, s_rel, s_sha, expected_raw_newer=s_rn, expected_raw_older=s_ro
2011
+ )
2012
+ verified_signed_keys.add(dk)
2013
+ if older_set:
2014
+ live_older[dk] = older_set
2015
+ if newer_set:
2016
+ live_newer[dk] = newer_set
2017
+ for dst in older_set:
2018
+ extra_superseded[dst].add(dk)
2019
+ for dst in newer_set:
2020
+ extra_superseded[dk].add(dst)
2021
+
2022
+ # Re-resolve wikilinks on unchanged disk notes whose target was deleted or affected by added/renamed notes
2023
+ for dk, d_src, d_rel, base_links, d_raw_links in disk_link_candidates:
2024
+ new_links = sorted({dst for dst in (resolve(d_src, d_rel, dk, t) for t in d_raw_links) if dst and dst != dk})
2025
+ old_live_links = sorted(k for k in base_links if k not in removed)
2026
+ if new_links != old_live_links:
2027
+ links_overrides[dk] = new_links
2028
+ old_set = set(old_live_links)
2029
+ new_set = set(new_links)
2030
+ for dst in new_set - old_set:
2031
+ extra_backlinks[dst].add(dk)
2032
+ for dst in old_set - new_set:
2033
+ drop_backlinks[dst].add(dk)
2034
+
2035
+ # Compute live supersession & link targets from override notes
2036
+ ov_older = {}
2037
+ for k, note in overrides.items():
2038
+ new_older = {dst for dst in (resolve(note.source.label, note.rel, k, t) for t in note.raw_older) if dst and dst != k}
2039
+ new_newer = {dst for dst in (resolve(note.source.label, note.rel, k, t) for t in note.raw_newer) if dst and dst != k}
2040
+ ov_older[k] = new_older
2041
+ for dst in new_older:
2042
+ extra_superseded[dst].add(k)
2043
+ for dst in new_newer:
2044
+ extra_superseded[k].add(dst)
2045
+ if self.bundle_version == 2:
2046
+ ov_pinned = self.get_bundle_graph_entry(k)
2047
+ if isinstance(ov_pinned, dict):
2048
+ for s in ov_pinned.get("superseded_by", ()):
2049
+ if s in live_keys:
2050
+ extra_superseded[k].add(s)
2051
+ new_links = sorted({dst for dst in (resolve(note.source.label, note.rel, k, t) for t in note.raw_links) if dst and dst != k})
2052
+ links_overrides[k] = new_links
2053
+ old = prev_disk.get(k)
2054
+ old_links = set(old.links) if old is not None else set()
2055
+ new_set = set(new_links)
2056
+ for dst in new_set:
2057
+ if dst in overrides or dst not in old_links:
2058
+ extra_backlinks[dst].add(k)
2059
+ for dst in old_links - new_set:
2060
+ if dst not in removed:
2061
+ drop_backlinks[dst].add(k)
2062
+ if old is not None:
2063
+ for bl in old.backlinks:
2064
+ if bl in live_keys and bl not in overrides and bl not in drop_backlinks.get(k, ()):
2065
+ extra_backlinks[k].add(bl)
2066
+
2067
+ # Drop any base superseded_by edge on unchanged disk notes that is no longer backed by live declarations.
2068
+ # For signed v2 bundles, authenticated bundle_graph edges between two live notes are immutable and
2069
+ # must NEVER be discarded due to unauthenticated SQLite declarations.
2070
+ for k, base_sup in disk_base_sup.items():
2071
+ k_newer = live_newer.get(k, ())
2072
+ k_pinned_sup = signed_pinned_sup.get(k, ()) if self.bundle_version == 2 else ()
2073
+ for sup in base_sup:
2074
+ if sup in removed:
2075
+ continue
2076
+ if self.bundle_version == 2 and sup in k_pinned_sup:
2077
+ continue
2078
+ if sup in overrides:
2079
+ if k not in ov_older.get(sup, ()) and sup not in k_newer:
2080
+ drop_superseded[k].add(sup)
2081
+ else:
2082
+ if k not in live_older.get(sup, ()) and sup not in k_newer:
2083
+ drop_superseded[k].add(sup)
2084
+
2085
+ return (
2086
+ dict(extra_superseded),
2087
+ dict(drop_superseded),
2088
+ links_overrides,
2089
+ dict(extra_backlinks),
2090
+ dict(drop_backlinks),
2091
+ )
2092
+
2093
+ def iter_keys(self):
2094
+ with self._lock:
2095
+ cur = self._con.execute("SELECT key FROM notes ORDER BY note_id")
2096
+ while True:
2097
+ batch = cur.fetchmany(2048)
2098
+ if not batch:
2099
+ break
2100
+ for (k,) in batch:
2101
+ yield k
2102
+
2103
+ def batch_signatures(self, keys):
2104
+ """Return {key: (signature_tuple, sha256)} for a batch of keys."""
2105
+ if not keys:
2106
+ return {}
2107
+ out = {}
2108
+ with self._lock:
2109
+ for start in range(0, len(keys), 900):
2110
+ chunk = keys[start : start + 900]
2111
+ placeholders = ",".join("?" * len(chunk))
2112
+ rows = self._con.execute(
2113
+ f"SELECT key, mtime_ns, ctime_ns, size, ino, sha256 FROM notes WHERE key IN ({placeholders})",
2114
+ chunk,
2115
+ ).fetchall()
2116
+ for key, mt, ct, sz, ino, sha in rows:
2117
+ out[key] = ((mt, ct, sz, ino), sha)
2118
+ return out
2119
+
2120
+ def missing_keys(self, seen_keys):
2121
+ """Return {key: full_path} for notes in DiskIndex absent from seen_keys."""
2122
+ missing = {}
2123
+ with self._lock:
2124
+ cur = self._con.execute("SELECT key, source_idx, rel FROM notes")
2125
+ while True:
2126
+ batch = cur.fetchmany(2048)
2127
+ if not batch:
2128
+ break
2129
+ for key, s_idx, rel in batch:
2130
+ if type(s_idx) is not int or not (0 <= s_idx < len(self.sources)):
2131
+ raise IndexInvalid(f"corrupt source_idx in notes table: {s_idx!r}")
2132
+ if key not in seen_keys:
2133
+ missing[key] = os.path.join(self.sources[s_idx].root, rel)
2134
+ return missing
2135
+
2136
+ def load_gone(self):
2137
+ if self._initial_gone is not None:
2138
+ return dict(self._initial_gone)
2139
+ with self._lock:
2140
+ rows = self._con.execute("SELECT key, path, mtime_ns, ctime_ns, size, ino FROM gone").fetchall()
2141
+ out = {}
2142
+ for key, path, mt, ct, sz, ino in rows:
2143
+ sig = None if mt is None else (mt, ct, sz, ino)
2144
+ out[key] = (path, sig)
2145
+ return out
2146
+
2147
+ # ---- Bundle graph lookups ----
2148
+
2149
+ def has_bundle_graph_key(self, key):
2150
+ with self._lock:
2151
+ return self._con.execute("SELECT 1 FROM bundle_graph WHERE key = ?", (key,)).fetchone() is not None
2152
+
2153
+ def get_bundle_graph_entry(self, key):
2154
+ with self._lock:
2155
+ row = self._con.execute("SELECT entry_blob FROM bundle_graph WHERE key = ?", (key,)).fetchone()
2156
+ if row is None:
2157
+ return None
2158
+ return _decode_json_blob(row[0], compressed=False)
2159
+
2160
+ def iter_bundle_graph_keys(self):
2161
+ with self._lock:
2162
+ cur = self._con.execute("SELECT key FROM bundle_graph")
2163
+ while True:
2164
+ batch = cur.fetchmany(2048)
2165
+ if not batch:
2166
+ break
2167
+ for (k,) in batch:
2168
+ yield k
2169
+
2170
+ # ---- LinkGraph lookups ----
2171
+
2172
+ @staticmethod
2173
+ def _unpack_uint32_blob(blob, max_bytes=None):
2174
+ if not isinstance(blob, (bytes, bytearray, memoryview)) or len(blob) % 4 != 0:
2175
+ raise IndexInvalid("corrupt LinkGraph uint32 blob length")
2176
+ data = blob[:max_bytes] if max_bytes is not None else blob
2177
+ arr = array("I")
2178
+ arr.frombytes(data)
2179
+ return arr
2180
+
2181
+ def lg_lookup_phrases(self, phrases, *, max_per_phrase=None):
2182
+ """Return ({phrase: list[key]}, {phrase: list[key]}) for (names, members).
2183
+
2184
+ When `max_per_phrase` is set (e.g. `len(removed) + 2` for unique-anchor resolution),
2185
+ at most `max_per_phrase` note IDs are unpacked and looked up per phrase, avoiding
2186
+ O(N) key fetches on vault-wide tags."""
2187
+ if not phrases:
2188
+ return {}, {}
2189
+ uniq = list(dict.fromkeys(phrases))
2190
+ names_raw, members_raw = {}, {}
2191
+ all_ids = set()
2192
+ max_bytes = 4 * max_per_phrase if max_per_phrase is not None else None
2193
+ with self._lock:
2194
+ for start in range(0, len(uniq), 900):
2195
+ chunk = uniq[start : start + 900]
2196
+ ph = ",".join("?" * len(chunk))
2197
+ for phrase, blob in self._con.execute(
2198
+ f"SELECT phrase, note_ids FROM lg_names WHERE phrase IN ({ph})", chunk
2199
+ ).fetchall():
2200
+ arr = self._unpack_uint32_blob(blob, max_bytes)
2201
+ names_raw[phrase] = arr
2202
+ all_ids.update(arr)
2203
+ for phrase, blob in self._con.execute(
2204
+ f"SELECT phrase, note_ids FROM lg_members WHERE phrase IN ({ph})", chunk
2205
+ ).fetchall():
2206
+ arr = self._unpack_uint32_blob(blob, max_bytes)
2207
+ members_raw[phrase] = arr
2208
+ all_ids.update(arr)
2209
+ id_to_key = self._batch_keys_locked(all_ids)
2210
+ names = {p: [id_to_key[nid] for nid in arr] for p, arr in names_raw.items()}
2211
+ members = {p: [id_to_key[nid] for nid in arr] for p, arr in members_raw.items()}
2212
+ return names, members
2213
+
2214
+ def lg_shared_neighbors(self, key, *, max_group=64, live_count=None):
2215
+ """Return set of note keys sharing a specific LinkGraph label with `key`.
2216
+
2217
+ Skips vault-wide broadcast labels shared by more than `max_group` notes on large corpora."""
2218
+ nid = self.get_note_id(key)
2219
+ if nid is None:
2220
+ return set()
2221
+ note_count = self.n_notes if live_count is None else live_count
2222
+ cap_bytes = 4 * max_group if note_count > 128 and max_group is not None else None
2223
+ with self._lock:
2224
+ row = self._con.execute("SELECT phrases_blob FROM lg_labels WHERE note_id = ?", (nid,)).fetchone()
2225
+ if row is None or not row[0]:
2226
+ return set()
2227
+ phrases = _decode_utf8(_decompress_blob(row[0])).split("\n")
2228
+ phrases = [p for p in phrases if p]
2229
+ if not phrases:
2230
+ return set()
2231
+ neighbor_ids = set()
2232
+ for start in range(0, len(phrases), 900):
2233
+ chunk = phrases[start : start + 900]
2234
+ ph = ",".join("?" * len(chunk))
2235
+ if cap_bytes is not None:
2236
+ rows = self._con.execute(
2237
+ f"SELECT note_ids FROM lg_members WHERE phrase IN ({ph}) AND length(note_ids) <= ?",
2238
+ (*chunk, cap_bytes),
2239
+ ).fetchall()
2240
+ else:
2241
+ rows = self._con.execute(
2242
+ f"SELECT note_ids FROM lg_members WHERE phrase IN ({ph})", chunk
2243
+ ).fetchall()
2244
+ for (blob,) in rows:
2245
+ arr = self._unpack_uint32_blob(blob)
2246
+ neighbor_ids.update(arr)
2247
+ neighbor_ids.discard(nid)
2248
+ id_to_key = self._batch_keys_locked(neighbor_ids)
2249
+ return set(id_to_key.values())
2250
+
2251
+ def _batch_keys_locked(self, note_ids):
2252
+ if not note_ids:
2253
+ return {}
2254
+ out = {}
2255
+ missing = []
2256
+ for nid in note_ids:
2257
+ pair = self._id_key_lru.get(nid)
2258
+ if pair is not None:
2259
+ out[nid] = pair[0]
2260
+ else:
2261
+ missing.append(nid)
2262
+ for start in range(0, len(missing), 900):
2263
+ chunk = missing[start : start + 900]
2264
+ ph = ",".join("?" * len(chunk))
2265
+ for nid, k, lc in self._con.execute(
2266
+ f"SELECT note_id, key, line_count FROM notes WHERE note_id IN ({ph})", chunk
2267
+ ).fetchall():
2268
+ if not isinstance(k, str) or type(lc) is not int or lc < 0:
2269
+ raise IndexInvalid(f"corrupt key or line_count for note_id: {nid}")
2270
+ out[nid] = k
2271
+ self._id_key_lru[nid] = (k, lc)
2272
+ if len(out) != len(note_ids):
2273
+ raise IndexInvalid("missing note_id referenced by LinkGraph")
2274
+ while len(self._id_key_lru) > 1024:
2275
+ self._id_key_lru.popitem(last=False)
2276
+ return out
2277
+
2278
+
2279
+ # ---- SQLite schema creation & atomic writer helpers ----
2280
+
2281
+
2282
+ def _create_schema(con):
2283
+ con.executescript(
2284
+ """
2285
+ PRAGMA journal_mode = OFF;
2286
+ PRAGMA synchronous = OFF;
2287
+ PRAGMA temp_store = MEMORY;
2288
+ PRAGMA cache_size = -16000;
2289
+ CREATE TABLE meta (
2290
+ k TEXT PRIMARY KEY,
2291
+ v TEXT NOT NULL
2292
+ ) WITHOUT ROWID;
2293
+ CREATE TABLE terms (
2294
+ term TEXT PRIMARY KEY,
2295
+ df INTEGER NOT NULL,
2296
+ sec_off INTEGER NOT NULL,
2297
+ note_df INTEGER NOT NULL,
2298
+ note_off INTEGER NOT NULL,
2299
+ ceil_cnt INTEGER NOT NULL,
2300
+ ceil_off INTEGER NOT NULL,
2301
+ ceil_max REAL NOT NULL
2302
+ ) WITHOUT ROWID;
2303
+ CREATE TABLE trigrams (
2304
+ first_char TEXT NOT NULL,
2305
+ term_len INTEGER NOT NULL,
2306
+ trigram TEXT NOT NULL,
2307
+ terms_blob BLOB NOT NULL,
2308
+ PRIMARY KEY (first_char, term_len, trigram)
2309
+ ) WITHOUT ROWID;
2310
+ CREATE TABLE notes (
2311
+ note_id INTEGER PRIMARY KEY,
2312
+ key TEXT UNIQUE NOT NULL,
2313
+ source_idx INTEGER NOT NULL,
2314
+ rel TEXT NOT NULL,
2315
+ sha256 TEXT NOT NULL,
2316
+ mtime_ns INTEGER NOT NULL,
2317
+ ctime_ns INTEGER NOT NULL,
2318
+ size INTEGER NOT NULL,
2319
+ ino INTEGER NOT NULL,
2320
+ title TEXT NOT NULL,
2321
+ body_start INTEGER NOT NULL,
2322
+ line_count INTEGER NOT NULL,
2323
+ status TEXT NOT NULL,
2324
+ date TEXT NOT NULL,
2325
+ dangling INTEGER NOT NULL,
2326
+ meta_blob BLOB NOT NULL
2327
+ );
2328
+ CREATE TABLE lg_names (
2329
+ phrase TEXT PRIMARY KEY,
2330
+ note_ids BLOB NOT NULL
2331
+ ) WITHOUT ROWID;
2332
+ CREATE TABLE lg_members (
2333
+ phrase TEXT PRIMARY KEY,
2334
+ note_ids BLOB NOT NULL
2335
+ ) WITHOUT ROWID;
2336
+ CREATE TABLE lg_labels (
2337
+ note_id INTEGER PRIMARY KEY,
2338
+ phrases_blob BLOB NOT NULL
2339
+ );
2340
+ CREATE TABLE bundle_graph (
2341
+ key TEXT PRIMARY KEY,
2342
+ entry_blob BLOB NOT NULL
2343
+ ) WITHOUT ROWID;
2344
+ CREATE TABLE gone (
2345
+ key TEXT PRIMARY KEY,
2346
+ path TEXT NOT NULL,
2347
+ mtime_ns INTEGER,
2348
+ ctime_ns INTEGER,
2349
+ size INTEGER,
2350
+ ino INTEGER
2351
+ ) WITHOUT ROWID;
2352
+ """
2353
+ )
2354
+
2355
+
2356
+ def _compute_ceiling_arrays(docs, counts, owners, norm, n_nums, n_counts, note_norm, idf_val, note_idf_val, note_blend):
2357
+ """Compute impact-ordered ceilings (sorted by share desc, note_id asc) for exact Threshold Algorithm early stop.
2358
+
2359
+ Returns (ceil_note_ids: array('I'), ceil_shares: array('d'), max_share)."""
2360
+ numbers = []
2361
+ shares_d = []
2362
+ for doc, count in zip(docs, counts):
2363
+ share = count * 2.2 / (count + norm[doc])
2364
+ owner = owners[doc]
2365
+ if numbers and numbers[-1] == owner:
2366
+ if share > shares_d[-1]:
2367
+ shares_d[-1] = share
2368
+ else:
2369
+ numbers.append(owner)
2370
+ shares_d.append(share)
2371
+ if note_blend > 0 and n_nums:
2372
+ ratio = note_idf_val / (idf_val or 1.0)
2373
+ note_bonus = {n: note_blend * ratio * (c * 2.2 / (c + note_norm[n])) for n, c in zip(n_nums, n_counts)}
2374
+ for idx, num in enumerate(numbers):
2375
+ b = note_bonus.get(num)
2376
+ if b:
2377
+ shares_d[idx] += b
2378
+ # Sort descending by share, ties broken by note_id ascending for exact Threshold Algorithm tie-pruning
2379
+ if len(numbers) > 1:
2380
+ order = sorted(range(len(numbers)), key=lambda i: (-shares_d[i], numbers[i]))
2381
+ sorted_nums = array("I", (numbers[i] for i in order))
2382
+ sorted_shares = array("d", (shares_d[i] for i in order))
2383
+ else:
2384
+ sorted_nums = array("I", numbers)
2385
+ sorted_shares = array("d", shares_d)
2386
+ ceil_max = float(sorted_shares[0]) if sorted_shares else 0.0
2387
+ return sorted_nums, sorted_shares, ceil_max
2388
+
2389
+
2390
+ def _read_verified_graph(graph_path, expected_sha256, *, required=False):
2391
+ """Read graph.json and verify its SHA-256 digest before parsing."""
2392
+ if graph_path is None or not Path(graph_path).is_file():
2393
+ if required or expected_sha256 is not None:
2394
+ raise FileNotFoundError(f"missing verified graph.json: {graph_path}")
2395
+ return None
2396
+ raw_bytes = Path(graph_path).read_bytes()
2397
+ if expected_sha256 is not None and hashlib.sha256(raw_bytes).hexdigest() != expected_sha256:
2398
+ raise ValueError("graph.json digest mismatch during index build")
2399
+ return json.loads(raw_bytes)
2400
+
2401
+
2402
+ def _populate_bundle_graph(con, graph_path, expected_sha256=None, *, parsed_graph=None):
2403
+ raw = (
2404
+ parsed_graph
2405
+ if parsed_graph is not None
2406
+ else _read_verified_graph(graph_path, expected_sha256, required=(expected_sha256 is not None))
2407
+ )
2408
+ if raw is None:
2409
+ return False, 0
2410
+ rows = []
2411
+ count = 0
2412
+ for key, entry in raw.items():
2413
+ rows.append(
2414
+ (
2415
+ key,
2416
+ json.dumps(
2417
+ entry, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
2418
+ ).encode("utf-8"),
2419
+ )
2420
+ )
2421
+ count += 1
2422
+ if len(rows) >= 4096:
2423
+ con.executemany("INSERT INTO bundle_graph (key, entry_blob) VALUES (?, ?)", rows)
2424
+ rows.clear()
2425
+ if rows:
2426
+ con.executemany("INSERT INTO bundle_graph (key, entry_blob) VALUES (?, ?)", rows)
2427
+ return True, count
2428
+
2429
+
2430
+ def _create_private_temp(folder, prefix):
2431
+ fd, name = tempfile.mkstemp(prefix=prefix, dir=folder)
2432
+ os.fchmod(fd, 0o600)
2433
+ return fd, Path(name)
2434
+
2435
+
2436
+ def build_disk_index_in_memory(
2437
+ sqlite_path,
2438
+ bin_path,
2439
+ bundle,
2440
+ corpus,
2441
+ terms_fn,
2442
+ parse_iso_date_fn,
2443
+ note_blend,
2444
+ *,
2445
+ walked_at=None,
2446
+ ):
2447
+ """Build (sqlite_path, bin_path) atomically from an in-memory Corpus (fast path for < STREAM_THRESHOLD notes)."""
2448
+ sqlite_path, bin_path = Path(sqlite_path), Path(bin_path)
2449
+ folder = sqlite_path.parent
2450
+ _ensure_owner_dir(folder)
2451
+
2452
+ pair_id = os.urandom(16)
2453
+ source_idx_map = {(s.kind, s.label, s.root): idx for idx, s in enumerate(bundle.sources)}
2454
+
2455
+ # Collect per-note and per-section stats in exact pre-PR _candidates() walk order
2456
+ keys = sorted(
2457
+ corpus.notes.keys(),
2458
+ key=lambda k: (
2459
+ source_idx_map[(corpus.notes[k].source.kind, corpus.notes[k].source.label, corpus.notes[k].source.root)],
2460
+ _canonical_rel_key(corpus.notes[k].source.kind, corpus.notes[k].rel),
2461
+ ),
2462
+ )
2463
+ n_notes = len(keys)
2464
+ spans = array("I")
2465
+ doc_meta = array("I")
2466
+ doc_sizes = array("I")
2467
+ owners = array("I")
2468
+ headings_buf = bytearray()
2469
+ note_sizes = array("I")
2470
+
2471
+ sec_postings = defaultdict(lambda: (array("I"), array("I")))
2472
+ note_postings = defaultdict(lambda: (array("I"), array("I")))
2473
+ dated_ords = []
2474
+ note_date_ords = array("I")
2475
+
2476
+ lg_names = defaultdict(list)
2477
+ lg_members = defaultdict(list)
2478
+ lg_labels_rows = []
2479
+ lg_max_name = 0
2480
+
2481
+ note_rows = []
2482
+
2483
+ for number, key in enumerate(keys):
2484
+ note = corpus.notes[key]
2485
+ spans.append(len(doc_sizes))
2486
+ lines = note.lines
2487
+ line_count = len(lines)
2488
+
2489
+ # LinkGraph metadata (exact parity with multihop_retriever.LinkGraph)
2490
+ fm, _ = frontmatter(lines)
2491
+ raw_labels = [note.title, *note.aliases, *note.tags, *fm.get("entities", []), *fm.get("entity", [])]
2492
+ note_phrases = sorted(
2493
+ {
2494
+ " ".join(w)
2495
+ for label in raw_labels
2496
+ if MARK not in label and (w := _words(label))
2497
+ }
2498
+ )
2499
+ for p in note_phrases:
2500
+ lg_members[p].append(number)
2501
+ wc = p.count(" ") + 1
2502
+ if wc > lg_max_name:
2503
+ lg_max_name = wc
2504
+ name_phrases = {
2505
+ " ".join(w)
2506
+ for label in (note.title, *note.aliases)
2507
+ if MARK not in label and (w := _words(label))
2508
+ }
2509
+ for p in name_phrases:
2510
+ lg_names[p].append(number)
2511
+ if note_phrases:
2512
+ lg_labels_rows.append((number, _compress_blob("\n".join(note_phrases).encode("utf-8"))))
2513
+
2514
+ # Indexing postings (exact parity with verifier.Engine._index)
2515
+ shared = terms_fn(f"{note.title} " * 2 + " ".join([*note.aliases, *note.tags]))
2516
+ note_counts = Counter(shared)
2517
+ for begin, heading, end in note.sections:
2518
+ doc_id = len(doc_sizes)
2519
+ body_terms = terms_fn(f"{heading} " * 2) + terms_fn("\n".join(lines[begin:end]))
2520
+ counts = Counter(shared + body_terms)
2521
+ note_counts.update(body_terms)
2522
+ for term, count in counts.items():
2523
+ d_arr, c_arr = sec_postings[term]
2524
+ d_arr.append(doc_id)
2525
+ c_arr.append(count)
2526
+ h_bytes = heading.encode("utf-8")
2527
+ h_off = len(headings_buf)
2528
+ headings_buf.extend(h_bytes)
2529
+ doc_meta.extend((number, begin, end, counts.total(), h_off, len(h_bytes)))
2530
+ doc_sizes.append(counts.total())
2531
+ owners.append(number)
2532
+ for term, count in note_counts.items():
2533
+ n_arr, nc_arr = note_postings[term]
2534
+ n_arr.append(number)
2535
+ nc_arr.append(count)
2536
+ note_sizes.append(note_counts.total())
2537
+
2538
+ d_ord = 0
2539
+ if note.date:
2540
+ parsed_d = parse_iso_date_fn(note.date)
2541
+ if parsed_d is not None:
2542
+ d_ord = parsed_d.toordinal()
2543
+ dated_ords.append(d_ord)
2544
+ note_date_ords.append(d_ord)
2545
+
2546
+ s_idx = source_idx_map[(note.source.kind, note.source.label, note.source.root)]
2547
+ meta_blob = _compress_blob(
2548
+ json.dumps(
2549
+ [
2550
+ note.tags,
2551
+ note.aliases,
2552
+ note.links,
2553
+ note.backlinks,
2554
+ note.superseded_by,
2555
+ note.raw_links,
2556
+ note.raw_newer,
2557
+ note.raw_older,
2558
+ ],
2559
+ separators=(",", ":"),
2560
+ ensure_ascii=False,
2561
+ ).encode("utf-8")
2562
+ )
2563
+ sig = note.signature or (0, 0, 0, 0)
2564
+ note_rows.append(
2565
+ (
2566
+ number,
2567
+ key,
2568
+ s_idx,
2569
+ note.rel,
2570
+ note.sha256,
2571
+ sig[0],
2572
+ sig[1],
2573
+ sig[2],
2574
+ sig[3],
2575
+ note.title,
2576
+ note.body_start,
2577
+ line_count,
2578
+ note.status,
2579
+ note.date,
2580
+ note.dangling,
2581
+ meta_blob,
2582
+ )
2583
+ )
2584
+
2585
+ spans.append(len(doc_sizes))
2586
+ n_docs = len(doc_sizes)
2587
+ average = sum(doc_sizes) / (n_docs or 1) or 1.0
2588
+ norm = array("d", (1.2 * (0.25 + 0.75 * (sz / average)) for sz in doc_sizes))
2589
+ avg_note = sum(note_sizes) / (n_notes or 1) or 1.0
2590
+ note_norm = array("d", (1.2 * (0.25 + 0.75 * (sz / avg_note)) for sz in note_sizes))
2591
+ min_date_ord = min(dated_ords) if dated_ords else None
2592
+ max_date_ord = max(dated_ords) if dated_ords else None
2593
+ max_date_str = datetime.date.fromordinal(max_date_ord).isoformat() if max_date_ord else ""
2594
+
2595
+ # Write binary + sqlite atomically to temp files
2596
+ bin_fd = -1
2597
+ tmp_bin = tmp_sql = None
2598
+
2599
+ try:
2600
+ bin_fd, tmp_bin = _create_private_temp(folder, f".{bin_path.name}.")
2601
+ sql_fd, tmp_sql = _create_private_temp(folder, f".{sqlite_path.name}.")
2602
+ os.close(sql_fd)
2603
+ con = sqlite3.connect(str(tmp_sql))
2604
+ try:
2605
+ _create_schema(con)
2606
+ con.executemany(
2607
+ "INSERT INTO notes VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
2608
+ note_rows,
2609
+ )
2610
+ con.executemany(
2611
+ "INSERT INTO lg_names VALUES (?,?)",
2612
+ ((p, array("I", ids).tobytes()) for p, ids in lg_names.items()),
2613
+ )
2614
+ con.executemany(
2615
+ "INSERT INTO lg_members VALUES (?,?)",
2616
+ ((p, array("I", ids).tobytes()) for p, ids in lg_members.items()),
2617
+ )
2618
+ if lg_labels_rows:
2619
+ con.executemany("INSERT INTO lg_labels VALUES (?,?)", lg_labels_rows)
2620
+ if corpus.gone:
2621
+ con.executemany(
2622
+ "INSERT INTO gone VALUES (?,?,?,?,?,?)",
2623
+ (
2624
+ (k, path, *(sig if sig is not None else (None, None, None, None)))
2625
+ for k, (path, sig) in corpus.gone.items()
2626
+ ),
2627
+ )
2628
+ expected_graph_sha = bundle.manifest.get("files", {}).get("graph.json")
2629
+ has_bg, n_bg = _populate_bundle_graph(con, bundle.path / "graph.json", expected_graph_sha)
2630
+
2631
+ # Write binary sections
2632
+ with os.fdopen(bin_fd, "wb") as bf:
2633
+ bin_fd = -1
2634
+ bf.write(b"\x00" * BIN_HEADER_SIZE)
2635
+
2636
+ def pad8():
2637
+ pos = bf.tell()
2638
+ rem = (-pos) & 7
2639
+ if rem:
2640
+ bf.write(b"\x00" * rem)
2641
+ return bf.tell()
2642
+
2643
+ norm_off = pad8()
2644
+ bf.write(norm.tobytes())
2645
+ note_norm_off = pad8()
2646
+ bf.write(note_norm.tobytes())
2647
+ spans_off = pad8()
2648
+ bf.write(spans.tobytes())
2649
+ date_ord_off = pad8()
2650
+ bf.write(note_date_ords.tobytes())
2651
+ doc_meta_off = pad8()
2652
+ bf.write(doc_meta.tobytes())
2653
+ headings_off = pad8()
2654
+ bf.write(headings_buf)
2655
+ headings_len = len(headings_buf)
2656
+ postings_off = pad8()
2657
+
2658
+ # Write terms in sorted alphabetical order so trigram buckets flush per first_char
2659
+ term_rows = []
2660
+ n_note_terms = 0
2661
+ cur_char = None
2662
+ tri_buckets = defaultdict(list)
2663
+
2664
+ def flush_trigrams():
2665
+ if not tri_buckets:
2666
+ return
2667
+ con.executemany(
2668
+ "INSERT INTO trigrams VALUES (?,?,?,?)",
2669
+ (
2670
+ (fc, tl, tri, _compress_blob("\n".join(words_list).encode("utf-8")))
2671
+ for (fc, tl, tri), words_list in tri_buckets.items()
2672
+ ),
2673
+ )
2674
+ tri_buckets.clear()
2675
+
2676
+ sorted_terms = sorted(sec_postings.keys() | note_postings.keys())
2677
+ n_sec_terms = 0
2678
+ for term in sorted_terms:
2679
+ sp_entry = sec_postings.get(term)
2680
+ if sp_entry is not None:
2681
+ d_arr, c_arr = sp_entry
2682
+ df = len(d_arr)
2683
+ n_sec_terms += 1
2684
+ sec_rel = bf.tell() - postings_off
2685
+ bf.write(d_arr.tobytes())
2686
+ bf.write(c_arr.tobytes())
2687
+ else:
2688
+ d_arr = c_arr = None
2689
+ df = 0
2690
+ sec_rel = 0
2691
+
2692
+ np_entry = note_postings.get(term)
2693
+ if np_entry is not None:
2694
+ n_arr, nc_arr = np_entry
2695
+ note_df = len(n_arr)
2696
+ n_note_terms += 1
2697
+ note_rel = bf.tell() - postings_off
2698
+ bf.write(n_arr.tobytes())
2699
+ bf.write(nc_arr.tobytes())
2700
+ else:
2701
+ n_arr, nc_arr = None, None
2702
+ note_df = 0
2703
+ note_rel = 0
2704
+
2705
+ if df > 0:
2706
+ idf_val = math.log(1 + (n_docs - df + 0.5) / (df + 0.5))
2707
+ note_idf_val = math.log(1 + (n_notes - note_df + 0.5) / (note_df + 0.5))
2708
+ c_nums, c_shares, ceil_max = _compute_ceiling_arrays(
2709
+ d_arr, c_arr, owners, norm, n_arr, nc_arr, note_norm, idf_val, note_idf_val, note_blend
2710
+ )
2711
+ ceil_cnt = len(c_nums)
2712
+ ceil_rel = pad8() - postings_off
2713
+ bf.write(c_shares.tobytes())
2714
+ bf.write(c_nums.tobytes())
2715
+ else:
2716
+ ceil_cnt = 0
2717
+ ceil_rel = 0
2718
+ ceil_max = 0.0
2719
+
2720
+ term_rows.append(
2721
+ (term, df, sec_rel, note_df, note_rel, ceil_cnt, ceil_rel, ceil_max)
2722
+ )
2723
+ if len(term_rows) >= 10000:
2724
+ con.executemany("INSERT INTO terms VALUES (?,?,?,?,?,?,?,?)", term_rows)
2725
+ term_rows.clear()
2726
+
2727
+ if df > 0 and len(term) >= 5 and term.isalpha():
2728
+ fc = term[0]
2729
+ if cur_char is not None and fc != cur_char:
2730
+ flush_trigrams()
2731
+ cur_char = fc
2732
+ tl = len(term)
2733
+ for i in range(tl - 2):
2734
+ tri_buckets[(fc, tl, term[i : i + 3])].append(term)
2735
+
2736
+ if term_rows:
2737
+ con.executemany("INSERT INTO terms VALUES (?,?,?,?,?,?,?,?)", term_rows)
2738
+ flush_trigrams()
2739
+
2740
+ postings_len = bf.tell() - postings_off
2741
+ total_bytes = bf.tell()
2742
+ header_bytes = struct.pack(
2743
+ BIN_HEADER_FMT,
2744
+ BIN_MAGIC,
2745
+ pair_id,
2746
+ n_notes,
2747
+ n_docs,
2748
+ norm_off,
2749
+ note_norm_off,
2750
+ spans_off,
2751
+ doc_meta_off,
2752
+ headings_off,
2753
+ headings_len,
2754
+ postings_off,
2755
+ postings_len,
2756
+ total_bytes,
2757
+ date_ord_off,
2758
+ )
2759
+ bf.seek(0)
2760
+ bf.write(header_bytes)
2761
+ bf.flush()
2762
+ os.fsync(bf.fileno())
2763
+
2764
+ meta_rows = [
2765
+ ("schema_version", str(SCHEMA_VERSION)),
2766
+ ("pair_id", pair_id.hex()),
2767
+ ("parser_hash", INDEX_CODE_HASH),
2768
+ ("bundle_id", bundle.id),
2769
+ ("bundle_revision", bundle.revision),
2770
+ ("bundle_version", str(bundle.manifest["version"])),
2771
+ (
2772
+ "sources_json",
2773
+ json.dumps([(s.kind, s.label, s.root) for s in bundle.sources], separators=(",", ":")),
2774
+ ),
2775
+ ("n_notes", str(n_notes)),
2776
+ ("n_docs", str(n_docs)),
2777
+ ("n_terms", str(n_sec_terms)),
2778
+ ("n_note_terms", str(n_note_terms)),
2779
+ ("average", repr(average)),
2780
+ ("avg_note", repr(avg_note)),
2781
+ ("min_date_ord", "" if min_date_ord is None else str(min_date_ord)),
2782
+ ("max_date_ord", "" if max_date_ord is None else str(max_date_ord)),
2783
+ ("max_date_str", max_date_str),
2784
+ ("lg_max_name", str(lg_max_name)),
2785
+ ("walked_at", repr(time.time() if walked_at is None else walked_at)),
2786
+ ("has_bundle_graph", "1" if has_bg else "0"),
2787
+ ("n_bundle_graph", str(n_bg)),
2788
+ ]
2789
+ con.executemany("INSERT INTO meta VALUES (?,?)", meta_rows)
2790
+ con.commit()
2791
+ finally:
2792
+ con.close()
2793
+
2794
+ _fsync_file(tmp_sql)
2795
+ with _publish_lock(folder):
2796
+ os.replace(tmp_bin, bin_path)
2797
+ os.replace(tmp_sql, sqlite_path)
2798
+ keep_revs = _live_revisions_for_bundle(bundle.path)
2799
+ _prune_stale_indexes(
2800
+ folder,
2801
+ bundle.path.parent,
2802
+ keep_names=(sqlite_path.name, bin_path.name),
2803
+ keep_rev_tags=keep_revs,
2804
+ current_rev_tag=_rev_tag(bundle.revision),
2805
+ )
2806
+ _fsync_dir(folder)
2807
+ except BaseException:
2808
+ if bin_fd >= 0:
2809
+ os.close(bin_fd)
2810
+ for p in (tmp_bin, tmp_sql):
2811
+ if p is not None:
2812
+ try:
2813
+ os.unlink(p)
2814
+ except OSError:
2815
+ pass
2816
+ raise
2817
+
2818
+
2819
+ # ---- Streaming External-Merge Builder for Large Vaults (>= STREAM_THRESHOLD notes) ----
2820
+
2821
+
2822
+ def _worker_parse_and_tokenize(item):
2823
+ """Run in worker process: read, parse, tokenize, extract LinkGraph labels, discard lines immediately."""
2824
+ from .ingest import Corpus
2825
+ from .verifier import terms as _terms
2826
+
2827
+ source_idx, source, rel, expected_sha = item
2828
+ try:
2829
+ note = Corpus.read(source, rel)
2830
+ except (Refused, FileNotFoundError) as err:
2831
+ return ("err", source_idx, rel, str(err) if isinstance(err, Refused) else None)
2832
+ if expected_sha is not None and note.sha256 != expected_sha:
2833
+ return ("mismatch", source_idx, rel, note.key)
2834
+
2835
+ lines = note.lines
2836
+ line_count = len(lines)
2837
+ fm, _ = frontmatter(lines)
2838
+ raw_labels = [note.title, *note.aliases, *note.tags, *fm.get("entities", []), *fm.get("entity", [])]
2839
+ note_phrases = sorted({" ".join(w) for label in raw_labels if MARK not in label and (w := _words(label))})
2840
+ name_phrases = sorted({" ".join(w) for label in (note.title, *note.aliases) if MARK not in label and (w := _words(label))})
2841
+
2842
+ shared = _terms(f"{note.title} " * 2 + " ".join([*note.aliases, *note.tags]))
2843
+ note_counts = Counter(shared)
2844
+ sec_data = []
2845
+ for begin, heading, end in note.sections:
2846
+ body_terms = _terms(f"{heading} " * 2) + _terms("\n".join(lines[begin:end]))
2847
+ counts = Counter(shared + body_terms)
2848
+ note_counts.update(body_terms)
2849
+ sec_data.append((begin, heading, end, counts.total(), list(counts.items())))
2850
+
2851
+ # Return slim tuple with ZERO note.lines!
2852
+ slim = (
2853
+ note.key,
2854
+ source_idx,
2855
+ note.rel,
2856
+ note.sha256,
2857
+ note.signature,
2858
+ note.title,
2859
+ note.body_start,
2860
+ line_count,
2861
+ note.tags,
2862
+ note.aliases,
2863
+ note.status,
2864
+ note.raw_links,
2865
+ note.raw_newer,
2866
+ note.raw_older,
2867
+ note.date,
2868
+ note_phrases,
2869
+ name_phrases,
2870
+ sec_data,
2871
+ list(note_counts.items()),
2872
+ note_counts.total(),
2873
+ )
2874
+ return ("ok", slim)
2875
+
2876
+
2877
+ def _write_run_file(path, sec_postings, note_postings):
2878
+ """Write a sorted run file: repeated (term_utf8, sec_docs, sec_counts, note_ids, note_counts).
2879
+
2880
+ Includes terms present only in note_postings (e.g. whitespace-only notes with filename/title terms)
2881
+ so their note-level document frequency merges identically to the in-memory builder.
2882
+ """
2883
+ with open(path, "wb") as f:
2884
+ for term in sorted(sec_postings.keys() | note_postings.keys()):
2885
+ tb = term.encode("utf-8")
2886
+ sp_entry = sec_postings.get(term)
2887
+ if sp_entry is not None:
2888
+ sd, sc = sp_entry
2889
+ df = len(sd)
2890
+ else:
2891
+ sd = sc = None
2892
+ df = 0
2893
+ np_entry = note_postings.get(term)
2894
+ if np_entry is not None:
2895
+ nd, nc = np_entry
2896
+ ndf = len(nd)
2897
+ else:
2898
+ nd = nc = None
2899
+ ndf = 0
2900
+ f.write(struct.pack("<III", len(tb), df, ndf))
2901
+ f.write(tb)
2902
+ if df:
2903
+ f.write(sd.tobytes())
2904
+ f.write(sc.tobytes())
2905
+ if ndf:
2906
+ f.write(nd.tobytes())
2907
+ f.write(nc.tobytes())
2908
+
2909
+
2910
+ def _iter_run_file(path):
2911
+ """Stream (term, df, sd_bytes, sc_bytes, ndf, nd_bytes, nc_bytes) from a sorted run file."""
2912
+ with open(path, "rb") as f:
2913
+ hdr_read = f.read
2914
+ while True:
2915
+ hdr = hdr_read(12)
2916
+ if not hdr:
2917
+ break
2918
+ tlen, df, ndf = struct.unpack("<III", hdr)
2919
+ term = hdr_read(tlen).decode("utf-8")
2920
+ sd = hdr_read(4 * df) if df else b""
2921
+ sc = hdr_read(4 * df) if df else b""
2922
+ nd = hdr_read(4 * ndf) if ndf else b""
2923
+ nc = hdr_read(4 * ndf) if ndf else b""
2924
+ yield term, df, sd, sc, ndf, nd, nc
2925
+
2926
+
2927
+ def _link_slim_notes(slim_meta):
2928
+ """Resolve wikilinks/path links/supersessions over slim note metadata (exact parity with Corpus._link)."""
2929
+ local = defaultdict(set)
2930
+ everywhere = defaultdict(set)
2931
+ by_key = {}
2932
+ for entry in slim_meta:
2933
+ key, source_label, rel, title, aliases = entry["key"], entry["source_label"], entry["rel"], entry["title"], entry["aliases"]
2934
+ by_key[key] = entry
2935
+ path = posixpath.splitext(rel)[0]
2936
+ names = {path, posixpath.basename(path), _NOTION_ID.sub("", posixpath.basename(path)), title, *aliases}
2937
+ for name in names:
2938
+ low = name.lower()
2939
+ local[(source_label, low)].add(key)
2940
+ everywhere[low].add(key)
2941
+ entry["links"] = []
2942
+ entry["backlinks"] = []
2943
+ entry["superseded_by"] = []
2944
+ entry["dangling"] = 0
2945
+
2946
+ def resolve(entry, target):
2947
+ kind, value = target
2948
+ if kind == "path":
2949
+ value = posixpath.normpath(posixpath.join(posixpath.dirname(entry["rel"]), value.partition("#")[0]))
2950
+ key = f"{entry['source_label']}/{value}"
2951
+ return key if key in by_key else None
2952
+ name = value.lower().removesuffix(".md")
2953
+ found = local[(entry["source_label"], name)]
2954
+ if not found and len(everywhere[name]) == 1:
2955
+ found = everywhere[name]
2956
+ here = posixpath.dirname(entry["key"])
2957
+ return min(found, key=lambda k: (posixpath.dirname(k) != here, k.count("/"), k), default=None)
2958
+
2959
+ for entry in slim_meta:
2960
+ found = [resolve(entry, t) for t in entry["raw_links"]]
2961
+ entry["links"] = sorted({k for k in found if k and k != entry["key"]})
2962
+ entry["dangling"] = found.count(None)
2963
+ for entry in slim_meta:
2964
+ key = entry["key"]
2965
+ for dst in entry["links"]:
2966
+ by_key[dst]["backlinks"].append(key)
2967
+ for dst in filter(None, (resolve(entry, t) for t in entry["raw_newer"])):
2968
+ if dst != key:
2969
+ entry["superseded_by"].append(dst)
2970
+ for dst in filter(None, (resolve(entry, t) for t in entry["raw_older"])):
2971
+ if dst != key:
2972
+ by_key[dst]["superseded_by"].append(key)
2973
+ for entry in slim_meta:
2974
+ entry["superseded_by"] = sorted(set(entry["superseded_by"]))
2975
+
2976
+
2977
+ def _streaming_build_worker(args):
2978
+ """Execute full streaming external-merge index build in a dedicated child process."""
2979
+ from .ingest import SUFFIXES
2980
+ from .verifier import NOTE_BLEND, _parse_iso_date
2981
+
2982
+ (
2983
+ sqlite_path,
2984
+ bin_path,
2985
+ bundle_id,
2986
+ bundle_rev,
2987
+ bundle_ver,
2988
+ sources_tuples,
2989
+ graph_path_str,
2990
+ expected_graph_sha,
2991
+ pinned_mode,
2992
+ run_flush_notes,
2993
+ gone_items,
2994
+ ) = args
2995
+ sqlite_path, bin_path = Path(sqlite_path), Path(bin_path)
2996
+ folder = sqlite_path.parent
2997
+ _ensure_owner_dir(folder)
2998
+ sources = [Source(*st) for st in sources_tuples]
2999
+ graph_path = Path(graph_path_str) if graph_path_str else None
3000
+
3001
+ # Verify graph.json bytes against manifest digest before using for signed pinning (fail-closed)
3002
+ pinned_shas = None
3003
+ if pinned_mode:
3004
+ if graph_path is None or expected_graph_sha is None:
3005
+ raise ValueError("signed streaming build requires verified graph.json digest")
3006
+ raw_g = _read_verified_graph(graph_path, expected_graph_sha, required=True)
3007
+ pinned_shas = {k: v["sha256"] for k, v in raw_g.items()}
3008
+ del raw_g
3009
+
3010
+ # Stage 1: Walk candidates
3011
+ walked_at = time.time()
3012
+ todo = []
3013
+ skipped = Counter()
3014
+ for s_idx, source in enumerate(sources):
3015
+ for rel in _candidates(source):
3016
+ key = f"{source.label}/{rel}"
3017
+ if pinned_shas is not None and key not in pinned_shas:
3018
+ continue
3019
+ if not rel.lower().endswith(SUFFIXES):
3020
+ continue
3021
+ try:
3022
+ check_rel(rel)
3023
+ os.lstat(os.path.join(source.root, rel))
3024
+ except Refused as reason:
3025
+ skipped[str(reason)] += 1
3026
+ continue
3027
+ except FileNotFoundError:
3028
+ continue
3029
+ todo.append((s_idx, source, rel, pinned_shas[key] if pinned_shas is not None else None))
3030
+ # Exact pre-PR _candidates() walk order matching build_disk_index_in_memory for identical tie-breaking
3031
+ todo.sort(key=lambda item: (item[0], _canonical_rel_key(item[1].kind, item[2])))
3032
+
3033
+ # Stage 2: Parallel parse + tokenize in chunks, flushing sorted posting runs to a private temp dir
3034
+ pair_id = os.urandom(16)
3035
+ run_dir = Path(tempfile.mkdtemp(prefix=".runs-", dir=folder))
3036
+ os.chmod(run_dir, 0o700)
3037
+ bin_fd = -1
3038
+ tmp_bin = tmp_sql = None
3039
+
3040
+ try:
3041
+ spans = array("I")
3042
+ doc_meta = array("I")
3043
+ doc_sizes = array("I")
3044
+ owners = array("I")
3045
+ note_sizes = array("I")
3046
+ headings_path = run_dir / "headings.raw"
3047
+ headings_len = 0
3048
+
3049
+ slim_meta = []
3050
+ lg_names = defaultdict(list)
3051
+ lg_members = defaultdict(list)
3052
+ lg_labels_rows = []
3053
+ lg_max_name = 0
3054
+ dated_ords = []
3055
+ note_date_ords = array("I")
3056
+
3057
+ sec_buf = defaultdict(lambda: (array("I"), array("I")))
3058
+ note_buf = defaultdict(lambda: (array("I"), array("I")))
3059
+ run_paths = []
3060
+ buffered_notes = 0
3061
+
3062
+ def flush_run():
3063
+ nonlocal buffered_notes
3064
+ if not sec_buf and not note_buf:
3065
+ return
3066
+ rp = run_dir / f"run-{len(run_paths):04d}.bin"
3067
+ _write_run_file(rp, sec_buf, note_buf)
3068
+ run_paths.append(rp)
3069
+ sec_buf.clear()
3070
+ note_buf.clear()
3071
+ buffered_notes = 0
3072
+
3073
+ workers = min(os.cpu_count() or 1, 16)
3074
+ with open(headings_path, "wb") as hf:
3075
+ with ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("forkserver")) as pool:
3076
+ batch_sz = 2048
3077
+ for bstart in range(0, len(todo), batch_sz):
3078
+ batch = todo[bstart : bstart + batch_sz]
3079
+ chunksize = max(1, len(batch) // (workers * 4))
3080
+ for result in pool.map(_worker_parse_and_tokenize, batch, chunksize=chunksize):
3081
+ if result[0] != "ok":
3082
+ if result[0] == "err" and result[3]:
3083
+ skipped[result[3]] += 1
3084
+ continue
3085
+ (
3086
+ key,
3087
+ s_idx,
3088
+ rel,
3089
+ sha256,
3090
+ sig,
3091
+ title,
3092
+ body_start,
3093
+ line_count,
3094
+ tags,
3095
+ aliases,
3096
+ status,
3097
+ raw_links,
3098
+ raw_newer,
3099
+ raw_older,
3100
+ date_str,
3101
+ note_phrases,
3102
+ name_phrases,
3103
+ sec_data,
3104
+ note_items,
3105
+ note_total,
3106
+ ) = result[1]
3107
+ note_id = len(slim_meta)
3108
+ spans.append(len(doc_sizes))
3109
+
3110
+ for p in note_phrases:
3111
+ lg_members[p].append(note_id)
3112
+ wc = p.count(" ") + 1
3113
+ if wc > lg_max_name:
3114
+ lg_max_name = wc
3115
+ for p in name_phrases:
3116
+ lg_names[p].append(note_id)
3117
+ if note_phrases:
3118
+ lg_labels_rows.append((note_id, _compress_blob("\n".join(note_phrases).encode("utf-8"))))
3119
+
3120
+ for begin, heading, end, sec_total, sec_items in sec_data:
3121
+ doc_id = len(doc_sizes)
3122
+ for term, count in sec_items:
3123
+ d_arr, c_arr = sec_buf[term]
3124
+ d_arr.append(doc_id)
3125
+ c_arr.append(count)
3126
+ hb = heading.encode("utf-8")
3127
+ h_off = headings_len
3128
+ hf.write(hb)
3129
+ headings_len += len(hb)
3130
+ doc_meta.extend((note_id, begin, end, sec_total, h_off, len(hb)))
3131
+ doc_sizes.append(sec_total)
3132
+ owners.append(note_id)
3133
+
3134
+ for term, count in note_items:
3135
+ n_arr, nc_arr = note_buf[term]
3136
+ n_arr.append(note_id)
3137
+ nc_arr.append(count)
3138
+ note_sizes.append(note_total)
3139
+
3140
+ d_ord = 0
3141
+ if date_str:
3142
+ pd = _parse_iso_date(date_str)
3143
+ if pd is not None:
3144
+ d_ord = pd.toordinal()
3145
+ dated_ords.append(d_ord)
3146
+ note_date_ords.append(d_ord)
3147
+
3148
+ slim_meta.append(
3149
+ {
3150
+ "note_id": note_id,
3151
+ "key": key,
3152
+ "source_idx": s_idx,
3153
+ "source_label": sources[s_idx].label,
3154
+ "rel": rel,
3155
+ "sha256": sha256,
3156
+ "sig": sig,
3157
+ "title": title,
3158
+ "body_start": body_start,
3159
+ "line_count": line_count,
3160
+ "tags": tags,
3161
+ "aliases": aliases,
3162
+ "status": status,
3163
+ "raw_links": raw_links,
3164
+ "raw_newer": raw_newer,
3165
+ "raw_older": raw_older,
3166
+ "date": date_str,
3167
+ }
3168
+ )
3169
+ buffered_notes += 1
3170
+ if buffered_notes >= run_flush_notes:
3171
+ flush_run()
3172
+ flush_run()
3173
+ del todo
3174
+
3175
+ # Stage 3: Link resolution over slim metadata
3176
+ _link_slim_notes(slim_meta)
3177
+
3178
+ spans.append(len(doc_sizes))
3179
+ n_notes = len(slim_meta)
3180
+ n_docs = len(doc_sizes)
3181
+ average = sum(doc_sizes) / (n_docs or 1) or 1.0
3182
+ norm = array("d", (1.2 * (0.25 + 0.75 * (sz / average)) for sz in doc_sizes))
3183
+ avg_note = sum(note_sizes) / (n_notes or 1) or 1.0
3184
+ note_norm = array("d", (1.2 * (0.25 + 0.75 * (sz / avg_note)) for sz in note_sizes))
3185
+ min_date_ord = min(dated_ords) if dated_ords else None
3186
+ max_date_ord = max(dated_ords) if dated_ords else None
3187
+ max_date_str = datetime.date.fromordinal(max_date_ord).isoformat() if max_date_ord else ""
3188
+ del doc_sizes, note_sizes, dated_ords
3189
+
3190
+ # Stage 4: Write SQLite + merged .bin atomically
3191
+ bin_fd, tmp_bin = _create_private_temp(folder, f".{bin_path.name}.")
3192
+ sql_fd, tmp_sql = _create_private_temp(folder, f".{sqlite_path.name}.")
3193
+ os.close(sql_fd)
3194
+
3195
+ con = sqlite3.connect(str(tmp_sql))
3196
+ try:
3197
+ _create_schema(con)
3198
+
3199
+ # Insert notes in chunks & immediately free slim_meta
3200
+ note_rows = []
3201
+ for e in slim_meta:
3202
+ sig = e["sig"] or (0, 0, 0, 0)
3203
+ meta_blob = _compress_blob(
3204
+ json.dumps(
3205
+ [
3206
+ e["tags"],
3207
+ e["aliases"],
3208
+ e["links"],
3209
+ e["backlinks"],
3210
+ e["superseded_by"],
3211
+ e["raw_links"],
3212
+ e["raw_newer"],
3213
+ e["raw_older"],
3214
+ ],
3215
+ separators=(",", ":"),
3216
+ ensure_ascii=False,
3217
+ ).encode("utf-8")
3218
+ )
3219
+ note_rows.append(
3220
+ (
3221
+ e["note_id"],
3222
+ e["key"],
3223
+ e["source_idx"],
3224
+ e["rel"],
3225
+ e["sha256"],
3226
+ sig[0],
3227
+ sig[1],
3228
+ sig[2],
3229
+ sig[3],
3230
+ e["title"],
3231
+ e["body_start"],
3232
+ e["line_count"],
3233
+ e["status"],
3234
+ e["date"],
3235
+ e["dangling"],
3236
+ meta_blob,
3237
+ )
3238
+ )
3239
+ if len(note_rows) >= 4096:
3240
+ con.executemany("INSERT INTO notes VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", note_rows)
3241
+ note_rows.clear()
3242
+ if note_rows:
3243
+ con.executemany("INSERT INTO notes VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", note_rows)
3244
+ note_rows.clear()
3245
+ del slim_meta
3246
+
3247
+ con.executemany(
3248
+ "INSERT INTO lg_names VALUES (?,?)",
3249
+ ((p, array("I", ids).tobytes()) for p, ids in lg_names.items()),
3250
+ )
3251
+ lg_names.clear()
3252
+ con.executemany(
3253
+ "INSERT INTO lg_members VALUES (?,?)",
3254
+ ((p, array("I", ids).tobytes()) for p, ids in lg_members.items()),
3255
+ )
3256
+ lg_members.clear()
3257
+ if lg_labels_rows:
3258
+ con.executemany("INSERT INTO lg_labels VALUES (?,?)", lg_labels_rows)
3259
+ lg_labels_rows.clear()
3260
+
3261
+ if gone_items:
3262
+ live_keys = set(k for (k,) in con.execute("SELECT key FROM notes").fetchall())
3263
+ gone_rows = []
3264
+ for k, path, sig in gone_items:
3265
+ if k not in live_keys:
3266
+ gone_rows.append((k, path, *(sig if sig is not None else (None, None, None, None))))
3267
+ if gone_rows:
3268
+ con.executemany("INSERT INTO gone VALUES (?,?,?,?,?,?)", gone_rows)
3269
+
3270
+ has_bg, n_bg = _populate_bundle_graph(con, graph_path, expected_graph_sha)
3271
+
3272
+ # Write .bin fixed sections + K-way merged postings
3273
+ with os.fdopen(bin_fd, "wb") as bf:
3274
+ bin_fd = -1
3275
+ bf.write(b"\x00" * BIN_HEADER_SIZE)
3276
+
3277
+ def pad8():
3278
+ pos = bf.tell()
3279
+ rem = (-pos) & 7
3280
+ if rem:
3281
+ bf.write(b"\x00" * rem)
3282
+ return bf.tell()
3283
+
3284
+ norm_off = pad8()
3285
+ bf.write(norm.tobytes())
3286
+ note_norm_off = pad8()
3287
+ bf.write(note_norm.tobytes())
3288
+ spans_off = pad8()
3289
+ bf.write(spans.tobytes())
3290
+ del spans
3291
+ date_ord_off = pad8()
3292
+ bf.write(note_date_ords.tobytes())
3293
+ del note_date_ords
3294
+ doc_meta_off = pad8()
3295
+ bf.write(doc_meta.tobytes())
3296
+ del doc_meta
3297
+ headings_off = pad8()
3298
+ with open(headings_path, "rb") as hf:
3299
+ shutil.copyfileobj(hf, bf, 1 << 20)
3300
+ postings_off = pad8()
3301
+
3302
+ # K-way merge over sorted run files in alphabetical term order
3303
+ iters = [_iter_run_file(rp) for rp in run_paths]
3304
+ heap = []
3305
+ for r_idx, it in enumerate(iters):
3306
+ first = next(it, None)
3307
+ if first is not None:
3308
+ heapq.heappush(heap, (first[0], r_idx, first))
3309
+
3310
+ term_rows = []
3311
+ n_terms = 0
3312
+ n_note_terms = 0
3313
+ cur_char = None
3314
+ tri_buckets = defaultdict(list)
3315
+
3316
+ def flush_trigrams():
3317
+ if not tri_buckets:
3318
+ return
3319
+ con.executemany(
3320
+ "INSERT INTO trigrams VALUES (?,?,?,?)",
3321
+ (
3322
+ (fc, tl, tri, _compress_blob("\n".join(words_list).encode("utf-8")))
3323
+ for (fc, tl, tri), words_list in tri_buckets.items()
3324
+ ),
3325
+ )
3326
+ tri_buckets.clear()
3327
+
3328
+ while heap:
3329
+ term = heap[0][0]
3330
+ sd_parts = []
3331
+ sc_parts = []
3332
+ nd_parts = []
3333
+ nc_parts = []
3334
+ df = 0
3335
+ ndf = 0
3336
+ while heap and heap[0][0] == term:
3337
+ _, r_idx, (_, r_df, sd_b, sc_b, r_ndf, nd_b, nc_b) = heapq.heappop(heap)
3338
+ if r_df:
3339
+ sd_parts.append(sd_b)
3340
+ sc_parts.append(sc_b)
3341
+ df += r_df
3342
+ if r_ndf:
3343
+ nd_parts.append(nd_b)
3344
+ nc_parts.append(nc_b)
3345
+ ndf += r_ndf
3346
+ nxt = next(iters[r_idx], None)
3347
+ if nxt is not None:
3348
+ heapq.heappush(heap, (nxt[0], r_idx, nxt))
3349
+
3350
+ if df == 0 and ndf == 0:
3351
+ continue
3352
+
3353
+ if df:
3354
+ sd_all = b"".join(sd_parts) if len(sd_parts) > 1 else sd_parts[0]
3355
+ sc_all = b"".join(sc_parts) if len(sc_parts) > 1 else sc_parts[0]
3356
+ sec_rel = bf.tell() - postings_off
3357
+ bf.write(sd_all)
3358
+ bf.write(sc_all)
3359
+ else:
3360
+ sd_all = sc_all = b""
3361
+ sec_rel = 0
3362
+
3363
+ if ndf:
3364
+ nd_all = b"".join(nd_parts) if len(nd_parts) > 1 else nd_parts[0]
3365
+ nc_all = b"".join(nc_parts) if len(nc_parts) > 1 else nc_parts[0]
3366
+ note_rel = bf.tell() - postings_off
3367
+ bf.write(nd_all)
3368
+ bf.write(nc_all)
3369
+ n_note_terms += 1
3370
+ n_arr = array("I")
3371
+ n_arr.frombytes(nd_all)
3372
+ nc_arr = array("I")
3373
+ nc_arr.frombytes(nc_all)
3374
+ else:
3375
+ note_rel = 0
3376
+ n_arr = nc_arr = None
3377
+
3378
+ if df:
3379
+ d_arr = array("I")
3380
+ d_arr.frombytes(sd_all)
3381
+ c_arr = array("I")
3382
+ c_arr.frombytes(sc_all)
3383
+ idf_val = math.log(1 + (n_docs - df + 0.5) / (df + 0.5))
3384
+ note_idf_val = math.log(1 + (n_notes - ndf + 0.5) / (ndf + 0.5))
3385
+ c_nums, c_shares, ceil_max = _compute_ceiling_arrays(
3386
+ d_arr, c_arr, owners, norm, n_arr, nc_arr, note_norm, idf_val, note_idf_val, NOTE_BLEND
3387
+ )
3388
+ ceil_cnt = len(c_nums)
3389
+ ceil_rel = pad8() - postings_off
3390
+ bf.write(c_shares.tobytes())
3391
+ bf.write(c_nums.tobytes())
3392
+ n_terms += 1
3393
+ else:
3394
+ ceil_cnt = 0
3395
+ ceil_rel = 0
3396
+ ceil_max = 0.0
3397
+
3398
+ term_rows.append(
3399
+ (term, df, sec_rel, ndf, note_rel, ceil_cnt, ceil_rel, ceil_max)
3400
+ )
3401
+ if len(term_rows) >= 10000:
3402
+ con.executemany("INSERT INTO terms VALUES (?,?,?,?,?,?,?,?)", term_rows)
3403
+ term_rows.clear()
3404
+
3405
+ if df and len(term) >= 5 and term.isalpha():
3406
+ fc = term[0]
3407
+ if cur_char is not None and fc != cur_char:
3408
+ flush_trigrams()
3409
+ cur_char = fc
3410
+ tl = len(term)
3411
+ for i in range(tl - 2):
3412
+ tri_buckets[(fc, tl, term[i : i + 3])].append(term)
3413
+
3414
+ if term_rows:
3415
+ con.executemany("INSERT INTO terms VALUES (?,?,?,?,?,?,?,?)", term_rows)
3416
+ flush_trigrams()
3417
+
3418
+ postings_len = bf.tell() - postings_off
3419
+ total_bytes = bf.tell()
3420
+ header_bytes = struct.pack(
3421
+ BIN_HEADER_FMT,
3422
+ BIN_MAGIC,
3423
+ pair_id,
3424
+ n_notes,
3425
+ n_docs,
3426
+ norm_off,
3427
+ note_norm_off,
3428
+ spans_off,
3429
+ doc_meta_off,
3430
+ headings_off,
3431
+ headings_len,
3432
+ postings_off,
3433
+ postings_len,
3434
+ total_bytes,
3435
+ date_ord_off,
3436
+ )
3437
+ bf.seek(0)
3438
+ bf.write(header_bytes)
3439
+ bf.flush()
3440
+ os.fsync(bf.fileno())
3441
+
3442
+ meta_rows = [
3443
+ ("schema_version", str(SCHEMA_VERSION)),
3444
+ ("pair_id", pair_id.hex()),
3445
+ ("parser_hash", INDEX_CODE_HASH),
3446
+ ("bundle_id", bundle_id),
3447
+ ("bundle_revision", bundle_rev),
3448
+ ("bundle_version", str(bundle_ver)),
3449
+ ("sources_json", json.dumps(list(sources_tuples), separators=(",", ":"))),
3450
+ ("n_notes", str(n_notes)),
3451
+ ("n_docs", str(n_docs)),
3452
+ ("n_terms", str(n_terms)),
3453
+ ("n_note_terms", str(n_note_terms)),
3454
+ ("average", repr(average)),
3455
+ ("avg_note", repr(avg_note)),
3456
+ ("min_date_ord", "" if min_date_ord is None else str(min_date_ord)),
3457
+ ("max_date_ord", "" if max_date_ord is None else str(max_date_ord)),
3458
+ ("max_date_str", max_date_str),
3459
+ ("lg_max_name", str(lg_max_name)),
3460
+ ("walked_at", repr(walked_at)),
3461
+ ("has_bundle_graph", "1" if has_bg else "0"),
3462
+ ("n_bundle_graph", str(n_bg)),
3463
+ ]
3464
+ con.executemany("INSERT INTO meta VALUES (?,?)", meta_rows)
3465
+ con.commit()
3466
+ finally:
3467
+ con.close()
3468
+
3469
+ _fsync_file(tmp_sql)
3470
+ with _publish_lock(folder):
3471
+ os.replace(tmp_bin, bin_path)
3472
+ os.replace(tmp_sql, sqlite_path)
3473
+ keep_revs = _live_revisions_for_bundle(graph_path.parent) if graph_path is not None else None
3474
+ if graph_path is not None:
3475
+ _prune_stale_indexes(
3476
+ folder,
3477
+ graph_path.parent.parent,
3478
+ keep_names=(sqlite_path.name, bin_path.name),
3479
+ keep_rev_tags=keep_revs,
3480
+ current_rev_tag=_rev_tag(bundle_rev),
3481
+ )
3482
+ _fsync_dir(folder)
3483
+ return dict(skipped)
3484
+ except BaseException:
3485
+ if bin_fd >= 0:
3486
+ os.close(bin_fd)
3487
+ for p in (tmp_bin, tmp_sql):
3488
+ if p is not None:
3489
+ try:
3490
+ os.unlink(p)
3491
+ except OSError:
3492
+ pass
3493
+ raise
3494
+ finally:
3495
+ shutil.rmtree(run_dir, ignore_errors=True)
3496
+
3497
+
3498
+ def _streaming_process_entry(args, conn):
3499
+ try:
3500
+ res = _streaming_build_worker(args)
3501
+ conn.send(("ok", res))
3502
+ except BaseException as exc:
3503
+ kind = "other"
3504
+ if isinstance(exc, sqlite3.Error):
3505
+ kind = "sqlite"
3506
+ elif isinstance(exc, Refused):
3507
+ kind = "refused"
3508
+ elif isinstance(exc, OSError) and not isinstance(exc, FileNotFoundError):
3509
+ kind = "os"
3510
+ conn.send(("err", (kind, type(exc).__name__, getattr(exc, "errno", None), str(exc))))
3511
+ finally:
3512
+ conn.close()
3513
+
3514
+
3515
+ def build_disk_index_streaming(sqlite_path, bin_path, bundle, *, run_flush_notes=RUN_FLUSH_NOTES, gone=None):
3516
+ """Build (sqlite_path, bin_path) in an isolated non-daemon child process so the parent daemon keeps zero build RSS."""
3517
+ gone_items = [(k, path, sig) for k, (path, sig) in (gone or {}).items()]
3518
+ args = (
3519
+ str(sqlite_path),
3520
+ str(bin_path),
3521
+ bundle.id,
3522
+ bundle.revision,
3523
+ bundle.manifest["version"],
3524
+ [(s.kind, s.label, s.root) for s in bundle.sources],
3525
+ str(bundle.path / "graph.json"),
3526
+ bundle.manifest.get("files", {}).get("graph.json"),
3527
+ bundle.manifest["version"] == 2,
3528
+ int(run_flush_notes),
3529
+ gone_items,
3530
+ )
3531
+ ctx = multiprocessing.get_context("forkserver")
3532
+ parent_conn, child_conn = ctx.Pipe(duplex=False)
3533
+ proc = ctx.Process(target=_streaming_process_entry, args=(args, child_conn), daemon=False)
3534
+ proc.start()
3535
+ child_conn.close()
3536
+ try:
3537
+ status, payload = parent_conn.recv()
3538
+ except EOFError:
3539
+ proc.join()
3540
+ raise RuntimeError(f"disk index builder exited unexpectedly (code {proc.exitcode})") from None
3541
+ finally:
3542
+ parent_conn.close()
3543
+ proc.join()
3544
+ if status != "ok":
3545
+ kind, cls_name, err_no, msg = payload
3546
+ if kind == "sqlite":
3547
+ raise sqlite3.OperationalError(f"{cls_name}: {msg}")
3548
+ if kind == "refused":
3549
+ raise Refused(msg)
3550
+ if kind == "os":
3551
+ raise OSError(err_no, msg)
3552
+ raise RuntimeError(f"disk index build failed: {cls_name}: {msg}")
3553
+ return payload