dsh-feiyu-memgate 0.3.2 → 0.4.0

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.
Files changed (103) hide show
  1. package/CHANGELOG.md +73 -12
  2. package/README.md +68 -11
  3. package/README.zh.md +93 -36
  4. package/client/README.md +267 -0
  5. package/client/art/mascot-asleep.webp +0 -0
  6. package/client/art/mascot-busy.webp +0 -0
  7. package/client/art/mascot-nag.webp +0 -0
  8. package/client/art/mascot-ready.webp +0 -0
  9. package/client/art/mascot-trouble.webp +0 -0
  10. package/client/client.js +4226 -1269
  11. package/client/src/clipboard.cjs +52 -0
  12. package/client/src/constants.cjs +43 -0
  13. package/client/src/fields.cjs +960 -0
  14. package/client/src/hooks.cjs +220 -0
  15. package/client/src/i18n.cjs +444 -0
  16. package/client/src/index.cjs +69 -0
  17. package/client/src/kit/controls.cjs +189 -0
  18. package/client/src/kit/icons.cjs +40 -0
  19. package/client/src/kit/layout.cjs +124 -0
  20. package/client/src/layout.cjs +143 -0
  21. package/client/src/model/changelog.cjs +29 -0
  22. package/client/src/model/feedback.cjs +168 -0
  23. package/client/src/model/form.cjs +83 -0
  24. package/client/src/model/models.cjs +87 -0
  25. package/client/src/model/overview.cjs +111 -0
  26. package/client/src/model/page.cjs +104 -0
  27. package/client/src/model/status.cjs +57 -0
  28. package/client/src/model/trial.cjs +111 -0
  29. package/client/src/net.cjs +101 -0
  30. package/client/src/react.cjs +11 -0
  31. package/client/src/theme/page.css +1284 -0
  32. package/client/src/theme/styles.cjs +43 -0
  33. package/client/src/view/feedback.cjs +180 -0
  34. package/client/src/view/field-row.cjs +98 -0
  35. package/client/src/view/hero.cjs +54 -0
  36. package/client/src/view/markdown.cjs +96 -0
  37. package/client/src/view/models.cjs +154 -0
  38. package/client/src/view/page.cjs +199 -0
  39. package/client/src/view/settings-tab.cjs +78 -0
  40. package/client/src/view/tabs.cjs +71 -0
  41. package/client/src/view/trial.cjs +84 -0
  42. package/docs/DETAIL.en.md +55 -6
  43. package/docs/DETAIL.md +63 -14
  44. package/locale/zh.json +1 -1
  45. package/package.json +2 -1
  46. package/python/GATEWAY_VERSION.json +37 -31
  47. package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
  48. package/python/feiyu_memgate/backends/base.py +121 -6
  49. package/python/feiyu_memgate/backends/embedding.py +265 -178
  50. package/python/feiyu_memgate/backends/hybrid.py +330 -83
  51. package/python/feiyu_memgate/backends/inmemory.py +115 -24
  52. package/python/feiyu_memgate/backends/openviking.py +7 -10
  53. package/python/feiyu_memgate/backends/sqlite.py +129 -145
  54. package/python/feiyu_memgate/builtins.py +1 -0
  55. package/python/feiyu_memgate/cli.py +124 -20
  56. package/python/feiyu_memgate/client/block.py +4 -2
  57. package/python/feiyu_memgate/client/http.py +106 -19
  58. package/python/feiyu_memgate/client/local.py +4 -3
  59. package/python/feiyu_memgate/config.py +118 -24
  60. package/python/feiyu_memgate/core/limits.py +2 -1
  61. package/python/feiyu_memgate/core/pool.py +29 -2
  62. package/python/feiyu_memgate/core/recall.py +179 -10
  63. package/python/feiyu_memgate/core/redact.py +4 -2
  64. package/python/feiyu_memgate/core/stages.py +52 -9
  65. package/python/feiyu_memgate/core/tidy.py +2 -1
  66. package/python/feiyu_memgate/core/watch.py +3 -2
  67. package/python/feiyu_memgate/core/write.py +9 -3
  68. package/python/feiyu_memgate/forgetting/archive.py +38 -10
  69. package/python/feiyu_memgate/forgetting/engine.py +46 -10
  70. package/python/feiyu_memgate/forgetting/stage.py +4 -2
  71. package/python/feiyu_memgate/gateway/app.py +168 -272
  72. package/python/feiyu_memgate/gateway/fields.py +121 -0
  73. package/python/feiyu_memgate/gateway/policies.py +162 -0
  74. package/python/feiyu_memgate/gateway/server.py +12 -4
  75. package/python/feiyu_memgate/gateway/tokens.py +137 -0
  76. package/python/feiyu_memgate/gateway/validate.py +120 -0
  77. package/python/feiyu_memgate/identity.py +152 -0
  78. package/python/feiyu_memgate/model.py +170 -2
  79. package/python/feiyu_memgate/registry.py +6 -3
  80. package/python/feiyu_memgate/tools/crypto.py +5 -4
  81. package/python/feiyu_memgate/tools/evaluate.py +2 -1
  82. package/python/feiyu_memgate/tools/tenants.py +2 -0
  83. package/src/block.js +9 -3
  84. package/src/capture.js +98 -0
  85. package/src/catalogue.js +4 -4
  86. package/src/changelog.js +72 -0
  87. package/src/client.js +145 -10
  88. package/src/commands.js +112 -62
  89. package/src/config.js +139 -62
  90. package/src/followup.js +139 -0
  91. package/src/gateway.js +79 -4
  92. package/src/migrate.py +54 -9
  93. package/src/mirror.py +44 -7
  94. package/src/plugin.js +416 -412
  95. package/src/pool.js +298 -0
  96. package/src/recent.js +68 -0
  97. package/src/relevance.js +80 -0
  98. package/src/routes.js +320 -0
  99. package/src/setup.js +36 -36
  100. package/src/shared.js +77 -0
  101. package/src/tiers.js +4 -4
  102. package/src/time.js +27 -0
  103. package/src/tools.js +164 -0
