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
@@ -20,36 +20,52 @@ keyword child adds little there and the line it forces up costs delivered hits.
20
20
  `Hit.meta` (when Hit has it) carries each child's own score under "child_scores" (None where
21
21
  a child did not return the memory) and the vector child's raw cosine.
22
22
 
23
- Failure handling: a child that raises during a search is skipped for that search; only when
24
- every child fails is it an error. A write is all or nothing: if any child fails, the memories
23
+ Concurrency: `find` and `neighbours` ask every child at the same time, each with the whole budget
24
+ (one thread per child per call, owned here; the call waits for them until the budget is spent. A
25
+ child that has not answered by then is cancelled through its own control object and winds down alone;
26
+ `close()` cancels and joins such threads). The answers are ordered by child index before fusing, so the
27
+ result does not depend on which child was faster. With a single child the call runs inline with the
28
+ caller's own `ctl`.
29
+
30
+ Failure handling: a child that raises or does not answer in time during a search is skipped for that
31
+ search and recorded: `child_failures` (a list of ints, one per child, never reset) and the word
32
+ `child-failed` through the caller's `ctl.note` (the access log). Only when every child fails is it an error.
33
+ A write is all or nothing: if any child fails, the memories
25
34
  are deleted again from every child (best effort; replacing an existing ref and failing
26
35
  removes it, so re-put it). Children must be able to `put(text, ref=..., date=...)` and
27
36
  `delete` when the hybrid is writable.
28
37
 
38
+ Record fields (model.FIELDS): `stores_fields` is True when any child's is. A write hands the fields only to
39
+ the children that store them (the others are called exactly as before, so a child written for the old
40
+ `put(text, ref=None, date=None)` keeps working). Fused hits and merged neighbours carry the fields of the
41
+ first child, in child order, that returned any for that memory; `records()` and `record(ref)` come from the
42
+ first child that stores fields (else from the first child that has the method).
43
+
44
+ Audiences: `stamp_audience(level)` and `set_audience(level, only_missing)` go to the children that have them, and
45
+ `checks_audience` is True when any of them checks. A memory that only a child without record fields returned has
46
+ no audience in the answer, so for a client below owner level it counts as "owner" and is not shown: the check
47
+ fails closed.
48
+
29
49
  Secrets: the `children` list is not walked by the configuration's `<name>_env` rule, so
30
50
  a child option ending in `_env` (for example `key_env`) is resolved here from the process
31
51
  environment, the same way.
