forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.py
More file actions
2072 lines (1926 loc) · 93.6 KB
/
Copy pathsync.py
File metadata and controls
2072 lines (1926 loc) · 93.6 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 asyncio
import json
import logging
import os
import shutil
import threading
import time
import uuid as _uuid
from datetime import datetime, timedelta, timezone
from typing import Dict, List, Optional
from fastapi import APIRouter, UploadFile, File, Depends, HTTPException, Query, Request, Response, Header
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from database import conversations as conversations_db
from database import fair_use as fair_use_db
from database import users as users_db
from database.firestore_read_metrics import FirestoreReadSite
from database.sync_jobs import (
SyncLedgerFenceMode,
TERMINAL_STATUSES,
create_sync_job,
delete_sync_job,
delete_sync_job_run_lock_epoch,
fenced_mark_job_queued_for_retry,
get_sync_ledger_fence_mode,
get_sync_job,
is_sync_job_stale,
mark_job_completed,
mark_job_queued_for_retry,
sync_job_uses_ledger_fence,
try_acquire_sync_job_run_lock,
try_acquire_job_run_lock,
release_job_run_lock,
)
from database.sync_ledger import (
claim_sync_content,
release_sync_content_claim,
release_sync_content_claim_after_job_retired,
)
from models.conversation_enums import ConversationSource
from models.sync_contract import SYNC_LOCAL_FILES_V2_RESPONSES
from models.geolocation import geolocation_from_private_header
from models.sync_audio import AudioPrecacheResponse, AudioUrlsResponse
from utils.analytics import record_usage
from utils.other import endpoints as auth
from utils.account_cutover.access import should_skip_background_account_mutation
from utils.other.storage import (
get_playback_artifact_signed_url,
upload_playback_artifact,
mark_playback_unavailable,
compute_audio_files_fingerprint,
get_conversation_playback_signed_url,
upload_conversation_playback_artifact,
mark_conversation_playback_unavailable,
)
from utils.byok import has_byok_keys
from utils.cloud_tasks import (
enqueue_sync_job,
get_sync_tasks_max_attempts,
is_cloud_tasks_dispatch_enabled,
verify_cloud_tasks_oidc,
)
from utils.executors import (
critical_executor,
db_executor,
storage_executor,
sync_executor,
run_blocking,
start_background_task,
)
from utils.fair_use import (
FAIR_USE_ENABLED,
FAIR_USE_RESTRICT_DAILY_DG_MS,
check_soft_caps,
get_enforcement_stage,
get_hard_restriction_status,
get_rolling_speech_ms,
is_daily_audio_ceiling_exceeded,
is_dg_budget_exhausted,
record_dg_usage_ms,
record_speech_ms,
trigger_classifier_if_needed,
)
from utils.observability.fallback import record_fallback
from utils.multipart import MultipartMaxPartSizeRoute, SYNC_AUDIO_MAX_PART_SIZE, max_part_size
from utils.metrics import (
OMI_SYNC_DISPATCH_ATTEMPTS_TOTAL,
OMI_SYNC_LANE_JOBS_TOTAL,
OMI_SYNC_QUEUE_WAIT_SECONDS,
OMI_SYNC_RECORDING_AGE_SECONDS,
)
from utils.client_device import resolve_client_device, resolve_client_device_from_request
from utils.subscription import has_transcription_credits
from utils.sync import playback as sync_playback
from utils.sync.files import (
decode_files_to_wav,
detect_source_from_filenames,
get_timestamp_from_path,
get_wav_duration,
retrieve_file_paths,
)
from utils.sync.pipeline import (
_OrderedTurnstile,
_cleanup_files,
_delete_staged_blobs_async,
_download_staged_files,
_finalize_sync_job_failure,
finalize_sync_job_failure_now,
finalize_sync_job_superseded,
SyncJobRunLeaseLost,
bind_or_converge_sync_ledger_completion,
_finalize_sync_audio_files,
_reprocess_merged_conversations,
_retrieve_file_paths_v2,
_run_full_pipeline_background_async,
_stage_files_to_gcs,
build_person_embeddings_cache,
process_segment,
retrieve_vad_segments,
SyncConversationPersistenceFenced,
)
from utils.stt.outcomes import TranscriptionOutcome, failure_from_exception
from utils.sync.rate_limit import (
FAIR_USE_RATE_LIMIT_CODE,
bounded_fair_use_retry_after,
build_sync_rate_limit_event,
emit_sync_rate_limit_event,
fair_use_rate_limit_headers,
validated_correlation_id,
)
from utils.sync.backfill import (
release_backfill_slot,
reserve_backfill_speech,
retry_after_next_utc_day,
try_acquire_backfill_slot,
)
from utils.sync.content_id import compute_sync_content_id
from utils.sync.capture_manifest import (
claim_conversation_manifest,
issue_capture_manifest,
manifest_claims_match_paths,
verify_capture_manifest,
)
from utils.sync.lanes import SyncLane, classify_sync_lane
from utils.sync.provenance import capture_matches_server_conversation as _capture_matches_server_conversation
logger = logging.getLogger(__name__)
# Audio constants
AUDIO_SAMPLE_RATE = 16000
_V1_DEPRECATION_HEADERS = {'Deprecation': 'true', 'Link': '</v2/sync-local-files>; rel="successor-version"'}
router = APIRouter(route_class=MultipartMaxPartSizeRoute)
class SyncLocalFilesResultResponse(BaseModel):
new_memories: list[str] = Field(default_factory=list)
updated_memories: list[str] = Field(default_factory=list)
failed_segments: int = 0
total_segments: int = 0
errors: list[str] = Field(default_factory=list)
class SyncJobStartResponse(BaseModel):
job_id: str
status: str
total_files: int
total_segments: int
poll_after_ms: int
lane: str = SyncLane.FRESH.value
class SyncJobStatusResponse(BaseModel):
job_id: str
status: str
total_segments: int = 0
processed_segments: int = 0
successful_segments: int = 0
failed_segments: int = 0
result: SyncLocalFilesResultResponse | None = None
error: str | None = None
lane: str = SyncLane.FRESH.value
reason_code: str | None = None
retry_after: int | None = None
recording_age_seconds: int | None = None
class SyncCaptureManifestFile(BaseModel):
name: str = Field(min_length=1, max_length=255)
sha256: str = Field(pattern=r'^[0-9a-fA-F]{64}$')
class SyncCaptureManifestRequest(BaseModel):
conversation_id: str = Field(min_length=1, max_length=128)
files: List[SyncCaptureManifestFile] = Field(min_length=1, max_length=20)
class SyncCaptureManifestResponse(BaseModel):
manifest: str
@router.post('/v2/sync-capture-manifest', response_model=SyncCaptureManifestResponse)
async def create_sync_capture_manifest(
payload: SyncCaptureManifestRequest,
uid: str = Depends(auth.get_current_user_uid),
x_app_platform: Optional[str] = Header(None, alias='X-App-Platform'),
x_device_id_hash: Optional[str] = Header(None, alias='X-Device-Id-Hash'),
x_app_version: Optional[str] = Header(None, alias='X-App-Version'),
):
device = resolve_client_device(
x_app_platform=x_app_platform,
x_device_id_hash=x_device_id_hash,
x_app_version=x_app_version,
)
filenames = [item.name for item in payload.files]
trusted = await run_blocking(
db_executor,
_capture_matches_server_conversation,
uid,
payload.conversation_id,
filenames,
device.client_device_id,
)
if not trusted:
raise HTTPException(status_code=403, detail='Fresh capture provenance could not be verified')
claims = [item.model_dump() for item in payload.files]
try:
claimed = await run_blocking(
db_executor,
claim_conversation_manifest,
uid,
payload.conversation_id,
claims,
)
except Exception as e:
logger.error('sync capture manifest claim unavailable uid=%s error=%s', uid, type(e).__name__)
raise HTTPException(status_code=503, detail='Fresh capture provenance is temporarily unavailable') from e
if not claimed:
raise HTTPException(status_code=409, detail='Conversation fresh content was already claimed')
manifest = issue_capture_manifest(
uid,
device.client_device_id,
payload.conversation_id,
claims,
)
return SyncCaptureManifestResponse(manifest=manifest)
class AudioDownloadPendingResponse(BaseModel):
status: str
poll_after_ms: int
def _get_sync_rate_limit_telemetry_fields(uid: str) -> Dict[str, object]:
"""Load rejection-only account metadata without affecting the response path on read failures."""
fields: Dict[str, object] = {
'subscription_plan': 'unknown',
'subscription_status': 'unknown',
'fair_use_stage': 'unknown',
'classifier_type': 'unknown',
}
try:
state = fair_use_db.get_fair_use_state(uid)
fields['fair_use_stage'] = state.get('stage')
fields['classifier_type'] = state.get('last_classifier_type')
except Exception as e:
logger.warning('sync_rate_limit_telemetry fair_use_state_read_failed error=%s', type(e).__name__)
try:
subscription = users_db.get_existing_user_subscription(uid)
if subscription is None:
# This is the same effective default as get_user_subscription(), without
# creating a Firestore record from a telemetry-only rejection path.
fields['subscription_plan'] = 'basic'
fields['subscription_status'] = 'active'
else:
fields['subscription_plan'] = subscription.plan
fields['subscription_status'] = subscription.status
except Exception as e:
logger.warning('sync_rate_limit_telemetry subscription_read_failed error=%s', type(e).__name__)
return fields
def _retry_after_until_next_utc_day() -> int:
now = datetime.now(timezone.utc)
next_day = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
return max(1, int((next_day - now).total_seconds()))
async def _fair_use_restriction_response(
*,
uid: str,
retry_after: int | None,
client_platform: object,
device_hash: object,
app_version: object,
request_id: object = None,
cloud_trace_context: object = None,
base_headers: Optional[Dict[str, str]] = None,
extra_content: Optional[Dict[str, object]] = None,
) -> JSONResponse:
telemetry = await run_blocking(db_executor, _get_sync_rate_limit_telemetry_fields, uid)
correlation_id = (
validated_correlation_id(request_id) or validated_correlation_id(cloud_trace_context) or str(_uuid.uuid4())
)
safe_retry_after = bounded_fair_use_retry_after(retry_after)
event = build_sync_rate_limit_event(
uid=uid,
device_hash=device_hash,
app_platform=client_platform,
app_version=app_version,
subscription_plan=telemetry['subscription_plan'],
subscription_status=telemetry['subscription_status'],
fair_use_stage=telemetry['fair_use_stage'],
classifier_type=telemetry['classifier_type'],
retry_after=safe_retry_after,
backend_revision=os.getenv('K_REVISION') or os.getenv('DD_VERSION'),
correlation_id=correlation_id,
)
try:
emit_sync_rate_limit_event(event)
except Exception as e:
logger.warning('sync_rate_limit_telemetry emit_failed error=%s', type(e).__name__)
headers = fair_use_rate_limit_headers(safe_retry_after, base_headers)
headers['X-Request-ID'] = correlation_id
content: Dict[str, object] = {
'code': FAIR_USE_RATE_LIMIT_CODE,
'detail': 'Account temporarily restricted due to fair-use policy',
}
if extra_content:
content.update(extra_content)
return JSONResponse(status_code=429, headers=headers, content=content)
@router.post("/v1/sync/audio/{conversation_id}/precache", response_model=AudioPrecacheResponse, tags=['v1'])
def precache_conversation_audio_endpoint(
conversation_id: str,
uid: str = Depends(auth.get_current_user_uid),
):
"""
Warm the audio cache for a conversation.
Returns immediately - caching happens in background.
"""
conversation = conversations_db.get_conversation(uid, conversation_id)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.get('is_locked', False):
raise HTTPException(status_code=402, detail="A paid plan is required to access this conversation.")
return sync_playback.precache_audio_files(uid, conversation_id, conversation.get('audio_files', []))
@router.get("/v1/sync/audio/{conversation_id}/urls", response_model=AudioUrlsResponse, tags=['v1'])
def get_audio_signed_urls_endpoint(
conversation_id: str,
uid: str = Depends(auth.get_current_user_uid),
):
"""
Get signed URLs for all audio files in a conversation.
Synchronously caches the first uncached file for immediate playback.
Remaining files are cached in background.
Returns:
List of audio file info with signed_url (if cached) or status "pending"
"""
conversation = conversations_db.get_conversation(
uid, conversation_id, read_site=FirestoreReadSite.SYNC_AUDIO_URLS_POLL
)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.get('is_locked', False):
raise HTTPException(status_code=402, detail="A paid plan is required to access this conversation.")
return sync_playback.get_audio_signed_urls(
uid, conversation_id, conversation.get('audio_files', []), conversation=conversation
)
# **********************************************
# ********** AUDIO DOWNLOAD ENDPOINT ***********
# **********************************************
@router.get(
"/v1/sync/audio/{conversation_id}/{audio_file_id}",
tags=['v1'],
response_class=StreamingResponse,
responses={
200: {
"description": "Audio stream.",
"content": {
"audio/wav": {"schema": {"type": "string", "format": "binary"}},
"audio/mpeg": {"schema": {"type": "string", "format": "binary"}},
"application/octet-stream": {"schema": {"type": "string", "format": "binary"}},
},
},
202: {
"description": "Audio artifact is being prepared.",
"model": AudioDownloadPendingResponse,
},
206: {
"description": "Partial audio stream.",
"content": {
"audio/wav": {"schema": {"type": "string", "format": "binary"}},
"audio/mpeg": {"schema": {"type": "string", "format": "binary"}},
"application/octet-stream": {"schema": {"type": "string", "format": "binary"}},
},
},
},
)
def download_audio_file_endpoint(
conversation_id: str,
audio_file_id: str,
request: Request,
format: str = Query(default="wav", regex="^(wav|pcm)$"),
uid: str = Depends(auth.get_current_user_uid),
):
"""
Download audio file from private cloud sync in the specified format.
Merges chunks on-demand.
Args:
conversation_id: ID of the conversation
audio_file_id: ID of the audio file within the conversation
request: FastAPI Request object (for Range header)
format: Output format - 'wav' or 'pcm' (raw) (default: wav)
uid: User ID (from authentication)
Returns:
StreamingResponse with the audio file in the requested format.
Returns 206 Partial Content for Range requests, 200 OK for full file.
"""
# Verify user owns the conversation
conversation = conversations_db.get_conversation(uid, conversation_id)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.get('is_locked', False):
raise HTTPException(status_code=402, detail="A paid plan is required to access this conversation.")
# Find the audio file in the conversation
audio_files = conversation.get('audio_files', [])
audio_file = None
for af in audio_files:
if af.get('id') == audio_file_id:
audio_file = af
break
if not audio_file:
raise HTTPException(status_code=404, detail="Audio file not found in conversation")
return sync_playback.download_audio_file_response(uid, conversation_id, audio_file_id, audio_file, request, format)
# **********************************************
# ************ SYNC LOCAL FILES ****************
# **********************************************
# response_model omitted: deprecated v1 endpoint with mixed dict + JSONResponse returns;
# the v2 typed equivalent (SyncJobStatusResponse) covers the contract.
@router.post("/v1/sync-local-files", deprecated=True)
@max_part_size(SYNC_AUDIO_MAX_PART_SIZE)
async def sync_local_files(
request: Request,
response: Response,
files: List[UploadFile] = File(...),
uid: str = Depends(auth.get_current_user_uid),
conversation_id: str = Query(
None, description="Target conversation ID to attach audio to (auto-sync from live capture)"
),
):
if await run_blocking(db_executor, get_sync_ledger_fence_mode) is SyncLedgerFenceMode.STANDBY:
return JSONResponse(
status_code=503,
headers={**_V1_DEPRECATION_HEADERS, 'Retry-After': '60'},
content={
'code': 'sync_ledger_fence_cutover',
'detail': 'Sync is briefly pausing safely; local audio was not consumed',
},
)
logger.warning(
f'sync: deprecated v1 sync-local-files called uid={uid} files={len(files)} '
f'user_agent={request.headers.get("user-agent", "")}'
)
response.headers.update(_V1_DEPRECATION_HEADERS)
client_device_context = resolve_client_device_from_request(request)
filenames = [f.filename or '' for f in files]
has_server_capture_proof = False
lane_decision = classify_sync_lane(
filenames,
client_device_id=client_device_context.client_device_id if has_server_capture_proof else None,
)
logger.info(
'sync_lane_admission uid=%s device_hash=%s platform=%s app_version=%s lane=%s trust=%s age_seconds=%s reason=%s',
uid,
client_device_context.device_hash,
client_device_context.platform,
client_device_context.app_version,
lane_decision.lane.value,
lane_decision.trust.value,
lane_decision.maximum_age_seconds,
lane_decision.reason,
)
if lane_decision.lane == SyncLane.BACKFILL and os.getenv('SYNC_BACKFILL_ENABLED', 'true').lower() != 'true':
return JSONResponse(
status_code=503,
headers={
**_V1_DEPRECATION_HEADERS,
'Retry-After': '3600',
'X-Omi-Rate-Limit-Reason': 'backfill_capacity',
},
content={
'code': 'backfill_capacity',
'detail': 'Historical recovery is paused; local audio was not consumed',
},
)
if lane_decision.lane == SyncLane.BACKFILL:
# The deprecated inline endpoint has no isolated worker boundary.
# Historical audio must use v2 so it can never consume fresh capacity.
return JSONResponse(
status_code=503,
headers={
**_V1_DEPRECATION_HEADERS,
'Retry-After': '30',
'X-Omi-Rate-Limit-Reason': 'backfill_capacity',
},
content={
'code': 'backfill_capacity',
'detail': 'Historical recovery requires the v2 isolated worker; local audio was not consumed',
},
)
if not lane_decision.automatic_recovery_allowed:
return JSONResponse(
status_code=422,
headers=_V1_DEPRECATION_HEADERS,
content={
'code': 'backfill_lookback_exceeded',
'detail': 'Recording is older than the automatic recovery window; local audio was not consumed',
},
)
# Pre-check gates (#5854)
hard_restricted, retry_after = get_hard_restriction_status(uid)
if lane_decision.lane == SyncLane.FRESH and hard_restricted:
return await _fair_use_restriction_response(
uid=uid,
retry_after=retry_after,
client_platform=client_device_context.platform,
device_hash=client_device_context.device_hash,
app_version=client_device_context.app_version,
request_id=request.headers.get('x-request-id'),
cloud_trace_context=request.headers.get('x-cloud-trace-context'),
base_headers=_V1_DEPRECATION_HEADERS,
)
# Hard anti-abuse daily-audio ceiling (all plans): reject fresh sync once the user is
# already over the rolling-24h total. Set high enough that no legitimate user hits it;
# it exists to stop bulk-sync dumps. Backfill has its own separate pacing.
if lane_decision.lane == SyncLane.FRESH and is_daily_audio_ceiling_exceeded(uid):
logger.info(f'sync: daily audio ceiling reached uid={uid}')
return await _fair_use_restriction_response(
uid=uid,
retry_after=_retry_after_until_next_utc_day(),
client_platform=client_device_context.platform,
device_hash=client_device_context.device_hash,
app_version=client_device_context.app_version,
request_id=request.headers.get('x-request-id'),
cloud_trace_context=request.headers.get('x-cloud-trace-context'),
base_headers=_V1_DEPRECATION_HEADERS,
)
# Check credits: if exhausted, still process but lock the conversation so user can pay to unlock
should_lock = not has_transcription_credits(uid)
# Detect source from filenames
source = detect_source_from_filenames([f.filename for f in files])
paths = []
wav_paths = []
segmented_paths = set()
backfill_slot_token: Optional[str] = None
if lane_decision.lane == SyncLane.BACKFILL:
backfill_slot_token = f'v1-{_uuid.uuid4()}'
try:
if not try_acquire_backfill_slot(uid, backfill_slot_token):
return JSONResponse(
status_code=429,
headers={
**_V1_DEPRECATION_HEADERS,
'Retry-After': '30',
'X-Omi-Rate-Limit-Reason': 'backfill_paced',
},
content={'code': 'backfill_paced', 'detail': 'Another historical recovery job is in flight'},
)
except Exception:
return JSONResponse(
status_code=503,
headers={
**_V1_DEPRECATION_HEADERS,
'Retry-After': '30',
'X-Omi-Rate-Limit-Reason': 'backfill_capacity',
},
content={'code': 'backfill_capacity', 'detail': 'Historical recovery is temporarily unavailable'},
)
try:
try:
paths = retrieve_file_paths(files, uid)
wav_paths = decode_files_to_wav(paths)
except HTTPException as e:
raise HTTPException(status_code=e.status_code, detail=e.detail, headers=_V1_DEPRECATION_HEADERS)
vad_errors = []
def _run_vad(path):
retrieve_vad_segments(path, segmented_paths, vad_errors)
await asyncio.gather(*[run_blocking(sync_executor, _run_vad, path) for path in wav_paths])
# Clean up original wav files after VAD segmentation (segments are now in segmented_paths)
_cleanup_files(wav_paths)
wav_paths = [] # Clear to avoid double cleanup in finally
# Check for VAD errors - if any failed, abort to prevent data loss
if vad_errors:
error_detail = f"VAD processing failed for {len(vad_errors)} file(s): {'; '.join(vad_errors[:3])}"
if len(vad_errors) > 3:
error_detail += f" (and {len(vad_errors) - 3} more)"
raise HTTPException(status_code=500, detail=error_detail, headers=_V1_DEPRECATION_HEADERS)
# Fair-use speech tracking from raw VAD segments (#5854)
# Compute duration from raw segments BEFORE merging (silence gaps not counted)
total_speech_seconds = sum(get_wav_duration(p) for p in segmented_paths)
total_speech_ms = int(total_speech_seconds * 1000)
logger.info(
f'sync_local_files len(segmented_paths) {len(segmented_paths)} speech_seconds={int(total_speech_seconds)}'
)
if lane_decision.lane == SyncLane.BACKFILL:
reservation = reserve_backfill_speech(uid, backfill_slot_token or f'v1-{_uuid.uuid4()}', total_speech_ms)
if not reservation.allowed:
return JSONResponse(
status_code=429,
headers={
**_V1_DEPRECATION_HEADERS,
'Retry-After': str(reservation.retry_after or retry_after_next_utc_day()),
'X-Omi-Rate-Limit-Reason': reservation.reason or 'backfill_paced',
},
content={
'code': reservation.reason or 'backfill_paced',
'detail': 'Historical recovery is paced; local audio should be retained',
},
)
if FAIR_USE_ENABLED and total_speech_ms > 0:
meter_source = 'sync_backfill' if lane_decision.lane == SyncLane.BACKFILL else 'sync_fresh'
record_speech_ms(uid, total_speech_ms, source=meter_source)
if lane_decision.lane == SyncLane.FRESH:
fair_use_sub = await run_blocking(db_executor, users_db.get_existing_user_subscription, uid)
fair_use_plan = fair_use_sub.plan if fair_use_sub else None
speech_totals = get_rolling_speech_ms(uid)
triggered_caps = check_soft_caps(uid, speech_totals=speech_totals, plan=fair_use_plan)
if triggered_caps:
logger.info(f'sync: soft caps triggered for {uid}: {triggered_caps}')
asyncio.create_task(trigger_classifier_if_needed(uid, triggered_caps))
is_locked = should_lock
response = {'updated_memories': set(), 'new_memories': set()}
segment_errors = []
segment_lock = threading.Lock()
total_segments = len(segmented_paths)
# DG budget gate: throttle cloud STT for restrict-stage users (#6083)
# Check budget first; only record usage after successful processing.
dg_budget_blocked = False
fair_use_restrict_dg = False
if FAIR_USE_ENABLED and lane_decision.lane == SyncLane.FRESH:
try:
fair_use_stage = get_enforcement_stage(uid)
if fair_use_stage == 'restrict' and FAIR_USE_RESTRICT_DAILY_DG_MS > 0:
fair_use_restrict_dg = True
dg_budget_blocked = is_dg_budget_exhausted(uid)
except Exception as e:
logger.error(f'sync: DG budget check error for {uid}: {e}')
if dg_budget_blocked:
logger.info(f'sync: DG budget exhausted, skipping {total_segments} segments uid={uid}')
_cleanup_files(list(segmented_paths))
return await _fair_use_restriction_response(
uid=uid,
retry_after=_retry_after_until_next_utc_day(),
client_platform=client_device_context.platform,
device_hash=client_device_context.device_hash,
app_version=client_device_context.app_version,
request_id=request.headers.get('x-request-id'),
cloud_trace_context=request.headers.get('x-cloud-trace-context'),
base_headers=_V1_DEPRECATION_HEADERS,
extra_content={
'new_memories': [],
'updated_memories': [],
'credits_exhausted': should_lock,
'dg_budget_exhausted': True,
'skipped_segments': total_segments,
},
)
# Fetch user transcription preferences once before spawning threads
transcription_prefs = await run_blocking(db_executor, users_db.get_user_transcription_preferences, uid)
private_cloud_sync_enabled = bool(
await run_blocking(db_executor, users_db.get_user_private_cloud_sync_enabled, uid)
)
data_protection_level = (
await run_blocking(db_executor, users_db.get_data_protection_level, uid)
if private_cloud_sync_enabled
else None
)
# Build speaker embeddings cache once for all segments (voice + text identification)
try:
person_embeddings_cache = await run_blocking(db_executor, build_person_embeddings_cache, uid)
if person_embeddings_cache:
logger.info(f'sync: loaded {len(person_embeddings_cache)} person embeddings for speaker ID uid={uid}')
except Exception as e:
logger.warning(f'sync: failed to load person embeddings, skipping speaker ID uid={uid}: {e}')
person_embeddings_cache = {}
# Chronological order + turnstile: STT runs in parallel, but conversation
# assignment is serialized oldest-first so adjacent chunks merge instead of
# racing into separate conversations (#6551, #5747).
ordered_paths = sorted(segmented_paths, key=get_timestamp_from_path)
assignment_turnstile = _OrderedTurnstile(ordered_paths)
await asyncio.gather(
*[
run_blocking(
sync_executor,
process_segment,
path,
uid,
response,
segment_lock,
segment_errors,
source,
is_locked,
transcription_prefs,
person_embeddings_cache,
conversation_id,
assignment_turnstile,
private_cloud_sync_enabled=private_cloud_sync_enabled,
data_protection_level=data_protection_level,
client_device_id=client_device_context.client_device_id,
client_platform=client_device_context.platform,
)
for path in ordered_paths
]
)
await run_blocking(sync_executor, _reprocess_merged_conversations, uid, response)
if private_cloud_sync_enabled:
await run_blocking(sync_executor, _finalize_sync_audio_files, uid, response)
# Record DG usage after successful processing (not before, to avoid charging on retries)
if fair_use_restrict_dg:
try:
dg_ms = int(total_speech_seconds * 1000)
if dg_ms > 0:
record_dg_usage_ms(uid, dg_ms)
except Exception as e:
logger.error(f'sync: DG usage record error for {uid}: {e}')
# Build JSON-serializable response
result = {
'new_memories': sorted(response['new_memories']),
'updated_memories': sorted(response['updated_memories']),
}
failed_segments = len(segment_errors)
successful_segments = total_segments - failed_segments
if failed_segments > 0:
result['failed_segments'] = failed_segments
result['total_segments'] = total_segments
result['errors'] = segment_errors[:10] # Cap error details to avoid huge responses
logger.error(
f'sync_local_files partial failure uid={uid} '
f'success={successful_segments}/{total_segments} errors={segment_errors[:3]}'
)
if total_segments > 0 and successful_segments == 0:
# All segments failed — return 500 (consistent with VAD error behavior)
raise HTTPException(
status_code=500,
detail=f"All {total_segments} segment(s) failed processing: {'; '.join(segment_errors[:3])}",
headers=_V1_DEPRECATION_HEADERS,
)
# Record subscription usage only when at least one segment succeeded
try:
usage_seconds = int(total_speech_seconds)
if usage_seconds > 0:
record_usage(uid, transcription_seconds=usage_seconds, speech_seconds=usage_seconds)
except Exception as e:
logger.error(f'sync: usage record error for {uid}: {e}')
if failed_segments > 0:
# Partial failure — return 207 Multi-Status so old clients retry the batch
return JSONResponse(
status_code=207,
headers=_V1_DEPRECATION_HEADERS,
content=result,
)
return result
finally:
# Clean up any remaining temporary files
_cleanup_files(paths) # .bin files (in case decode_files_to_wav didn't finish)
_cleanup_files(wav_paths) # Original wav files (if VAD didn't complete)
_cleanup_files(segmented_paths) # Segmented wav files after processing
if backfill_slot_token:
try:
release_backfill_slot(uid, backfill_slot_token)
except Exception as e:
logger.warning('sync: failed to release v1 backfill slot uid=%s error=%s', uid, type(e).__name__)
@router.post( # v2 async sync-local-files
"/v2/sync-local-files",
status_code=202,
response_model=SyncJobStartResponse,
responses=SYNC_LOCAL_FILES_V2_RESPONSES,
)
@max_part_size(SYNC_AUDIO_MAX_PART_SIZE)
async def sync_local_files_v2(
files: List[UploadFile] = File(...),
uid: str = Depends(auth.get_current_user_uid),
conversation_id: str = Query(
None, description="Target conversation ID to attach audio to (auto-sync from live capture)"
),
x_app_platform: Optional[str] = Header(None, alias='X-App-Platform'),
x_device_id_hash: Optional[str] = Header(None, alias='X-Device-Id-Hash'),
x_app_version: Optional[str] = Header(None, alias='X-App-Version'),
x_request_id: Optional[str] = Header(None, alias='X-Request-ID'),
x_cloud_trace_context: Optional[str] = Header(None, alias='X-Cloud-Trace-Context'),
x_omi_sync_capture_manifest: Optional[str] = Header(None, alias='X-Omi-Sync-Capture-Manifest'),
x_omi_conversation_geolocation: Optional[str] = Header(None, alias='X-Omi-Conversation-Geolocation'),
):
"""
Async version of sync-local-files. Saves raw files and returns 202
immediately, then runs the full pipeline (decode → VAD → STT → LLM) as
an async background task. The app polls GET /v2/sync-local-files/{job_id}.
"""
ledger_fence_mode = await run_blocking(db_executor, get_sync_ledger_fence_mode)
if ledger_fence_mode is SyncLedgerFenceMode.STANDBY:
# The one-time hard-revision-retirement cutover intentionally blocks
# before app-managed raw-file persistence or a content claim. Clients
# retain their WAL/audio and retry after the services become active.
return JSONResponse(
status_code=503,
headers={'Retry-After': '60'},
content={
'code': 'sync_ledger_fence_cutover',
'detail': 'Sync is briefly pausing safely; local audio was not consumed',
},
)
ledger_fence_active = ledger_fence_mode is SyncLedgerFenceMode.ACTIVE
# Browser/mobile clients carry capture provenance in these request headers.
# It must survive both the inline and Cloud Tasks pipeline branches.
client_device_context = resolve_client_device(
x_app_platform=x_app_platform if isinstance(x_app_platform, str) else None,
x_device_id_hash=x_device_id_hash if isinstance(x_device_id_hash, str) else None,
x_app_version=x_app_version if isinstance(x_app_version, str) else None,
)
geolocation = geolocation_from_private_header(x_omi_conversation_geolocation)
filenames = [f.filename or '' for f in files]
manifest_claims = verify_capture_manifest(
x_omi_sync_capture_manifest,
uid,
client_device_context.client_device_id,
conversation_id,
filenames,
)
has_server_capture_proof = manifest_claims is not None and await run_blocking(
db_executor,
_capture_matches_server_conversation,
uid,
conversation_id,
filenames,
client_device_context.client_device_id,
)
lane_decision = classify_sync_lane(
filenames,
client_device_id=client_device_context.client_device_id if has_server_capture_proof else None,
)
logger.info(
'sync_lane_admission uid=%s device_hash=%s platform=%s app_version=%s lane=%s trust=%s age_seconds=%s reason=%s',
uid,
client_device_context.device_hash,
client_device_context.platform,
client_device_context.app_version,
lane_decision.lane.value,
lane_decision.trust.value,
lane_decision.maximum_age_seconds,
lane_decision.reason,
)
if lane_decision.lane == SyncLane.BACKFILL and os.getenv('SYNC_BACKFILL_ENABLED', 'true').lower() != 'true':
return JSONResponse(
status_code=503,
headers={'Retry-After': '3600', 'X-Omi-Rate-Limit-Reason': 'backfill_capacity'},
content={
'code': 'backfill_capacity',
'detail': 'Historical recovery is paused; local audio was not consumed',
},
)
if not lane_decision.automatic_recovery_allowed:
return JSONResponse(
status_code=422,
content={
'code': 'backfill_lookback_exceeded',
'detail': 'Recording is older than the automatic recovery window; local audio was not consumed',
'lane': lane_decision.lane.value,
},
)
try:
OMI_SYNC_RECORDING_AGE_SECONDS.labels(lane=lane_decision.lane.value).observe(
lane_decision.maximum_age_seconds or 0
)
except Exception:
pass
# Live restrictions apply only to the realtime/fresh domain. Historical
# recovery has independent admission and spend caps below.
if lane_decision.lane == SyncLane.FRESH:
hard_restricted, retry_after = await run_blocking(critical_executor, get_hard_restriction_status, uid)
if hard_restricted:
return await _fair_use_restriction_response(
uid=uid,
retry_after=retry_after,
client_platform=client_device_context.platform,
device_hash=client_device_context.device_hash,
app_version=client_device_context.app_version,
request_id=x_request_id if isinstance(x_request_id, str) else None,
cloud_trace_context=x_cloud_trace_context if isinstance(x_cloud_trace_context, str) else None,
)
if await run_blocking(db_executor, is_daily_audio_ceiling_exceeded, uid):
logger.info('sync_v2: daily audio ceiling reached uid=%s', uid)
return await _fair_use_restriction_response(
uid=uid,
retry_after=_retry_after_until_next_utc_day(),
client_platform=client_device_context.platform,
device_hash=client_device_context.device_hash,
app_version=client_device_context.app_version,
request_id=x_request_id if isinstance(x_request_id, str) else None,
cloud_trace_context=x_cloud_trace_context if isinstance(x_cloud_trace_context, str) else None,
)
should_lock = not await run_blocking(critical_executor, has_transcription_credits, uid)
# Detect source
source = detect_source_from_filenames([f.filename for f in files])
cloud_tasks_dispatch_enabled = is_cloud_tasks_dispatch_enabled()
byok_enabled = has_byok_keys()
cloud_task_eligible = cloud_tasks_dispatch_enabled and not byok_enabled
# Create job_id early so we have it for the directory
job_id = str(_uuid.uuid4())
job_dir = f'syncing/{uid}/{job_id}'
backfill_slot_acquired = False
if lane_decision.lane == SyncLane.BACKFILL:
try:
backfill_slot_acquired = await run_blocking(db_executor, try_acquire_backfill_slot, uid, job_id)
except Exception as e:
logger.error('sync_v2: backfill admission unavailable uid=%s error=%s', uid, type(e).__name__)
return JSONResponse(
status_code=503,
headers={'Retry-After': '30', 'X-Omi-Rate-Limit-Reason': 'backfill_capacity'},
content={'code': 'backfill_capacity', 'detail': 'Historical recovery is temporarily unavailable'},
)
if not backfill_slot_acquired:
try:
OMI_SYNC_LANE_JOBS_TOTAL.labels(
lane=lane_decision.lane.value,
trust=lane_decision.trust.value,
outcome='paced',
).inc()
except Exception:
pass
return JSONResponse(
status_code=429,
headers={'Retry-After': '30', 'X-Omi-Rate-Limit-Reason': 'backfill_paced'},
content={'code': 'backfill_paced', 'detail': 'Another historical recovery job is still in flight'},
)