forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversations.py
More file actions
2340 lines (1955 loc) · 96.7 KB
/
Copy pathconversations.py
File metadata and controls
2340 lines (1955 loc) · 96.7 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
import copy
import json
import logging
import uuid
import zlib
from collections.abc import Mapping
from datetime import datetime, timedelta, timezone
from typing import List, Optional, Dict, Any, Callable
from google.api_core.exceptions import AlreadyExists, Conflict, NotFound
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
import utils.other.hume as hume
from models.audio_file import AudioFile
from models.client_processing import PROJECTION_FAMILY_FIELDS
from models.conversation_enums import ConversationStatus, PostProcessingModel, PostProcessingStatus
from models.conversation_photo import ConversationPhoto
from models.transcript_segment import TranscriptSegment
from utils import encryption
from utils.conversations.transcript_hash import (
canonicalize_transcript_segments_for_storage,
transcript_sha256_for_binding,
)
from ._client import db, delete_collection_recursive, get_firestore_client, run_transactional
from .firestore_index_registry import MCP_CONVERSATION_CARD_QUERY_SPECS, STALE_IN_PROGRESS_CONVERSATIONS_QUERY
from .firestore_read_metrics import FirestoreReadOutcome, FirestoreReadSite, record_document_read
from .conversation_revisions import ensure_timezone_aware, firestore_revision_datetime
from .helpers import set_data_protection_level, prepare_for_write, prepare_for_read, with_photos
from utils.other.list_budget import ListReadBudget, ListReadBudgetExhausted, budgeted_stream_iter
from utils.other.storage import list_audio_chunks
from .first_open_obligations import (
FIRST_OPEN_EFFECTS,
claim_authorized_first_open_work,
claim_first_open_work,
commit_first_open_app_result,
commit_first_open_app_usage,
commit_first_open_conversation_patch,
commit_first_open_folder_count,
complete_first_open_effect,
finish_first_open_work,
first_open_effect_is_authorized,
initialize_first_open_work,
)
logger = logging.getLogger(__name__)
conversations_collection = 'conversations'
_LIFECYCLE_FIELDS = frozenset({'status', 'discarded'})
# Top-level fields behind the Typesense conversation projection (see
# utils/conversations/typesense_index.py). A generic update re-syncs the index
# only when it touches one of these roots — segment/photo/app-result writes
# never reach Typesense, so they must not pay for it.
_SEARCH_INDEXED_FIELD_ROOTS = frozenset({'structured', 'created_at', 'started_at', 'finished_at', 'geolocation'})
_PUBLIC_TRANSCRIPT_MAX_STORED_BYTES = 256 * 1024
_PUBLIC_TRANSCRIPT_MAX_DECODED_BYTES = 512 * 1024
_PUBLIC_TRANSCRIPT_MAX_SEGMENTS = 4096
_PUBLIC_TRANSCRIPT_MAX_SEGMENT_TEXT_CHARS = 24_000
_MCP_CONVERSATION_CARD_FIELD_PATHS = (
'id',
'discarded',
'created_at',
'started_at',
'finished_at',
'language',
'is_locked',
'data_protection_level',
'user_title',
'structured.title',
'structured.overview',
'structured.category',
'structured.emoji',
)
_MCP_CONVERSATION_TRANSCRIPT_FIELD_PATHS = _MCP_CONVERSATION_CARD_FIELD_PATHS + (
'transcript_segments',
'transcript_segments_compressed',
)
def get_conversation_ids(uid: str) -> List[str]:
"""Return all conversation document IDs for a user without decrypting any fields.
IDs-only projection (``select([])``) — used for bulk operations like account deletion where
only the IDs are needed (e.g. to purge derived Pinecone vectors).
"""
coll = db.collection('users').document(uid).collection(conversations_collection)
return [doc.id for doc in coll.select([]).stream()]
# *********************************
# ******* ENCRYPTION HELPERS ******
# *********************************
def _decrypt_conversation_data(conversation_data: Dict[str, Any], uid: str) -> Dict[str, Any]:
data = copy.deepcopy(conversation_data)
if 'transcript_segments' not in data:
return data
if isinstance(data['transcript_segments'], str):
try:
decrypted_payload = encryption.decrypt(data['transcript_segments'], uid)
if data.get('transcript_segments_compressed'):
compressed_bytes = bytes.fromhex(decrypted_payload)
decompressed_json = zlib.decompress(compressed_bytes).decode('utf-8')
data['transcript_segments'] = json.loads(decompressed_json)
# backward compatibility, will be removed soon
else:
data['transcript_segments'] = json.loads(decrypted_payload)
except (json.JSONDecodeError, TypeError, zlib.error, ValueError) as e:
logger.error(f"{e} {uid}")
data['transcript_segments'] = []
# backward compatibility, will be removed soon
elif isinstance(data['transcript_segments'], bytes):
try:
compressed_bytes = data['transcript_segments']
if data.get('transcript_segments_compressed'):
decompressed_json = zlib.decompress(compressed_bytes).decode('utf-8')
data['transcript_segments'] = json.loads(decompressed_json)
except (json.JSONDecodeError, TypeError, zlib.error, ValueError) as e:
logger.error(f"{e} {uid}")
data['transcript_segments'] = []
return data
def _prepare_conversation_for_write(data: Dict[str, Any], uid: str, level: str) -> Dict[str, Any]:
data = copy.deepcopy(data)
if 'transcript_segments' in data and isinstance(data['transcript_segments'], list):
data['transcript_segments'] = canonicalize_transcript_segments_for_storage(data['transcript_segments'])
segments_json = json.dumps(data['transcript_segments'])
compressed_segments_bytes = zlib.compress(segments_json.encode('utf-8'))
data['transcript_segments_compressed'] = True
if level == 'enhanced':
encrypted_segments = encryption.encrypt(compressed_segments_bytes.hex(), uid)
data['transcript_segments'] = encrypted_segments
else:
data['transcript_segments'] = compressed_segments_bytes
return data
def encode_conversation_for_write(
uid: str, conversation_data: Dict[str, Any], level: str = 'standard'
) -> Dict[str, Any]:
"""Encode a conversation exactly as the write path stores it.
The seam exists for harnesses that seed Firestore directly: a hand-written
document with a plain ``transcript_segments`` list is a state production
never writes, and seeding one hides encoding-aware guard bugs.
"""
return _prepare_conversation_for_write(conversation_data, uid, level)
def _require_segment_list(parsed: Any) -> List[Any]:
if not isinstance(parsed, list):
raise ValueError(f'undecodable transcript_segments: parsed {type(parsed).__name__}')
return parsed
def _decode_transcript_segments_strict(uid: str, raw_segments: Any, compressed: bool) -> List[Any]:
"""Decode a stored ``transcript_segments`` blob, raising when it cannot be read.
The read path swallows decode failures into an empty list, which is safe for
rendering but unsafe for a caller deciding whether a conversation is empty
or whether a client projection may bind to it. Binding is authorization,
not display: an unreadable blob must not become ``[]``.
"""
if isinstance(raw_segments, list):
return raw_segments
if isinstance(raw_segments, str):
payload = encryption.decrypt(raw_segments, uid)
if compressed:
parsed = json.loads(zlib.decompress(bytes.fromhex(payload)).decode('utf-8'))
else:
parsed = json.loads(payload)
return _require_segment_list(parsed)
if isinstance(raw_segments, bytes) and compressed:
return _require_segment_list(json.loads(zlib.decompress(raw_segments).decode('utf-8')))
raise ValueError(f'undecodable transcript_segments: {type(raw_segments).__name__} compressed={compressed}')
def _decode_public_transcript_segments_bounded(
uid: str,
raw_segments: Any,
*,
compressed: bool,
max_stored_bytes: int = _PUBLIC_TRANSCRIPT_MAX_STORED_BYTES,
max_decoded_bytes: int = _PUBLIC_TRANSCRIPT_MAX_DECODED_BYTES,
max_segments: int = _PUBLIC_TRANSCRIPT_MAX_SEGMENTS,
max_segment_text_chars: int = _PUBLIC_TRANSCRIPT_MAX_SEGMENT_TEXT_CHARS,
decompressor_factory: Callable[[], Any] = zlib.decompressobj,
) -> List[Dict[str, Any]]:
"""Decode only the bounded compressed transcript shape used by public chat."""
def invalid() -> ValueError:
return ValueError('invalid bounded public transcript')
if (
compressed is not True
or max_stored_bytes <= 0
or max_decoded_bytes <= 0
or max_segments < 0
or max_segment_text_chars < 0
):
raise invalid()
try:
if isinstance(raw_segments, str):
# Enhanced storage encrypts the hex-encoded compressed bytes. Check
# the encoded representation before invoking the decryptor so a
# malformed Firestore value cannot allocate without a fixed bound.
max_encrypted_chars = (((max_stored_bytes * 2) + 28 + 2) // 3) * 4
if not raw_segments.isascii() or len(raw_segments) > max_encrypted_chars:
raise invalid()
decrypted_hex = encryption.decrypt(raw_segments, uid)
if len(decrypted_hex) > max_stored_bytes * 2 or len(decrypted_hex) % 2 != 0:
raise invalid()
compressed_bytes = bytes.fromhex(decrypted_hex)
elif isinstance(raw_segments, (bytes, bytearray, memoryview)):
if len(raw_segments) > max_stored_bytes:
raise invalid()
compressed_bytes = bytes(raw_segments)
else:
raise invalid()
if len(compressed_bytes) > max_stored_bytes:
raise invalid()
decompressor = decompressor_factory()
decoded = decompressor.decompress(compressed_bytes, max_decoded_bytes + 1)
if (
len(decoded) > max_decoded_bytes
or decompressor.unconsumed_tail
or not decompressor.eof
or decompressor.unused_data
):
raise invalid()
parsed = json.loads(decoded.decode('utf-8'))
if not isinstance(parsed, list) or len(parsed) > max_segments:
raise invalid()
safe_segments: List[Dict[str, Any]] = []
for segment in parsed:
if not isinstance(segment, Mapping):
raise invalid()
text = segment.get('text')
if not isinstance(text, str) or len(text) > max_segment_text_chars:
raise invalid()
safe_segment: Dict[str, Any] = {'text': text}
is_user = segment.get('is_user')
if isinstance(is_user, bool):
safe_segment['is_user'] = is_user
speaker_id = segment.get('speaker_id')
if isinstance(speaker_id, int) and not isinstance(speaker_id, bool):
safe_segment['speaker_id'] = speaker_id
safe_segments.append(safe_segment)
return safe_segments
except (json.JSONDecodeError, RecursionError, TypeError, UnicodeDecodeError, ValueError, zlib.error) as exc:
if isinstance(exc, ValueError) and str(exc) == 'invalid bounded public transcript':
raise
raise invalid() from exc
def raw_conversation_has_content(uid: str, conversation: Dict[str, Any]) -> bool:
"""Decide whether an un-decoded Firestore snapshot holds user content.
``transcript_segments`` is written compressed (and encrypted for enhanced
users), so an empty segment list is a non-empty blob on the raw document.
Only the decoded value distinguishes an empty recording from a real one.
Undecodable segments count as content: never delete data we cannot read.
"""
if conversation.get('has_content') or conversation.get('photos'):
return True
raw_segments = conversation.get('transcript_segments')
if not raw_segments:
return False
try:
segments = _decode_transcript_segments_strict(
uid, raw_segments, bool(conversation.get('transcript_segments_compressed'))
)
except (json.JSONDecodeError, TypeError, zlib.error, ValueError) as e:
logger.error(f'raw_conversation_has_content: undecodable segments, assuming content. {uid} {e}')
return True
return bool(segments)
def _prepare_conversation_for_read(conversation_data: Optional[Dict[str, Any]], uid: str) -> Optional[Dict[str, Any]]:
if not conversation_data:
return None
data = copy.deepcopy(conversation_data)
# User titles are durable overrides. Conversation processing owns the
# generated title, but must never erase an explicit user edit.
user_title = data.get('user_title')
if isinstance(user_title, str):
structured = data.get('structured')
if not isinstance(structured, dict):
structured = {}
data['structured'] = structured
structured['title'] = user_title
level = data.get('data_protection_level')
if level == 'enhanced':
return _decrypt_conversation_data(data, uid)
# Handle standard level with potential compression
if data.get('transcript_segments_compressed'):
if 'transcript_segments' in data and isinstance(data['transcript_segments'], bytes):
try:
decompressed_json = zlib.decompress(data['transcript_segments']).decode('utf-8')
data['transcript_segments'] = json.loads(decompressed_json)
except (json.JSONDecodeError, TypeError, zlib.error) as e:
logger.error(e)
pass
return data
def _document_data_with_revision(document) -> Optional[Dict[str, Any]]:
"""Return Firestore document data with its canonical server revision."""
data = document.to_dict()
if data is None:
return None
revision = firestore_revision_datetime(getattr(document, 'update_time', None))
if revision is not None:
data['updated_at'] = revision
return data
def prepare_photo_for_write(data: Dict[str, Any], uid: str, level: str) -> Dict[str, Any]:
data = copy.deepcopy(data)
data['data_protection_level'] = level
if level == 'enhanced' and 'base64' in data and isinstance(data['base64'], str):
data['base64'] = encryption.encrypt(data['base64'], uid)
return data
def _prepare_photo_for_read(photo_data: Optional[Dict[str, Any]], uid: str) -> Optional[Dict[str, Any]]:
if not photo_data:
return None
data = copy.deepcopy(photo_data)
level = data.get('data_protection_level')
if level == 'enhanced' and 'base64' in data and isinstance(data['base64'], str):
try:
data['base64'] = encryption.decrypt(data['base64'], uid)
except Exception:
# If decryption fails, it might be already decrypted or not encrypted.
# We can log this, but for now, we'll just pass.
pass
return data
@prepare_for_read(decrypt_func=_prepare_photo_for_read)
def get_conversation_photos(uid: str, conversation_id: str):
user_ref = db.collection('users').document(uid)
conversation_ref = user_ref.collection(conversations_collection).document(conversation_id)
photos_ref = conversation_ref.collection('photos')
photos = [doc.to_dict() for doc in photos_ref.stream()]
return photos
def iter_all_conversation_photos(uid: str):
start_key = db.document(f'users/{uid}/conversations/ /photos/ ')
end_key = db.document(f'users/{uid}/conversations//photos/')
query = (
db.collection_group('photos')
.where(filter=FieldFilter('__name__', '>=', start_key))
.where(filter=FieldFilter('__name__', '<=', end_key))
)
for doc in query.stream():
# Path format: users/{uid}/conversations/{conversation_id}/photos/{photo_id}
parts = doc.reference.path.split('/')
if len(parts) >= 6 and parts[-2] == 'photos' and parts[-4] == 'conversations':
conversation_id = parts[-3]
yield conversation_id, doc.to_dict()
def _sync_conversation_search_index(uid: str, conversation_id: str) -> None:
"""Converge the Typesense projection after a durable write (fail-open).
The import stays inside the hook on purpose: several test harnesses load
this module against stubbed ``utils`` packages without a real
``utils.conversations`` path, and a module-top import of the projection
breaks them (PR #12819 round one).
"""
try:
from utils.conversations.typesense_index import sync_conversation_index_after_write
sync_conversation_index_after_write(uid, conversation_id)
except Exception as exc:
logger.warning(
"conversation Typesense sync hook failed uid=%s conversation_id=%s: %s", uid, conversation_id, exc
)
def _delete_conversation_search_index(uid: str, conversation_id: str) -> None:
"""Remove one conversation from Typesense after a durable delete (fail-open)."""
try:
from utils.conversations.typesense_index import delete_conversation_index_doc
delete_conversation_index_doc(uid, conversation_id)
except Exception as exc:
logger.warning(
"conversation Typesense delete hook failed uid=%s conversation_id=%s: %s", uid, conversation_id, exc
)
# *****************************
# ********** CRUD *************
# *****************************
@set_data_protection_level(data_arg_name='conversation_data')
@prepare_for_write(data_arg_name='conversation_data', prepare_func=_prepare_conversation_for_write)
def upsert_conversation_with_lifecycle(uid: str, conversation_data: dict):
# `updated_at` is Firestore document metadata exposed by reads, never an
# application-owned field to replay into a later write.
conversation_data.pop('updated_at', None)
if 'audio_base64_url' in conversation_data:
del conversation_data['audio_base64_url']
if 'photos' in conversation_data:
del conversation_data['photos']
user_ref = db.collection('users').document(uid)
conversation_ref = user_ref.collection(conversations_collection).document(conversation_data['id'])
transaction = db.transaction()
@firestore.transactional
def _write_processing_result(transaction):
write_data = copy.deepcopy(conversation_data)
existing_snapshot = conversation_ref.get(transaction=transaction)
if getattr(existing_snapshot, 'exists', False):
existing = existing_snapshot.to_dict() or {}
# Processing owns generated content, while these fields are explicitly
# user-owned. The transaction retries if a concurrent mutation lands,
# so an older in-memory Conversation cannot clobber that edit.
# A null existing value means "never user-set" (stub docs dump None
# fields), so only non-null values are preserved — otherwise the
# stub's folder_id: None would revert every AI folder assignment.
for field in ('starred', 'folder_id', 'visibility', 'user_title'):
if existing.get(field) is not None:
write_data[field] = existing[field]
# folder_id is user-owned even when explicitly cleared: the folder
# move endpoints stamp folder_user_set, so "no folder" chosen by the
# user (folder_id None + marker) must survive processing output.
# Only a stub's never-user-touched None may be overwritten by the
# AI folder assignment above.
if existing.get('folder_user_set'):
write_data['folder_id'] = existing.get('folder_id')
user_title = existing.get('user_title')
if isinstance(user_title, str):
structured = write_data.get('structured')
if not isinstance(structured, dict):
structured = {}
write_data['structured'] = structured
structured['title'] = user_title
transaction.set(conversation_ref, write_data, merge=True)
return
write_data.setdefault('has_photos', False)
transaction.set(conversation_ref, write_data)
_write_processing_result(transaction)
_sync_conversation_search_index(uid, conversation_data['id'])
@set_data_protection_level(data_arg_name='conversation_data')
@prepare_for_write(
data_arg_name='conversation_data',
prepare_func=_prepare_conversation_for_write,
preserve_result=True,
)
def persist_processing_result_with_lifecycle(
uid: str,
conversation_data: dict,
) -> bool:
"""Merge a processor result into its conversation.
Only deletion is refused. Lifecycle state is not: a discard is the system's
own verdict that a conversation held nothing, and a status is bookkeeping
about which generation ran, and every processor re-derives what it writes
from the content in front of it. Fencing on either stranded conversations a
later sync had filled with speech — transcribed, untitled, and invisible to
their owner — to prevent races that had never been observed.
"""
conversation_data.pop('updated_at', None)
if 'audio_base64_url' in conversation_data:
del conversation_data['audio_base64_url']
if 'photos' in conversation_data:
del conversation_data['photos']
user_ref = db.collection('users').document(uid)
conversation_ref = user_ref.collection(conversations_collection).document(conversation_data['id'])
transaction = db.transaction()
@firestore.transactional
def _persist(transaction) -> bool:
write_data = copy.deepcopy(conversation_data)
existing_snapshot = conversation_ref.get(transaction=transaction)
if not getattr(existing_snapshot, 'exists', False):
# A processor is never an authority to recreate a conversation.
# Deleting one is a decision its owner made, and a merge write to a
# missing document would create it, so a late processor could bring
# back what they removed and emit derived side effects from it.
return False
existing = existing_snapshot.to_dict() or {}
# Generated processing content never owns user-managed fields.
# A null existing value means "never user-set" (stub docs dump None
# fields), so only non-null values are preserved — otherwise the
# stub's folder_id: None would revert every AI folder assignment.
for field in ('starred', 'folder_id', 'visibility', 'user_title'):
if existing.get(field) is not None:
write_data[field] = existing[field]
# folder_id is user-owned even when explicitly cleared: the folder
# move endpoints stamp folder_user_set, so "no folder" chosen by the
# user (folder_id None + marker) must survive processing output.
# Only a stub's never-user-touched None may be overwritten by the
# AI folder assignment above.
if existing.get('folder_user_set'):
write_data['folder_id'] = existing.get('folder_id')
user_title = existing.get('user_title')
if isinstance(user_title, str):
structured = write_data.get('structured')
if not isinstance(structured, dict):
structured = {}
write_data['structured'] = structured
structured['title'] = user_title
transaction.set(conversation_ref, write_data, merge=True)
return True
persisted = _persist(transaction)
if persisted:
_sync_conversation_search_index(uid, conversation_data['id'])
else:
# A processor result for a conversation whose owner is already gone:
# converge the search index to absence too.
_delete_conversation_search_index(uid, conversation_data['id'])
return persisted
@set_data_protection_level(data_arg_name='conversation_data')
@prepare_for_write(
data_arg_name='conversation_data',
prepare_func=_prepare_conversation_for_write,
preserve_result=True,
)
def create_conversation_if_absent_with_lifecycle(uid: str, conversation_data: dict) -> bool:
"""Atomically create a conversation document if it does not already exist."""
conversation_data.pop('updated_at', None)
if 'audio_base64_url' in conversation_data:
del conversation_data['audio_base64_url']
if 'photos' in conversation_data:
del conversation_data['photos']
conversation_data.setdefault('has_photos', False)
user_ref = db.collection('users').document(uid)
conversation_ref = user_ref.collection(conversations_collection).document(conversation_data['id'])
try:
conversation_ref.create(conversation_data)
except (AlreadyExists, Conflict):
# The conversation exists but may be new to the search index (writer
# lag, backfill gap); the read-back sync converges it either way.
_sync_conversation_search_index(uid, conversation_data['id'])
return False
_sync_conversation_search_index(uid, conversation_data['id'])
return True
@prepare_for_read(decrypt_func=_prepare_conversation_for_read)
@with_photos(get_conversation_photos)
def get_conversation(uid, conversation_id, *, read_site: FirestoreReadSite = FirestoreReadSite.UNATTRIBUTED):
user_ref = db.collection('users').document(uid)
conversation_ref = user_ref.collection(conversations_collection).document(conversation_id)
conversation_data = _document_data_with_revision(conversation_ref.get())
record_document_read(
read_site, FirestoreReadOutcome.HIT if conversation_data is not None else FirestoreReadOutcome.MISS
)
return conversation_data
def get_public_shared_conversation_bounded(
uid: str,
conversation_id: str,
*,
firestore_client: Any = None,
) -> Optional[Dict[str, Any]]:
"""Read only public-chat fields and decode the transcript within fixed bounds."""
client = firestore_client if firestore_client is not None else get_firestore_client()
conversation_ref = (
client.collection('users').document(uid).collection(conversations_collection).document(conversation_id)
)
snapshot = conversation_ref.get(
field_paths=[
'visibility',
'is_locked',
'transcript_segments_compressed',
'transcript_segments',
]
)
if not snapshot.exists:
return None
raw = snapshot.to_dict()
if not isinstance(raw, dict):
return None
visibility = raw.get('visibility')
is_locked = raw.get('is_locked', False)
public_conversation: Dict[str, Any] = {
'visibility': visibility,
'is_locked': is_locked,
}
if not isinstance(visibility, str) or visibility not in {'shared', 'public'} or is_locked:
return public_conversation
try:
public_conversation['transcript_segments'] = _decode_public_transcript_segments_bounded(
uid,
raw.get('transcript_segments'),
compressed=raw.get('transcript_segments_compressed') is True,
)
except ValueError:
return None
return public_conversation
def get_conversation_audio_stamp(uid: str, conversation_id: str) -> Optional[dict]:
"""Field-masked read of just the conversation_audio stamp — cheap enough for
the pusher's per-batch staleness check (the full doc carries transcripts)."""
doc_ref = db.collection('users').document(uid).collection(conversations_collection).document(conversation_id)
snapshot = doc_ref.get(field_paths=['conversation_audio'])
if not snapshot.exists:
return None
return (snapshot.to_dict() or {}).get('conversation_audio')
@prepare_for_read(decrypt_func=_prepare_conversation_for_read)
@with_photos(get_conversation_photos)
def get_conversations(
uid: str,
limit: int = 100,
offset: int = 0,
include_discarded: bool = False,
statuses: List[str] = [],
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
categories: Optional[List[str]] = None,
folder_id: Optional[str] = None,
starred: Optional[bool] = None,
date_field: str = 'created_at',
):
conversations_ref = db.collection('users').document(uid).collection(conversations_collection)
if not include_discarded:
conversations_ref = conversations_ref.where(filter=FieldFilter('discarded', '==', False))
if len(statuses) > 0:
conversations_ref = conversations_ref.where(filter=FieldFilter('status', 'in', statuses))
if categories:
conversations_ref = conversations_ref.where(filter=FieldFilter('structured.category', 'in', categories))
if folder_id:
conversations_ref = conversations_ref.where(filter=FieldFilter('folder_id', '==', folder_id))
if starred is not None:
conversations_ref = conversations_ref.where(filter=FieldFilter('starred', '==', starred))
# Apply date range filters if provided
if start_date:
conversations_ref = conversations_ref.where(filter=FieldFilter(date_field, '>=', start_date))
if end_date:
conversations_ref = conversations_ref.where(filter=FieldFilter(date_field, '<=', end_date))
# Sort — must match the range-filter field to satisfy Firestore index requirements
sort_field = date_field if (start_date or end_date) else 'created_at'
conversations_ref = conversations_ref.order_by(sort_field, direction=firestore.Query.DESCENDING)
# Limits
conversations_ref = conversations_ref.limit(limit).offset(offset)
conversations = [_document_data_with_revision(doc) for doc in conversations_ref.stream()]
conversations = [conversation for conversation in conversations if conversation is not None]
return conversations
def get_conversations_count(
uid: str,
include_discarded: bool = False,
statuses: Optional[List[str]] = None,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
categories: Optional[List[str]] = None,
folder_id: Optional[str] = None,
starred: Optional[bool] = None,
sources: Optional[List[str]] = None,
):
conversations_ref = db.collection('users').document(uid).collection(conversations_collection)
if not include_discarded:
conversations_ref = conversations_ref.where(filter=FieldFilter('discarded', '==', False))
if sources:
# The archive's `sources=omi` must compose with the multi-status `in`
# filter below. Firestore allows only one disjunctive `in` filter per
# query, so a singleton source is an equality predicate, not a
# degenerate `in` predicate.
if len(sources) == 1:
conversations_ref = conversations_ref.where(filter=FieldFilter('source', '==', sources[0]))
else:
conversations_ref = conversations_ref.where(filter=FieldFilter('source', 'in', sources))
if statuses:
if len(statuses) == 1:
conversations_ref = conversations_ref.where(filter=FieldFilter('status', '==', statuses[0]))
else:
conversations_ref = conversations_ref.where(filter=FieldFilter('status', 'in', statuses))
if categories:
conversations_ref = conversations_ref.where(filter=FieldFilter('structured.category', 'in', categories))
if folder_id:
conversations_ref = conversations_ref.where(filter=FieldFilter('folder_id', '==', folder_id))
if starred is not None:
conversations_ref = conversations_ref.where(filter=FieldFilter('starred', '==', starred))
if start_date:
conversations_ref = conversations_ref.where(filter=FieldFilter('created_at', '>=', start_date))
if end_date:
conversations_ref = conversations_ref.where(filter=FieldFilter('created_at', '<=', end_date))
result = conversations_ref.count().get()
return int(result[0][0].value)
@prepare_for_read(decrypt_func=_prepare_conversation_for_read)
def get_conversations_without_photos(
uid: str,
limit: int = 100,
offset: int = 0,
include_discarded: bool = False,
statuses: List[str] = [],
sources: Optional[List[str]] = None,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
categories: Optional[List[str]] = None,
folder_id: Optional[str] = None,
starred: Optional[bool] = None,
budget: Optional[ListReadBudget] = None,
):
"""
Same as get_conversations but without loading photos.
Much faster for list endpoints and bulk operations where full photo base64 isn't needed.
With a request ``budget`` (#11831) the server-side ``offset()`` is charged
before the query — Firestore bills and streams every skipped row, so a
large offset consumes real read work — and the page's stream runs under
the budget's per-RPC timeout with each fetched row charged. An offset
that exhausts the allowance returns an empty, explicitly truncated page
instead of pretending to be complete.
"""
conversations_ref = db.collection('users').document(uid).collection(conversations_collection)
if not include_discarded:
conversations_ref = conversations_ref.where(filter=FieldFilter('discarded', '==', False))
if sources:
# Keep the paginated list semantically identical to the count query;
# see `get_conversations_count` for why a singleton is equality.
if len(sources) == 1:
conversations_ref = conversations_ref.where(filter=FieldFilter('source', '==', sources[0]))
else:
conversations_ref = conversations_ref.where(filter=FieldFilter('source', 'in', sources))
if len(statuses) > 0:
if len(statuses) == 1:
conversations_ref = conversations_ref.where(filter=FieldFilter('status', '==', statuses[0]))
else:
conversations_ref = conversations_ref.where(filter=FieldFilter('status', 'in', statuses))
if categories:
conversations_ref = conversations_ref.where(filter=FieldFilter('structured.category', 'in', categories))
if folder_id:
conversations_ref = conversations_ref.where(filter=FieldFilter('folder_id', '==', folder_id))
if starred is not None:
conversations_ref = conversations_ref.where(filter=FieldFilter('starred', '==', starred))
# Apply date range filters if provided
if start_date:
conversations_ref = conversations_ref.where(filter=FieldFilter('created_at', '>=', start_date))
if end_date:
conversations_ref = conversations_ref.where(filter=FieldFilter('created_at', '<=', end_date))
# Sort
conversations_ref = conversations_ref.order_by('created_at', direction=firestore.Query.DESCENDING)
if budget is not None and offset > 0:
# Charge the skipped prefix before querying: Firestore streams (and
# bills) every offset row even though none is yielded here.
try:
budget.charge(offset)
except ListReadBudgetExhausted:
return []
# Limits
conversations_ref = conversations_ref.limit(limit).offset(offset)
conversations = []
try:
for doc in budgeted_stream_iter(conversations_ref, budget):
conversations.append(_document_data_with_revision(doc))
except ListReadBudgetExhausted:
# Deadline or allowance ended mid-page: rows already fetched stay in
# the list as an honest created_at-DESC prefix; the budget remains
# flagged truncated so the route marks the response (#11831).
pass
conversations = [conversation for conversation in conversations if conversation is not None]
return conversations
@prepare_for_read(decrypt_func=_prepare_conversation_for_read)
def get_mcp_conversation_cards(
uid: str,
limit: int,
offset: int,
*,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
categories: Optional[List[str]] = None,
firestore_client: Any = None,
) -> List[Dict[str, Any]]:
"""Return the transcript-free Firestore projection used by hosted MCP lists."""
client = firestore_client if firestore_client is not None else get_firestore_client()
collection = client.collection('users').document(uid).collection(conversations_collection)
query_spec = MCP_CONVERSATION_CARD_QUERY_SPECS[(bool(categories), start_date is not None, end_date is not None)]
query = query_spec.build(
collection,
{
'discarded': False,
'status': 'completed',
'categories': categories,
'start_date': start_date,
'end_date': end_date,
},
field_filter_factory=FieldFilter,
)
query = (
query.order_by('created_at', direction=firestore.Query.DESCENDING)
.select(list(_MCP_CONVERSATION_CARD_FIELD_PATHS))
.limit(limit)
.offset(offset)
)
conversations: List[Dict[str, Any]] = []
for doc in query.stream():
conversation = _document_data_with_revision(doc)
if conversation is None:
continue
conversation.setdefault('id', doc.id)
conversations.append(conversation)
return conversations
@prepare_for_read(decrypt_func=_prepare_conversation_for_read)
def get_mcp_conversations_by_id(
uid: str,
conversation_ids: List[str],
*,
include_transcript: bool,
include_discarded: bool = False,
firestore_client: Any = None,
) -> List[Dict[str, Any]]:
"""Return MCP card fields, optionally with transcript blobs, without photos or other result payloads."""
client = firestore_client if firestore_client is not None else get_firestore_client()
conversations_ref = client.collection('users').document(uid).collection(conversations_collection)
doc_refs = [conversations_ref.document(str(conversation_id)) for conversation_id in conversation_ids]
field_paths = _MCP_CONVERSATION_TRANSCRIPT_FIELD_PATHS if include_transcript else _MCP_CONVERSATION_CARD_FIELD_PATHS
docs = client.get_all(doc_refs, field_paths=list(field_paths))
conversations_by_id: Dict[str, Dict[str, Any]] = {}
for doc in docs:
if not doc.exists:
continue
data = _document_data_with_revision(doc)
if data is None:
continue
if data.get('discarded') and not include_discarded:
continue
data.setdefault('id', doc.id)
conversations_by_id[str(data['id'])] = data
return [
conversations_by_id[str(conversation_id)]
for conversation_id in conversation_ids
if str(conversation_id) in conversations_by_id
]
def iter_all_conversations(uid: str, batch_size: int = 400, include_discarded: bool = True):
"""Yield all conversations for a user, decrypted, in batches. Used for streaming data export."""
conversations_ref = db.collection('users').document(uid).collection(conversations_collection)
if not include_discarded:
conversations_ref = conversations_ref.where(filter=FieldFilter('discarded', '==', False))
conversations_ref = conversations_ref.order_by('created_at', direction=firestore.Query.DESCENDING)
cursor = None
while True:
batch_ref = conversations_ref.limit(batch_size)
if cursor is not None:
batch_ref = batch_ref.start_after(cursor)
batch = []
snapshots = list(batch_ref.stream())
for doc in snapshots:
conv = doc.to_dict()
conv = _prepare_conversation_for_read(conv, uid) or conv
batch.append(conv)
yield from batch
if len(snapshots) < batch_size:
break
cursor = snapshots[-1]
def update_conversation(uid: str, conversation_id: str, update_data: dict) -> bool:
"""Apply ``update_data`` to a conversation.
Returns False when the conversation no longer exists, so callers that keep
producing work for it (e.g. the pusher's private-cloud audio sync) can stop
instead of writing into a deleted owner.
"""
lifecycle_fields = _LIFECYCLE_FIELDS.intersection(update_data)
if lifecycle_fields:
raise ValueError(
'lifecycle fields may only be changed through utils.conversations.lifecycle: '
+ ', '.join(sorted(lifecycle_fields))
)
doc_ref = db.collection('users').document(uid).collection(conversations_collection).document(conversation_id)
doc_snapshot = doc_ref.get()
if not doc_snapshot.exists:
return False
doc_level = doc_snapshot.to_dict().get('data_protection_level', 'standard')
prepared_data = _prepare_conversation_for_write(update_data, uid, doc_level)
try:
doc_ref.update(prepared_data)
except NotFound:
# The conversation was deleted between the existence read above and
# this commit. The contract of this function is to report a gone owner
# as False — not to raise — so callers like the pusher's private-cloud
# audio sync take their designed gone-owner path (stop syncing, release
# the audio budget) instead of logging an ERROR and retrying forever.
return False
if _SEARCH_INDEXED_FIELD_ROOTS.intersection(str(key).split('.', 1)[0] for key in update_data):
_sync_conversation_search_index(uid, conversation_id)
return True
def try_claim_conversation_memory_analytics(uid: str, conversation_id: str, firestore_client: Any = None) -> bool:
"""Atomically claim the one analytics success slot for a conversation.
The marker lives in Firestore under the authoritative conversation document,
rather than in a best-effort cache. ``create`` is atomic: the caller that
creates the marker is the only caller allowed to capture the optional
analytics event; an existing marker means a retry/re-finalization must not
emit again. It deliberately has no TTL, so Redis loss, cache eviction, and
arbitrary retry windows cannot re-open the slot.
Callers must treat storage errors as *not acquired*. This is telemetry-only:
failing closed avoids a possible duplicate and must never interrupt the
underlying conversation extraction.
"""
client = firestore_client if firestore_client is not None else get_firestore_client()
marker_ref = (
client.collection('users')
.document(uid)
.collection(conversations_collection)
.document(conversation_id)
.collection('analytics_markers')
.document('conversation_memories_extracted')
)
try:
marker_ref.create({'created_at': firestore.SERVER_TIMESTAMP})
return True
except AlreadyExists:
return False
def create_audio_files_from_chunks(
uid: str,
conversation_id: str,
) -> List[AudioFile]:
"""
Create audio file records by merging chunks from a conversation.
Chunks are merged unless there's a gap > 30 seconds between segments.
Args:
uid: User ID
conversation_id: Conversation ID
Returns:
List of AudioFile objects
"""
# Get all chunks for this conversation