32
52
  """
33
53
  import inspect
34
54
  import os
55
+ import socket
56
+ import threading
35
57
  import time
36
- import uuid
37
- from datetime import datetime, timezone
58
+ from typing import Any
38
59
 
39
60
  from .. import registry
40
61
  from ..errors import BackendError, ConfigError
41
- from ..model import Hit
42
62
  from ..registry import register
43
- from .base import MemoryBackend, message_date
63
+ from .base import (DEFAULT_BUDGET, MemoryBackend, as_roles, clamp01, kept_messages, make_hit, message_fields,
64
+ new_receipt, parse_record, receipt_ref, require_writable)
65
+ from .base import today as _today
44
66
 
45
- DEFAULT_BUDGET = 10.0
46
67
  OVERFETCH = 3 # each child is asked for limit * 3 hits so that fusion has material to rank
47
-
48
- _HAS_META = "meta" in getattr(Hit, "__dataclass_fields__", {})
49
-
50
-
51
- def _today():
52
- return datetime.now(timezone.utc).strftime("%Y-%m-%d")
68
+ CLOSE_WAIT = 2.0 # seconds close() waits for cancelled child calls to wind down
53
69
 
54
70
 
55
71
  def _resolve_env(spec, where):
@@ -84,6 +100,114 @@ def _extras(fn, timeout, ctl):
84
100
  return extra
85
101
 
86
102
 
103
+ class _ChildCtl:
104
+ """The control object of ONE child call: what children use of a `Task` (attach, detach, on_cancel,
105
+ cancelled) with a socket slot of its own, so two children never share the parent's single slot.
106
+ It is cancelled when the parent is, or by the hybrid when the child ran out of time.
107
+
108
+ A parent that cannot register cancel hooks (no `on_cancel`: a plain object with attach/detach, as
109
+ older callers pass) has no other way to reach the socket, so for it attach and detach are forwarded
110
+ as well; the own slot stays the one that cancels."""
111
+
112
+ def __init__(self, parent):
113
+ self._forward = None
114
+ self._forward_detach = None
115
+ self._lock = threading.Lock()
116
+ self._sock = None
117
+ self._cancelled = False
118
+ self._finished = False
119
+ self._hooks = []
120
+ hook = getattr(parent, "on_cancel", None)
121
+ if callable(hook):
122
+ hook(self.cancel)
123
+ else:
124
+ self._forward = getattr(parent, "attach", None)
125
+ self._forward_detach = getattr(parent, "detach", None)
126
+
127
+ @property
128
+ def cancelled(self):
129
+ with self._lock:
130
+ return self._cancelled
131
+
132
+ def attach(self, sock):
133
+ with self._lock:
134
+ if self._cancelled:
135
+ self._kill(sock)
136
+ raise BackendError("cancelled")
137
+ self._sock = sock
138
+ if callable(self._forward):
139
+ self._forward(sock)
140
+
141
+ def detach(self):
142
+ with self._lock:
143
+ self._sock = None
144
+ if callable(self._forward_detach):
145
+ self._forward_detach()
146
+
147
+ def on_cancel(self, fn):
148
+ with self._lock:
149
+ if self._finished:
150
+ return
151
+ if not self._cancelled:
152
+ self._hooks.append(fn)
153
+ return
154
+ self._quietly(fn)
155
+
156
+ def cancel(self):
157
+ with self._lock:
158
+ self._cancelled = True
159
+ sock = self._sock
160
+ hooks, self._hooks = self._hooks, []
161
+ if sock is not None:
162
+ self._kill(sock)
163
+ for fn in hooks:
164
+ self._quietly(fn)
165
+
166
+ def finish(self):
167
+ with self._lock:
168
+ self._finished = True
169
+ self._hooks = []
170
+
171
+ @staticmethod
172
+ def _kill(sock):
173
+ try:
174
+ sock.shutdown(socket.SHUT_RDWR)
175
+ except OSError:
176
+ pass
177
+
178
+ @staticmethod
179
+ def _quietly(fn):
180
+ try:
181
+ fn()
182
+ except Exception: # noqa: BLE001 - a failing hook must not stop the canceller
183
+ pass
184
+
185
+
186
+ class _Run:
187
+ """One child call on its own thread: its answer or its error, and its control object."""
188
+
189
+ def __init__(self, index, fn, timeout, parent):
190
+ self.index = index
191
+ self.ctl = _ChildCtl(parent)
192
+ self.done = threading.Event()
193
+ self.thread = None
194
+ self.on_exit = None
195
+ self.result = None
196
+ self.error = None
197
+ self._fn, self._timeout = fn, timeout
198
+
199
+ def run(self):
200
+ try:
201
+ self.result = self._fn(self._timeout, self.ctl)
202
+ except BaseException as err: # noqa: BLE001 - recorded here, the hybrid decides
203
+ self.error = err
204
+ finally:
205
+ self.ctl.finish()
206
+ self.done.set()
207
+ if self.on_exit is not None:
208
+ self.on_exit(self)
209
+
210
+
87
211
  @register("backend", "hybrid")
88
212
  class HybridBackend(MemoryBackend):
89
213
  """Options: children (a list of backend specs, each a table with a `type`), weights (a
@@ -103,18 +227,21 @@ class HybridBackend(MemoryBackend):
103
227
  broad_relative_ratio = 0.65
104
228
 
105
229
  def __init__(self, children, weights=None, writable=True, roles=("user",), timeout=DEFAULT_BUDGET):
106
- if isinstance(roles, str):
107
- roles = (roles,)
230
+ roles = as_roles(roles)
108
231
  if not isinstance(children, (list, tuple)) or not children:
109
232
  raise ValueError("children must be a non-empty list of backend specs")
110
233
  if weights is None:
111
234
  weights = [1.0] * len(children)
112
235
  if not isinstance(weights, (list, tuple)) or len(weights) != len(children):
113
236
  raise ValueError("weights needs one number per child")
114
- self.weights = [min(1.0, max(0.0, float(w))) for w in weights]
237
+ self.weights = [clamp01(float(w)) for w in weights]
115
238
  self.writable = bool(writable)
116
239
  self.roles = tuple(roles)
117
240
  self._timeout = float(timeout)
241
+ self._state = threading.Lock()
242
+ self._live = {} # thread -> its _Run, for every child call that has not been reaped yet
243
+ self._closed = False
244
+ self._failures = [0] * len(children)
118
245
  self.children = []
119
246
  try:
120
247
  for i, spec in enumerate(children):
@@ -125,16 +252,14 @@ class HybridBackend(MemoryBackend):
125
252
  for i, child in enumerate(self.children):
126
253
  if not (hasattr(child, "put") and hasattr(child, "delete")):
127
254
  raise ValueError("child %d cannot store a memory under a given ref (needs put and delete)" % i)
255
+ # True when any child keeps the record fields (see the module docstring).
256
+ self.stores_fields = any(getattr(child, "stores_fields", False) is True for child in self.children)
128
257
  except Exception:
129
258
  self.close()
130
259
  raise
131
260
 
132
261
  # ------------------------------------------------------------ writing
133
262
 
134
- def _require_writable(self):
135
- if not self.writable:
136
- raise PermissionError("this backend is read-only")
137
-
138
263
  def _rollback(self, refs):
139
264
  """Best effort: take `refs` out of every child again."""
140
265
  for child in self.children:
@@ -144,47 +269,49 @@ class HybridBackend(MemoryBackend):
144
269
  except Exception: # noqa: BLE001 - the original failure is what the caller must see
145
270
  pass
146
271
 
147
- def put(self, text, ref=None, date=None, timeout=None, ctl=None):
148
- """Store one memory in every child under one ref and return it."""
149
- return self.put_many([(text, ref, date)], timeout=timeout, ctl=ctl)[0]
272
+ def put(self, text, ref=None, date=None, timeout=None, ctl=None, fields=None):
273
+ """Store one memory in every child under one ref and return it. `fields` go to the children that
274
+ store them."""
275
+ item = {"text": text, "ref": ref, "date": date, "fields": fields}
276
+ return self.put_many([item], timeout=timeout, ctl=ctl)[0]
150
277
 
151
278
  def put_many(self, items, timeout=None, ctl=None):
152
279
  """Store several memories in every child (batched where the child can) and return the refs."""
153
- self._require_writable()
154
- rows = []
155
- for item in items:
156
- if isinstance(item, str):
157
- item = (item,)
158
- if isinstance(item, dict):
159
- text, ref, date = item.get("text"), item.get("ref"), item.get("date")
160
- else:
161
- text, ref, date = (tuple(item) + (None, None))[:3]
162
- if not isinstance(text, str) or not text.strip():
163
- raise ValueError("a memory text must be a non-empty string")
164
- rows.append((text, ref or "mem-" + uuid.uuid4().hex, date))
280
+ require_writable(self)
281
+ rows = [parse_record(item) for item in items]
165
282
  if not rows:
166
283
  return []
167
284
  refs = [r[1] for r in rows]
168
285
  try:
169
286
  for child in self.children:
170
287
  self._child_put(child, rows, timeout, ctl)
171
- except Exception:
288
+ except Exception: # noqa: BLE001 - any child failure rolls the write back and surfaces as one BackendError
172
289
  self._rollback(refs)
173
290
  raise BackendError("a child failed to store; the write was rolled back") from None
174
291
  return refs
175
292
 
176
293
  @staticmethod
177
294
  def _child_put(child, rows, timeout, ctl):
295
+ """Write `rows` ((text, ref, date, fields)) to one child; only a child that stores fields sees them."""
296
+ keeps = getattr(child, "stores_fields", False) is True
178
297
  if hasattr(child, "put_many"):
179
- child.put_many(rows, **_extras(child.put_many, timeout, ctl))
298
+ batch: list[Any]
299
+ if keeps:
300
+ batch = [{"text": text, "ref": ref, "date": date, "fields": fields} for text, ref, date, fields in rows]
301
+ else:
302
+ batch = [(text, ref, date) for text, ref, date, _ in rows]
303
+ child.put_many(batch, **_extras(child.put_many, timeout, ctl))
180
304
  return
181
- for text, ref, date in rows:
182
- child.put(text, ref=ref, date=date)
305
+ for text, ref, date, fields in rows:
306
+ if keeps:
307
+ child.put(text, ref=ref, date=date, fields=fields)
308
+ else:
309
+ child.put(text, ref=ref, date=date)
183
310
 
184
311
  def delete(self, ref):
185
312
  """Remove a memory from every child. True when any child had it; a failing child
186
313
  makes the call fail after the others were tried."""
187
- self._require_writable()
314
+ require_writable(self)
188
315
  found, failed = False, False
189
316
  for child in self.children:
190
317
  try:
@@ -200,13 +327,19 @@ class HybridBackend(MemoryBackend):
200
327
  def remember(self, messages, timeout=None, ctl=None):
201
328
  """Put every message whose role is in `roles` into every child. Returns a receipt id,
202
329
  or None when nothing was kept."""
203
- self._require_writable()
330
+ require_writable(self)
204
331
  today = _today()
205
- kept = [(i, m["content"], message_date(m, today)) for i, m in enumerate(messages) if m["role"] in self.roles]
332
+ kept = kept_messages(messages, self.roles, today)
206
333
  if not kept:
207
334
  return None
208
- receipt = "w-" + uuid.uuid4().hex
209
- self.put_many([(content, "%s-%d" % (receipt, i), date) for i, content, date in kept], timeout=timeout, ctl=ctl)
335
+ receipt = new_receipt()
336
+ items: list[Any] = []
337
+ for i, content, date in kept:
338
+ fields = message_fields(messages[i])
339
+ ref = receipt_ref(receipt, i)
340
+ items.append({"text": content, "ref": ref, "date": date, "fields": fields} if fields
341
+ else (content, ref, date))
342
+ self.put_many(items, timeout=timeout, ctl=ctl)
210
343
  return receipt
211
344
 
212
345
  def receipt_refs(self, receipt):
@@ -218,30 +351,106 @@ class HybridBackend(MemoryBackend):
218
351
 
219
352
  # ------------------------------------------------------------ reading
220
353
 
354
+ @property
355
+ def child_failures(self):
356
+ """How many searches each child failed (raised, or did not answer in time), in child order, never reset."""
357
+ with self._state:
358
+ return list(self._failures)
359
+
360
+ def _record_failed(self, indexes, ctl):
361
+ """Count failed children and say so for the access log."""
362
+ if not indexes:
363
+ return
364
+ with self._state:
365
+ for index in indexes:
366
+ self._failures[index] += 1
367
+ if getattr(ctl, "cancelled", False):
368
+ return # the caller gave up: its doing, not the children's
369
+ note = getattr(ctl, "note", None)
370
+ if callable(note):
371
+ try:
372
+ note("child-failed")
373
+ except Exception: # noqa: BLE001 - a note must never fail a search
374
+ pass
375
+
376
+ def _forget(self, run):
377
+ with self._state:
378
+ self._live.pop(run.thread, None)
379
+
380
+ def _start(self, run):
381
+ """Start the thread of one child call; False when none could be started."""
382
+ thread = threading.Thread(target=run.run, name="hybrid-child", daemon=True)
383
+ with self._state:
384
+ if self._closed:
385
+ return False
386
+ self._live[thread] = run
387
+ run.thread = thread
388
+ run.on_exit = self._forget
389
+ try:
390
+ thread.start()
391
+ except Exception: # noqa: BLE001 - no thread to run it on: the child fails
392
+ with self._state:
393
+ self._live.pop(thread, None)
394
+ return False
395
+ return True
396
+
397
+ def _gather(self, jobs, total, ctl):
398
+ """Run `jobs` ((child index, fn(timeout, ctl))) at the same time, each with the whole budget `total`.
399
+ Returns (answers ordered by child index, failed child indexes). A child that has not answered when
400
+ the budget is spent is cancelled and counts as failed."""
401
+ answers, failed = [], []
402
+ if len(jobs) == 1: # nothing to run beside it: inline, with the caller's own ctl
403
+ index, fn = jobs[0]
404
+ try:
405
+ answers.append((index, fn(total, ctl)))
406
+ except Exception: # noqa: BLE001 - one failing child must not silence the others
407
+ failed.append(index)
408
+ self._record_failed(failed, ctl)
409
+ return answers, failed
410
+ end = time.monotonic() + total
411
+ runs = [_Run(index, fn, total, ctl) for index, fn in jobs]
412
+ for run in runs:
413
+ if not self._start(run):
414
+ run.error = BackendError("no thread for the child call")
415
+ run.ctl.finish()
416
+ run.done.set()
417
+ for run in runs:
418
+ run.done.wait(max(end - time.monotonic(), 0.0))
419
+ for run in runs: # runs are in child order
420
+ if not run.done.is_set():
421
+ run.ctl.cancel()
422
+ failed.append(run.index)
423
+ elif run.error is not None:
424
+ if not isinstance(run.error, Exception):
425
+ raise run.error # KeyboardInterrupt and the like belong to the caller
426
+ failed.append(run.index)
427
+ else:
428
+ answers.append((run.index, run.result))
429
+ if run.thread is not None and run.done.is_set():
430
+ run.thread.join() # it only has to leave its function: instant
431
+ self._record_failed(failed, ctl)
432
+ return answers, failed
433
+
221
434
  def find(self, query, limit, timeout=None, ctl=None):
222
435
  total = self._timeout if timeout is None else max(0.0, float(timeout))
223
- end = time.monotonic() + total
224
436
  ask = max(1, int(limit)) * OVERFETCH
225
- answers, failures = [], 0
226
- for index, child in enumerate(self.children):
227
- left = max(0.0, end - time.monotonic()) / (len(self.children) - index)
228
- try:
229
- answers.append((index, child.find(query, ask, timeout=left, ctl=ctl)))
230
- except Exception: # noqa: BLE001 - one failing child must not silence the others
231
- failures += 1
232
- if failures == len(self.children):
437
+ jobs = [(index, lambda left, cctl, c=child: c.find(query, ask, timeout=left, ctl=cctl))
438
+ for index, child in enumerate(self.children)]
439
+ answers, failed = self._gather(jobs, total, ctl)
440
+ if len(failed) == len(self.children):
233
441
  raise BackendError("every child failed")
234
442
  return self._fuse(answers)[:limit]
235
443
 
236
444
  def _fuse(self, answers):
237
- merged = {} # ref -> {"text", "date", "scores": [per child], "cosine"}
445
+ merged: dict[Any, dict[str, Any]] = {} # ref -> {"text", "date", "scores": [per child], "cosine", "fields"}
238
446
  for index, hits in answers:
239
447
  for hit in hits:
240
448
  entry = merged.setdefault(hit.ref, {"text": "", "date": None, "scores": [None] * len(self.children),
241
- "cosine": None})
242
- entry["scores"][index] = min(1.0, max(0.0, float(hit.score)))
449
+ "cosine": None, "fields": {}})
450
+ entry["scores"][index] = clamp01(float(hit.score))
243
451
  entry["text"] = entry["text"] or hit.text
