forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanonical_memory_adapter.py
More file actions
3734 lines (3420 loc) · 153 KB
/
Copy pathcanonical_memory_adapter.py
File metadata and controls
3734 lines (3420 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Thin adapter over canonical apply/read services for the universal MemoryService."""
from __future__ import annotations
import copy
import hashlib
import json
import logging
import secrets
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Callable, Collection, Dict, List, Optional, Sequence, Tuple, cast
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
from database._client import db as default_db_client
from database import knowledge_graph as kg_db
from database.firestore_index_registry import UNIVERSAL_CANONICAL_LIST_SCAN_QUERY
from database.review_queue import purge_stale_review_conflicts_for_memories
from utils.client_device import DeviceScopeRequest
from utils.memory.device_scope_filter import filter_items_by_device_scope
from utils.memory.canonical_lineage import (
canonical_lineage_root,
canonical_lineage_survivor_sort_key,
collapse_canonical_lineages,
)
from utils.memory.canonical_visibility_filter import filter_canonical_default_visible_items
from utils.memory.belief_model import (
SUBJECT_SCOPE_ALIASES,
belief_model_enabled,
horizon_from_extraction,
public_belief_overlay,
public_belief_overlay_json,
subject_scope_from_extraction,
)
from database.memory_collections import MemoryCollections
from database.memory_apply_store import (
CanonicalApplyWrite,
CanonicalMemoryTombstoneConflict,
CanonicalMemoryTombstoneLimitError,
CanonicalReviewResolution,
CanonicalReviewResolutionConflict,
ConversationSourceReplacementConflict,
apply_direct_user_long_term_patch_firestore,
apply_long_term_patch_firestore,
read_trigger_feedback_replay_firestore,
replace_conversation_source_firestore,
tombstone_memory_items_firestore,
privacy_deletion_receipt_id,
)
from database.legal_holds import (
LegalHoldAuthorityUnavailable,
current_destructive_operation_token,
destructive_operation_gate,
)
from database.memory_vector_repair_outbox import build_vector_repair_purge_outbox_records
from database.memory_vector_metadata import canonical_memory_provider_id
from database.account_deletion_projection_fence import read_account_deletion_projection_fence
from utils.other.list_budget import ListReadBudget, budgeted_document_get, budgeted_stream_list
from models.memory_domain import (
MemoryLayer as DomainMemoryLayer,
MemoryProcessingState,
assert_legal_state,
physical_status_to_record_status,
)
from models.memory_evidence import (
ArtifactRef,
ArtifactPreservationState,
MemoryEvidence,
SourceState,
)
from models.memories import Evidence, MemoryDB, MemoryCategory, SubjectAttribution, decide_initial_memory_tier
from models.memory_apply import (
ApplyResult,
ApplyStatus,
MemoryControlState,
MemoryWriterClass,
apply_long_term_patch_transaction,
build_patch_mutation_identity,
require_writer_admitted,
)
from models.memory_contracts import DurablePatchDecision, LifecycleState, deterministic_contract_id
from models.memory_operations import MemoryLedgerReopenReceipt, MemoryOperation, MemoryOperationType
from models.memory_source_replacement import ConversationSourceReplacementReceipt
from models.jit_trigger_feedback import JITTriggerFeedbackReceipt
from models.product_memory import (
LedgerWriteReason,
MAX_MEMORY_ARGUMENTS_JSON_BYTES,
MemoryAccessPolicy,
MemoryItemStatus,
MemoryKind,
MemoryLayer,
MemorySubjectScope,
ProcessingState,
MemoryItem,
is_archive_access_eligible,
)
from utils.memory.short_term_lifecycle import default_short_term_expiry
from utils.memory.required_promotion import (
REQUIRED_PROCESSING_STATUS_PENDING,
REQUIRED_PROCESSING_STATUS_REJECTED,
REQUIRED_PROCESSOR_ID,
REQUIRED_PROCESSOR_VERSION,
REQUIRED_PROMOTION_STATUS_PENDING,
)
from utils.memory.memory_system import ensure_canonical_apply_control_state
from utils.memory.jit_trigger_contract import TriggerFeedback, TriggerFeedbackAction, apply_trigger_feedback
from utils.retrieval.hybrid import rrf_rerank
from utils.memory.canonical_vector_sync import delete_canonical_memory_vector
from utils.memory.product_memory_read_service import (
fetch_authoritative_product_memory_items,
fetch_authoritative_product_memory_items_by_ids,
fetch_authoritative_product_memory_items_for_source,
fetch_authoritative_superseded_memory_items_for_targets,
)
from utils.memory.v3.account_generation_source import read_memory_v3_trusted_account_generation
logger = logging.getLogger(__name__)
# Canonical item identity remains ``memory_id``. Shared external providers use
# a user-scoped opaque projection id so one account can never overwrite another.
_ALLOWED_MEMORY_VISIBILITIES = {"private", "public", "shared"}
Payload = Dict[str, Any]
SortKey = tuple[int, datetime | int]
UserMutationPatchBuilder = Callable[[MemoryItem, datetime], Tuple[Payload, Payload]]
_LEDGER_WRITE_AUTHORITY = object()
_DIRECT_USER_LEDGER_WRITE_AUTHORITY = object()
_DIRECT_USER_LEDGER_EVIDENCE_TYPES = {
"explicit_user_statement",
"explicit_user_correction",
"explicit_user_reopen",
"explicit_user_revert",
}
def mint_direct_user_write_authority() -> object:
"""Mint the in-process capability held by authenticated user routes.
The returned object carries no user data and is intentionally checked by
identity. Internal integration and extraction callers cannot opt into
the direct-user ledger seam by setting a payload field.
"""
return _DIRECT_USER_LEDGER_WRITE_AUTHORITY
def is_direct_user_write_authority(value: object | None) -> bool:
"""Return whether ``value`` is the route-minted direct-user capability."""
return value is _DIRECT_USER_LEDGER_WRITE_AUTHORITY
# ``knowledge_ledger`` imports this adapter, so the wire discriminator cannot
# be imported back without a cycle. Keep this private copy contract-tested.
_LEDGER_SCHEMA_VERSION = "knowledge_ledger.v1"
# Concurrent same-account canonical writes race the account-global control
# CAS inside the conversation source replacement. Retraction — the delete and
# merge path — converges across those races instead of failing (#11726).
_RETRACT_CONFLICT_ATTEMPTS = 5
_RETRACT_CONFLICT_BACKOFF_SECONDS = (0.05, 0.1, 0.25, 0.5)
# Extraction races the same control CAS but runs inside conversation processing,
# which has no outer convergence loop: an immediate retry re-reads the control a
# peer just advanced, so same-account writers keep losing in lockstep and the
# whole enrichment fails. Back the replacement's own rounds off by default.
_REPLACEMENT_CONFLICT_BACKOFF_SECONDS = (0.05, 0.1, 0.25, 0.5)
# Retraction already wraps this call in the converging loop above; keeping its
# inner rounds immediate stops the delete path's latency budget being multiplied.
_IMMEDIATE_REPLACEMENT_RETRY_BACKOFF = (0.0, 0.0)
_SETTLED_PROMOTION_FIELDS = frozenset(
{
"route",
"reconciliation",
"target_memory_id",
"relationship_to_user",
"aboutness",
"basis_for_memory",
"confidence",
"rationale",
"processed_at",
"processed_by",
"from_tier",
"to_tier",
"promoted_at",
"graph_plan",
"admission_receipt",
}
)
class CanonicalBatchMutationLimitError(ValueError):
"""Raised before commit when a canonical batch cannot fit one transaction."""
class CanonicalMemoryNotFoundError(ValueError):
"""Raised when an item is absent or already tombstoned during an atomic batch read."""
class ConversationReplacementConflictError(RuntimeError):
"""Conversation source replacement exhausted its bounded conflict retries.
Subclasses :class:`RuntimeError` so pre-existing callers keep their
``except RuntimeError`` contract. Callers that can retry the operation —
cascade delete, merge — get a typed signal instead of an opaque 500
(#11726).
"""
def _payload_or_empty(value: object) -> Payload:
return cast(Payload, value) if isinstance(value, dict) else {}
def _bounded_memory_arguments(value: object) -> Dict[str, Any]:
"""Project only JSON-safe proposition arguments within the graph bound.
``MemoryItem.arguments`` is typed as a JSON-shaped mapping, but the
historical model predates a serialized-size validator on that field. Keep
the released MemoryDB projection bounded and fail closed for malformed or
oversized nested values rather than emitting an unbounded payload.
"""
if not isinstance(value, dict):
return {}
try:
encoded = json.dumps(
value,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=True,
allow_nan=False,
)
if len(encoded.encode("utf-8")) > MAX_MEMORY_ARGUMENTS_JSON_BYTES:
return {}
return copy.deepcopy(value)
except (TypeError, ValueError, OverflowError, RecursionError):
return {}
def _snapshot_payload(snapshot: Any) -> Payload:
return _payload_or_empty(snapshot.to_dict() if getattr(snapshot, "exists", False) else {})
def _clear_settled_promotion_route(promotion: Payload) -> Payload:
"""Return pending metadata without a stale terminal consolidation decision."""
for field in _SETTLED_PROMOTION_FIELDS:
promotion.pop(field, None)
return promotion
def invalidate_kg_for_memory_retraction(uid: str, memory_ids: List[str], *, db_client: Any = None) -> None:
"""Prune retracted/superseded memory citations from the user's KG."""
if not memory_ids:
return
client = db_client if db_client is not None else default_db_client
pruned = kg_db.prune_memory_citations_from_kg(uid, memory_ids, db_client=client)
logger.info(
"kg_citations_pruned uid=%s retracted_memory_count=%d pruned_entities=%d",
uid,
len(memory_ids),
pruned,
)
def extraction_memory_id(
*,
uid: str,
source_id: str,
content: str,
subject_entity_id: Optional[str] = None,
) -> str:
"""Hash-derived neutral memory id, partitioned by non-default subject."""
identity = {"uid": uid, "source_id": source_id, "content": (content or "").strip()}
normalized_subject = (subject_entity_id or "").strip()
if normalized_subject and normalized_subject != "user":
identity["subject_entity_id"] = normalized_subject
return (
"mem_"
+ deterministic_contract_id(
"canonical-extraction-memory",
identity,
)[:32]
)
def search_result_to_memorydb(uid: str, item: Dict[str, Any]) -> MemoryDB:
updated_at = item.get("date") or item.get("updated_at")
if isinstance(updated_at, str):
updated_at = datetime.fromisoformat(updated_at.replace("Z", "+00:00"))
if not isinstance(updated_at, datetime):
updated_at = datetime.now(timezone.utc)
tier_value = item.get("tier") or MemoryLayer.short_term.value
tier = tier_value if isinstance(tier_value, MemoryLayer) else MemoryLayer(tier_value)
return MemoryDB(
id=item["memory_id"],
uid=uid,
content=item.get("content") or "",
category=MemoryCategory.interesting,
tags=[],
created_at=updated_at,
updated_at=updated_at,
manually_added=False,
reviewed=False,
is_locked=bool(item.get("is_locked", False)),
visibility=item.get("visibility") or "private",
memory_tier=tier,
valid_at=updated_at,
ledger_schema_version=item.get("ledger_schema_version"),
kind=item.get("kind"),
subject_scope=item.get("subject_scope"),
slot=item.get("slot"),
curation_weight=int(item.get("curation_weight") or 0),
intent_backed=bool(item.get("intent_backed", False)),
write_reason=item.get("write_reason"),
)
def memory_item_to_memorydb(item: MemoryItem) -> MemoryDB:
"""Map authoritative memory memory_items row to legacy MemoryDB response shape."""
conversation_id = None
evidence_payload: List[Payload] = []
promotion = item.promotion or {}
raw_submission = promotion.get("submission")
raw_receipt = promotion.get("processing_receipt")
submission: Payload = cast(Payload, raw_submission) if isinstance(raw_submission, dict) else {}
receipt: Payload = cast(Payload, raw_receipt) if isinstance(raw_receipt, dict) else {}
for evidence in item.evidence:
artifact_ref = evidence.artifact_refs[0].model_dump(mode="json") if evidence.artifact_refs else {}
evidence_payload.append(
{
"evidence_id": evidence.evidence_id,
"source_id": evidence.source_id,
"source_type": evidence.source_type,
"source_signal": "manual" if item.user_asserted else str(submission.get("source_surface") or "api"),
"extractor_id": receipt.get("processor_id") or "canonical_memory_adapter",
"extractor_version": receipt.get("processor_version") or "v1",
"artifact_ref": artifact_ref,
"capture_confidence": 0.5,
"independence_group": evidence.source_id or evidence.source_type,
"redaction_status": evidence.redaction_status.value,
"created_at": item.captured_at,
"client_device_id": evidence.client_device_id,
}
)
if evidence.source_type == "conversation" and evidence.source_id:
conversation_id = evidence.source_id
category_raw = promotion.get("category", MemoryCategory.interesting.value)
try:
category = MemoryCategory(category_raw)
except ValueError:
category = MemoryCategory.interesting
tags = list(promotion.get("tags") or [])
reviewed = bool(promotion.get("reviewed", False))
is_baseline = bool(promotion.get("is_baseline", False))
is_locked = bool(promotion.get("is_locked", False))
is_read = bool(promotion.get("is_read", False))
is_dismissed = bool(promotion.get("is_dismissed", False))
user_review = promotion.get("user_review")
source_attribution = _payload_or_empty(promotion.get("source_attribution"))
raw_subject_attribution = source_attribution.get("subject_attribution", SubjectAttribution.unknown.value)
try:
subject_attribution = SubjectAttribution(raw_subject_attribution)
except (TypeError, ValueError):
subject_attribution = SubjectAttribution.unknown
return MemoryDB(
id=item.memory_id,
uid=item.uid,
content=item.content or "",
category=category,
tags=tags,
created_at=item.captured_at,
updated_at=item.updated_at,
conversation_id=conversation_id,
manually_added=item.user_asserted,
reviewed=reviewed,
is_baseline=is_baseline,
is_locked=is_locked,
is_read=is_read,
is_dismissed=is_dismissed,
user_review=user_review,
visibility=item.visibility,
evidence=evidence_payload,
memory_tier=item.tier,
primary_capture_device=item.primary_capture_device,
capture_device_ids=item.capture_device_ids or [],
subject_entity_id=item.subject_entity_id,
subject_attribution=subject_attribution,
ledger_schema_version=item.ledger_schema_version,
kind=item.kind if item.ledger_schema_version else None,
subject_scope=item.subject_scope if item.ledger_schema_version else None,
slot=item.slot,
body=item.body,
valid_at=item.valid_from or item.captured_at,
invalid_at=item.valid_to,
superseded_by=item.superseded_by,
canonical_memory_id=item.canonical_memory_id,
ledger_status=item.status if item.ledger_schema_version else None,
curation_weight=item.curation_weight,
trigger_condition=item.trigger_condition,
# MemoryItem validates this as a JSON object; preserve the canonical
# proposition arguments for ledger mirrors instead of silently
# degrading entity/alias context to content-only text.
arguments=_bounded_memory_arguments(item.arguments),
intent_backed=item.intent_backed,
write_reason=item.write_reason,
**public_belief_overlay(item, now=datetime.now(timezone.utc)),
)
def _canonical_lineage_root(item: MemoryItem, *, items_by_id: Dict[str, MemoryItem]) -> str:
"""Resolve one item to its authoritative alias target without trusting cycles."""
return canonical_lineage_root(item, items_by_id=items_by_id)
def _lineage_survivor_sort_key(item: MemoryItem, *, lineage_root: str) -> tuple[int, int, float, str]:
"""Prefer the Long-term canonical survivor, then the newest deterministic row."""
return canonical_lineage_survivor_sort_key(item, lineage_root=lineage_root)
def _deduplicate_canonical_items(
items: List[MemoryItem],
*,
lineage_context: Optional[List[MemoryItem]] = None,
) -> List[MemoryItem]:
"""Collapse default-read aliases without moving a lineage behind its freshest evidence."""
return collapse_canonical_lineages(
items,
lineage_context=lineage_context,
survivor_context=items,
)
def _deduplicate_canonical_search_candidates(
candidates: List[Payload],
*,
lineage_items_by_id: Dict[str, MemoryItem],
survivor_items_by_id: Dict[str, MemoryItem],
) -> List[Payload]:
"""Collapse alias lineages while preserving the best query position for each."""
grouped: Dict[str, List[tuple[int, Payload]]] = {}
for position, candidate in enumerate(candidates):
item = cast(MemoryItem, candidate["item"])
lineage_root = _canonical_lineage_root(item, items_by_id=lineage_items_by_id)
grouped.setdefault(lineage_root, []).append((position, candidate))
deduplicated: List[tuple[int, Payload]] = []
for lineage_root, entries in grouped.items():
candidate_items = {cast(MemoryItem, candidate["item"]).memory_id: candidate for _, candidate in entries}
canonical_item = survivor_items_by_id.get(lineage_root)
if canonical_item is not None:
candidate_items.setdefault(
canonical_item.memory_id,
{
"id": canonical_item.memory_id,
"content": canonical_item.content or "",
"category": "interesting",
"vector_score": 0.0,
"item": canonical_item,
},
)
survivor = min(
(cast(MemoryItem, candidate["item"]) for candidate in candidate_items.values()),
key=lambda item: _lineage_survivor_sort_key(item, lineage_root=lineage_root),
)
selected = dict(candidate_items[survivor.memory_id])
selected["vector_score"] = max(float(candidate.get("vector_score", 0.0)) for _, candidate in entries)
deduplicated.append((min(position for position, _ in entries), selected))
deduplicated.sort(key=lambda entry: (entry[0], cast(MemoryItem, entry[1]["item"]).memory_id))
return [candidate for _, candidate in deduplicated]
def _canonical_search_result_sort_key(candidate: Payload) -> tuple[float, float, float, str]:
"""Make hybrid-score ties stable while allowing fresh unique Short-term evidence."""
item = cast(MemoryItem, candidate["item"])
return (
-float(candidate.get("_hybrid_score", 0.0)),
-float(candidate.get("vector_score", 0.0)),
-item.updated_at.timestamp(),
item.memory_id,
)
def read_canonical_memories(
uid: str,
*,
limit: int = 100,
offset: int = 0,
db_client: Any = None,
device_scope_request: Optional[DeviceScopeRequest] = None,
include_pending_processing: bool = False,
include_archive: bool = False,
now: Optional[datetime] = None,
budget: Optional[ListReadBudget] = None,
) -> List[MemoryDB]:
"""Read canonical items, optionally exposing explicit pending submissions.
Pending text is withheld by default so agent/chat consumers cannot use raw
submissions. Dedicated memory-list APIs opt in and display those records as
Short-term while processing is underway.
Archive rows stay excluded unless ``include_archive`` is an explicit owner
opt-in. That flag is the only way this default list gains
``archive_capability``; chat/MCP archive routes keep their own grants.
With a ``budget`` the authoritative item stream runs under the request's
per-RPC timeout and charges every fetched row (#11831).
"""
client = db_client if db_client is not None else default_db_client
device_scope = device_scope_request.device_scope if device_scope_request else "all"
client_device_id = device_scope_request.client_device_id if device_scope_request else None
items = fetch_authoritative_product_memory_items(uid=uid, db_client=client, budget=budget)
current_time = now or datetime.now(timezone.utc)
archive_explicit = bool(include_archive)
policy = MemoryAccessPolicy.for_omi_chat(archive_capability=archive_explicit)
visible = filter_canonical_default_visible_items(items, policy=policy, now=current_time)
visible_by_id = {item.memory_id: item for item in visible}
if archive_explicit:
for item in items:
# MemoryLayer.archive is visible only with archive_capability + explicit opt-in.
if is_archive_access_eligible(item, policy, now=current_time).allowed:
visible_by_id.setdefault(item.memory_id, item)
if include_pending_processing:
for item in items:
promotion = item.promotion or {}
if (
item.tier == MemoryLayer.short_term
and item.status == MemoryItemStatus.active
and item.processing_state == ProcessingState.pending
and item.source_state == SourceState.active
and promotion.get("required") is True
and promotion.get("user_review") is not False
):
visible_by_id[item.memory_id] = item
visible = sorted(visible_by_id.values(), key=lambda item: (-item.updated_at.timestamp(), item.memory_id))
else:
visible = [
item
for item in sorted(visible_by_id.values(), key=lambda item: (-item.updated_at.timestamp(), item.memory_id))
if item.processing_state == ProcessingState.processed
]
visible = filter_items_by_device_scope(
visible,
device_scope=device_scope if device_scope in ("current", "all", "explicit") else "all",
client_device_id=client_device_id,
)
visible = _deduplicate_canonical_items(visible, lineage_context=items)
paged = visible[offset : offset + limit]
return [memory_item_to_memorydb(item) for item in paged]
_CANONICAL_SCAN_PAGE_MAX = 500
_CANONICAL_SCAN_LINEAGE_MAX_HOPS = 12
_LEDGER_SEARCH_MAX_PROVIDER_CANDIDATES = 60
CanonicalScanCursor = tuple[datetime, str]
CanonicalScanSlot = tuple[Optional[MemoryDB], CanonicalScanCursor]
@dataclass(frozen=True)
class BoundedLedgerSearchHydration:
"""Named result for bounded provider-candidate and lineage hydration."""
candidate_items: Tuple[MemoryItem, ...]
lineage_items_by_id: Dict[str, MemoryItem]
survivor_items_by_id: Dict[str, MemoryItem]
def _coerce_scan_updated_at(value: datetime) -> datetime:
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _canonical_scan_item_visible(
item: MemoryItem,
*,
policy: MemoryAccessPolicy,
now: datetime,
include_pending_processing: bool,
include_archive: bool,
device_scope: str,
client_device_id: Optional[str],
) -> bool:
"""Apply list visibility predicates to one raw scan row without full-set loads."""
default_visible = filter_canonical_default_visible_items([item], policy=policy, now=now)
visible = bool(default_visible)
if include_archive and is_archive_access_eligible(item, policy, now=now).allowed:
visible = True
if include_pending_processing:
promotion = item.promotion or {}
if (
item.tier == MemoryLayer.short_term
and item.status == MemoryItemStatus.active
and item.processing_state == ProcessingState.pending
and item.source_state == SourceState.active
and promotion.get("required") is True
and promotion.get("user_review") is not False
):
visible = True
elif item.processing_state != ProcessingState.processed:
visible = False
if not visible:
return False
scoped = filter_items_by_device_scope(
[item],
device_scope=device_scope if device_scope in ("current", "all", "explicit") else "all",
client_device_id=client_device_id,
)
return bool(scoped)
def _read_canonical_memory_item_for_lineage(
uid: str,
memory_id: str,
*,
db_client: Any,
budget: Optional[ListReadBudget] = None,
) -> Optional[MemoryItem]:
"""Read one canonical document for lineage traversal without status filtering.
Snapshot/document id is the sole identity authority. Payload ``memory_id`` or
``uid`` mismatches fail closed. Non-active (superseded/hidden/tombstoned)
rows are returned so callers can traverse restricted intermediates.
"""
requested_id = (memory_id or "").strip()
if not requested_id:
return None
path = f"{MemoryCollections(uid=uid).memory_items}/{requested_id}"
snapshot = budgeted_document_get(db_client.document(path), budget)
if not getattr(snapshot, "exists", False):
return None
doc_id = getattr(snapshot, "id", None)
if not isinstance(doc_id, str) or not doc_id.strip():
raise ValueError(f"canonical lineage target missing document id: requested {requested_id}")
if doc_id != requested_id:
raise ValueError(f"canonical lineage document id mismatch: requested {requested_id}, found {doc_id}")
raw_payload: object = snapshot.to_dict()
payload = cast(Dict[str, Any], raw_payload) if isinstance(raw_payload, dict) else {}
item = MemoryItem.model_validate(payload)
if item.memory_id != doc_id:
raise ValueError(f"canonical memory id mismatch: requested {requested_id}, found {item.memory_id}")
if item.uid != uid:
raise ValueError(f"canonical memory uid mismatch: expected {uid}, got {item.uid}")
return item
def _hydrate_bounded_ledger_search_items(
uid: str,
candidate_ids: Sequence[str],
*,
db_client: Any,
policy: MemoryAccessPolicy,
now: datetime,
device_scope: str,
client_device_id: Optional[str],
) -> BoundedLedgerSearchHydration:
"""Hydrate provider candidates plus a bounded canonical lineage closure.
Ledger search must never turn a provider candidate into an account-wide
canonical collection scan. Candidate rows are read in one bounded batch;
each of at most twelve lineage hops reads only the next ids referenced by
that batch. Every point is checked against both the owning path and the
Firestore document id by the read-service seam.
"""
requested_ids = list(dict.fromkeys(memory_id for memory_id in candidate_ids if memory_id))[
:_LEDGER_SEARCH_MAX_PROVIDER_CANDIDATES
]
if not requested_ids:
return BoundedLedgerSearchHydration(
candidate_items=(),
lineage_items_by_id={},
survivor_items_by_id={},
)
hydrated_by_id: Dict[str, MemoryItem] = {}
frontier = fetch_authoritative_product_memory_items_by_ids(uid, requested_ids, db_client=db_client)
for item in frontier:
hydrated_by_id[item.memory_id] = item
seen_ids = set(requested_ids)
for _ in range(_CANONICAL_SCAN_LINEAGE_MAX_HOPS):
next_ids = [
target_id
for item in frontier
if (target_id := (item.canonical_memory_id or item.superseded_by or "").strip())
and target_id not in seen_ids
]
next_ids = list(dict.fromkeys(next_ids))[:_LEDGER_SEARCH_MAX_PROVIDER_CANDIDATES]
if not next_ids:
break
seen_ids.update(next_ids)
frontier = fetch_authoritative_product_memory_items_by_ids(uid, next_ids, db_client=db_client)
for item in frontier:
hydrated_by_id[item.memory_id] = item
all_items = list(hydrated_by_id.values())
visible_items = filter_canonical_default_visible_items(all_items, policy=policy, now=now)
scoped_items = filter_items_by_device_scope(
visible_items,
device_scope=device_scope if device_scope in ("current", "all", "explicit") else "all",
client_device_id=client_device_id,
)
return BoundedLedgerSearchHydration(
candidate_items=tuple(hydrated_by_id[memory_id] for memory_id in requested_ids if memory_id in hydrated_by_id),
lineage_items_by_id=hydrated_by_id,
survivor_items_by_id={item.memory_id: item for item in scoped_items},
)
def _ledger_search_lineage_is_complete(item: MemoryItem, *, lineage_items_by_id: Dict[str, MemoryItem]) -> bool:
"""Require a candidate's canonical lineage to terminate in bounded data."""
current = item
visited: set[str] = set()
for _ in range(_CANONICAL_SCAN_LINEAGE_MAX_HOPS + 1):
if current.memory_id in visited:
return True
visited.add(current.memory_id)
target_id = (current.canonical_memory_id or current.superseded_by or "").strip()
if not target_id or target_id == current.memory_id:
return True
target = lineage_items_by_id.get(target_id)
if target is None:
return False
current = target
# The closure was bounded before a terminating root was observed.
return False
def _canonical_scan_lineage_suppressed(
item: MemoryItem,
*,
uid: str,
db_client: Any,
policy: MemoryAccessPolicy,
now: datetime,
include_pending_processing: bool,
include_archive: bool,
device_scope: str,
client_device_id: Optional[str],
budget: Optional[ListReadBudget] = None,
) -> bool:
"""Suppress a visible alias when a visible authoritative survivor wins.
Bounded identity-checked point-follow of ``canonical_memory_id`` /
``superseded_by`` (max ``_CANONICAL_SCAN_LINEAGE_MAX_HOPS``). Non-visible
superseded/hidden/tombstoned nodes are traversal-only. Never reloads the
full canonical set. Cycles stop the walk; payload id/uid mismatches fail
closed without inventing a survivor.
"""
outbound = (item.canonical_memory_id or item.superseded_by or "").strip()
if not outbound or outbound == item.memory_id:
return False
closure_by_id: Dict[str, MemoryItem] = {item.memory_id: item}
path: List[str] = [item.memory_id]
position_by_id: Dict[str, int] = {item.memory_id: 0}
current = item
lineage_root = item.memory_id
for _ in range(_CANONICAL_SCAN_LINEAGE_MAX_HOPS):
next_id = (current.canonical_memory_id or current.superseded_by or "").strip()
if not next_id or next_id == current.memory_id:
lineage_root = current.memory_id
break
cycle_start = position_by_id.get(next_id)
if cycle_start is not None:
lineage_root = min(path[cycle_start:])
break
try:
target = _read_canonical_memory_item_for_lineage(uid, next_id, db_client=db_client, budget=budget)
except ValueError:
# Payload/id/uid mismatch fail-closed for that hop: stop walking and
# only evaluate identity-checked nodes already in the closure.
break
if target is None:
# Unresolved pointer: treat the missing id as the chain end/root.
lineage_root = next_id
break
closure_by_id[target.memory_id] = target
position_by_id[target.memory_id] = len(path)
path.append(target.memory_id)
current = target
lineage_root = current.memory_id
else:
lineage_root = current.memory_id
visible_candidates = [
candidate
for candidate in closure_by_id.values()
if candidate.memory_id != item.memory_id
and _canonical_scan_item_visible(
candidate,
policy=policy,
now=now,
include_pending_processing=include_pending_processing,
include_archive=include_archive,
device_scope=device_scope,
client_device_id=client_device_id,
)
]
if not visible_candidates:
return False
item_key = canonical_lineage_survivor_sort_key(item, lineage_root=lineage_root)
return any(
canonical_lineage_survivor_sort_key(candidate, lineage_root=lineage_root) < item_key
for candidate in visible_candidates
)
def read_canonical_scan_page(
uid: str,
*,
limit: int = 100,
start_after: Optional[CanonicalScanCursor] = None,
db_client: Any = None,
device_scope_request: Optional[DeviceScopeRequest] = None,
include_pending_processing: bool = False,
include_archive: bool = False,
now: Optional[datetime] = None,
budget: Optional[ListReadBudget] = None,
) -> Tuple[List[CanonicalScanSlot], bool]:
"""Read one bounded canonical raw scan page via Firestore keyset order.
Each slot corresponds to one raw ``memory_items`` document in newest-first
``updated_at DESC, __name__ ASC`` order. ``None`` memory means the row was
filtered by access/device/pending/archive/lineage policy and must still
advance the scan cursor. ``snapshot.id`` is the sole ``__name__`` authority;
payload ``memory_id`` mismatches fail closed as filtered slots. Callers
over-fetch additional pages when filters shrink the visible stream. Never
loads the full canonical set.
"""
client = db_client if db_client is not None else default_db_client
bounded_limit = max(1, min(int(limit or 100), _CANONICAL_SCAN_PAGE_MAX))
device_scope = device_scope_request.device_scope if device_scope_request else "all"
client_device_id = device_scope_request.client_device_id if device_scope_request else None
current_time = now or datetime.now(timezone.utc)
archive_explicit = bool(include_archive)
policy = MemoryAccessPolicy.for_omi_chat(archive_capability=archive_explicit)
items_ref = client.collection(MemoryCollections(uid=uid).memory_items)
query = UNIVERSAL_CANONICAL_LIST_SCAN_QUERY.build(
items_ref,
{},
field_filter_factory=FieldFilter,
)
query = query.order_by('updated_at', direction=firestore.Query.DESCENDING).order_by('__name__')
if start_after is not None:
cursor_time, cursor_memory_id = start_after
if not cursor_memory_id.strip():
raise ValueError('canonical scan cursor memory_id must not be blank')
query = query.start_after(
{
'updated_at': _coerce_scan_updated_at(cursor_time),
'__name__': items_ref.document(cursor_memory_id),
}
)
snapshots = budgeted_stream_list(query.limit(bounded_limit), budget)
slots: List[CanonicalScanSlot] = []
for snapshot in snapshots:
doc_id = getattr(snapshot, 'id', None)
if not isinstance(doc_id, str) or not doc_id.strip():
continue
raw_payload = cast(object, snapshot.to_dict())
payload = cast(Dict[str, Any], raw_payload) if isinstance(raw_payload, dict) else {}
updated_raw = payload.get('updated_at')
if isinstance(updated_raw, datetime):
scan_updated_at = _coerce_scan_updated_at(updated_raw)
else:
scan_updated_at = datetime.fromtimestamp(0, tz=timezone.utc)
scan_cursor = (scan_updated_at, doc_id)
try:
item = MemoryItem.model_validate(payload)
except Exception:
# Malformed docs still consume scan position via snapshot identity.
slots.append((None, scan_cursor))
continue
if item.uid != uid:
raise ValueError(f'memory item uid mismatch: expected {uid}, got {item.uid}')
if item.memory_id != doc_id:
# Fail closed: payload identity must match document __name__.
slots.append((None, scan_cursor))
continue
if not _canonical_scan_item_visible(
item,
policy=policy,
now=current_time,
include_pending_processing=include_pending_processing,
include_archive=archive_explicit,
device_scope=device_scope,
client_device_id=client_device_id,
):
slots.append((None, scan_cursor))
continue
if _canonical_scan_lineage_suppressed(
item,
uid=uid,
db_client=client,
policy=policy,
now=current_time,
include_pending_processing=include_pending_processing,
include_archive=archive_explicit,
device_scope=device_scope,
client_device_id=client_device_id,
budget=budget,
):
slots.append((None, scan_cursor))
continue
slots.append((memory_item_to_memorydb(item), scan_cursor))
exhausted = len(snapshots) < bounded_limit
return slots, exhausted
def search_canonical_memories(
uid: str,
query: str,
*,
limit: int = 5,
db_client: Any = None,
vector_query: Any = None,
device_scope_request: Optional[DeviceScopeRequest] = None,
item_filter: Optional[Callable[[MemoryItem], bool]] = None,
ledger_kinds: Optional[Collection[str]] = None,
) -> List[Dict[str, Any]]:
"""Hybrid search over default-visible Short-term and Long-term memories."""
client = db_client if db_client is not None else default_db_client
device_scope = device_scope_request.device_scope if device_scope_request else "all"
client_device_id = device_scope_request.client_device_id if device_scope_request else None
capped_limit = max(1, min(limit, 20))
fetch_limit = min(capped_limit * 3, 60)
normalized_query = (query or "").strip()
if not normalized_query:
if ledger_kinds is not None:
return []
memories = read_canonical_memories(
uid,
limit=capped_limit,
offset=0,
db_client=client,
device_scope_request=device_scope_request,
)
return [
{
"memory_id": memory.id,
"content": memory.content,
"tier": memory.memory_tier.value if memory.memory_tier is not None else MemoryLayer.short_term.value,
"date": memory.updated_at.isoformat(),
"visibility": memory.visibility,
"is_locked": memory.is_locked,
**public_belief_overlay_json(memory, now=datetime.now(timezone.utc)),
}
for memory in memories[:capped_limit]
]
from utils.memory.atom_keyword_index import (
keyword_search_ledger_memory_ids,
keyword_search_memory_ids,
merge_memory_search_ids,
require_typesense_projection_ready,
)
if ledger_kinds is None:
keyword_ids = keyword_search_memory_ids(uid, normalized_query, limit=fetch_limit, db_client=client)
else:
require_typesense_projection_ready(uid)
keyword_ids = keyword_search_ledger_memory_ids(
uid,
normalized_query,
kinds=ledger_kinds,
limit=fetch_limit,
db_client=client,
)
if vector_query is None:
from database.vector_db import query_memory_vector_candidates
vector_query_fn = query_memory_vector_candidates
else:
vector_query_fn = vector_query
if ledger_kinds is None:
vector_result = vector_query_fn(uid, normalized_query, limit=fetch_limit)
else:
vector_result = vector_query_fn(
uid,
normalized_query,
limit=fetch_limit,
ledger_kinds=sorted(ledger_kinds),
)
vector_ids = [hit.memory_id for hit in vector_result.hits if hit.memory_id]
merged_ids = merge_memory_search_ids(keyword_ids, vector_ids)
if not merged_ids:
return []
now = datetime.now(timezone.utc)
policy = MemoryAccessPolicy.for_omi_chat(archive_capability=False)
hydration = _hydrate_bounded_ledger_search_items(