Repository navigation
Expand file tree
/
Copy pathvector_store.py
More file actions
2963 lines (2779 loc) · 122 KB
/
Copy pathvector_store.py
File metadata and controls
2963 lines (2779 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""SQLite-backed storage and brute-force KNN for summary embeddings.
This module is intentionally not wired into the LCM engine yet. It owns only
the durable embedding schema operations and the dependency-optional compute
ladder used by later semantic retrieval work.
"""
from __future__ import annotations
import copy
import hashlib
import logging
import math
import sqlite3
import struct
import threading
import time
import uuid
from collections import OrderedDict
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Any, Iterator, Optional, Sequence
from .config import LCMConfig
from .db_bootstrap import (
configure_connection,
ensure_chunk_tables,
ensure_embedding_tables,
mark_migration_step_complete,
refuse_schema_version_too_new,
run_versioned_migrations,
verify_chunk_schema,
verify_embedding_schema,
)
from .sqlite_util import _is_sqlite_locked_error
logger = logging.getLogger(__name__)
_monotonic = time.monotonic
def _prescreen_deadline_expired(deadline: float | None, scanned_rows: int) -> bool:
"""Deadline check for the binary-prescreen loop, position-aware.
``scanned_rows`` is how many rows have completed when the check runs (the
batch's ``start`` before scoring, its ``end`` after). Tests patch THIS
seam keyed on position — not the process clock, call counts, or frame
inspection — so a loop refactor cannot silently disable the covered
branch.
"""
del scanned_rows
return deadline is not None and _monotonic() >= deadline
# Vectors are float32 in native little-endian order by default. These are
# recorded as part of the canonical profile identity so a dtype/byteorder change
# is detectable rather than silently reinterpreting stored bytes.
_VECTOR_DTYPE = "float32"
_VECTOR_BYTEORDER = "little"
# Opt-in int8 storage dtype (SPEC C1): vectors are stored per-vector
# symmetrically quantized — ``dim`` signed int8 values followed by a little-endian
# float32 scale in the SAME ``vec`` BLOB (total ``dim + 4`` bytes) — and a
# sign-bit prescreen is written to the companion binary table. dtype is part of
# the profile identity hash, so int8 vectors never mix with float32 ones (a
# float32 reader's ``len(blob) == dim*4`` guard also rejects an int8 blob).
_INT8_DTYPE = "int8"
_SUPPORTED_DTYPES = frozenset({_VECTOR_DTYPE, _INT8_DTYPE})
# int8 symmetric quantization uses the full signed range except -128 (kept out so
# the range is symmetric and dequantization has no bias toward negatives).
_INT8_MAX = 127
# Per-byte set-bit counts for the binary Hamming prescreen (built once; converted
# to a NumPy lookup array at query time). Indexing a uint8 XOR result into this
# table and summing rows is the popcount without a per-element Python loop.
_POPCOUNT_TABLE = tuple(bin(value).count("1") for value in range(256))
# Revision tag that folds the float32 sign-bit prescreen opt-in
# (LCM_EMBEDDING_BINARY_PRESCREEN) into the profile identity. A prescreen corpus
# grows a companion sign-bit table that drives the two-stage KNN, so it MUST be a
# distinct identity from a legacy binary-free float32 corpus — otherwise flipping
# the flag on a populated identity leaves a mixed corpus the two-stage INNER JOIN
# silently truncates. See VectorStore._prescreen_revision / FIX 1.
_BINARY_PRESCREEN_REVISION_TAG = "binprescreen"
_DEFAULT_TASK = "summary"
_CHUNK_TASK = "chunk"
# Tasks this store can encode. Summary and chunk corpora coexist in the shared
# profile table, each keyed by its own canonical identity (task is part of the
# identity hash), so their vectors never collide.
_SUPPORTED_TASKS = frozenset({_DEFAULT_TASK, _CHUNK_TASK})
# Candidate-enumeration sentinel: SQLite reads a negative LIMIT as "no limit",
# so a full-corpus scan enumerates every live candidate for the identity.
_SCAN_ALL_ROWS = -1
# SQLite caps host parameters per statement (SQLITE_MAX_VARIABLE_NUMBER); a
# single ``WHERE id IN (?, ?, ...)`` over tens of thousands of ids overflows it
# (observed failure at ~33k ids). Candidate id resolution loads ids into a temp
# table in bounded chunks and JOINs instead, so it scales past that limit.
_ID_INSERT_CHUNK = 500
_SOURCE_LINEAGE_WORK_LIMIT = 4096
class _UnverifiableProvenance(RuntimeError):
"""A requested provenance filter could not be checked completely."""
class _PrescreenDeadlineExpired(TimeoutError):
def __init__(self, scanned: int = 0) -> None:
super().__init__("binary prescreen deadline expired")
self.scanned = max(0, int(scanned))
def _require_supported_identity(identity: "EmbeddingIdentity") -> None:
"""Reject profile representations this implementation cannot encode."""
unsupported = []
if identity.dtype not in _SUPPORTED_DTYPES:
unsupported.append(f"dtype={identity.dtype!r}")
if identity.byteorder != _VECTOR_BYTEORDER:
unsupported.append(f"byteorder={identity.byteorder!r}")
if identity.task not in _SUPPORTED_TASKS:
unsupported.append(f"task={identity.task!r}")
if unsupported:
raise ValueError(
"unsupported embedding representation: "
+ ", ".join(unsupported)
+ "; supported representation is float32|int8/little/summary|chunk"
)
@dataclass(frozen=True)
class EmbeddingIdentity:
"""Immutable canonical identity captured before provider execution."""
provider: str
model_name: str
revision: str
dim: int
dtype: str
byteorder: str
task: str
@classmethod
def canonical(
cls,
provider: str,
model_name: str,
revision: str,
dim: int,
dtype: str,
byteorder: str,
task: str,
) -> "EmbeddingIdentity":
return cls(
provider=str(provider).strip().lower(),
model_name=str(model_name).strip(),
revision=str(revision).strip(),
dim=int(dim),
dtype=str(dtype).strip().lower(),
byteorder=str(byteorder).strip().lower(),
task=str(task).strip().lower(),
)
@property
def identity_hash(self) -> str:
canonical = "\x1f".join(
[
self.provider,
self.model_name,
self.revision,
str(self.dim),
self.dtype,
self.byteorder,
self.task,
]
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _identity_hash(
provider: str,
model_name: str,
revision: str,
dim: int,
dtype: str,
byteorder: str,
task: str,
) -> str:
"""Return the stable canonical-identity hash for an embedding profile."""
identity = EmbeddingIdentity.canonical(
provider, model_name, revision, dim, dtype, byteorder, task
)
return identity.identity_hash
def _load_numpy():
"""Import NumPy lazily. Kept isolated so fallback behavior is testable."""
import numpy
return numpy
def _encode_int8_vector(normalized: Sequence[float]) -> bytes:
"""Symmetrically quantize a normalized vector to int8 + a float32 scale.
Layout is ``dim`` signed bytes followed by a little-endian float32 scale, so
dequantization is ``value_i = q_i * scale``. The scale is the per-vector max
magnitude divided by 127; a degenerate all-zero vector (never produced by the
non-zero-magnitude normalizer, but handled defensively) uses scale 0.
"""
dim = len(normalized)
amax = max((abs(float(value)) for value in normalized), default=0.0)
scale = amax / _INT8_MAX if amax > 0.0 else 0.0
if scale > 0.0:
quantized = [
max(-_INT8_MAX, min(_INT8_MAX, int(round(float(value) / scale))))
for value in normalized
]
else:
quantized = [0] * dim
return struct.pack(f"<{dim}b", *quantized) + struct.pack("<f", scale)
def _decode_int8_vector(blob: bytes, dim: int) -> tuple[float, ...] | None:
"""Dequantize an int8 ``vec`` BLOB (``dim`` bytes + float32 scale) to floats."""
if len(blob) != dim + 4:
return None
try:
quantized = struct.unpack(f"<{dim}b", blob[:dim])
(scale,) = struct.unpack("<f", blob[dim:dim + 4])
except struct.error:
return None
return tuple(value * scale for value in quantized)
def _pack_sign_bits(normalized: Sequence[float]) -> bytes:
"""Pack the sign bits of a vector MSB-first, ``ceil(dim/8)`` bytes.
Bit ``i`` is 1 when ``value_i >= 0``. Matches ``numpy.packbits`` (MSB-first),
so the query side can XOR-and-popcount against these bytes for a Hamming
prescreen without re-deriving the bit order.
"""
out = bytearray((len(normalized) + 7) // 8)
for index, value in enumerate(normalized):
if float(value) >= 0.0:
out[index >> 3] |= 0x80 >> (index & 7)
return bytes(out)
class KNNResult(list[tuple[str, float, str]]):
"""Ranked KNN rows with result-level vector coverage metadata."""
def __init__(
self,
rows: Sequence[tuple[str, float, str]] = (),
*,
coverage: str,
reason: str | None = None,
scanned: int | None = None,
total: int | None = None,
) -> None:
super().__init__(rows)
self.coverage = coverage
self.reason = reason
# Bounded-coverage provenance: how many of the corpus's live vectors were
# actually scored (``scanned``) out of the total live for the identity
# (``total``), so a caller can surface partial-archive coverage (SCAN-1).
self.scanned = scanned
self.total = total
class EmbeddingPublishOutcome(str, Enum):
"""Typed result for the post-provider publication CAS."""
PUBLISHED = "published"
OWNERSHIP_LOST = "ownership_lost"
IDENTITY_SUPERSEDED = "identity_superseded"
@dataclass(frozen=True)
class BatchPublishResult:
"""Per-row result from a batched publication.
``outcome`` carries the same CAS verdict a single-row publish would return;
``error`` is set (and ``outcome`` is ``None``) when that row's publish raised
— its savepoint was rolled back, so the row stayed in-flight while its
batch siblings that already succeeded remain committed. The caller reproduces
exactly the accounting it applied on the single-row path.
"""
embedded_id: str
outcome: EmbeddingPublishOutcome | None
error: Exception | None = None
class VectorStore:
"""SQLite-backed store for normalized summary embedding vectors."""
# Opt-in marker read by the retrieval-core pool: only the genuine store is
# long-lived/poolable (test fakes injected as ``vector_store_cls`` are not).
_supports_pooling = True
# Per-store matrix-cache ceiling. A bounded LRU (not clear-on-every-miss) so
# back-to-back recalls over an unchanged corpus reuse the loaded candidate
# matrix across BOTH arms and across calls once the store is pooled, without
# letting distinct candidate sets grow the cache without bound (sprint-opt-6).
_MATRIX_CACHE_MAX_ENTRIES = 4
def __init__(
self,
db_path: str | Path,
*,
config: LCMConfig | None = None,
bounded_scan_rows: int | None = None,
) -> None:
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
resolved_config = config or LCMConfig.from_env()
self.bounded_scan_rows = (
resolved_config.embedding_bounded_scan_rows
if bounded_scan_rows is None
else int(bounded_scan_rows)
)
# Stage-1 prescreen breadth for the two-stage (binary Hamming -> int8
# rescore) KNN: M = max(1, multiplier) x k survivors are rescored. Read
# once at construction so a pooled store honors the configured value.
self.knn_prescreen_multiplier = max(
1, int(getattr(resolved_config, "knn_prescreen_multiplier", 4) or 4)
)
# Opt-in: also write the sign-bit prescreen for float32 identities (not
# just int8). A float32-vec identity carrying the prescreen gets the
# full-corpus two-stage path with EXACT float rescore of survivors — the
# high-recall, low-RAM config. Default-off keeps stock float32 identities
# byte-identical AND binary-free (legacy bounded path). Operators pick a
# distinct identity (e.g. via revision) so prescreen rows never mix into a
# legacy float32 identity.
self._write_binary_prescreen = bool(
getattr(resolved_config, "embedding_binary_prescreen", False)
)
self._conn: Optional[sqlite3.Connection] = None
self._write_lock = threading.RLock()
self._cache_lock = threading.RLock()
# Nesting depth for _write_transaction. The outermost entry owns the
# BEGIN IMMEDIATE/COMMIT (one fsync); a re-entrant inner entry (e.g. a
# single-row publish invoked from publish_*_batch_under_lease) rides the
# open transaction under a SAVEPOINT so its failure rolls back only its
# own row, never the sibling rows already written in the same batch.
self._txn_depth = 0
# Cache key: (identity_hash, data_version, candidate_ids). The durable
# per-identity ``data_version`` counter is bumped inside every vector
# write/delete transaction, so a cross-process write invalidates this
# cache even when max_rowid and row_count are unchanged.
self._matrix_cache: "OrderedDict[tuple[str, int, tuple[str, ...]], tuple[list[int], list[str], list[str], Any]]" = OrderedDict()
# Separate cache for chunk-corpus matrices: chunk identities never
# collide with summary identities (task is part of the hash), but the
# loaders differ (chunk vectors join messages, summary vectors join
# summary_nodes), so the two corpora keep independent matrix caches.
self._chunk_matrix_cache: "OrderedDict[tuple[str, int, tuple[str, ...]], tuple[list[int], list[str], list[str], Any]]" = OrderedDict()
# Full-corpus binary prescreen matrices for the two-stage path, keyed by
# (identity_hash, data_version). Only the UNFILTERED full corpus is cached
# (filtered loads vary per call); this lets a pooled store's back-to-back
# recalls skip re-loading the whole sign-bit corpus (the dominant
# two-stage cost) — the same amortization the float matrix cache gives.
self._binary_matrix_cache: "OrderedDict[tuple[str, int], tuple[list[str], Any]]" = OrderedDict()
self._chunk_binary_matrix_cache: "OrderedDict[tuple[str, int], tuple[list[str], Any]]" = OrderedDict()
self._chunk_schema_ready = False
self._init_db()
def _init_db(self) -> None:
# isolation_level=None (autocommit) so every read runs as its own
# short read transaction rather than pinning a WAL snapshot for the
# life of the connection. Without this, a long-lived VectorStore never
# observes another process's committed vector writes (or the bumped
# data_version), defeating the cross-process cache invalidation. Write
# atomicity is preserved via the explicit BEGIN IMMEDIATE in
# _write_transaction.
self._conn = sqlite3.connect(
str(self.db_path),
timeout=5.0,
check_same_thread=False,
isolation_level=None,
)
refuse_schema_version_too_new(self._conn)
configure_connection(self._conn)
self._conn.row_factory = sqlite3.Row
run_versioned_migrations(self._conn)
self._ensure_embedding_schema()
self._conn.commit()
def _ensure_embedding_schema(self) -> None:
"""Materialize (and verify) the opt-in embedding tables on VectorStore use.
Constructing a VectorStore means embeddings are in use; the core
migration path leaves these tables uncreated so a disabled install
stays at schema_version 5 with none of them. Creation is idempotent
(CREATE TABLE/INDEX IF NOT EXISTS).
The ``embeddings_v1`` marker is NOT trusted on its own: it can be set
while a table or index is absent (e.g. one was dropped after the marker
was written). So the required tables/indexes are re-ensured and then
VERIFIED every init — a set marker over a missing table is repaired
rather than believed. Only a fully-materialized schema keeps the marker.
"""
with self._write_lock:
ensure_embedding_tables(self._conn)
errors = verify_embedding_schema(self._conn)
if errors:
# Should be unreachable: the ensure above is a superset of the
# verified set. Re-ensure once more and fail loudly if a
# required object still cannot be created, rather than marking a
# broken schema complete.
ensure_embedding_tables(self._conn)
errors = verify_embedding_schema(self._conn)
if errors:
raise sqlite3.OperationalError(
"embedding schema incompatible after ensure: "
+ "; ".join(errors)
)
# Skip the marker write + commit when it is already stamped and the
# schema verified clean -- re-writing it every construction is an
# otherwise-needless write-transaction contending with real writers
# (sprint-opt-1). CREATE-IF-NOT-EXISTS and verify above are read-only
# no-ops on an already-materialized schema.
if not self._migration_step_present("embeddings_v1"):
mark_migration_step_complete(self._conn, "embeddings_v1")
self._conn.commit()
@contextmanager
def _write_transaction(self) -> Iterator[None]:
# The connection is in autocommit mode (isolation_level=None), so a
# multi-statement write must open its own explicit transaction to stay
# atomic — the data_version bump has to commit with the vector write it
# accompanies, never separately.
#
# Re-entrant: the outermost caller owns the BEGIN IMMEDIATE + COMMIT (one
# fsync); a nested caller opens a SAVEPOINT instead so a batch of per-row
# publications shares a single transaction. A nested failure rolls back
# to its own savepoint and re-raises, leaving the earlier rows of the
# batch intact for the outer COMMIT.
try:
with self._write_lock, self._cache_lock:
if self._txn_depth > 0:
savepoint = f"lcm_pub_sp_{self._txn_depth}"
self._conn.execute(f"SAVEPOINT {savepoint}")
self._txn_depth += 1
try:
yield
self._conn.execute(f"RELEASE {savepoint}")
except BaseException:
self._conn.execute(f"ROLLBACK TO {savepoint}")
self._conn.execute(f"RELEASE {savepoint}")
raise
finally:
self._txn_depth -= 1
return
self._conn.execute("BEGIN IMMEDIATE")
self._txn_depth = 1
try:
yield
self._conn.commit()
except BaseException:
self._conn.rollback()
raise
finally:
self._txn_depth = 0
self._matrix_cache.clear()
self._binary_matrix_cache.clear()
self._chunk_binary_matrix_cache.clear()
except sqlite3.Error as exc:
if _is_sqlite_locked_error(exc):
logger.warning("Embedding write blocked by SQLite lock contention")
raise
@property
def connection(self) -> sqlite3.Connection | None:
"""The live connection for read-only diagnostics, or ``None`` after close."""
return getattr(self, "_conn", None)
@staticmethod
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
@staticmethod
def _normalized(values: Sequence[float], *, expected_dim: int) -> list[float]:
try:
floats = [float(value) for value in values]
except (TypeError, ValueError) as exc:
raise ValueError("embedding vector must contain only numeric values") from exc
if len(floats) != expected_dim:
raise ValueError(
f"embedding dimension mismatch: expected {expected_dim}, got {len(floats)}"
)
if not all(math.isfinite(value) for value in floats):
raise ValueError("embedding vector values must be finite")
magnitude = math.sqrt(sum(value * value for value in floats))
if magnitude == 0.0:
raise ValueError("embedding vector must have non-zero magnitude")
return [value / magnitude for value in floats]
def _profile_by_identity(self, identity_hash: str) -> sqlite3.Row | None:
return self._conn.execute(
"""
SELECT identity_hash, model_name, provider, revision, dim, dtype,
byteorder, task, registered_at, active, archived_at, data_version
FROM lcm_embedding_profile
WHERE identity_hash = ?
""",
(str(identity_hash),),
).fetchone()
def _resolve_profile(
self, model_name: str, provider: str | None = None
) -> sqlite3.Row | None:
"""Resolve a model name to its profile, preferring the current/active one.
Multiple identities can share a ``model_name`` (e.g. the same model
served by two providers). When ``provider`` is given the resolution is
constrained to that provider too, so the read path selects vectors that
match the *configured* provider identity rather than whichever provider
happens to be active for the bare model name — switching provider A→B
for the same model no longer scores a B-embedded query against A's
vectors. With no ``provider`` the bare-name active identity is used
(recording targets the operator's current selection).
"""
# Task-scoped: summary and chunk profiles coexist for the same
# (model, provider) in the shared table. Without the task filter this
# lookup returned whichever row registered most recently — registering
# the chunk profile silently redirected the SUMMARY knn to the chunk
# identity (zero summary meta rows → coverage 'none'). The chunk read
# path has its own resolver (_resolve_chunk_profile).
model_name = str(model_name).strip()
if provider is not None:
provider = str(provider).strip().lower()
return self._conn.execute(
"""
SELECT identity_hash, model_name, provider, revision, dim, dtype,
byteorder, task, registered_at, active, archived_at, data_version
FROM lcm_embedding_profile
WHERE model_name = ? AND provider = ? AND task = ?
ORDER BY (active = 1 AND archived_at IS NULL) DESC,
registered_at DESC, identity_hash DESC
LIMIT 1
""",
(model_name, provider, _DEFAULT_TASK),
).fetchone()
return self._conn.execute(
"""
SELECT identity_hash, model_name, provider, revision, dim, dtype,
byteorder, task, registered_at, active, archived_at, data_version
FROM lcm_embedding_profile
WHERE model_name = ? AND task = ?
ORDER BY (active = 1 AND archived_at IS NULL) DESC,
registered_at DESC, identity_hash DESC
LIMIT 1
""",
(model_name, _DEFAULT_TASK),
).fetchone()
@staticmethod
def _as_node_id(embedded_id: str) -> int | None:
"""Coerce an embedded id to the integer ``summary_nodes.node_id`` PK.
``node_id`` is an ``INTEGER PRIMARY KEY``; binding the integer lets the
lookup use the PK/rowid index instead of a ``CAST(node_id AS TEXT)``
full scan. A non-integer id can never match a node, so it maps to None.
"""
try:
return int(str(embedded_id))
except (TypeError, ValueError):
return None
def _table_columns(self, table: str) -> set[str]:
return {
str(row[1])
for row in self._conn.execute(f"PRAGMA table_info({table})").fetchall()
}
def _current_profile(self) -> sqlite3.Row | None:
# The current SUMMARY profile. Task-scoped so a coexisting active chunk
# profile can never be mistaken for the summary corpus's current profile.
return self._conn.execute(
"""
SELECT identity_hash, model_name, provider, revision, dim, dtype,
byteorder, task, registered_at, active, archived_at, data_version
FROM lcm_embedding_profile
WHERE active = 1 AND archived_at IS NULL AND task = ?
ORDER BY registered_at DESC, identity_hash DESC
LIMIT 1
""",
(_DEFAULT_TASK,),
).fetchone()
def _resolve_chunk_profile(
self, model_name: str, *, provider: str | None = None
) -> sqlite3.Row | None:
"""Resolve a profile by model (+optional provider) within task='chunk'."""
base = (
"SELECT identity_hash, model_name, provider, revision, dim, dtype, "
"byteorder, task, registered_at, active, archived_at, data_version "
"FROM lcm_embedding_profile WHERE model_name = ? AND task = ?"
)
order = (
" ORDER BY (active = 1 AND archived_at IS NULL) DESC, "
"registered_at DESC, identity_hash DESC LIMIT 1"
)
if provider is not None:
return self._conn.execute(
base + " AND provider = ?" + order,
(str(model_name), _CHUNK_TASK, str(provider).strip().lower()),
).fetchone()
return self._conn.execute(
base + order, (str(model_name), _CHUNK_TASK)
).fetchone()
@staticmethod
def _identity_from_profile(profile: sqlite3.Row) -> EmbeddingIdentity:
identity = EmbeddingIdentity.canonical(
profile["provider"],
profile["model_name"],
profile["revision"],
profile["dim"],
profile["dtype"],
profile["byteorder"],
profile["task"],
)
if identity.identity_hash != str(profile["identity_hash"]):
raise ValueError("embedding profile identity hash does not match its fields")
_require_supported_identity(identity)
return identity
def capture_identity(
self, model_name: str | None = None, *, provider: str | None = None
) -> EmbeddingIdentity:
"""Capture the full immutable identity before provider execution."""
profile = (
self._resolve_profile(model_name, provider=provider)
if model_name is not None
else self._current_profile()
)
if profile is None:
target = model_name if model_name is not None else "active"
raise ValueError(f"embedding profile is not registered: {target}")
return self._identity_from_profile(profile)
def _prescreen_revision(self, revision: str, *, dtype: str) -> str:
"""Fold the float32 sign-bit prescreen opt-in into the identity via revision.
``LCM_EMBEDDING_BINARY_PRESCREEN`` changes a float32 identity's stored
corpus shape (it grows a companion sign-bit table that drives the
two-stage KNN), so a prescreen corpus MUST be a distinct identity from a
legacy binary-free one. Otherwise flipping the flag on a populated
float32 identity leaves a mixed corpus (a few post-flip rows with
sign-bits, the rest without) that the two-stage INNER JOIN silently
truncates while reporting coverage='full' (FIX 1).
Only the default (empty) revision is auto-tagged: an operator who set an
explicit revision has already taken ownership of identity separation (the
documented manual escape hatch), so their value is respected verbatim.
int8 identities always carry the prescreen and are already distinguished
by dtype, so the tag is float32-only — int8 identity hashes stay stable.
"""
base = str(revision).strip()
if base or str(dtype).strip().lower() == _INT8_DTYPE:
return base
return _BINARY_PRESCREEN_REVISION_TAG if self._write_binary_prescreen else base
def register_profile(
self,
model_name: str,
provider: str,
dim: int,
*,
revision: str = "",
dtype: str = _VECTOR_DTYPE,
byteorder: str = _VECTOR_BYTEORDER,
task: str = _DEFAULT_TASK,
) -> str:
"""Register (or reactivate) the profile for a canonical identity.
The identity is ``(provider, model_name, revision, dim, dtype,
byteorder, task)``. Registering a *different* identity for the same
model_name creates a new profile row rather than clobbering the old
provider's metadata; re-registering an already-known identity
reactivates it (its vectors remain valid, so switching config back
needs no re-backfill). Exactly one profile is left active. Returns the
identity hash.
"""
revision = self._prescreen_revision(revision, dtype=dtype)
canonical = EmbeddingIdentity.canonical(
provider, model_name, revision, dim, dtype, byteorder, task
)
if not canonical.model_name:
raise ValueError("model_name must not be empty")
if not canonical.provider:
raise ValueError("provider must not be empty")
if canonical.dim < 1 or canonical.dim > 4096:
raise ValueError("embedding dimension must be between 1 and 4096")
_require_supported_identity(canonical)
identity = canonical.identity_hash
with self._write_transaction():
existing = self._profile_by_identity(identity)
if existing is None:
self._conn.execute(
"""
INSERT INTO lcm_embedding_profile(
identity_hash, provider, model_name, revision, dim,
dtype, byteorder, task, registered_at, active,
archived_at, data_version
)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, 0)
""",
(
identity,
canonical.provider,
canonical.model_name,
canonical.revision,
canonical.dim,
canonical.dtype,
canonical.byteorder,
canonical.task,
self._now(),
),
)
else:
# Reactivate a previously-registered identity in place; its
# vectors are still valid so no re-backfill is required.
self._conn.execute(
"""
UPDATE lcm_embedding_profile
SET active = 1, archived_at = NULL
WHERE identity_hash = ?
""",
(identity,),
)
# Selection of the "current" profile is by identity WITHIN A TASK:
# only the just-registered identity stays active for its task; other
# profiles of the SAME task are deactivated (retained so their
# vectors survive a later switch back). Profiles of a DIFFERENT task
# are untouched, so the summary and chunk corpora coexist — each has
# its own active profile.
self._conn.execute(
"UPDATE lcm_embedding_profile SET active = 0 "
"WHERE identity_hash != ? AND task = ?",
(identity, canonical.task),
)
return identity
def record_embedding(
self,
embedded_id: str,
kind: str,
model: str,
vec: Sequence[float],
*,
identity: EmbeddingIdentity,
) -> None:
with self._write_transaction():
profile = self._validate_embedding_write(identity, model=model)
self._write_embedding_row(
str(embedded_id), kind, vec, identity=identity, profile=profile
)
def publish_embedding_under_lease(
self,
embedded_id: str,
kind: str,
model: str,
vec: Sequence[float],
*,
identity: EmbeddingIdentity,
claim_key: str,
lease_id: str,
generation: int,
request_id: str,
) -> EmbeddingPublishOutcome:
"""Atomically revalidate ownership and publish one accepted summary vector."""
embedded_id = str(embedded_id)
return self._publish_under_lease(
embedded_id,
model=model,
identity=identity,
claim_key=claim_key,
lease_id=lease_id,
generation=generation,
request_id=request_id,
write_row=lambda profile: self._write_embedding_row(
embedded_id, kind, vec, identity=identity, profile=profile
),
)
def publish_embedding_batch_under_lease(
self,
rows: Sequence[tuple[str, str, str, Sequence[float]]],
*,
identity: EmbeddingIdentity,
claim_key: str,
lease_id: str,
generation: int,
) -> list[BatchPublishResult]:
"""Publish an accepted network batch of summary vectors in ONE transaction.
``rows`` is a sequence of ``(embedded_id, kind, model, vec)`` in provider
order. All rows share one ``BEGIN IMMEDIATE`` (a single fsync per network
batch instead of one per row), yet each still runs the full per-row
ownership/identity CAS under its own savepoint via the single-row
``publish_embedding_under_lease``. Publication stops at the first row that
is not ``PUBLISHED`` (or that raises), mirroring the single-row loop it
replaces; the rows already published in that transaction are kept.
"""
return self._run_publish_batch(
[
(
str(embedded_id),
lambda embedded_id=embedded_id, kind=kind, model=model, vec=vec, request_id=request_id: self.publish_embedding_under_lease(
embedded_id,
kind,
model,
vec,
identity=identity,
claim_key=claim_key,
lease_id=lease_id,
generation=generation,
request_id=request_id,
),
)
for embedded_id, kind, model, vec, request_id in rows
]
)
def _run_publish_batch(
self, publishers: Sequence[tuple[str, "Any"]]
) -> list[BatchPublishResult]:
"""Run per-row publishers inside one write transaction.
Each entry is ``(embedded_id, publish)`` where ``publish`` is a zero-arg
call into the corpus-specific single-row publish method (kept as the
per-row worker so its behaviour — and any test monkeypatch of it — is
exercised unchanged, now under a savepoint). A raised publisher rolls its
own savepoint back and is reported as an errored row; the loop then stops
so the caller can quarantine the request exactly as the single-row path
did, while the committed siblings survive.
"""
results: list[BatchPublishResult] = []
with self._write_transaction():
for embedded_id, publish in publishers:
try:
outcome = publish()
except Exception as exc: # noqa: BLE001 — reported to the caller
results.append(
BatchPublishResult(embedded_id, outcome=None, error=exc)
)
break
results.append(BatchPublishResult(embedded_id, outcome=outcome))
if outcome is not EmbeddingPublishOutcome.PUBLISHED:
break
return results
def _publish_under_lease(
self,
embedded_id: str,
*,
model: str,
identity: EmbeddingIdentity,
claim_key: str,
lease_id: str,
generation: int,
request_id: str,
write_row,
) -> EmbeddingPublishOutcome:
"""Corpus-agnostic lease publication CAS shared by summary and chunk.
The metadata owner/generation check, active captured identity check,
matching dispatched-row check, corpus-specific vector/meta write (via
``write_row``), data-version bump, and in-flight clear all share one
``BEGIN IMMEDIATE`` transaction. A superseded worker therefore performs
none of these mutations. Summary and chunk publications share the one
``lcm_embedding_backfill_inflight`` table because their embedded_ids are
disjoint (numeric node ids vs ``store_id:chunk_index``) and their
identity hashes differ (task is part of the hash).
"""
embedded_id = str(embedded_id)
with self._write_transaction():
owner = self._conn.execute(
"""
SELECT 1
FROM metadata
WHERE key = ?
AND json_extract(value, '$.owner') = ?
AND CAST(json_extract(value, '$.generation') AS INTEGER) = ?
""",
(claim_key, str(lease_id), int(generation)),
).fetchone()
inflight = self._conn.execute(
"""
SELECT 1
FROM lcm_embedding_backfill_inflight
WHERE embedded_id = ? AND identity_hash = ?
AND lease_id = ? AND generation = ?
AND request_id = ? AND state = 'dispatched'
""",
(
embedded_id,
identity.identity_hash,
str(lease_id),
int(generation),
str(request_id),
),
).fetchone()
if owner is None or inflight is None:
return EmbeddingPublishOutcome.OWNERSHIP_LOST
profile = self._validate_embedding_write(identity, model=model)
if int(profile["active"] or 0) != 1 or profile["archived_at"] is not None:
transitioned = self._conn.execute(
"""
UPDATE lcm_embedding_backfill_inflight
SET state = 'uncertain', updated_at = ?,
last_error = 'embedding identity superseded after remote acceptance'
WHERE identity_hash = ? AND lease_id = ? AND generation = ?
AND request_id = ? AND state = 'dispatched'
""",
(
datetime.now(timezone.utc).timestamp(),
identity.identity_hash,
str(lease_id),
int(generation),
str(request_id),
),
)
if int(transitioned.rowcount or 0) < 1:
return EmbeddingPublishOutcome.OWNERSHIP_LOST
released = self._conn.execute(
"""
DELETE FROM metadata
WHERE key = ?
AND json_extract(value, '$.owner') = ?
AND CAST(json_extract(value, '$.generation') AS INTEGER) = ?
""",
(claim_key, str(lease_id), int(generation)),
)
if int(released.rowcount or 0) != 1:
raise sqlite3.OperationalError(
"identity supersession lost lease release ownership"
)
return EmbeddingPublishOutcome.IDENTITY_SUPERSEDED
write_row(profile)
cleared = self._conn.execute(
"""
DELETE FROM lcm_embedding_backfill_inflight
WHERE embedded_id = ? AND identity_hash = ?
AND lease_id = ? AND generation = ?
AND request_id = ? AND state = 'dispatched'
""",
(
embedded_id,
identity.identity_hash,
str(lease_id),
int(generation),
str(request_id),
),
)
if cleared.rowcount != 1:
raise sqlite3.OperationalError(
"embedding publication lost its in-flight ownership"
)
return EmbeddingPublishOutcome.PUBLISHED
def _validate_embedding_write(
self, identity: EmbeddingIdentity, *, model: str
) -> sqlite3.Row:
model = str(model)
if not isinstance(identity, EmbeddingIdentity):
raise TypeError("identity must be an EmbeddingIdentity captured before provider work")
canonical_identity = EmbeddingIdentity.canonical(
identity.provider,
identity.model_name,
identity.revision,
identity.dim,
identity.dtype,
identity.byteorder,
identity.task,
)
if identity != canonical_identity:
raise ValueError("embedding identity fields are not canonical")
_require_supported_identity(identity)
expected_identity = identity.identity_hash
profile = self._profile_by_identity(expected_identity)
if profile is None:
raise ValueError(f"embedding profile is not registered: {expected_identity}")
registered_identity = self._identity_from_profile(profile)
if registered_identity != identity:
raise ValueError(
"captured embedding identity does not match registered profile"
)
if str(profile["model_name"]) != model.strip():
raise ValueError(
"embedding model does not match captured identity: "
f"{model} != {profile['model_name']}"
)
return profile