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.
- package/CHANGELOG.md +73 -12
- package/README.md +68 -11
- package/README.zh.md +93 -36
- package/client/README.md +267 -0
- package/client/art/mascot-asleep.webp +0 -0
- package/client/art/mascot-busy.webp +0 -0
- package/client/art/mascot-nag.webp +0 -0
- package/client/art/mascot-ready.webp +0 -0
- package/client/art/mascot-trouble.webp +0 -0
- package/client/client.js +4226 -1269
- package/client/src/clipboard.cjs +52 -0
- package/client/src/constants.cjs +43 -0
- package/client/src/fields.cjs +960 -0
- package/client/src/hooks.cjs +220 -0
- package/client/src/i18n.cjs +444 -0
- package/client/src/index.cjs +69 -0
- package/client/src/kit/controls.cjs +189 -0
- package/client/src/kit/icons.cjs +40 -0
- package/client/src/kit/layout.cjs +124 -0
- package/client/src/layout.cjs +143 -0
- package/client/src/model/changelog.cjs +29 -0
- package/client/src/model/feedback.cjs +168 -0
- package/client/src/model/form.cjs +83 -0
- package/client/src/model/models.cjs +87 -0
- package/client/src/model/overview.cjs +111 -0
- package/client/src/model/page.cjs +104 -0
- package/client/src/model/status.cjs +57 -0
- package/client/src/model/trial.cjs +111 -0
- package/client/src/net.cjs +101 -0
- package/client/src/react.cjs +11 -0
- package/client/src/theme/page.css +1284 -0
- package/client/src/theme/styles.cjs +43 -0
- package/client/src/view/feedback.cjs +180 -0
- package/client/src/view/field-row.cjs +98 -0
- package/client/src/view/hero.cjs +54 -0
- package/client/src/view/markdown.cjs +96 -0
- package/client/src/view/models.cjs +154 -0
- package/client/src/view/page.cjs +199 -0
- package/client/src/view/settings-tab.cjs +78 -0
- package/client/src/view/tabs.cjs +71 -0
- package/client/src/view/trial.cjs +84 -0
- package/docs/DETAIL.en.md +55 -6
- package/docs/DETAIL.md +63 -14
- package/locale/zh.json +1 -1
- package/package.json +2 -1
- package/python/GATEWAY_VERSION.json +37 -31
- package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
- package/python/feiyu_memgate/backends/base.py +121 -6
- package/python/feiyu_memgate/backends/embedding.py +265 -178
- package/python/feiyu_memgate/backends/hybrid.py +330 -83
- package/python/feiyu_memgate/backends/inmemory.py +115 -24
- package/python/feiyu_memgate/backends/openviking.py +7 -10
- package/python/feiyu_memgate/backends/sqlite.py +129 -145
- package/python/feiyu_memgate/builtins.py +1 -0
- package/python/feiyu_memgate/cli.py +124 -20
- package/python/feiyu_memgate/client/block.py +4 -2
- package/python/feiyu_memgate/client/http.py +106 -19
- package/python/feiyu_memgate/client/local.py +4 -3
- package/python/feiyu_memgate/config.py +118 -24
- package/python/feiyu_memgate/core/limits.py +2 -1
- package/python/feiyu_memgate/core/pool.py +29 -2
- package/python/feiyu_memgate/core/recall.py +179 -10
- package/python/feiyu_memgate/core/redact.py +4 -2
- package/python/feiyu_memgate/core/stages.py +52 -9
- package/python/feiyu_memgate/core/tidy.py +2 -1
- package/python/feiyu_memgate/core/watch.py +3 -2
- package/python/feiyu_memgate/core/write.py +9 -3
- package/python/feiyu_memgate/forgetting/archive.py +38 -10
- package/python/feiyu_memgate/forgetting/engine.py +46 -10
- package/python/feiyu_memgate/forgetting/stage.py +4 -2
- package/python/feiyu_memgate/gateway/app.py +168 -272
- package/python/feiyu_memgate/gateway/fields.py +121 -0
- package/python/feiyu_memgate/gateway/policies.py +162 -0
- package/python/feiyu_memgate/gateway/server.py +12 -4
- package/python/feiyu_memgate/gateway/tokens.py +137 -0
- package/python/feiyu_memgate/gateway/validate.py +120 -0
- package/python/feiyu_memgate/identity.py +152 -0
- package/python/feiyu_memgate/model.py +170 -2
- package/python/feiyu_memgate/registry.py +6 -3
- package/python/feiyu_memgate/tools/crypto.py +5 -4
- package/python/feiyu_memgate/tools/evaluate.py +2 -1
- package/python/feiyu_memgate/tools/tenants.py +2 -0
- package/src/block.js +9 -3
- package/src/capture.js +98 -0
- package/src/catalogue.js +4 -4
- package/src/changelog.js +72 -0
- package/src/client.js +145 -10
- package/src/commands.js +112 -62
- package/src/config.js +139 -62
- package/src/followup.js +139 -0
- package/src/gateway.js +79 -4
- package/src/migrate.py +54 -9
- package/src/mirror.py +44 -7
- package/src/plugin.js +416 -412
- package/src/pool.js +298 -0
- package/src/recent.js +68 -0
- package/src/relevance.js +80 -0
- package/src/routes.js +320 -0
- package/src/setup.js +36 -36
- package/src/shared.js +77 -0
- package/src/tiers.js +4 -4
- package/src/time.js +27 -0
- package/src/tools.js +164 -0
|
@@ -38,48 +38,51 @@ above DF_PROBE memories); the store size N in the weights is the exact row count
|
|
|
38
38
|
Index versions: stores written before CJK single characters were indexed hold bigrams only. A
|
|
39
39
|
writable open rebuilds the index once (a pass over the stored texts); a read-only open of such a
|
|
40
40
|
file keeps working on bigrams alone.
|
|
41
|
+
|
|
42
|
+
Record fields: the `memories` table also has a nullable TEXT column for each of model.FIELDS (speaker,
|
|
43
|
+
about, channel, audience, origin, event_date, kind). `put` and the messages of `remember` (key "fields")
|
|
44
|
+
may carry them; `find` returns them in `Hit.fields`, `records()` / `record(ref)` return them with
|
|
45
|
+
the memory. A store made before they existed gets the columns when it is opened writable (and `info`
|
|
46
|
+
record_version "2"); opened read-only it is left alone, answers without fields and `stores_fields` is
|
|
47
|
+
False. Today's `INSERT OR REPLACE INTO memories (ref, text, created_at, date) ...` still works on the new
|
|
48
|
+
table (the row then has no fields).
|
|
49
|
+
|
|
50
|
+
Audiences: `stamp_audience(level)` gives every memory without an audience `level` the first time it is called
|
|
51
|
+
and records that in `info` (row `audience_stamp`); from then on `checks_audience` is True and the `record_audience`
|
|
52
|
+
recall stage drops a memory narrower than its client, a memory without an audience counting as "owner".
|
|
53
|
+
`set_audience(level, only_missing)` is the deliberate way to change it later (the `restamp` command).
|
|
41
54
|
"""
|
|
42
55
|
import contextlib
|
|
43
56
|
import json
|
|
44
|
-
import os
|
|
45
57
|
import sqlite3
|
|
46
58
|
import threading
|
|
47
59
|
import time
|
|
48
|
-
import
|
|
49
|
-
from datetime import datetime, timezone
|
|
60
|
+
from typing import Any
|
|
50
61
|
|
|
51
62
|
from ..core.tidy import PreparedQuery, gram_weights, index_grams, normalize
|
|
52
63
|
from ..errors import BackendError
|
|
53
|
-
from ..model import Hit
|
|
64
|
+
from ..model import Hit, clean_fields
|
|
54
65
|
from ..registry import register
|
|
55
|
-
from .
|
|
66
|
+
from . import _sqlfile
|
|
67
|
+
from ._sqlfile import SCAN_BATCH
|
|
68
|
+
from ._sqlfile import Readers as _Readers # noqa: F401 - the pool lives in _sqlfile, shared with the embedding backend
|
|
69
|
+
from .base import (DEFAULT_BUDGET, MemoryBackend, as_roles, message_date, message_fields, new_receipt, new_ref,
|
|
70
|
+
receipt_ref, require_writable)
|
|
71
|
+
from .base import today as _today
|
|
56
72
|
|
|
57
|
-
DEFAULT_BUDGET = 10.0 # seconds for one find() when the caller gives none
|
|
58
73
|
MAX_QUERY_GRAMS = 600 # distinct query grams looked at (their document frequency is probed)
|
|
59
74
|
DF_PROBE = 500 # document frequency is counted up to this many postings per gram
|
|
60
|
-
SCAN_BATCH = 500
|
|
61
75
|
SCORE_BATCH = 200 # memories fetched per step while scoring (the deadline is checked between steps)
|
|
62
76
|
PROGRESS_OPS = 20000 # SQLite virtual-machine steps between two looks at the deadline
|
|
63
77
|
|
|
64
|
-
_SCHEMA = """
|
|
65
|
-
CREATE TABLE IF NOT EXISTS memories (
|
|
66
|
-
ref TEXT PRIMARY KEY,
|
|
67
|
-
text TEXT NOT NULL,
|
|
68
|
-
created_at INTEGER NOT NULL,
|
|
69
|
-
date TEXT
|
|
70
|
-
);
|
|
71
|
-
CREATE TABLE IF NOT EXISTS grams (
|
|
78
|
+
_SCHEMA = _sqlfile.memories_table() + """CREATE TABLE IF NOT EXISTS grams (
|
|
72
79
|
gram TEXT NOT NULL,
|
|
73
80
|
ref TEXT NOT NULL,
|
|
74
81
|
PRIMARY KEY (gram, ref)
|
|
75
82
|
) WITHOUT ROWID;
|
|
76
83
|
CREATE INDEX IF NOT EXISTS grams_by_ref ON grams (ref);
|
|
77
84
|
CREATE INDEX IF NOT EXISTS memories_by_created ON memories (created_at);
|
|
78
|
-
|
|
79
|
-
key TEXT PRIMARY KEY,
|
|
80
|
-
value TEXT NOT NULL
|
|
81
|
-
);
|
|
82
|
-
"""
|
|
85
|
+
""" + _sqlfile.INFO_TABLE
|
|
83
86
|
# What the grams table holds: "1" bigrams only (stores of older versions), "2" bigrams and CJK unigrams.
|
|
84
87
|
GRAM_SCHEME = "2"
|
|
85
88
|
|
|
@@ -89,63 +92,6 @@ GRAM_SCHEME = "2"
|
|
|
89
92
|
# interval. One row per statement keeps parallel searches parallel.
|
|
90
93
|
|
|
91
94
|
|
|
92
|
-
def _today():
|
|
93
|
-
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
class _Readers:
|
|
97
|
-
"""A bounded pool of read-only connections. Many searches run at once; none waits for another
|
|
98
|
-
one's SQL (WAL lets readers run beside the writer). Closed with the backend."""
|
|
99
|
-
|
|
100
|
-
def __init__(self, connect, maximum):
|
|
101
|
-
self._connect = connect
|
|
102
|
-
self._max = max(1, int(maximum))
|
|
103
|
-
self._cond = threading.Condition()
|
|
104
|
-
self._free = []
|
|
105
|
-
self._made = 0
|
|
106
|
-
self._closed = False
|
|
107
|
-
|
|
108
|
-
def acquire(self, deadline):
|
|
109
|
-
with self._cond:
|
|
110
|
-
while True:
|
|
111
|
-
if self._closed:
|
|
112
|
-
raise BackendError("the store is closed")
|
|
113
|
-
if self._free:
|
|
114
|
-
return self._free.pop()
|
|
115
|
-
if self._made < self._max:
|
|
116
|
-
self._made += 1
|
|
117
|
-
break
|
|
118
|
-
left = deadline - time.monotonic()
|
|
119
|
-
if left <= 0:
|
|
120
|
-
raise BackendError("no free read connection in time")
|
|
121
|
-
self._cond.wait(left)
|
|
122
|
-
try:
|
|
123
|
-
return self._connect()
|
|
124
|
-
except Exception:
|
|
125
|
-
with self._cond:
|
|
126
|
-
self._made -= 1
|
|
127
|
-
self._cond.notify()
|
|
128
|
-
raise
|
|
129
|
-
|
|
130
|
-
def release(self, conn):
|
|
131
|
-
with self._cond:
|
|
132
|
-
if not self._closed:
|
|
133
|
-
self._free.append(conn)
|
|
134
|
-
self._cond.notify()
|
|
135
|
-
return
|
|
136
|
-
self._made -= 1
|
|
137
|
-
conn.close() # the store was closed while this one was in use
|
|
138
|
-
|
|
139
|
-
def close(self):
|
|
140
|
-
with self._cond:
|
|
141
|
-
self._closed = True
|
|
142
|
-
free, self._free = self._free, []
|
|
143
|
-
self._made -= len(free)
|
|
144
|
-
self._cond.notify_all()
|
|
145
|
-
for conn in free:
|
|
146
|
-
conn.close()
|
|
147
|
-
|
|
148
|
-
|
|
149
95
|
class _Run:
|
|
150
96
|
"""The deadline and cancellation of one find(), as the SQL progress handler and the scoring
|
|
151
97
|
loop see them."""
|
|
@@ -192,11 +138,13 @@ class SQLiteBackend(MemoryBackend):
|
|
|
192
138
|
# (--search --profile broad): precision >= 50 % and half of the default's quiet rate, best deployed hit.
|
|
193
139
|
broad_min_score = 0.25
|
|
194
140
|
broad_relative_ratio = 0.70
|
|
141
|
+
# Keeps the record fields (see the module docstring); an instance over an old file it may not upgrade
|
|
142
|
+
# (read-only) sets it False.
|
|
143
|
+
stores_fields = True
|
|
195
144
|
|
|
196
145
|
def __init__(self, path, writable=True, roles=("user",), max_candidates=2000, max_postings=20000,
|
|
197
146
|
max_readers=16):
|
|
198
|
-
|
|
199
|
-
roles = (roles,)
|
|
147
|
+
roles = as_roles(roles)
|
|
200
148
|
self.writable = bool(writable)
|
|
201
149
|
self.roles = tuple(roles)
|
|
202
150
|
self.max_candidates = max(1, int(max_candidates))
|
|
@@ -205,16 +153,11 @@ class SQLiteBackend(MemoryBackend):
|
|
|
205
153
|
self._shared = self._path == ":memory:" # one connection for everything
|
|
206
154
|
self._lock = threading.Lock() # the writer (and, for ":memory:", every reader)
|
|
207
155
|
self._closed = False
|
|
208
|
-
|
|
209
|
-
parent = os.path.dirname(os.path.abspath(self._path))
|
|
210
|
-
os.makedirs(parent, exist_ok=True)
|
|
211
|
-
self._db = sqlite3.connect(self._path, check_same_thread=False, timeout=10.0)
|
|
156
|
+
self._db = _sqlfile.open_store(self._path, _SCHEMA)
|
|
212
157
|
try:
|
|
213
|
-
if not self._shared:
|
|
214
|
-
self._db.execute("PRAGMA journal_mode=WAL")
|
|
215
|
-
self._db.executescript(_SCHEMA)
|
|
216
|
-
self._db.commit()
|
|
217
158
|
self._unigrams = self._open_scheme()
|
|
159
|
+
self.stores_fields = self._stored = _sqlfile.ensure_fields(self._db, self.writable)
|
|
160
|
+
self._stamped = self._stored and _sqlfile.is_stamped(self._db)
|
|
218
161
|
except Exception:
|
|
219
162
|
self._db.close()
|
|
220
163
|
raise
|
|
@@ -245,13 +188,7 @@ class SQLiteBackend(MemoryBackend):
|
|
|
245
188
|
[(g, ref) for ref, text in rows[start:start + SCAN_BATCH] for g in index_grams(normalize(text))])
|
|
246
189
|
|
|
247
190
|
def _open_reader(self):
|
|
248
|
-
|
|
249
|
-
try:
|
|
250
|
-
conn.execute("PRAGMA query_only=ON")
|
|
251
|
-
except Exception:
|
|
252
|
-
conn.close()
|
|
253
|
-
raise
|
|
254
|
-
return conn
|
|
191
|
+
return _sqlfile.open_reader(self._path)
|
|
255
192
|
|
|
256
193
|
@contextlib.contextmanager
|
|
257
194
|
def _read(self, deadline=None):
|
|
@@ -268,6 +205,7 @@ class SQLiteBackend(MemoryBackend):
|
|
|
268
205
|
finally:
|
|
269
206
|
self._lock.release()
|
|
270
207
|
return
|
|
208
|
+
assert self._readers is not None # None only for the shared in-memory store, handled above
|
|
271
209
|
conn = self._readers.acquire(deadline)
|
|
272
210
|
try:
|
|
273
211
|
yield conn
|
|
@@ -276,27 +214,31 @@ class SQLiteBackend(MemoryBackend):
|
|
|
276
214
|
|
|
277
215
|
# ------------------------------------------------------------ writing
|
|
278
216
|
|
|
279
|
-
def put(self, text, ref=None, date=None):
|
|
217
|
+
def put(self, text, ref=None, date=None, fields=None):
|
|
280
218
|
"""Store one memory text as it is and return its ref. An existing ref is replaced
|
|
281
|
-
together with its index rows."""
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
ref = ref or
|
|
219
|
+
together with its index rows and its fields (a put without fields clears them)."""
|
|
220
|
+
require_writable(self)
|
|
221
|
+
fields = clean_fields(fields)
|
|
222
|
+
ref = ref or new_ref()
|
|
285
223
|
grams = [(g, ref) for g in index_grams(normalize(text), self._unigrams)]
|
|
286
224
|
with self._lock:
|
|
287
225
|
with self._db: # one transaction: a memory and its index rows go together
|
|
288
226
|
self._db.execute("DELETE FROM grams WHERE ref = ?", (ref,))
|
|
289
|
-
self.
|
|
290
|
-
"INSERT OR REPLACE INTO memories (ref, text, created_at, date) VALUES (?, ?, ?, ?)",
|
|
291
|
-
(ref, text, int(time.time()), date),
|
|
292
|
-
)
|
|
227
|
+
self._insert(ref, text, int(time.time()), date, fields)
|
|
293
228
|
self._db.executemany("INSERT OR IGNORE INTO grams (gram, ref) VALUES (?, ?)", grams)
|
|
294
229
|
return ref
|
|
295
230
|
|
|
231
|
+
def _insert(self, ref, text, created_at, date, fields):
|
|
232
|
+
"""Write one memory row, with its fields (inside the caller's transaction and lock)."""
|
|
233
|
+
self._db.execute(
|
|
234
|
+
"INSERT OR REPLACE INTO memories (ref, text, created_at, date, %s) VALUES (?, ?, ?, ?, %s)"
|
|
235
|
+
% (_sqlfile.FIELD_LIST, _sqlfile.FIELD_MARKS),
|
|
236
|
+
(ref, text, created_at, date) + _sqlfile.field_values(fields),
|
|
237
|
+
)
|
|
238
|
+
|
|
296
239
|
def delete(self, ref):
|
|
297
240
|
"""Remove one memory and its index rows. True when it existed."""
|
|
298
|
-
|
|
299
|
-
raise PermissionError("this backend is read-only")
|
|
241
|
+
require_writable(self)
|
|
300
242
|
with self._lock:
|
|
301
243
|
with self._db:
|
|
302
244
|
self._db.execute("DELETE FROM grams WHERE ref = ?", (ref,))
|
|
@@ -305,61 +247,65 @@ class SQLiteBackend(MemoryBackend):
|
|
|
305
247
|
|
|
306
248
|
def remember(self, messages, timeout=None, ctl=None):
|
|
307
249
|
"""Keep the messages whose role is in `roles`; returns the receipt id, or None when
|
|
308
|
-
no message qualified (nothing was kept, so there is no receipt for it).
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
250
|
+
no message qualified (nothing was kept, so there is no receipt for it).
|
|
251
|
+
|
|
252
|
+
All or nothing: every row is prepared first, then one transaction stores them all. A failure,
|
|
253
|
+
or a caller that has given up (`ctl.cancelled`) when the write is about to commit, leaves
|
|
254
|
+
the store exactly as it was (BackendError for the cancelled call)."""
|
|
255
|
+
require_writable(self)
|
|
256
|
+
receipt = new_receipt()
|
|
312
257
|
today = _today()
|
|
313
|
-
|
|
258
|
+
rows = [] # (ref, text, date, gram rows, fields)
|
|
314
259
|
for index, message in enumerate(messages):
|
|
315
260
|
if message["role"] in self.roles:
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
261
|
+
ref = receipt_ref(receipt, index)
|
|
262
|
+
text = message["content"]
|
|
263
|
+
grams = [(g, ref) for g in index_grams(normalize(text), self._unigrams)]
|
|
264
|
+
rows.append((ref, text, message_date(message, today), grams, message_fields(message)))
|
|
265
|
+
if not rows:
|
|
266
|
+
return None
|
|
267
|
+
now = int(time.time())
|
|
268
|
+
with self._lock:
|
|
269
|
+
with self._db: # one transaction for every memory and its index rows
|
|
270
|
+
for ref, text, date, grams, fields in rows:
|
|
271
|
+
self._db.execute("DELETE FROM grams WHERE ref = ?", (ref,))
|
|
272
|
+
self._insert(ref, text, now, date, fields)
|
|
273
|
+
self._db.executemany("INSERT OR IGNORE INTO grams (gram, ref) VALUES (?, ?)", grams)
|
|
274
|
+
if ctl is not None and ctl.cancelled:
|
|
275
|
+
raise BackendError("cancelled") # leaving the block rolls everything back
|
|
276
|
+
return receipt
|
|
319
277
|
|
|
320
278
|
# ------------------------------------------------------------ reading
|
|
321
279
|
|
|
322
280
|
def count(self):
|
|
323
|
-
|
|
324
|
-
return db.execute("SELECT COUNT(*) FROM memories").fetchone()[0]
|
|
281
|
+
return _sqlfile.count(self._read)
|
|
325
282
|
|
|
326
283
|
def items(self):
|
|
327
284
|
"""Iterate (ref, text, date) over everything stored, oldest first."""
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
285
|
+
return _sqlfile.items(self._read)
|
|
286
|
+
|
|
287
|
+
def records(self):
|
|
288
|
+
"""Iterate {"ref", "text", "date", "fields"} over everything stored, in the order of items()."""
|
|
289
|
+
return iter(_sqlfile.record_rows(self._read, self._stored))
|
|
290
|
+
|
|
291
|
+
def record(self, ref):
|
|
292
|
+
"""{"ref", "text", "date", "fields"} of one memory; KeyError when it is not stored."""
|
|
293
|
+
rows = _sqlfile.record_rows(self._read, self._stored, ref)
|
|
294
|
+
if not rows:
|
|
295
|
+
raise KeyError(ref)
|
|
296
|
+
return rows[0]
|
|
331
297
|
|
|
332
298
|
def refs(self):
|
|
333
299
|
"""Iterate (ref, date or None) over every memory, ordered by ref, without texts.
|
|
334
300
|
|
|
335
301
|
Read in batches by key, the connection is released between them, so a big store is never
|
|
336
302
|
held in memory and deleting while iterating is safe."""
|
|
337
|
-
|
|
338
|
-
while True:
|
|
339
|
-
with self._read() as db:
|
|
340
|
-
if last is None:
|
|
341
|
-
rows = db.execute("SELECT ref, date FROM memories ORDER BY ref LIMIT ?", (SCAN_BATCH,)).fetchall()
|
|
342
|
-
else:
|
|
343
|
-
rows = db.execute(
|
|
344
|
-
"SELECT ref, date FROM memories WHERE ref > ? ORDER BY ref LIMIT ?", (last, SCAN_BATCH)
|
|
345
|
-
).fetchall()
|
|
346
|
-
for row in rows:
|
|
347
|
-
yield row[0], row[1]
|
|
348
|
-
if len(rows) < SCAN_BATCH:
|
|
349
|
-
return
|
|
350
|
-
last = rows[-1][0]
|
|
303
|
+
yield from _sqlfile.iter_refs(self._read, SCAN_BATCH)
|
|
351
304
|
|
|
352
305
|
def receipt_refs(self, receipt):
|
|
353
306
|
"""The refs remember() stored for `receipt` (it names them "<receipt>-<index>").
|
|
354
307
|
Only the messages it kept have one; a memory deleted since is absent."""
|
|
355
|
-
|
|
356
|
-
return None
|
|
357
|
-
prefix = receipt + "-"
|
|
358
|
-
with self._read() as db:
|
|
359
|
-
rows = db.execute(
|
|
360
|
-
"SELECT ref FROM memories WHERE substr(ref, 1, ?) = ? ORDER BY ref", (len(prefix), prefix)
|
|
361
|
-
).fetchall()
|
|
362
|
-
return [r[0] for r in rows]
|
|
308
|
+
return _sqlfile.receipt_refs(self._read, receipt)
|
|
363
309
|
|
|
364
310
|
def read(self, ref, timeout=None, ctl=None):
|
|
365
311
|
with self._read() as db:
|
|
@@ -417,7 +363,7 @@ class SQLiteBackend(MemoryBackend):
|
|
|
417
363
|
weight of the shared grams, the same thing the score is made of. The rarest gram is the one
|
|
418
364
|
with the greatest weight."""
|
|
419
365
|
weights = prepared.weights
|
|
420
|
-
shared = {}
|
|
366
|
+
shared: dict[Any, float] = {}
|
|
421
367
|
budget = self.max_postings
|
|
422
368
|
for gram in sorted(weights, key=lambda g: (-weights[g], g)):
|
|
423
369
|
if budget <= 0 or run.should_stop():
|
|
@@ -463,8 +409,8 @@ class SQLiteBackend(MemoryBackend):
|
|
|
463
409
|
chunk = refs[start:start + SCORE_BATCH]
|
|
464
410
|
try:
|
|
465
411
|
rows = json.loads(db.execute(
|
|
466
|
-
"SELECT json_group_array(json_array(ref, text, date)) FROM memories WHERE ref IN (%s)"
|
|
467
|
-
% ",".join("?" * len(chunk)), chunk
|
|
412
|
+
"SELECT json_group_array(json_array(ref, text, date%s)) FROM memories WHERE ref IN (%s)"
|
|
413
|
+
% (_sqlfile.field_columns(self._stored), ",".join("?" * len(chunk))), chunk
|
|
468
414
|
).fetchone()[0])
|
|
469
415
|
except sqlite3.OperationalError:
|
|
470
416
|
if run.cancelled:
|
|
@@ -472,16 +418,54 @@ class SQLiteBackend(MemoryBackend):
|
|
|
472
418
|
if run.time_up():
|
|
473
419
|
break
|
|
474
420
|
raise
|
|
475
|
-
for ref, text, date in rows:
|
|
421
|
+
for ref, text, date, *values in rows:
|
|
476
422
|
score = prepared.score(text)
|
|
477
423
|
if score > 0:
|
|
478
|
-
|
|
424
|
+
hit = Hit(ref=ref, score=score, text=text, date=date)
|
|
425
|
+
if values:
|
|
426
|
+
hit.fields = _sqlfile.fields_of(values)
|
|
427
|
+
hits.append(hit)
|
|
479
428
|
if run.should_stop():
|
|
480
429
|
break
|
|
481
430
|
if run.cancelled:
|
|
482
431
|
raise BackendError("cancelled")
|
|
483
432
|
return hits
|
|
484
433
|
|
|
434
|
+
# ------------------------------------------------------------ audiences
|
|
435
|
+
|
|
436
|
+
@property
|
|
437
|
+
def checks_audience(self):
|
|
438
|
+
"""True once the store was stamped (stamp_audience, set_audience): the recall stage
|
|
439
|
+
`record_audience` then reads the audience of each record. A record without one counts as "owner"."""
|
|
440
|
+
return self._stamped
|
|
441
|
+
|
|
442
|
+
def stamp_audience(self, level):
|
|
443
|
+
"""The first time it is called on a store: give every memory without an audience `level` and
|
|
444
|
+
remember that the store was stamped (info row `audience_stamp`). Later calls do nothing. Only a
|
|
445
|
+
writable store that has the field columns can be stamped; on any other this does nothing. Returns
|
|
446
|
+
how many memories got the level."""
|
|
447
|
+
_sqlfile.check_level(level)
|
|
448
|
+
if self._stamped or not (self.writable and self._stored):
|
|
449
|
+
return 0
|
|
450
|
+
with self._lock:
|
|
451
|
+
if self._stamped:
|
|
452
|
+
return 0
|
|
453
|
+
changed = _sqlfile.stamp(self._db, level)
|
|
454
|
+
self._stamped = True
|
|
455
|
+
return changed
|
|
456
|
+
|
|
457
|
+
def set_audience(self, level, only_missing=True):
|
|
458
|
+
"""Give the memories `level` as their audience: only those without one (`only_missing`), or every
|
|
459
|
+
memory. Also marks the store stamped. Returns how many memories changed; 0, and nothing done, on a
|
|
460
|
+
store that is read-only or has no field columns."""
|
|
461
|
+
_sqlfile.check_level(level)
|
|
462
|
+
if not (self.writable and self._stored):
|
|
463
|
+
return 0
|
|
464
|
+
with self._lock:
|
|
465
|
+
changed = _sqlfile.restamp(self._db, level, only_missing)
|
|
466
|
+
self._stamped = True
|
|
467
|
+
return changed
|
|
468
|
+
|
|
485
469
|
# ------------------------------------------------------------ lifecycle
|
|
486
470
|
|
|
487
471
|
def health(self, timeout=2.0):
|
|
@@ -2,4 +2,5 @@
|
|
|
2
2
|
from .backends import embedding, hybrid, inmemory, openviking, sqlite # noqa: F401
|
|
3
3
|
from .core import redact, stages, write # noqa: F401
|
|
4
4
|
from .forgetting import curve, stage # noqa: F401
|
|
5
|
+
from . import identity # noqa: F401
|
|
5
6
|
from .tenants import directory, keyfile # noqa: F401
|