@@ -44,31 +44,61 @@ no redirects (any non-2xx answer is a failure), the response size is bounded, on
44
44
  deadline per call, the socket is attached to `ctl` so the gateway can cut a late call.
45
45
  Errors are BackendError and never carry upstream text, memory text or the key.
46
46
 
47
- Thread safety: one SQLite connection shared by all threads under a lock; HTTP calls use a
48
- connection each and run outside the lock.
47
+ Thread safety: one writer connection under a lock (`_lock`), and a bounded pool of read-only reader
48
+ connections (`max_readers`) for everything that reads, so a search never waits for a write (file
49
+ databases use WAL; a ":memory:" database cannot be shared between connections and keeps the one
50
+ connection under the lock). The vectors are loaded on a reader connection without the writer's lock; only
51
+ the swap of the in-memory cache is guarded (`_cache_lock`), and one search loads while the others wait for
52
+ it. HTTP calls use a connection each and run outside every lock. close() closes every connection.
53
+
54
+ How a change is noticed: the `info` table holds a write counter, `gen`, that every write of this backend
55
+ raises by one inside its own transaction (the transaction takes the file's write lock first, so the number
56
+ read there is exact). The cache remembers the `gen` it was loaded at, and a load reads it in the same read
57
+ transaction as the vectors. A search reads `gen` on a reader connection; the cache is used when it is the
58
+ same and reloaded when it is not. A write of this backend applies itself to the cache and moves the cache's
59
+ `gen` forward when the cache was current, so a search right after remember() needs no reload; a write of
60
+ another backend object or process (to the same file) raises `gen` and is noticed by the next search. (SQLite's
61
+ `PRAGMA data_version` is not used: it is per connection and counts every other connection's commits, the
62
+ backend's own writer included, so it cannot be compared between pooled readers.)
63
+
64
+ Record fields: the `memories` table also has a nullable TEXT column for each of model.FIELDS (speaker, about,
65
+ channel, audience, origin, event_date, kind). `put`, the dict items of `put_many` ("fields") and the messages of
66
+ `remember` (key "fields") may carry them; the hits of `find` and `neighbours` return them in `Hit.fields`, and
67
+ `records()` / `record(ref)` return them with the memory. Fields never reach the embeddings endpoint: only the
68
+ text is embedded. A store made before they existed gets the columns when it is opened writable (and `info`
69
+ record_version "2"); opened read-only it is left alone, answers without fields and `stores_fields` is False.
70
+ Today's named-column `INSERT OR REPLACE INTO memories (ref, text, created_at, date, vector) ...` still works on
71
+ the new table (the row then has no fields).
72
+
73
+ Audiences: `stamp_audience(level)` gives every memory without an audience `level` the first time it is called and
74
+ records that in `info` (row `audience_stamp`); `checks_audience` is True from then on, and the `record_audience`
75
+ recall stage drops a memory narrower than its client (a memory without an audience counts as "owner").
76
+ `set_audience(level, only_missing)` changes it later on purpose (the `restamp` command). Neither touches a vector or
77
+ the generation counter.
49
78
  """
50
79
  import array
51
80
  import collections
81
+ import contextlib
52
82
  import heapq
53
83
  import http.client
54
84
  import json
55
85
  import logging
56
86
  import math
57
- import os
58
87
  import socket
59
- import sqlite3
60
88
  import ssl
61
89
  import threading
62
90
  import time
63
91
  import urllib.parse
64
- import uuid
65
- from datetime import datetime, timezone
92
+ from typing import Any
66
93
 
67
94
  from ..core.pool import _NoCtl
68
95
  from ..errors import BackendError
69
- from ..model import Hit
70
96
  from ..registry import register
71
- from .base import MemoryBackend, message_date
97
+ from . import _sqlfile
98
+ from ._sqlfile import SCAN_BATCH, Readers
99
+ from .base import (DEFAULT_BUDGET, MemoryBackend, as_roles, clamp01, kept_messages, make_hit, # noqa: F401
100
+ message_fields, new_receipt, parse_item, parse_record, receipt_ref, require_writable)
101
+ from .base import today as _today
72
102
 
73
103
  PRESETS = (
74
104
  # (pattern, values): the first pattern contained in the lower-cased model name wins. "min_score" and
@@ -96,40 +126,25 @@ PRESETS = (
96
126
  )
97
127
  # What an unknown model gets: the bge-m3 numbers, without prefixes.
98
128
  # The broad numbers are the bge-m3 ones too (a guess for an unknown model, like the rest).
99
- GENERIC = {"floor": 0.40, "ceil": 0.80, "min_score": 0.50, "ratio": 0.85, "broad_min_score": 0.30,
129
+ GENERIC: dict[str, Any] = {"floor": 0.40, "ceil": 0.80, "min_score": 0.50, "ratio": 0.85, "broad_min_score": 0.30,
100
130
  "broad_ratio": 0.60, "query_prefix": "", "document_prefix": ""}
101
131
 
102
132
  _log = logging.getLogger("feiyu_memgate.backends.embedding")
103
- _warned = set() # model names already warned about in this process
133
+ _warned: set[str] = set() # model names already warned about in this process
104
134
 
105
- DEFAULT_BUDGET = 10.0 # seconds for one find() when neither the caller nor the options say
106
135
  MAX_RESPONSE = 16 * 1024 * 1024 # a batch of 32 vectors of 3072 floats is about 2 MB of JSON
107
136
  QUERY_CACHE = 256
137
+ MAX_READERS = 8 # read connections of one store (default of the max_readers option)
108
138
  MAX_PREFIX = 512 # characters; the longest recommended instruction is about 100
109
- SCAN_BATCH = 500
110
139
  SCORE_CHECK_EVERY = 256 # vectors scored between two deadline checks
111
140
 
112
- _HAS_META = "meta" in getattr(Hit, "__dataclass_fields__", {})
113
-
114
141
  try:
115
- _sumprod = math.sumprod # Python 3.12+: the dot product in C
142
+ _sumprod = math.sumprod # type: ignore[attr-defined] # Python 3.12+: the dot product in C
116
143
  except AttributeError: # pragma: no cover - Python 3.11
117
144
  def _sumprod(a, b):
118
145
  return sum(x * y for x, y in zip(a, b))
119
146
 
120
- _SCHEMA = """
121
- CREATE TABLE IF NOT EXISTS memories (
122
- ref TEXT PRIMARY KEY,
123
- text TEXT NOT NULL,
124
- created_at INTEGER NOT NULL,
125
- date TEXT,
126
- vector BLOB NOT NULL
127
- );
128
- CREATE TABLE IF NOT EXISTS info (
129
- key TEXT PRIMARY KEY,
130
- value TEXT NOT NULL
131
- );
132
- """
147
+ _SCHEMA = _sqlfile.memories_table(",\n vector BLOB NOT NULL") + _sqlfile.INFO_TABLE
133
148
 
134
149
 
135
150
  def preset_for(model):
@@ -141,20 +156,6 @@ def preset_for(model):
141
156
  return GENERIC, False
142
157
 
143
158
 
144
- def _today():
145
- return datetime.now(timezone.utc).strftime("%Y-%m-%d")
146
-
147
-
148
- def _make_hit(ref, score, text, date, cosine):
149
- """A Hit, with the raw cosine in meta when this version of Hit has a meta field."""
150
- if _HAS_META:
151
- try:
152
- return Hit(ref=ref, score=score, text=text, date=date, meta={"cosine": cosine})
153
- except TypeError: # pragma: no cover - a Hit whose meta has another shape
154
- pass
155
- return Hit(ref=ref, score=score, text=text, date=date)
156
-
157
-
158
159
  def _unit(values):
159
160
  """`values` (floats) as an L2-normalised float32 array. BackendError for a zero or non-finite vector."""
160
161
  norm = math.sqrt(math.fsum(v * v for v in values))
@@ -163,6 +164,12 @@ def _unit(values):
163
164
  return array.array("f", [v / norm for v in values])
164
165
 
165
166
 
167
+ def _generation(db):
168
+ """The write counter of the store as `db` sees it (0 for a store nothing has written to yet)."""
169
+ row = db.execute("SELECT value FROM info WHERE key = 'gen'").fetchone()
170
+ return int(row[0]) if row else 0
171
+
172
+
166
173
  def _blob_to_vector(blob):
167
174
  vec = array.array("f")
168
175
  vec.frombytes(blob)
@@ -207,6 +214,7 @@ class _Http:
207
214
  attach(raw)
208
215
  sock = raw
209
216
  if self.https:
217
+ assert self._ssl is not None # built in __init__ whenever https is on
210
218
  sock = self._ssl.wrap_socket(raw, server_hostname=self.host)
211
219
  conn = (http.client.HTTPSConnection if self.https else http.client.HTTPConnection)(self.host, self.port)
212
220
  conn.sock = sock
@@ -274,7 +282,7 @@ class EmbeddingBackend(MemoryBackend):
274
282
  request, default 32), floor and ceil (the cosine range mapped to scores 0..1), query_prefix and
275
283
  document_prefix (text put before every query / every stored text when it is embedded). floor, ceil
276
284
  and both prefixes default to the preset of the model (PRESETS), or to 0.40, 0.80 and no prefix with a
277
- warning for a model that has none."""
285
+ warning for a model that has none. max_readers (read connections, default 8)."""
278
286
 
279
287
  tracks_writes = False # a write is final as soon as remember() returns
280
288
  # Scores are floor/ceil-mapped relevance: with floor 0.40 and ceil 0.80 a min_score of 0.50 is a cosine
@@ -287,11 +295,14 @@ class EmbeddingBackend(MemoryBackend):
287
295
  # below, from `bench/dev_eval.py --search --profile broad` (experiments: bench/results/dev/*-broad.md).
288
296
  broad_min_score = GENERIC["broad_min_score"]
289
297
  broad_relative_ratio = GENERIC["broad_ratio"]
298
+ # Keeps the record fields (see the module docstring); an instance over an old file it may not upgrade
299
+ # (read-only) sets it False.
300
+ stores_fields = True
290
301
 
291
302
  def __init__(self, path, url, model, key=None, writable=True, roles=("user",), timeout=10.0,
292
- batch=32, floor=None, ceil=None, query_prefix=None, document_prefix=None):
293
- if isinstance(roles, str):
294
- roles = (roles,)
303
+ batch=32, floor=None, ceil=None, query_prefix=None, document_prefix=None,
304
+ max_readers=MAX_READERS):
305
+ roles = as_roles(roles)
295
306
  if not isinstance(model, str) or not model:
296
307
  raise ValueError("model must be a non-empty string")
297
308
  if key is not None and not isinstance(key, str):
@@ -326,27 +337,30 @@ class EmbeddingBackend(MemoryBackend):
326
337
  self._query_prefix, self._doc_prefix = query_prefix, document_prefix
327
338
  self._http = _Http(url, model, key or None, timeout)
328
339
  self._path = str(path)
329
- self._lock = threading.Lock()
340
+ self._shared = self._path == ":memory:" # one connection for everything
341
+ self._lock = threading.Lock() # the writer (and, for ":memory:", every reader)
330
342
  self._closed = False
331
343
  self._dim = None
332
- # Scan cache: ref -> float32 unit vector, loaded on the first search, then kept in step
333
- # with our own writes. PRAGMA data_version tells when another connection wrote.
344
+ # Scan cache: ref -> float32 unit vector, loaded on the first search, then kept in step with our
345
+ # own writes. `_generation` is the write counter (see the module docstring) the cache is current at.
346
+ # `_cache_lock` guards `_vectors` and `_generation` (held for a swap or a copy, never for a load);
347
+ # `_load_lock` lets one search load at a time. Order: _lock, then _cache_lock; _load_lock is taken
348
+ # alone (a ":memory:" load takes _lock inside it).
334
349
  self._vectors = None
335
- self._data_version = None
350
+ self._generation = None
351
+ self._cache_lock = threading.Lock()
352
+ self._load_lock = threading.Lock()
336
353
  self._qcache = collections.OrderedDict()
337
354
  self._qlock = threading.Lock()
338
- if self._path != ":memory:":
339
- os.makedirs(os.path.dirname(os.path.abspath(self._path)), exist_ok=True)
340
- self._db = sqlite3.connect(self._path, check_same_thread=False, timeout=10.0)
355
+ self._db = _sqlfile.open_store(self._path, _SCHEMA)
341
356
  try:
342
- if self._path != ":memory:":
343
- self._db.execute("PRAGMA journal_mode=WAL")
344
- self._db.executescript(_SCHEMA)
345
- self._db.commit()
346
357
  self._check_model()
358
+ self.stores_fields = self._stored = _sqlfile.ensure_fields(self._db, self.writable)
359
+ self._stamped = self._stored and _sqlfile.is_stamped(self._db)
347
360
  except Exception:
348
361
  self._db.close()
349
362
  raise
363
+ self._readers = None if self._shared else Readers(lambda: _sqlfile.open_reader(self._path), max_readers)
350
364
 
351
365
  @staticmethod
352
366
  def _warn_unknown(model):
@@ -396,7 +410,7 @@ class EmbeddingBackend(MemoryBackend):
396
410
  gives every request the default budget (for writes, where the batch count is the caller's choice)."""
397
411
  if prefix:
398
412
  texts = [prefix + t for t in texts]
399
- out = []
413
+ out: list[Any] = []
400
414
  end = None if total is None else time.monotonic() + total
401
415
  for start in range(0, len(texts), self._batch):
402
416
  chunk = texts[start:start + self._batch]
@@ -419,152 +433,228 @@ class EmbeddingBackend(MemoryBackend):
419
433
 
420
434
  # ------------------------------------------------------------ writing
421
435
 
422
- def _require_writable(self):
423
- if not self.writable:
424
- raise PermissionError("this backend is read-only")
425
-
426
- def put(self, text, ref=None, date=None, timeout=None, ctl=None):
427
- """Store one memory text as it is and return its ref (an existing ref is replaced)."""
428
- return self.put_many([(text, ref, date)], timeout=timeout, ctl=ctl)[0]
436
+ def put(self, text, ref=None, date=None, timeout=None, ctl=None, fields=None):
437
+ """Store one memory text as it is and return its ref (an existing ref is replaced, its fields
438
+ too: a put without fields clears them)."""
439
+ item = {"text": text, "ref": ref, "date": date, "fields": fields}
440
+ return self.put_many([item], timeout=timeout, ctl=ctl)[0]
429
441
 
430
442
  def put_many(self, items, timeout=None, ctl=None):
431
443
  """Store several memories with batched embedding requests and return their refs.
432
444
 
433
445
  Each item is a text, a (text, ref, date) tuple (ref and date optional) or a dict with
434
- "text" and optionally "ref" and "date". All embeddings are fetched before anything is
446
+ "text" and optionally "ref", "date" and "fields" (a dict of model.FIELDS; text and tuple items have
447
+ none). All embeddings are fetched before anything is
435
448
  written, so a failing endpoint leaves the store unchanged."""
436
- self._require_writable()
437
- rows = [self._item(i) for i in items]
449
+ require_writable(self)
450
+ rows = [parse_record(i) for i in items]
438
451
  if not rows:
439
452
  return []
440
453
  vectors = self._embed([r[0] for r in rows], timeout, ctl, self._doc_prefix)
454
+ self._store([(ref, text, date, vec, fields) for (text, ref, date, fields), vec in zip(rows, vectors)])
455
+ return [r[1] for r in rows]
456
+
457
+ def _store(self, rows):
458
+ """Write `rows` ((ref, text, date, vector, fields), at least one) in one transaction and bring the
459
+ cache along."""
441
460
  now = int(time.time())
442
- refs = []
443
461
  with self._lock:
444
- self._bind_dim(len(vectors[0]))
445
- with self._db:
446
- for (text, ref, date), vec in zip(rows, vectors):
462
+ self._db.execute("BEGIN IMMEDIATE") # the file's write lock: the counter read below is exact
463
+ try:
464
+ self._bind_dim(len(rows[0][3]))
465
+ before = _generation(self._db)
466
+ self._db.execute("INSERT OR REPLACE INTO info (key, value) VALUES ('gen', ?)", (str(before + 1),))
467
+ for ref, text, date, vec, fields in rows:
447
468
  self._db.execute(
448
- "INSERT OR REPLACE INTO memories (ref, text, created_at, date, vector) VALUES (?, ?, ?, ?, ?)",
449
- (ref, text, now, date, vec.tobytes()),
469
+ "INSERT OR REPLACE INTO memories (ref, text, created_at, date, vector, %s) "
470
+ "VALUES (?, ?, ?, ?, ?, %s)" % (_sqlfile.FIELD_LIST, _sqlfile.FIELD_MARKS),
471
+ (ref, text, now, date, vec.tobytes()) + _sqlfile.field_values(fields),
450
472
  )
451
- refs.append(ref)
452
- if self._vectors is not None:
453
- for (text, ref, date), vec in zip(rows, vectors):
473
+ self._db.commit()
474
+ except BaseException:
475
+ self._db.rollback()
476
+ raise
477
+ self._apply(before, [(ref, vec) for ref, _, _, vec, _ in rows], ())
478
+
479
+ def _apply(self, before, upserts, removed):
480
+ """Bring the cache along with a write that took the counter from `before` to `before + 1`. A cache
481
+ that was not at `before` (not loaded, or behind another writer) is left for the next search to reload."""
482
+ with self._cache_lock:
483
+ if self._vectors is not None and self._generation == before:
484
+ for ref, vec in upserts:
454
485
  self._vectors[ref] = vec
455
- return refs
456
-
457
- @staticmethod
458
- def _item(item):
459
- if isinstance(item, str):
460
- item = (item,)
461
- if isinstance(item, dict):
462
- text, ref, date = item.get("text"), item.get("ref"), item.get("date")
463
- else:
464
- text, ref, date = (tuple(item) + (None, None))[:3]
465
- if not isinstance(text, str) or not text.strip():
466
- raise ValueError("a memory text must be a non-empty string")
467
- return text, ref or "mem-" + uuid.uuid4().hex, date
486
+ for ref in removed:
487
+ self._vectors.pop(ref, None)
488
+ self._generation = before + 1
468
489
 
469
490
  def delete(self, ref):
470
491
  """Remove one memory. True when it existed."""
471
- self._require_writable()
492
+ require_writable(self)
472
493
  with self._lock:
473
- with self._db:
494
+ self._db.execute("BEGIN IMMEDIATE")
495
+ try:
496
+ before = _generation(self._db)
474
497
  cur = self._db.execute("DELETE FROM memories WHERE ref = ?", (ref,))
475
- if self._vectors is not None:
476
- self._vectors.pop(ref, None)
477
- return cur.rowcount > 0
498
+ deleted = cur.rowcount > 0
499
+ if deleted:
500
+ self._db.execute("INSERT OR REPLACE INTO info (key, value) VALUES ('gen', ?)", (str(before + 1),))
501
+ self._db.commit()
502
+ except BaseException:
503
+ self._db.rollback()
504
+ raise
505
+ if deleted:
506
+ self._apply(before, (), (ref,))
507
+ return deleted
478
508
 
479
509
  def remember(self, messages, timeout=None, ctl=None):
480
510
  """Keep the messages whose role is in `roles`. Returns a receipt id, or None when
481
511
  nothing matched (nothing was embedded or stored)."""
482
- self._require_writable()
512
+ require_writable(self)
483
513
  today = _today()
484
- kept = [(i, m["content"], message_date(m, today)) for i, m in enumerate(messages) if m["role"] in self.roles]
514
+ kept = kept_messages(messages, self.roles, today)
485
515
  if not kept:
486
516
  return None
487
- receipt = "w-" + uuid.uuid4().hex
517
+ receipt = new_receipt()
488
518
  texts = [content for _, content, _ in kept]
489
519
  if any(not isinstance(t, str) or not t.strip() for t in texts):
490
520
  raise ValueError("a memory text must be a non-empty string")
521
+ kept_fields = [message_fields(messages[index]) for index, _, _ in kept]
491
522
  vectors = self._embed(texts, timeout, ctl, self._doc_prefix)
492
- now = int(time.time())
493
- with self._lock:
494
- self._bind_dim(len(vectors[0]))
495
- with self._db:
496
- for (index, content, date), vec in zip(kept, vectors):
497
- self._db.execute(
498
- "INSERT OR REPLACE INTO memories (ref, text, created_at, date, vector) VALUES (?, ?, ?, ?, ?)",
499
- ("%s-%d" % (receipt, index), content, now, date, vec.tobytes()),
500
- )
501
- if self._vectors is not None:
502
- for (index, _, _), vec in zip(kept, vectors):
503
- self._vectors["%s-%d" % (receipt, index)] = vec
523
+ self._store([(receipt_ref(receipt, index), content, date, vec, fields)
524
+ for (index, content, date), vec, fields in zip(kept, vectors, kept_fields)])
504
525
  return receipt
505
526
 
506
527
  # ------------------------------------------------------------ reading
507
528
 
529
+ @contextlib.contextmanager
530
+ def _read(self, deadline=None):
531
+ """A connection to read with, used by this thread alone until the block ends: a pooled reader, or
532
+ for ":memory:" the one connection under the lock. Never waits for a write on a file database."""
533
+ if deadline is None:
534
+ deadline = time.monotonic() + DEFAULT_BUDGET
535
+ if self._closed:
536
+ raise BackendError("the store is closed")
537
+ if self._shared:
538
+ if not self._lock.acquire(timeout=max(0.0, deadline - time.monotonic())):
539
+ raise BackendError("the store is busy")
540
+ try:
541
+ yield self._db
542
+ finally:
543
+ self._lock.release()
544
+ return
545
+ assert self._readers is not None # None only for the shared in-memory store, handled above
546
+ conn = self._readers.acquire(deadline)
547
+ try:
548
+ yield conn
549
+ finally:
550
+ self._readers.release(conn)
551
+
508
552
  def count(self):
509
- with self._lock:
510
- return self._db.execute("SELECT COUNT(*) FROM memories").fetchone()[0]
553
+ return _sqlfile.count(self._read)
511
554
 
512
555
  def items(self):
513
556
  """Iterate (ref, text, date) over everything stored, oldest first."""
557
+ return _sqlfile.items(self._read)
558
+
559
+ # ------------------------------------------------------------ audiences
560
+
561
+ @property
562
+ def checks_audience(self):
563
+ """True once the store was stamped (stamp_audience, set_audience): the recall stage
564
+ `record_audience` then reads the audience of each record. A record without one counts as "owner"."""
565
+ return self._stamped
566
+
567
+ def stamp_audience(self, level):
568
+ """The first time it is called on a store: give every memory without an audience `level` and
569
+ remember that the store was stamped (info row `audience_stamp`). Later calls do nothing. Only a
570
+ writable store that has the field columns can be stamped; on any other this does nothing. Returns
571
+ how many memories got the level."""
572
+ _sqlfile.check_level(level)
573
+ if self._stamped or not (self.writable and self._stored):
574
+ return 0
514
575
  with self._lock:
515
- rows = self._db.execute("SELECT ref, text, date FROM memories ORDER BY created_at, ref").fetchall()
516
- return iter(rows)
576
+ if self._stamped:
577
+ return 0
578
+ changed = _sqlfile.stamp(self._db, level)
579
+ self._stamped = True
580
+ return changed
581
+
582
+ def set_audience(self, level, only_missing=True):
583
+ """Give the memories `level` as their audience: only those without one (`only_missing`), or every
584
+ memory. Also marks the store stamped. Returns how many memories changed; 0, and nothing done, on a
585
+ store that is read-only or has no field columns."""
586
+ _sqlfile.check_level(level)
587
+ if not (self.writable and self._stored):
588
+ return 0
589
+ with self._lock:
590
+ changed = _sqlfile.restamp(self._db, level, only_missing)
591
+ self._stamped = True
592
+ return changed
593
+
594
+ def records(self):
595
+ """Iterate {"ref", "text", "date", "fields"} over everything stored, in the order of items()."""
596
+ return iter(_sqlfile.record_rows(self._read, self._stored))
597
+
598
+ def record(self, ref):
599
+ """{"ref", "text", "date", "fields"} of one memory; KeyError when it is not stored."""
600
+ rows = _sqlfile.record_rows(self._read, self._stored, ref)
601
+ if not rows:
602
+ raise KeyError(ref)
603
+ return rows[0]
517
604
 
518
605
  def refs(self):
519
606
  """Iterate (ref, date or None) over every memory, ordered by ref, without texts or vectors.
520
- Read in batches by key with the lock released in between, so deleting while iterating is safe."""
521
- last = None
522
- while True:
523
- with self._lock:
524
- if last is None:
525
- rows = self._db.execute("SELECT ref, date FROM memories ORDER BY ref LIMIT ?",
526
- (SCAN_BATCH,)).fetchall()
527
- else:
528
- rows = self._db.execute("SELECT ref, date FROM memories WHERE ref > ? ORDER BY ref LIMIT ?",
529
- (last, SCAN_BATCH)).fetchall()
530
- for row in rows:
531
- yield row[0], row[1]
532
- if len(rows) < SCAN_BATCH:
533
- return
534
- last = rows[-1][0]
607
+ Read in batches by key with the connection released in between, so deleting while iterating is safe."""
608
+ yield from _sqlfile.iter_refs(self._read, SCAN_BATCH)
535
609
 
536
610
  def receipt_refs(self, receipt):
537
611
  """The refs remember() stored for `receipt` (named "<receipt>-<index>"); a memory deleted since is absent."""
538
- if not isinstance(receipt, str) or not receipt:
539
- return None
540
- prefix = receipt + "-"
541
- with self._lock:
542
- rows = self._db.execute(
543
- "SELECT ref FROM memories WHERE substr(ref, 1, ?) = ? ORDER BY ref", (len(prefix), prefix)
544
- ).fetchall()
545
- return [r[0] for r in rows]
612
+ return _sqlfile.receipt_refs(self._read, receipt)
546
613
 
547
614
  def read(self, ref, timeout=None, ctl=None):
548
- with self._lock:
549
- row = self._db.execute("SELECT text FROM memories WHERE ref = ?", (ref,)).fetchone()
615
+ with self._read() as db:
616
+ row = db.execute("SELECT text FROM memories WHERE ref = ?", (ref,)).fetchone()
550
617
  if row is None:
551
618
  raise KeyError(ref)
552
619
  return row[0]
553
620
 
554
- def _snapshot(self):
555
- """[(ref, vector)] of the whole store. Loads the cache on first use and again when
556
- another connection has written since."""
557
- with self._lock:
558
- version = self._db.execute("PRAGMA data_version").fetchone()[0]
559
- if self._vectors is None or version != self._data_version:
560
- self._vectors = {
561
- ref: _blob_to_vector(blob) for ref, blob in self._db.execute("SELECT ref, vector FROM memories")
562
- }
563
- self._data_version = version
564
- return list(self._vectors.items())
621
+ def _current(self, generation):
622
+ """[(ref, vector)] from the cache when it is at `generation` or newer, else None."""
623
+ with self._cache_lock:
624
+ if self._vectors is not None and self._generation >= generation:
625
+ return list(self._vectors.items())
626
+ return None
627
+
628
+ def _snapshot(self, deadline=None):
629
+ """[(ref, vector)] of the whole store. Loads the cache on first use and again when another writer
630
+ has written since (see the module docstring); the load runs on a reader connection, without the
631
+ writer's lock, and one search loads while the others wait for it."""
632
+ with self._read(deadline) as db:
633
+ generation = _generation(db)
634
+ found = self._current(generation)
635
+ if found is not None:
636
+ return found
637
+ with self._load_lock:
638
+ found = self._current(generation) # the search that held the load lock did it
639
+ if found is not None:
640
+ return found
641
+ with self._read(deadline) as db:
642
+ db.execute("BEGIN") # one snapshot for the counter and the vectors
643
+ try:
644
+ loaded_at = _generation(db)
645
+ loaded = {ref: _blob_to_vector(blob)
646
+ for ref, blob in db.execute("SELECT ref, vector FROM memories")}
647
+ finally:
648
+ db.rollback()
649
+ with self._cache_lock:
650
+ if self._closed:
651
+ raise BackendError("the store is closed")
652
+ if self._vectors is None or loaded_at > self._generation:
653
+ self._vectors, self._generation = loaded, loaded_at
654
+ return list(self._vectors.items())
565
655
 
566
656
  def _score(self, cosine):
567
- return min(1.0, max(0.0, (cosine - self.floor) / (self.ceil - self.floor)))
657
+ return clamp01((cosine - self.floor) / (self.ceil - self.floor))
568
658
 
569
659
  def find(self, query, limit, timeout=None, ctl=None):
570
660
  """Up to `limit` hits, best first; memories at or below `floor` cosine are left out.
@@ -574,7 +664,7 @@ class EmbeddingBackend(MemoryBackend):
574
664
  if not isinstance(query, str) or not query.strip() or limit < 1:
575
665
  return []
576
666
  qvec = self._query_vector(query, total, ctl)
577
- snapshot = self._snapshot()
667
+ snapshot = self._snapshot(deadline)
578
668
  if snapshot and len(snapshot[0][1]) != len(qvec):
579
669
  raise BackendError("embedding size differs from the store")
580
670
  scored = []
@@ -583,14 +673,7 @@ class EmbeddingBackend(MemoryBackend):
583
673
  raise BackendError("deadline exceeded")
584
674
  for ref, vec in snapshot[start:start + SCORE_CHECK_EVERY]:
585
675
  scored.append((_sumprod(qvec, vec), ref))
586
- best = [(c, r) for c, r in heapq.nlargest(limit, scored) if self._score(c) > 0.0]
587
- texts = self._texts([r for _, r in best])
588
- hits = []
589
- for cosine, ref in best:
590
- if ref in texts: # deleted by another connection between scan and fetch: skip
591
- text, date = texts[ref]
592
- hits.append(_make_hit(ref, self._score(cosine), text, date, cosine))
593
- return hits
676
+ return self._top_hits(scored, limit, deadline)
594
677
 
595
678
  def neighbours(self, ref, limit, timeout=None, ctl=None):
596
679
  """Up to `limit` memories most similar to the stored memory `ref`, best first, never `ref` itself.
@@ -611,7 +694,7 @@ class EmbeddingBackend(MemoryBackend):
611
694
  raise BackendError("cancelled")
612
695
 
613
696
  check()
614
- snapshot = self._snapshot()
697
+ snapshot = self._snapshot(deadline)
615
698
  own = next((vec for key, vec in snapshot if key == ref), None)
616
699
  if own is None:
617
700
  return []
@@ -621,24 +704,29 @@ class EmbeddingBackend(MemoryBackend):
621
704
  for key, vec in snapshot[start:start + SCORE_CHECK_EVERY]:
622
705
  if key != ref and len(vec) == len(own):
623
706
  scored.append((_sumprod(own, vec), key))
707
+ return self._top_hits(scored, limit, deadline)
708
+
709
+ def _top_hits(self, scored, limit, deadline=None):
710
+ """The `limit` best of `scored` ([(cosine, ref)]) above the floor, as hits with their text."""
624
711
  best = [(c, r) for c, r in heapq.nlargest(limit, scored) if self._score(c) > 0.0]
625
- texts = self._texts([r for _, r in best])
712
+ texts = self._texts([r for _, r in best], deadline)
626
713
  hits = []
627
- for cosine, key in best:
628
- if key in texts: # deleted by another connection between scan and fetch: skip
629
- text, date = texts[key]
630
- hits.append(_make_hit(key, self._score(cosine), text, date, cosine))
714
+ for cosine, ref in best:
715
+ if ref in texts: # deleted by another connection between scan and fetch: skip
716
+ text, date, fields = texts[ref]
717
+ hits.append(make_hit(ref, self._score(cosine), text, date, {"cosine": cosine}, fields))
631
718
  return hits
632
719
 
633
- def _texts(self, refs):
720
+ def _texts(self, refs, deadline=None):
634
721
  out = {}
635
- with self._lock:
722
+ with self._read(deadline) as db:
636
723
  for start in range(0, len(refs), SCAN_BATCH):
637
724
  chunk = refs[start:start + SCAN_BATCH]
638
- for ref, text, date in self._db.execute(
639
- "SELECT ref, text, date FROM memories WHERE ref IN (%s)" % ",".join("?" * len(chunk)), chunk
725
+ for ref, text, date, *values in db.execute(
726
+ "SELECT ref, text, date%s FROM memories WHERE ref IN (%s)"
727
+ % (_sqlfile.field_columns(self._stored), ",".join("?" * len(chunk))), chunk
640
728
  ):
641
- out[ref] = (text, date)
729
+ out[ref] = (text, date, _sqlfile.fields_of(values))
642
730
  return out
643
731
 
644
732
  # ------------------------------------------------------------ lifecycle
@@ -646,12 +734,8 @@ class EmbeddingBackend(MemoryBackend):
646
734
  def health(self, timeout=2.0):
647
735
  """True when the store is open and readable. The embeddings endpoint is not called."""
648
736
  try:
649
- if not self._lock.acquire(timeout=max(0.0, float(timeout))):
650
- return False
651
- try:
652
- return not self._closed and self._db.execute("SELECT 1").fetchone()[0] == 1
653
- finally:
654
- self._lock.release()
737
+ with self._read(time.monotonic() + max(0.0, float(timeout))) as db:
738
+ return not self._closed and db.execute("SELECT 1").fetchone()[0] == 1
655
739
  except Exception: # noqa: BLE001 - health never raises
656
740
  return False
657
741
 
@@ -660,5 +744,8 @@ class EmbeddingBackend(MemoryBackend):
660
744
  if self._closed:
661
745
  return
662
746
  self._closed = True
663
- self._vectors = None
664
747
  self._db.close()
748
+ with self._cache_lock:
749
+ self._vectors = None
750
+ if self._readers is not None:
751
+ self._readers.close()