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
|
@@ -20,12 +20,17 @@ One piece failing never takes the request down silently:
|
|
|
20
20
|
`return`) is a DROP with the note "bad-verdict:<class>";
|
|
21
21
|
- a stage whose prepare() raises fails the whole recall (StageError): there is no safe
|
|
22
22
|
way to go on without it.
|
|
23
|
+
|
|
24
|
+
An explained recall (ctx.trace, see Trace) runs the same steps and also records what became of
|
|
25
|
+
every candidate and which stage decided; it does not run the stages' finish(), so it counts as
|
|
26
|
+
no use. Without it nothing is recorded and nothing extra is done.
|
|
23
27
|
Each such note is also one "piece-error" log line, with names and exception types only.
|
|
24
28
|
|
|
25
29
|
Standard library only.
|
|
26
30
|
"""
|
|
27
31
|
import math
|
|
28
32
|
import time
|
|
33
|
+
from typing import Any
|
|
29
34
|
|
|
30
35
|
from ..model import Candidate, Hit
|
|
31
36
|
|
|
@@ -37,6 +42,8 @@ MAX_FETCH = 30
|
|
|
37
42
|
MAX_WAIT = 0.25 # the longest a call waits for a free worker
|
|
38
43
|
STAGE_SHARE = 0.2 # part of the deadline the finds leave to the stages...
|
|
39
44
|
MAX_STAGE_RESERVE = 0.5 # ...at most this many seconds
|
|
45
|
+
EXPLAIN_TEXT = 300 # characters of a candidate's text in an explained recall
|
|
46
|
+
EXPLAIN_MAX = 100 # candidates listed in an explained recall
|
|
40
47
|
|
|
41
48
|
# Outcomes of one pool call.
|
|
42
49
|
OK, BUSY, FAILED = "ok", "busy", "failed"
|
|
@@ -67,7 +74,7 @@ class RecallStage:
|
|
|
67
74
|
|
|
68
75
|
name = None
|
|
69
76
|
cheap = False
|
|
70
|
-
enforces = ()
|
|
77
|
+
enforces: tuple[str, ...] = ()
|
|
71
78
|
|
|
72
79
|
def prepare(self, candidates, ctx):
|
|
73
80
|
return candidates
|
|
@@ -89,11 +96,21 @@ class RecallContext:
|
|
|
89
96
|
tenant_source the name of the tenants provider whose store is part of this request
|
|
90
97
|
(None when there is none): a candidate from that source belongs to tenant_id
|
|
91
98
|
public True when the answer is shown to other people
|
|
99
|
+
audience who sees the answer: the client's reach, "owner", "group" or "public"
|
|
100
|
+
show_fields the record fields (model.FIELDS) the answer adds to each item (the client's `fields`)
|
|
101
|
+
person who is asking, as the identity table resolves the request's "speaker": a person's name, or
|
|
102
|
+
"anon:" and a code for an account nobody listed; None when the request named no speaker
|
|
103
|
+
(and always without an identity table). No built-in stage uses it
|
|
104
|
+
history the request's optional "history" (already checked): up to 6 recent turns, a list of
|
|
105
|
+
{"role": "user" or "assistant", "content": str} dicts, [] when the request has none. It is
|
|
106
|
+
an entry for stages someone writes: no built-in stage reads it, it is not stored and not
|
|
107
|
+
logged, and the answer of a request does not depend on it
|
|
92
108
|
redact the text cleaner chosen for this client (str -> str)
|
|
93
109
|
context the request's optional "context" object (small, already checked)
|
|
94
110
|
accepted the candidates kept so far, in order
|
|
95
111
|
notes words for the access log (reasons only, never content)
|
|
96
112
|
state a dict for the stages' own per-request state
|
|
113
|
+
trace a Trace when the request is an explained recall (trace=True), else None
|
|
97
114
|
|
|
98
115
|
The gateway also gives it the log, the per-store call slots and how many workers a
|
|
99
116
|
tenant request must leave free (keep); a stage only uses them through run().
|
|
@@ -101,7 +118,8 @@ class RecallContext:
|
|
|
101
118
|
|
|
102
119
|
def __init__(self, query, limit, *, pool, clock=time.monotonic, deadline=None, public=False,
|
|
103
120
|
redact=None, client=None, tenant_id=None, notes=None, tenant_source=None, context=None,
|
|
104
|
-
log=None, slots=None, keep=0)
|
|
121
|
+
log=None, slots=None, keep=0, audience="owner", trace=False, show_fields=(),
|
|
122
|
+
person=None, history=()):
|
|
105
123
|
self.query = query
|
|
106
124
|
self.limit = limit
|
|
107
125
|
self.pool = pool
|
|
@@ -111,6 +129,10 @@ class RecallContext:
|
|
|
111
129
|
# The finds stop a little before the deadline, so the stages still have time.
|
|
112
130
|
self.find_deadline = self.deadline - min(MAX_STAGE_RESERVE, STAGE_SHARE * max(self.deadline - now, 0.0))
|
|
113
131
|
self.public = public
|
|
132
|
+
self.audience = audience
|
|
133
|
+
self.show_fields = tuple(show_fields)
|
|
134
|
+
self.person = person
|
|
135
|
+
self.history = [dict(item) for item in history or ()]
|
|
114
136
|
self.redact = redact or (lambda text: text)
|
|
115
137
|
self.client = client
|
|
116
138
|
self.tenant_id = tenant_id
|
|
@@ -122,6 +144,7 @@ class RecallContext:
|
|
|
122
144
|
self.log = log
|
|
123
145
|
self.slots = slots
|
|
124
146
|
self.keep = keep
|
|
147
|
+
self.trace = Trace() if trace else None
|
|
125
148
|
|
|
126
149
|
def time_left(self):
|
|
127
150
|
return self.deadline - self.clock()
|
|
@@ -167,6 +190,108 @@ class RecallContext:
|
|
|
167
190
|
pass
|
|
168
191
|
|
|
169
192
|
|
|
193
|
+
class Trace:
|
|
194
|
+
"""What an explained recall records: one entry per candidate, keyed by (source, ref) since a
|
|
195
|
+
stage may return a new object for the same candidate. `by` is the stage that gave the last
|
|
196
|
+
non-KEEP verdict (set by _verdict, so the verdicts cost nothing extra when there is no trace)."""
|
|
197
|
+
|
|
198
|
+
def __init__(self):
|
|
199
|
+
self.entries = {}
|
|
200
|
+
self.by = None
|
|
201
|
+
self.delivered = []
|
|
202
|
+
|
|
203
|
+
def _entry(self, candidate, added_by=None):
|
|
204
|
+
key = (candidate.source, candidate.ref)
|
|
205
|
+
entry = self.entries.get(key)
|
|
206
|
+
if entry is None:
|
|
207
|
+
entry = self.entries[key] = {"found": candidate.score, "added_by": added_by}
|
|
208
|
+
entry.update(candidate=candidate, outcome=None, stage=None)
|
|
209
|
+
return entry
|
|
210
|
+
|
|
211
|
+
def found(self, candidates):
|
|
212
|
+
for candidate in candidates:
|
|
213
|
+
self._entry(candidate)
|
|
214
|
+
|
|
215
|
+
def prepared(self, stage, before, after):
|
|
216
|
+
"""`stage`'s prepare() turned `before` into `after`: the missing ones it dropped, the new ones it added."""
|
|
217
|
+
name = piece_name(stage)
|
|
218
|
+
kept = {(c.source, c.ref) for c in after}
|
|
219
|
+
for candidate in before:
|
|
220
|
+
if (candidate.source, candidate.ref) not in kept:
|
|
221
|
+
self._entry(candidate).update(outcome="dropped", stage=name)
|
|
222
|
+
for candidate in after:
|
|
223
|
+
key = (candidate.source, candidate.ref)
|
|
224
|
+
if key in self.entries:
|
|
225
|
+
self.entries[key].update(candidate=candidate, outcome=None, stage=None)
|
|
226
|
+
else:
|
|
227
|
+
self._entry(candidate, added_by=name)
|
|
228
|
+
|
|
229
|
+
def decided(self, candidate, outcome, stage=None):
|
|
230
|
+
entry = self._entry(candidate)
|
|
231
|
+
entry.update(outcome=outcome, stage=None if stage is None else piece_name(stage))
|
|
232
|
+
if outcome == "delivered":
|
|
233
|
+
self.delivered.append(entry)
|
|
234
|
+
|
|
235
|
+
def not_reached(self, candidates):
|
|
236
|
+
for candidate in candidates:
|
|
237
|
+
self.decided(candidate, "not_reached")
|
|
238
|
+
|
|
239
|
+
def report(self, ctx):
|
|
240
|
+
"""The candidates as the answer lists them: delivered first, then by score. Returns (list, cut)."""
|
|
241
|
+
first = {id(e) for e in self.delivered}
|
|
242
|
+
rest = sorted((e for e in self.entries.values() if id(e) not in first), key=lambda e: -e["candidate"].score)
|
|
243
|
+
out: list[dict[str, Any]] = []
|
|
244
|
+
cut = False
|
|
245
|
+
for entry in self.delivered + rest:
|
|
246
|
+
if len(out) >= EXPLAIN_MAX:
|
|
247
|
+
cut = True
|
|
248
|
+
break
|
|
249
|
+
out.append(self._row(entry, ctx))
|
|
250
|
+
return out, cut
|
|
251
|
+
|
|
252
|
+
@staticmethod
|
|
253
|
+
def _row(entry, ctx):
|
|
254
|
+
candidate = entry["candidate"]
|
|
255
|
+
row = {"source": candidate.source, "id": candidate.ref, "found": entry["found"], "score": candidate.score,
|
|
256
|
+
"outcome": entry["outcome"] or "dropped", "stage": entry["stage"], "added_by": entry["added_by"]}
|
|
257
|
+
text = candidate.text
|
|
258
|
+
if isinstance(text, str) and text:
|
|
259
|
+
try:
|
|
260
|
+
text = ctx.redact(text) # redact first, then cut: a mask must not be split by the cut
|
|
261
|
+
except Exception: # noqa: BLE001 - a redactor that fails shows nothing (fail closed)
|
|
262
|
+
text = ""
|
|
263
|
+
if isinstance(text, str) and text:
|
|
264
|
+
if len(text) > EXPLAIN_TEXT:
|
|
265
|
+
text, row["cut"] = text[:EXPLAIN_TEXT], True
|
|
266
|
+
row["text"] = text
|
|
267
|
+
if candidate.date:
|
|
268
|
+
row["date"] = candidate.date
|
|
269
|
+
if candidate.fields:
|
|
270
|
+
row["fields"] = dict(candidate.fields)
|
|
271
|
+
return row
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _item(candidate, ctx):
|
|
275
|
+
"""The answer's item for an accepted candidate: as_item() and, when the client lists record fields
|
|
276
|
+
(ctx.show_fields), "fields" with the listed ones the memory has (left out when it has none of them).
|
|
277
|
+
For a public answer each value goes through the redactor too; one that comes out empty is left out."""
|
|
278
|
+
item = candidate.as_item()
|
|
279
|
+
shown = {}
|
|
280
|
+
for name in getattr(ctx, "show_fields", ()):
|
|
281
|
+
value = candidate.fields.get(name)
|
|
282
|
+
if isinstance(value, str) and value:
|
|
283
|
+
if getattr(ctx, "public", False):
|
|
284
|
+
try:
|
|
285
|
+
value = ctx.redact(value)
|
|
286
|
+
except Exception: # noqa: BLE001 - a redactor that fails shows nothing (fail closed)
|
|
287
|
+
value = ""
|
|
288
|
+
if isinstance(value, str) and value:
|
|
289
|
+
shown[name] = value
|
|
290
|
+
if shown:
|
|
291
|
+
item["fields"] = shown
|
|
292
|
+
return item
|
|
293
|
+
|
|
294
|
+
|
|
170
295
|
def submit(pool, fn, *, wait=0.0, keep=0, slots=None, store=None):
|
|
171
296
|
"""Start fn(ctl) on the pool. Returns the task, or None when the call never started:
|
|
172
297
|
no worker became free within `wait` seconds, or `store` already has as many calls in
|
|
@@ -219,6 +344,7 @@ def _hits(result):
|
|
|
219
344
|
for hit in result:
|
|
220
345
|
ref, score = getattr(hit, "ref", None), getattr(hit, "score", None)
|
|
221
346
|
text, date, meta = getattr(hit, "text", ""), getattr(hit, "date", None), getattr(hit, "meta", None)
|
|
347
|
+
fields = getattr(hit, "fields", None)
|
|
222
348
|
if text is None:
|
|
223
349
|
text = ""
|
|
224
350
|
if (not isinstance(ref, str) or isinstance(score, bool) or not isinstance(score, (int, float))
|
|
@@ -226,7 +352,8 @@ def _hits(result):
|
|
|
226
352
|
or (date is not None and not isinstance(date, str))):
|
|
227
353
|
return None
|
|
228
354
|
out.append(Hit(ref=ref, score=float(score), text=text, date=date,
|
|
229
|
-
meta=dict(meta) if isinstance(meta, dict) else {}
|
|
355
|
+
meta=dict(meta) if isinstance(meta, dict) else {},
|
|
356
|
+
fields=dict(fields) if isinstance(fields, dict) else {}))
|
|
230
357
|
return out
|
|
231
358
|
|
|
232
359
|
|
|
@@ -243,14 +370,19 @@ def find_all(stores, query, fetch, ctx):
|
|
|
243
370
|
tasks[source] = submit(
|
|
244
371
|
ctx.pool, lambda t, s=store: s.find(query, fetch, max(ctx.find_deadline - ctx.clock(), 0.05), t),
|
|
245
372
|
wait=max(wait_until - time.monotonic(), 0.0), keep=ctx.keep, slots=ctx.slots, store=store)
|
|
246
|
-
out = {}
|
|
373
|
+
out: dict[Any, list[Any]] = {}
|
|
247
374
|
failed = busy = 0
|
|
248
375
|
for source, task in tasks.items():
|
|
249
376
|
out[source] = []
|
|
250
377
|
if task is None:
|
|
251
378
|
busy += 1
|
|
252
|
-
|
|
379
|
+
continue
|
|
380
|
+
finished = task.wait(ctx.find_deadline - ctx.clock())
|
|
381
|
+
if not finished:
|
|
253
382
|
task.cancel()
|
|
383
|
+
for word in task.notes: # what the store itself reported (for example a failed child)
|
|
384
|
+
ctx.note(word)
|
|
385
|
+
if not finished:
|
|
254
386
|
failed += 1
|
|
255
387
|
elif not task.ok():
|
|
256
388
|
ctx.fault(None, "store=%s where=find error=%s" % (source, type(task.error).__name__))
|
|
@@ -285,7 +417,9 @@ def _prepared(stage, candidates, ctx):
|
|
|
285
417
|
|
|
286
418
|
|
|
287
419
|
def _verdict(candidate, stages, ctx, cheap_only=False):
|
|
288
|
-
"""KEEP, DROP or DEFER for one candidate: the first stage that does not keep it decides.
|
|
420
|
+
"""KEEP, DROP or DEFER for one candidate: the first stage that does not keep it decides.
|
|
421
|
+
In an explained recall that stage is left in ctx.trace.by."""
|
|
422
|
+
trace = getattr(ctx, "trace", None) # a stand-in context (bench) may lack it
|
|
289
423
|
for stage in stages:
|
|
290
424
|
if cheap_only and not getattr(stage, "cheap", False):
|
|
291
425
|
continue
|
|
@@ -296,11 +430,17 @@ def _verdict(candidate, stages, ctx, cheap_only=False):
|
|
|
296
430
|
verdict = admit(candidate, ctx)
|
|
297
431
|
except Exception as error: # noqa: BLE001 - fail closed: the candidate is not returned
|
|
298
432
|
ctx.fault("stage-error:%s" % piece_name(stage), "where=admit error=%s" % type(error).__name__)
|
|
433
|
+
if trace is not None:
|
|
434
|
+
trace.by = stage
|
|
299
435
|
return DROP
|
|
300
436
|
if verdict not in VERDICTS:
|
|
301
437
|
ctx.fault("bad-verdict:%s" % type(stage).__name__, "stage=%s" % piece_name(stage))
|
|
438
|
+
if trace is not None:
|
|
439
|
+
trace.by = stage
|
|
302
440
|
return DROP
|
|
303
441
|
if verdict != KEEP:
|
|
442
|
+
if trace is not None:
|
|
443
|
+
trace.by = stage
|
|
304
444
|
return verdict
|
|
305
445
|
return KEEP
|
|
306
446
|
|
|
@@ -309,22 +449,32 @@ def _left_over(candidates, stages, ctx):
|
|
|
309
449
|
"""How many of the candidates past the limit are worth mentioning in "more": the ones
|
|
310
450
|
no cheap stage drops. After the deadline the rest are counted as they are."""
|
|
311
451
|
count = 0
|
|
452
|
+
trace = getattr(ctx, "trace", None)
|
|
312
453
|
for index, candidate in enumerate(candidates):
|
|
313
454
|
if ctx.expired():
|
|
314
455
|
ctx.note("deadline")
|
|
456
|
+
if trace is not None:
|
|
457
|
+
trace.not_reached(candidates[index:])
|
|
315
458
|
return count + len(candidates) - index
|
|
316
459
|
if _verdict(candidate, stages, ctx, cheap_only=True) != DROP:
|
|
317
460
|
count += 1
|
|
461
|
+
if trace is not None:
|
|
462
|
+
trace.decided(candidate, "over_limit")
|
|
463
|
+
elif trace is not None:
|
|
464
|
+
trace.decided(candidate, "dropped", trace.by)
|
|
318
465
|
return count
|
|
319
466
|
|
|
320
467
|
|
|
321
468
|
def _admit_all(candidates, stages, ctx):
|
|
322
469
|
"""Fill ctx.accepted, best score first. Returns "more"."""
|
|
323
470
|
more = 0
|
|
471
|
+
trace = getattr(ctx, "trace", None)
|
|
324
472
|
for index, candidate in enumerate(candidates):
|
|
325
473
|
if ctx.expired():
|
|
326
474
|
# The deadline covers the stages too: stop, the rest are "more".
|
|
327
475
|
ctx.note("deadline")
|
|
476
|
+
if trace is not None:
|
|
477
|
+
trace.not_reached(candidates[index:])
|
|
328
478
|
return more + len(candidates) - index
|
|
329
479
|
if len(ctx.accepted) >= ctx.limit:
|
|
330
480
|
return more + _left_over(candidates[index:], stages, ctx)
|
|
@@ -333,6 +483,9 @@ def _admit_all(candidates, stages, ctx):
|
|
|
333
483
|
more += 1
|
|
334
484
|
elif verdict == KEEP:
|
|
335
485
|
ctx.accepted.append(candidate)
|
|
486
|
+
if trace is not None:
|
|
487
|
+
outcome = "delivered" if verdict == KEEP else "deferred" if verdict == DEFER else "dropped"
|
|
488
|
+
trace.decided(candidate, outcome, None if verdict == KEEP else trace.by)
|
|
336
489
|
return more
|
|
337
490
|
|
|
338
491
|
|
|
@@ -355,6 +508,9 @@ def recall(stores, stages, ctx):
|
|
|
355
508
|
a worker; `more` is at most how many good candidates were left out (limit reached, a
|
|
356
509
|
stage deferred them, or the deadline came).
|
|
357
510
|
|
|
511
|
+
With ctx.trace the answer also holds "stages" (their names, in order) and "candidates" (see
|
|
512
|
+
Trace.report; "candidates_cut" when the list was cut), and the stages' finish() is not run.
|
|
513
|
+
|
|
358
514
|
Bounded by ctx.deadline overall: the finds stop a little before it, and once it passes
|
|
359
515
|
no more candidates are admitted. Raises StageError when a stage's prepare() fails.
|
|
360
516
|
"""
|
|
@@ -364,10 +520,23 @@ def recall(stores, stages, ctx):
|
|
|
364
520
|
for source, hits in found.items():
|
|
365
521
|
for hit in hits:
|
|
366
522
|
candidates.append(Candidate(score=hit.score, source=source, store=stores[source], ref=hit.ref,
|
|
367
|
-
text=hit.text, date=hit.date, meta=hit.meta))
|
|
523
|
+
text=hit.text, date=hit.date, meta=hit.meta, fields=dict(hit.fields)))
|
|
524
|
+
trace = getattr(ctx, "trace", None)
|
|
525
|
+
if trace is not None:
|
|
526
|
+
trace.found(candidates)
|
|
368
527
|
for stage in stages:
|
|
369
|
-
|
|
528
|
+
out = _prepared(stage, candidates, ctx)
|
|
529
|
+
if trace is not None:
|
|
530
|
+
trace.prepared(stage, candidates, out)
|
|
531
|
+
candidates = out
|
|
370
532
|
candidates.sort(key=lambda c: -c.score)
|
|
371
533
|
more = _admit_all(candidates, stages, ctx)
|
|
372
|
-
|
|
373
|
-
|
|
534
|
+
answer = {"results": [_item(c, ctx) for c in ctx.accepted], "more": more, "failed": failed, "busy": busy}
|
|
535
|
+
if trace is None:
|
|
536
|
+
_finish(stages, ctx)
|
|
537
|
+
return answer
|
|
538
|
+
answer["stages"] = [piece_name(stage) for stage in stages]
|
|
539
|
+
answer["candidates"], cut = trace.report(ctx)
|
|
540
|
+
if cut:
|
|
541
|
+
answer["candidates_cut"] = True
|
|
542
|
+
return answer
|
|
@@ -122,7 +122,8 @@ def _is_value_repl(match):
|
|
|
122
122
|
# -----BEGIN ... PRIVATE KEY----- up to the matching END line (or to the end of the text when the block is
|
|
123
123
|
# cut off). Every line of the block becomes MARK, so the number of lines does not change.
|
|
124
124
|
_PEM = re.compile(
|
|
125
|
-
r"-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----.*?
|
|
125
|
+
r"-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----.*?"
|
|
126
|
+
r"(?:-----END [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----|\Z)",
|
|
126
127
|
re.DOTALL,
|
|
127
128
|
)
|
|
128
129
|
|
|
@@ -186,7 +187,8 @@ _PUBLIC_RULES = (
|
|
|
186
187
|
# Building, unit and room numbers.
|
|
187
188
|
re.compile(r"[0-9]+(?:栋|幢|号楼|单元|室|层)(?:[0-9]+(?:单元|室|层|号))*"),
|
|
188
189
|
# English street addresses.
|
|
189
|
-
re.compile(r"\b[0-9]+\s+[A-Za-z]+(?:\s+[A-Za-z]+)?\s+(?:St|Street|Rd|Road|Ave|Avenue|Blvd|Lane|Ln)\b\.?",
|
|
190
|
+
re.compile(r"\b[0-9]+\s+[A-Za-z]+(?:\s+[A-Za-z]+)?\s+(?:St|Street|Rd|Road|Ave|Avenue|Blvd|Lane|Ln)\b\.?",
|
|
191
|
+
re.IGNORECASE),
|
|
190
192
|
)
|
|
191
193
|
|
|
192
194
|
|
|
@@ -5,9 +5,10 @@ Standard library only.
|
|
|
5
5
|
"""
|
|
6
6
|
import datetime
|
|
7
7
|
import math
|
|
8
|
+
from typing import Any
|
|
8
9
|
|
|
9
10
|
from ..errors import ConfigError
|
|
10
|
-
from ..model import Candidate
|
|
11
|
+
from ..model import AUDIENCES, Candidate
|
|
11
12
|
from ..registry import register
|
|
12
13
|
from . import tidy
|
|
13
14
|
from .recall import DEFER, DROP, KEEP, RecallStage, _hits
|
|
@@ -411,16 +412,25 @@ class Linked(RecallStage):
|
|
|
411
412
|
time left, so a store that hangs costs the request that much and not the answer it already has.
|
|
412
413
|
|
|
413
414
|
Put it after `min_score`, `relative_score` and `newer_first` (misplaced() reports the opposite order)
|
|
414
|
-
and before `fill_text`. Options: top (default 2, 1..5), max_added (
|
|
415
|
-
|
|
416
|
-
bge-m3 on the embedding backend,
|
|
415
|
+
and before `fill_text`. Options: top (default 2, 1..5), max_added (0..5; 0 switches the stage off; not
|
|
416
|
+
given: 2, or 0 when `profile` is "precise"; one that is given wins under any profile), minimum (default
|
|
417
|
+
0.60, 0..1; on the store's own 0..1 score scale: 0.60 was measured with bge-m3 on the embedding backend,
|
|
418
|
+
other models use it unmeasured), profile (None, "precise" or "broad": the recall profile this stage follows,
|
|
419
|
+
which `[recall] profile` sets like it does for the score lines; it only decides the default of max_added).
|
|
420
|
+
Why: the stage was measured only with the broad profile; under precise it would add to an answer that is
|
|
421
|
+
meant to be short, so there it adds nothing unless `max_added` is written.
|
|
417
422
|
"""
|
|
418
423
|
|
|
419
424
|
after = ("min_score", "relative_score", "newer_first")
|
|
420
425
|
|
|
421
|
-
def __init__(self, top=LINKED_TOP, max_added=
|
|
426
|
+
def __init__(self, top=LINKED_TOP, max_added=None, minimum=LINKED_MINIMUM, profile=None):
|
|
422
427
|
if not _whole(top, 1, 5):
|
|
423
428
|
raise ConfigError("linked: top must be a whole number from 1 to 5")
|
|
429
|
+
if profile is not None:
|
|
430
|
+
check_profile("linked", profile)
|
|
431
|
+
self.max_added_given = max_added is not None # describe() tells "precise holds it back" from "written 0"
|
|
432
|
+
if max_added is None:
|
|
433
|
+
max_added = 0 if profile == "precise" else LINKED_MAX_ADDED
|
|
424
434
|
if not _whole(max_added, 0, 5):
|
|
425
435
|
raise ConfigError("linked: max_added must be a whole number from 0 to 5")
|
|
426
436
|
if not _fraction(minimum):
|
|
@@ -428,6 +438,7 @@ class Linked(RecallStage):
|
|
|
428
438
|
self.top = top
|
|
429
439
|
self.max_added = max_added
|
|
430
440
|
self.minimum = float(minimum)
|
|
441
|
+
self.follows = profile # not named `profile`: that name marks a score line (cli.describe)
|
|
431
442
|
|
|
432
443
|
def prepare(self, candidates, ctx):
|
|
433
444
|
room = min(self.max_added, ctx.limit - len(candidates))
|
|
@@ -448,7 +459,7 @@ class Linked(RecallStage):
|
|
|
448
459
|
# All the lookups together wait at most this long, and never more than half of what is left: a store
|
|
449
460
|
# that hangs must not take the time the stages after this one (and the first-hop answer) need.
|
|
450
461
|
until = ctx.clock() + min(LINKED_WAIT, max(ctx.time_left(), 0.0) / 2)
|
|
451
|
-
found = {} # (id of store, ref) -> [similarity, order met, parent, hit]
|
|
462
|
+
found: dict[Any, list[Any]] = {} # (id of store, ref) -> [similarity, order met, parent, hit]
|
|
452
463
|
for parent in first:
|
|
453
464
|
if ctx.clock() >= until:
|
|
454
465
|
break
|
|
@@ -481,10 +492,40 @@ class Linked(RecallStage):
|
|
|
481
492
|
meta["similarity"] = ceiling
|
|
482
493
|
meta["linked_from"] = parent.ref
|
|
483
494
|
out.append(Candidate(score=ceiling, source=parent.source, store=parent.store, ref=hit.ref,
|
|
484
|
-
text=hit.text, date=hit.date, meta=meta))
|
|
495
|
+
text=hit.text, date=hit.date, meta=meta, fields=dict(hit.fields)))
|
|
485
496
|
return out
|
|
486
497
|
|
|
487
498
|
|
|
499
|
+
@register("recall_stage", "record_audience")
|
|
500
|
+
class RecordAudience(RecallStage):
|
|
501
|
+
"""Leave out a memory whose own audience is narrower than the client's: the second check, beside the
|
|
502
|
+
store-level rule of the configuration (a client reads only stores at least as wide as its audience).
|
|
503
|
+
|
|
504
|
+
A memory is stamped with an audience when it is written (and every older one when its store is first
|
|
505
|
+
stamped, see the backends' `stamp_audience`). A record that has none, or one this code does not know,
|
|
506
|
+
counts as "owner": it is shown to an owner-level client only. It catches what the store-level rule
|
|
507
|
+
cannot: a copied store file configured under a wider name, two names for one file, a record that
|
|
508
|
+
arrived without a stamp. A store that does not check audiences (`checks_audience` is not True: it keeps
|
|
509
|
+
no record fields, it is read-only and was never stamped, a third-party backend) keeps everything here:
|
|
510
|
+
the store-level rule is the only one there. An owner-level client is never affected. It works in
|
|
511
|
+
admit(), so memories the `linked` stage added are checked too. No options.
|
|
512
|
+
"""
|
|
513
|
+
|
|
514
|
+
cheap = True
|
|
515
|
+
enforces = ("record_audience",)
|
|
516
|
+
|
|
517
|
+
def admit(self, candidate, ctx):
|
|
518
|
+
if getattr(candidate.store, "checks_audience", False) is not True:
|
|
519
|
+
return KEEP
|
|
520
|
+
level = candidate.fields.get("audience") if isinstance(candidate.fields, dict) else None
|
|
521
|
+
if level not in AUDIENCES:
|
|
522
|
+
level = "owner"
|
|
523
|
+
asked = getattr(ctx, "audience", "owner")
|
|
524
|
+
if asked not in AUDIENCES:
|
|
525
|
+
asked = "owner"
|
|
526
|
+
return DROP if AUDIENCES.index(level) < AUDIENCES.index(asked) else KEEP
|
|
527
|
+
|
|
528
|
+
|
|
488
529
|
def misplaced(stages):
|
|
489
530
|
"""Names of the stages in `stages` that stand before a stage they must come after. Works on
|
|
490
531
|
stage objects (the order of a built gateway); newer_first and linked declare such a rule, in `after`."""
|
|
@@ -507,5 +548,7 @@ def misplaced(stages):
|
|
|
507
548
|
# linked acts after the lines (it never changes whether the gateway stays quiet) and before fill_text, so what it
|
|
508
549
|
# appends is read, redacted and counted like any other candidate; it does nothing for stores without `neighbours`.
|
|
509
550
|
# (drop_marker is not a default: add it after fill_text when something writes such markers.)
|
|
510
|
-
|
|
511
|
-
|
|
551
|
+
# record_audience stands right after linked, so what linked adds is checked too, and before fill_text, so a
|
|
552
|
+
# memory that is not shown is never read.
|
|
553
|
+
DEFAULT_STAGES = ("min_score", "relative_score", "newer_first", "linked", "record_audience", "fill_text",
|
|
554
|
+
"drop_oversize", "redact", "dedupe", "budget")
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"""Text helpers: normalising, near-duplicate detection for recall results, and the character grams (with their
|
|
1
|
+
"""Text helpers: normalising, near-duplicate detection for recall results, and the character grams (with their
|
|
2
|
+
IDF weights) the keyword backends score on.
|
|
2
3
|
|
|
3
4
|
Standard library only.
|
|
4
5
|
"""
|
|
@@ -10,6 +10,7 @@ looked, so it is not known to be missing.
|
|
|
10
10
|
import collections
|
|
11
11
|
import threading
|
|
12
12
|
import time
|
|
13
|
+
from typing import Any
|
|
13
14
|
|
|
14
15
|
EXTRACT_WAIT = 300.0
|
|
15
16
|
EXTRACT_POLL = 30.0
|
|
@@ -25,7 +26,7 @@ class RecallFailures:
|
|
|
25
26
|
def __init__(self, clock=time.monotonic, window=HOUR):
|
|
26
27
|
self._clock = clock
|
|
27
28
|
self._window = window
|
|
28
|
-
self._times = collections.deque()
|
|
29
|
+
self._times: collections.deque[float] = collections.deque()
|
|
29
30
|
self._lock = threading.Lock()
|
|
30
31
|
|
|
31
32
|
def _trim(self, now):
|
|
@@ -53,7 +54,7 @@ class ExtractionWatch:
|
|
|
53
54
|
self._window = window
|
|
54
55
|
self._max = max_pending
|
|
55
56
|
self._pending = collections.OrderedDict() # id -> [client, tracked_at, next_check]
|
|
56
|
-
self._done = collections.deque() # (time, state)
|
|
57
|
+
self._done: collections.deque[tuple[float, Any]] = collections.deque() # (time, state)
|
|
57
58
|
self._lock = threading.Lock()
|
|
58
59
|
self._halt = threading.Event()
|
|
59
60
|
self._thread = None
|
|
@@ -30,10 +30,15 @@ class WriteGuard:
|
|
|
30
30
|
name the registered name; registry.create fills it in (None: the class name is used)
|
|
31
31
|
enforces what the guard guarantees, for the configuration check: ("redaction",),
|
|
32
32
|
("daily_writes",)
|
|
33
|
+
|
|
34
|
+
A message is a dict with "role", "content" and optionally "time" and "speaker", and, when the store it
|
|
35
|
+
goes to keeps record fields, "fields": a dict of model.FIELDS (the audience of the record among them).
|
|
36
|
+
A guard that builds new message dicts must carry "fields" over; a guard that drops it drops what the
|
|
37
|
+
store would keep, and the record then has no audience.
|
|
33
38
|
"""
|
|
34
39
|
|
|
35
40
|
name = None
|
|
36
|
-
enforces = ()
|
|
41
|
+
enforces: tuple[str, ...] = ()
|
|
37
42
|
|
|
38
43
|
def before(self, messages, ctx):
|
|
39
44
|
return messages
|
|
@@ -49,7 +54,7 @@ class WriteContext:
|
|
|
49
54
|
"""What a guard may know about the write.
|
|
50
55
|
|
|
51
56
|
client, tenant_id who writes (names, never tokens)
|
|
52
|
-
policy the client's ClientPolicy
|
|
57
|
+
policy the client's ClientPolicy (policy.reach is who sees what it shows)
|
|
53
58
|
public True when the client is a public one
|
|
54
59
|
redact the text cleaner chosen for this client (str -> str)
|
|
55
60
|
key client name, or "client:tenant" for a tenant client
|
|
@@ -68,7 +73,8 @@ class WriteContext:
|
|
|
68
73
|
self.state = {}
|
|
69
74
|
|
|
70
75
|
|
|
71
|
-
# The message
|
|
76
|
+
# The message keys that hold free text: the redact guard cleans all of them. "fields" holds no free text (each
|
|
77
|
+
# value was checked against a fixed set or pattern by the gateway) and is carried over as it is.
|
|
72
78
|
TEXT_FIELDS = ("content", "speaker", "time")
|
|
73
79
|
|
|
74
80
|
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
"""The archive: the full text of forgotten memories, kept for a while so they can be restored.
|
|
2
2
|
|
|
3
|
-
It holds memory content: protect the file like the memories themselves.
|
|
3
|
+
It holds memory content: protect the file like the memories themselves. A memory's record fields (who said
|
|
4
|
+
it, the channel and so on, see model.FIELDS) are archived with it as one JSON object in the `fields` column,
|
|
5
|
+
NULL for a memory without any and for rows written before the column existed.
|
|
4
6
|
Standard library only.
|
|
5
7
|
"""
|
|
8
|
+
import json
|
|
6
9
|
import sqlite3
|
|
7
10
|
import threading
|
|
8
|
-
from dataclasses import dataclass
|
|
11
|
+
from dataclasses import dataclass, field
|
|
9
12
|
|
|
10
13
|
_SCHEMA = """
|
|
11
14
|
CREATE TABLE IF NOT EXISTS archive (
|
|
@@ -16,6 +19,7 @@ CREATE TABLE IF NOT EXISTS archive (
|
|
|
16
19
|
uses INTEGER NOT NULL DEFAULT 0,
|
|
17
20
|
forgotten_at REAL NOT NULL,
|
|
18
21
|
expires_at REAL NOT NULL,
|
|
22
|
+
fields TEXT,
|
|
19
23
|
PRIMARY KEY (store, ref)
|
|
20
24
|
)
|
|
21
25
|
"""
|
|
@@ -30,6 +34,14 @@ class Record:
|
|
|
30
34
|
uses: int
|
|
31
35
|
forgotten_at: float
|
|
32
36
|
expires_at: float
|
|
37
|
+
fields: dict = field(default_factory=dict)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _record(row):
|
|
41
|
+
"""A Record from a row of the columns store .. expires_at plus the `fields` JSON (or NULL)."""
|
|
42
|
+
fields = json.loads(row[7]) if row[7] else {}
|
|
43
|
+
return Record(row[0], row[1], row[2], row[3], row[4], row[5], row[6],
|
|
44
|
+
fields=fields if isinstance(fields, dict) else {})
|
|
33
45
|
|
|
34
46
|
|
|
35
47
|
class Archive:
|
|
@@ -40,30 +52,46 @@ class Archive:
|
|
|
40
52
|
if str(path) != ":memory:":
|
|
41
53
|
self._db.execute("PRAGMA journal_mode=WAL")
|
|
42
54
|
self._db.execute(_SCHEMA)
|
|
55
|
+
self._migrate()
|
|
56
|
+
|
|
57
|
+
def _migrate(self):
|
|
58
|
+
"""An archive file from before the record fields gets the column (its rows have none)."""
|
|
59
|
+
columns = [r[1] for r in self._db.execute("PRAGMA table_info(archive)").fetchall()]
|
|
60
|
+
if "fields" in columns:
|
|
61
|
+
return
|
|
62
|
+
try:
|
|
63
|
+
self._db.execute("ALTER TABLE archive ADD COLUMN fields TEXT")
|
|
64
|
+
except sqlite3.OperationalError:
|
|
65
|
+
# Another process (a command next to a running gateway) migrated first.
|
|
66
|
+
if "fields" not in [r[1] for r in self._db.execute("PRAGMA table_info(archive)").fetchall()]:
|
|
67
|
+
raise
|
|
43
68
|
|
|
44
|
-
def add(self, store, ref, text, date, uses, forgotten_at, expires_at):
|
|
69
|
+
def add(self, store, ref, text, date, uses, forgotten_at, expires_at, fields=None):
|
|
70
|
+
"""Archive one memory; `fields` is its record fields (a dict, none when empty)."""
|
|
71
|
+
encoded = json.dumps(fields, sort_keys=True, ensure_ascii=False) if fields else None
|
|
45
72
|
with self._lock:
|
|
46
73
|
self._db.execute(
|
|
47
|
-
"INSERT OR REPLACE INTO archive (store, ref, text, date, uses, forgotten_at, expires_at) "
|
|
48
|
-
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
74
|
+
"INSERT OR REPLACE INTO archive (store, ref, text, date, uses, forgotten_at, expires_at, fields) "
|
|
75
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
76
|
+
(store, ref, text, date, uses, forgotten_at, expires_at, encoded))
|
|
49
77
|
|
|
50
78
|
def get(self, store, ref):
|
|
51
79
|
with self._lock:
|
|
52
80
|
row = self._db.execute(
|
|
53
|
-
"SELECT store, ref, text, date, uses, forgotten_at, expires_at FROM archive "
|
|
81
|
+
"SELECT store, ref, text, date, uses, forgotten_at, expires_at, fields FROM archive "
|
|
54
82
|
"WHERE store = ? AND ref = ?", (store, ref)).fetchone()
|
|
55
|
-
return
|
|
83
|
+
return _record(row) if row else None
|
|
56
84
|
|
|
57
85
|
def list(self, store=None):
|
|
58
86
|
"""Records without their text, oldest forgotten first."""
|
|
59
|
-
sql = "SELECT store, ref, NULL, date, uses, forgotten_at, expires_at FROM archive"
|
|
60
|
-
args = ()
|
|
87
|
+
sql = "SELECT store, ref, NULL, date, uses, forgotten_at, expires_at, NULL FROM archive"
|
|
88
|
+
args: tuple[str, ...] = ()
|
|
61
89
|
if store is not None:
|
|
62
90
|
sql += " WHERE store = ?"
|
|
63
91
|
args = (store,)
|
|
64
92
|
with self._lock:
|
|
65
93
|
rows = self._db.execute(sql + " ORDER BY forgotten_at, store, ref", args).fetchall()
|
|
66
|
-
return [
|
|
94
|
+
return [_record(r) for r in rows]
|
|
67
95
|
|
|
68
96
|
def remove(self, store, ref):
|
|
69
97
|
with self._lock:
|