244
452
  entry["date"] = entry["date"] or hit.date
453
+ entry["fields"] = entry["fields"] or dict(getattr(hit, "fields", None) or {}) # first child wins
245
454
  cosine = (getattr(hit, "meta", None) or {}).get("cosine")
246
455
  if cosine is not None:
247
456
  entry["cosine"] = cosine
@@ -251,21 +460,12 @@ class HybridBackend(MemoryBackend):
251
460
  for weight, score in zip(self.weights, entry["scores"]):
252
461
  if score is not None:
253
462
  miss *= 1.0 - weight * score
254
- fused.append(self._hit(ref, 1.0 - miss, entry))
255
- fused.sort(key=lambda h: (-h.score, h.ref))
256
- return fused
257
-
258
- @staticmethod
259
- def _hit(ref, score, entry):
260
- if _HAS_META:
261
463
  meta = {"child_scores": entry["scores"]}
262
464
  if entry["cosine"] is not None:
263
465
  meta["cosine"] = entry["cosine"]
264
- try:
265
- return Hit(ref=ref, score=score, text=entry["text"], date=entry["date"], meta=meta)
266
- except TypeError: # pragma: no cover
267
- pass
268
- return Hit(ref=ref, score=score, text=entry["text"], date=entry["date"])
466
+ fused.append(make_hit(ref, 1.0 - miss, entry["text"], entry["date"], meta, entry["fields"]))
467
+ fused.sort(key=lambda h: (-h.score, h.ref))
468
+ return fused
269
469
 
270
470
  def read(self, ref, timeout=None, ctl=None):
271
471
  """The text from the first child that has it. KeyError when none does."""
@@ -286,30 +486,31 @@ class HybridBackend(MemoryBackend):
286
486
  the answers are merged by ref (the higher score wins) and cut to `limit`, best first. A child that
287
487
  fails is skipped; with no child that has the method (or none that answers) the answer is []."""
288
488
  total = self._timeout if timeout is None else max(0.0, float(timeout))
289
- end = time.monotonic() + total
290
- capable = [child for child in self.children if callable(getattr(child, "neighbours", None))]
291
- # ref -> [highest score, its hit, first text found, first date found]
292
- best = {}
293
- for index, child in enumerate(capable):
294
- left = max(0.0, end - time.monotonic()) / (len(capable) - index)
295
- try:
296
- hits = child.neighbours(ref, limit, **_extras(child.neighbours, left, ctl))
297
- rows = [(h.ref, min(1.0, max(0.0, float(h.score))), h) for h in hits]
298
- except Exception: # noqa: BLE001 - one failing child must not silence the others
299
- continue
489
+ capable = [(index, child) for index, child in enumerate(self.children)
490
+ if callable(getattr(child, "neighbours", None))]
491
+
492
+ def rows_of(child, left, cctl):
493
+ hits = child.neighbours(ref, limit, **_extras(child.neighbours, left, cctl))
494
+ return [(h.ref, clamp01(float(h.score)), h) for h in hits]
495
+
496
+ jobs = [(index, lambda left, cctl, c=child: rows_of(c, left, cctl)) for index, child in capable]
497
+ # ref -> [highest score, its hit, first text found, first date found, first fields found]
498
+ best: dict[Any, list[Any]] = {}
499
+ answers = self._gather(jobs, total, ctl)[0] if jobs else []
500
+ for _, rows in answers:
300
501
  for hit_ref, score, hit in rows:
301
502
  if hit_ref == ref:
302
503
  continue
303
- entry = best.setdefault(hit_ref, [score, hit, "", None])
504
+ entry = best.setdefault(hit_ref, [score, hit, "", None, {}])
304
505
  if score > entry[0]:
305
506
  entry[0], entry[1] = score, hit
306
507
  entry[2] = entry[2] or hit.text
307
508
  entry[3] = entry[3] or hit.date
509
+ entry[4] = entry[4] or dict(getattr(hit, "fields", None) or {}) # first child wins
308
510
  out = []
309
- for hit_ref, (score, hit, text, date) in best.items():
511
+ for hit_ref, (score, hit, text, date, fields) in best.items():
310
512
  meta = dict(getattr(hit, "meta", None) or {})
311
- out.append(Hit(ref=hit_ref, score=score, text=text, date=date, meta=meta) if _HAS_META
312
- else Hit(ref=hit_ref, score=score, text=text, date=date))
513
+ out.append(make_hit(hit_ref, score, text, date, meta, fields))
313
514
  out.sort(key=lambda h: (-h.score, h.ref))
314
515
  return out[:max(0, int(limit))]
315
516
 
@@ -329,6 +530,41 @@ class HybridBackend(MemoryBackend):
329
530
  def items(self):
330
531
  return self._first("items")()
331
532
 
533
+ def _keeper(self, name):
534
+ """`name` of the first child that stores fields and has it, else of the first child that has it."""
535
+ for child in self.children:
536
+ if getattr(child, "stores_fields", False) is True and hasattr(child, name):
537
+ return getattr(child, name)
538
+ return self._first(name)
539
+
540
+ @property
541
+ def checks_audience(self):
542
+ """True when any child checks audiences (it was stamped)."""
543
+ return any(getattr(child, "checks_audience", False) is True for child in self.children)
544
+
545
+ def stamp_audience(self, level):
546
+ """Call stamp_audience(level) on every child that has it. Returns the largest count (the children
547
+ hold the same memories, so the counts are one number seen once per child)."""
548
+ counts = [child.stamp_audience(level) for child in self.children
549
+ if callable(getattr(child, "stamp_audience", None))]
550
+ return max(counts, default=0)
551
+
552
+ def set_audience(self, level, only_missing=True):
553
+ """Call set_audience on every child that has it. Returns the largest count (the children hold the
554
+ same memories, so the counts are one number seen once per child)."""
555
+ counts = [child.set_audience(level, only_missing) for child in self.children
556
+ if callable(getattr(child, "set_audience", None))]
557
+ return max(counts, default=0)
558
+
559
+ def records(self):
560
+ """{"ref", "text", "date", "fields"} of every memory, from the first child that stores fields."""
561
+ return self._keeper("records")()
562
+
563
+ def record(self, ref):
564
+ """{"ref", "text", "date", "fields"} of one memory (KeyError when not stored), from the first child
565
+ that stores fields."""
566
+ return self._keeper("record")(ref)
567
+
332
568
  # ------------------------------------------------------------ lifecycle
333
569
 
334
570
  def health(self, timeout=2.0):
@@ -339,6 +575,17 @@ class HybridBackend(MemoryBackend):
339
575
  return False
340
576
 
341
577
  def close(self):
578
+ """Cancel and wait for child calls still winding down, then close the children."""
579
+ with self._state:
580
+ self._closed = True
581
+ live = list(self._live.items())
582
+ for _, run in live:
583
+ run.ctl.cancel()
584
+ end = time.monotonic() + CLOSE_WAIT
585
+ for thread, _ in live:
586
+ thread.join(max(end - time.monotonic(), 0.0))
587
+ with self._state:
588
+ self._live.clear()
342
589
  for child in self.children:
343
590
  try:
344
591
  child.close()