forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily_memory_sweep.py
More file actions
5509 lines (5111 loc) · 238 KB
/
Copy pathdaily_memory_sweep.py
File metadata and controls
5509 lines (5111 loc) · 238 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
"""Dark, bounded once-per-local-day automatic memory sweep.
This module is an authority seam, not a scheduler. It accepts a server-built
daily input, writes through the canonical ledger boundary, and stays completely
inert until an explicit backend authority opens it. The completed-day producer
reads the day's finished conversation SUMMARIES as one bounded spine and runs a
single two-phase agent pass over them (the agent may pull a bounded number of
raw transcript excerpts to verify specifics before finalizing), all under an
explicit cost budget. The onboarding cold-start channel still reads bounded
finished transcript text per conversation.
The contract is deliberately small:
* one completed user-local day per input, with at most three missed days per run;
* at most 32 candidates and 16 durable writes per day;
* stable source keys and receipts make retry after a crash an exact no-op;
* direct user statements outrank reusable agent conclusions, which outrank
sweep inferences;
* fact candidates may be added/amended automatically, while triggers may only
repair an existing trigger; passive behavior never creates standing intent;
* source references are metadata-only; raw pixels and image payloads are
rejected before any canonical write;
* account-deletion, owner, canonical-generation, and cursor CAS fences fail
closed; disabling the authority never deletes already-written user data.
The maintenance job may import the closed scheduler seam, but no current writer
is changed and every runtime call remains inert until backend authority opens.
"""
from __future__ import annotations
from datetime import date, datetime, time, timedelta, timezone
from enum import Enum
from dataclasses import dataclass, field
import atexit
import importlib
import logging
import os
import re
import threading
from typing import Any, Dict, Iterable, List, Literal, Mapping, Optional, Sequence, Tuple, cast
from uuid import uuid4
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
logger = logging.getLogger(__name__)
from google.cloud.firestore_v1 import FieldFilter
from google.cloud import firestore
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from database.account_deletion_policy import account_deletion_blocks_access, normalize_account_deletion_status
from database.account_deletion_projection_fence import read_account_deletion_projection_fence
from database.firestore_index_registry import (
DAILY_SWEEP_ACTIVE_FACT_ENTITY_SLOT_QUERY,
DAILY_SWEEP_ACTIVE_FACT_ENTITY_CONTENT_QUERY,
DAILY_SWEEP_ACTIVE_FACT_ENTITY_QUERY,
DAILY_SWEEP_ACTIVE_FACT_SUBJECT_CONTENT_QUERY,
DAILY_SWEEP_ACTIVE_FACT_SUBJECT_QUERY,
DAILY_SWEEP_ACTIVE_FACT_SLOT_QUERY,
DAILY_SWEEP_ONBOARDING_CONVERSATIONS_QUERY,
)
from database.memory_collections import MemoryCollections
from database.memory_apply_store import cleanup_expired_memory_deletion_receipts
from models.memory_apply import MemoryControlState, WriterMode
from models.memory_contracts import deterministic_contract_id
from models.product_memory import (
LedgerWriteReason,
MemoryItem,
MemoryItemStatus,
MemoryKind,
MemorySubjectScope,
normalized_memory_content_key,
)
from utils.free_tier_memory_policy import (
free_tier_memory_suppression_enabled,
memory_formation_verdict,
)
from utils.managed_compute import authorize_managed_compute
from utils.memory.canonical_memory_adapter import read_canonical_memory_item
from utils.memory.daily_memory_sweep_queue import ProcessOutcome, drain_sweep_uids
from utils.memory.knowledge_ledger import (
LedgerProvenance,
LedgerWrite,
amend_fact,
evidence_id_for_ledger_provenance,
save_ledger_write,
)
from utils.memory.memory_system import ensure_canonical_apply_control_state
from utils.memory.memory_authority import validate_uid_for_memory_path
from utils.memory.jit_trigger_contract import compile_trigger_condition
from utils.llm.usage_tracker import Features, track_usage
# These budgets are deliberately separate from the canonical write budget. A
# completed-day producer must prove that it read the whole bounded source
# window before the cursor can advance; it may never turn an unavailable read
# into an empty day.
MAX_COMPLETED_DAY_CONVERSATIONS = 32
MAX_COMPLETED_DAY_INPUT_CHARACTERS = 48_000
# The summary spine bounds the whole-day agent pass. Summaries are two orders
# of magnitude smaller than transcripts, so these ceilings are effectively
# unreachable for real days; they exist so an over-budget page is still a
# provable incomplete source rather than a silent truncation.
MAX_COMPLETED_DAY_SUMMARY_CONVERSATIONS = 200
MAX_COMPLETED_DAY_SUMMARY_INPUT_CHARACTERS = 120_000
MAX_DAILY_TRANSCRIPT_FETCHES = 8
MAX_DAILY_TRANSCRIPT_FETCH_CHARACTERS = 8_000
MAX_DAILY_MEMORY_LOOKUPS = 4
MAX_SUMMARY_FALLBACK_TRANSCRIPT_CHARACTERS = 1_200
# Rows whose "summary" is a raw transcript head (no structured summary exists)
# carry this marker so the agent prompt can refuse to source standing-profile
# slots from unstructured third-party speech without transcript verification.
UNSTRUCTURED_SUMMARY_MARKER = "(unstructured transcript excerpt)"
MAX_ONBOARDING_CONVERSATIONS = 8
MAX_ONBOARDING_SCAN_PAGES = 16
MAX_ONBOARDING_INPUT_CHARACTERS = 24_000
MAX_ONBOARDING_RECEIPT_KEYS = 4_096
MAX_LEGACY_COMPAT_OCCUPANTS = 64
# The compatibility occupant proof pages through the complete cohort; a real
# long-tenured account holds hundreds of active unslotted facts per subject,
# so completeness must come from draining a cursor, not from one bounded page.
# The ceiling still fails closed on a pathological cohort.
LEGACY_COMPAT_OCCUPANT_PAGE_SIZE = 300
MAX_LEGACY_COMPAT_OCCUPANT_SCAN = 5000
MODEL_COST_PER_1K_INPUT_CHARACTERS_USD = 0.002
ONBOARDING_CONSUMED_STATE_PATH = "memory_control/daily_memory_sweep_onboarding"
ONBOARDING_PERMANENT_RECEIPT_PREFIX = "onboarding_source_"
ONBOARDING_SOURCE_RECEIPT_PATH = "daily_memory_sweep_onboarding_sources"
ONBOARDING_STAGED_CANDIDATE_PATH = "daily_memory_sweep_onboarding_staged"
DAILY_SUMMARY_STAGED_CANDIDATE_PATH = "daily_memory_sweep_daily_summary_staged"
DAILY_SUMMARY_STAGE_SCHEMA_VERSION = "daily_memory_sweep_daily_summary_stage.v2"
MODEL_INVOCATION_PATH = "daily_memory_sweep_model_invocations"
# This collection is intentionally outside ``users/{uid}``. Account deletion
# recursively removes every user subcollection, but an in-flight provider call
# must retain a content-free identity fence so a source retry cannot charge the
# same logical invocation again.
MODEL_INVOCATION_FENCE_COLLECTION = "daily_memory_sweep_model_invocation_fences"
MODEL_INVOCATION_SCHEMA_VERSION = "daily_memory_sweep_model_invocation.v1"
SCHEMA_VERSION = "daily_memory_sweep.v1"
CURSOR_SCHEMA_VERSION = "daily_memory_sweep_cursor.v1"
RECEIPT_SCHEMA_VERSION = "daily_memory_sweep_receipt.v1"
MAX_CATCH_UP_DAYS = 3
MAX_CANDIDATES_PER_DAY = 32
MAX_ONBOARDING_SOURCE_KEYS_PER_PACKET = MAX_CANDIDATES_PER_DAY
MAX_ONBOARDING_STAGED_CANDIDATES = MAX_CANDIDATES_PER_DAY
MAX_WRITES_PER_DAY = 16
MAX_CONTENT_CHARACTERS = 1_200
MAX_SOURCE_ID_CHARACTERS = 256
MAX_SOURCE_REFS = 8
MAX_SOURCE_REF_CHARACTERS = 256
MAX_TRIGGER_CONDITION_KEYS = 12
DAILY_MEMORY_SWEEP_ENABLED_ENV = "MEMORY_DAILY_MEMORY_SWEEP_ENABLED"
DAILY_MEMORY_SWEEP_KILL_SWITCH_ENV = "MEMORY_DAILY_MEMORY_SWEEP_KILL_SWITCH"
DAILY_MEMORY_SWEEP_MODEL_ENABLED_ENV = "MEMORY_DAILY_MEMORY_SWEEP_MODEL_ENABLED"
DAILY_MEMORY_SWEEP_MODEL_NAME_ENV = "MEMORY_DAILY_MEMORY_SWEEP_MODEL_NAME"
DAILY_MEMORY_SWEEP_MAX_MODEL_CANDIDATES_ENV = "MEMORY_DAILY_MEMORY_SWEEP_MAX_MODEL_CANDIDATES"
DAILY_MEMORY_SWEEP_MAX_MODEL_COST_USD_ENV = "MEMORY_DAILY_MEMORY_SWEEP_MAX_MODEL_COST_USD"
DAILY_MEMORY_SWEEP_COHORT_ENABLED_ENV = "MEMORY_DAILY_MEMORY_SWEEP_COHORT_ENABLED"
DAILY_MEMORY_SWEEP_COHORT_NAME_ENV = "MEMORY_DAILY_MEMORY_SWEEP_COHORT_NAME"
DAILY_MEMORY_SWEEP_COHORT_FLAG_ENV = "MEMORY_DAILY_MEMORY_SWEEP_COHORT_FLAG"
DAILY_MEMORY_SWEEP_COHORT_TIMEOUT_ENV = "MEMORY_DAILY_MEMORY_SWEEP_COHORT_TIMEOUT_SECONDS"
DAILY_MEMORY_SWEEP_TIMEZONE_RECONCILIATION_ENV = "MEMORY_DAILY_MEMORY_SWEEP_TIMEZONE_RECONCILIATION_ENABLED"
# The QA run seam is intentionally separate from the ordinary scheduler
# controls. A caller must provide every QA-only gate below; setting a run id
# alone can never open the production sweep or its cohort.
QA_SWEEP_RUN_ID_ENV = "OMI_JIT_QA_SWEEP_RUN_ID"
QA_SWEEP_ADMISSION_ENV = "OMI_JIT_QA_SWEEP_ADMISSION"
QA_SWEEP_PROJECT = "based-hardware-dev"
QA_SWEEP_DATABASE = "jit-qa"
QA_SWEEP_UID = "vi7SA9ckQCe4ccobWNxlbdcNdC23"
QA_SWEEP_COHORT = "jit-qa-sweep-v1"
QA_SWEEP_MODEL_NAME = "gpt-5.6-luna"
QA_SWEEP_MAX_MODEL_CANDIDATES = 1
QA_SWEEP_MAX_MODEL_COST_USD = 0.05
# Qualification uses the same completed-day producer with an explicit tighter
# envelope. Zero phase-B requests/lookups makes one provider call the real
# maximum for one completed day, instead of pricing the production envelope as
# if it were a cheap single call.
QA_SWEEP_MAX_CATCH_UP_DAYS = 1
QA_SWEEP_MAX_SUMMARY_CONVERSATIONS = 1
QA_SWEEP_MAX_SUMMARY_INPUT_CHARACTERS = 2_000
QA_SWEEP_MAX_TRANSCRIPT_FETCHES = 0
QA_SWEEP_MAX_TRANSCRIPT_FETCH_CHARACTERS = 0
QA_SWEEP_MAX_MEMORY_LOOKUPS = 0
QA_SWEEP_MAX_SDK_RETRIES = 0
QA_SWEEP_MAX_GATEWAY_ATTEMPTS = 1
QA_SWEEP_MAX_PROVIDER_CALLS = 1
# The deployed memories route is gpt-5.6-luna at $0.20/M input and $1.20/M
# output. The parser instructions alone are about 9.6K UTF-8 bytes, so an
# 8K input cap would reject every real QA request. 12K input + 256 output
# reserves about $0.0028, below the $0.05 run envelope; the gateway enforces
# these same headers against the provider request and settles actual usage.
QA_SWEEP_MAX_INPUT_TOKENS = 12_288
QA_SWEEP_MAX_OUTPUT_TOKENS = 256
QA_SWEEP_MAX_SPEND_MICRO_USD = 50_000
QA_SWEEP_JIT_CONTRACT_VERSION = "jit-cloud-qa-v1"
QA_SWEEP_RECEIPT_SCHEMA_VERSION = "omi.jit.qa.daily-memory-sweep-run.v1"
QA_SWEEP_OUTPUT_SCHEMA_VERSION = "omi.jit.qa.daily-memory-sweep-output.v1"
QA_SWEEP_RUN_COLLECTION = "jit_qa_sweep_runs"
QA_SWEEP_OUTPUT_SUBCOLLECTION = "outputs"
QA_SWEEP_RUN_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,47}$")
RECEIPT_LEASE = timedelta(minutes=10)
MODEL_INVOCATION_LEASE = timedelta(minutes=15)
STAGED_CANDIDATE_RETENTION = timedelta(days=7)
MAX_AUTHORITATIVE_OCCUPANTS = 2
# Cohort assignment is a read-only control-plane operation, but creating a
# PostHog SDK client for every UID leaks transports and turns a bounded sweep
# into an unbounded client factory. Keep one client per (key, host, timeout)
# and close each transport when the worker exits.
_POSTHOG_CLIENTS: Dict[Tuple[str, str, float], Any] = {}
_POSTHOG_CLIENTS_LOCK = threading.RLock()
_MODEL_INVOCATION_LOCK = threading.RLock()
_ID_RE = re.compile(r"[a-z0-9][a-z0-9._:-]{0,127}")
_FORBIDDEN_SOURCE_MARKERS = (
"base64",
"data:image",
"pixel",
"raw_image",
"raw-image",
"screenshot_bytes",
"image_bytes",
)
_FORBIDDEN_PAYLOAD_MARKERS = (
"base64",
"data:image",
"image_bytes",
"raw_image",
"raw-image",
"pixel",
"screenshot",
"bytes",
"image",
"raw",
)
_ALLOWED_SOURCE_TYPES = frozenset(
{
"conversation",
"daily_summary",
"explicit_user_statement",
"onboarding",
"agent_conclusion",
"screen_metadata",
}
)
def _reject_payload(value: Any, *, depth: int = 0, nodes: int = 0) -> None:
"""Reject image/raw/base64-shaped values recursively before compilation.
Trigger conditions are metadata selectors, never a transport for pixels or
opaque model payloads. The recursive walk is intentionally stricter than
the canonical model's JSON check and bounded to keep validation cheap.
"""
if depth > 8 or nodes > 128:
raise ValueError("trigger condition nesting exceeds the daily sweep budget")
if isinstance(value, (bytes, bytearray, memoryview)):
raise ValueError("raw image/pixel payloads are not valid trigger metadata")
if isinstance(value, str):
lowered = value.casefold()
if any(marker in lowered for marker in _FORBIDDEN_PAYLOAD_MARKERS):
raise ValueError("raw image/base64 payloads are not valid trigger metadata")
if len(value) > 300:
raise ValueError("trigger condition values are oversized")
return
if isinstance(value, Mapping):
if len(value) > MAX_TRIGGER_CONDITION_KEYS:
raise ValueError("trigger condition exceeds the daily sweep budget")
for key, item in value.items():
if not isinstance(key, str) or not key.strip() or len(key) > 64:
raise ValueError("trigger condition keys must be bounded strings")
lowered_key = key.casefold()
if any(marker in lowered_key for marker in _FORBIDDEN_PAYLOAD_MARKERS):
raise ValueError("raw image/base64 fields are not valid trigger metadata")
_reject_payload(item, depth=depth + 1, nodes=nodes + 1)
return
if isinstance(value, (list, tuple, set, frozenset)):
if len(value) > 128:
raise ValueError("trigger condition has too many nested values")
for item in value:
_reject_payload(item, depth=depth + 1, nodes=nodes + 1)
return
if value is not None and not isinstance(value, (bool, int, float)):
raise ValueError("trigger condition contains an unsupported value")
class SweepAuthorityState(BaseModel):
"""Backend-owned activation and kill-switch state.
A client or candidate cannot set either field. Both must be true to write;
the separate kill switch is intentionally checked on every invocation.
"""
model_config = ConfigDict(extra="forbid", frozen=True)
enabled: bool = False
kill_switch_active: bool = False
authority_version: str = Field(default="v1", min_length=1, max_length=32)
@property
def may_write(self) -> bool:
return self.enabled and not self.kill_switch_active
class DailySweepCohortAuthority(BaseModel):
"""Read-only per-user rollout seam (for example a PostHog flag read).
The sweep never writes PostHog. A deployment may inject a resolver that
reads the cohort assignment; when the seam is enabled without a resolver,
the scheduler fails closed for every user.
"""
model_config = ConfigDict(extra="forbid", frozen=True)
enabled: bool = False
cohort_name: str = ""
class DailySweepCohortDecision(str, Enum):
"""Tri-state result for the read-only cohort control-plane lookup."""
enabled = "enabled"
disabled = "disabled"
unavailable = "unavailable"
def __bool__(self) -> bool:
# Preserve the old truthiness seam for small adapters while keeping
# outage distinct from a definite false assignment.
return self is DailySweepCohortDecision.enabled
def daily_memory_sweep_cohort_authority_from_environment() -> DailySweepCohortAuthority:
truthy = {"1", "true", "yes", "on"}
return DailySweepCohortAuthority(
enabled=os.getenv(DAILY_MEMORY_SWEEP_COHORT_ENABLED_ENV, "false").casefold() in truthy,
# The feature-flag binding is intentionally the only deployment input;
# a legacy free-form cohort-name alias could reopen an unrestricted
# rollout under a different name.
cohort_name=os.getenv(DAILY_MEMORY_SWEEP_COHORT_FLAG_ENV, "").strip(),
)
def read_daily_memory_sweep_cohort_assignment(
uid: str,
cohort_name: str,
*,
resolver: Optional[Any] = None,
) -> DailySweepCohortDecision:
"""Read-only per-user cohort seam used by the maintenance entrypoint.
The default is deliberately fail-closed. A deployment may inject a
read-only PostHog resolver at this function boundary; this code never
creates flags, identifies users, or mutates PostHog state.
"""
normalized_uid = (uid or "").strip()
normalized_flag = (cohort_name or "").strip()
if not normalized_uid or not normalized_flag:
return DailySweepCohortDecision.unavailable
# Tests and the maintenance adaptor inject a read-only resolver. The
# production fallback is lazy so importing this module never constructs a
# client or performs network I/O. No identify/capture call is made and
# the user id comes only from the server-side inventory.
reader = resolver
if reader is None:
api_key = (os.getenv("POSTHOG_PROJECT_API_KEY") or os.getenv("POSTHOG_API_KEY") or "").strip()
host = (os.getenv("POSTHOG_HOST") or "https://app.posthog.com").strip()
if not api_key or not host:
return DailySweepCohortDecision.unavailable
try:
posthog_module = importlib.import_module("posthog")
client_type = getattr(posthog_module, "Posthog")
timeout = float(os.getenv(DAILY_MEMORY_SWEEP_COHORT_TIMEOUT_ENV, "3"))
if timeout <= 0 or timeout > 10:
return DailySweepCohortDecision.unavailable
client_key = (api_key, host, timeout)
with _POSTHOG_CLIENTS_LOCK:
reader = _POSTHOG_CLIENTS.get(client_key)
if reader is None:
reader = client_type(
project_api_key=api_key,
host=host,
feature_flags_request_timeout_seconds=timeout,
)
_POSTHOG_CLIENTS[client_key] = reader
except Exception:
return DailySweepCohortDecision.unavailable
try:
get_flag = getattr(reader, "get_feature_flag", None)
if callable(get_flag):
result = get_flag(
normalized_flag,
normalized_uid,
only_evaluate_locally=False,
send_feature_flag_events=False,
)
elif callable(reader):
result = reader(normalized_uid, normalized_flag)
else:
return DailySweepCohortDecision.unavailable
except Exception:
return DailySweepCohortDecision.unavailable
# A boolean true is the only accepted assignment. String variants are
# deliberately not treated as enrollment: a flag configured with a named
# variant must use a server-side boolean rollout or stay closed.
if result is True:
return DailySweepCohortDecision.enabled
if result is False:
return DailySweepCohortDecision.disabled
return DailySweepCohortDecision.unavailable
def close_daily_memory_sweep_cohort_clients() -> None:
"""Close cached PostHog transports at worker shutdown.
The SDK has used both ``shutdown`` and ``close`` across released versions;
invoke whichever lifecycle method the installed client exposes. Closing is
best effort and never changes the fail-closed assignment result.
"""
with _POSTHOG_CLIENTS_LOCK:
clients = tuple(_POSTHOG_CLIENTS.values())
_POSTHOG_CLIENTS.clear()
for client in clients:
for method_name in ("shutdown", "close"):
method = getattr(client, method_name, None)
if callable(method):
try:
method()
except Exception:
pass
break
atexit.register(close_daily_memory_sweep_cohort_clients)
class DailySweepModelAuthority(BaseModel):
"""Explicit authority for the bounded completed-day candidate producer.
``model_name`` is checked against the configured ``memories`` route before
the built-in extractor is called. The optional extractor injection is for
deterministic emulator/unit tests; production uses the same existing
memory model route and never accepts a client-selected model.
"""
model_config = ConfigDict(extra="forbid", frozen=True)
enabled: bool = False
model_name: str = "disabled"
max_candidates: int = Field(default=8, ge=0, le=MAX_CANDIDATES_PER_DAY)
max_cost_usd: float = Field(default=0.0, ge=0.0, le=10.0)
@property
def route_is_budgeted(self) -> bool:
return self.enabled and self.model_name not in {"", "disabled"} and self.max_cost_usd > 0
def daily_memory_sweep_model_authority_from_environment() -> DailySweepModelAuthority:
truthy = {"1", "true", "yes", "on"}
raw_candidates = os.getenv(DAILY_MEMORY_SWEEP_MAX_MODEL_CANDIDATES_ENV, "8")
raw_cost = os.getenv(DAILY_MEMORY_SWEEP_MAX_MODEL_COST_USD_ENV, "0")
try:
max_candidates = int(raw_candidates)
max_cost = float(raw_cost)
except ValueError as exc:
raise ValueError("daily sweep model budget environment is malformed") from exc
return DailySweepModelAuthority(
enabled=os.getenv(DAILY_MEMORY_SWEEP_MODEL_ENABLED_ENV, "false").casefold() in truthy,
model_name=os.getenv(DAILY_MEMORY_SWEEP_MODEL_NAME_ENV, "disabled").strip() or "disabled",
max_candidates=max_candidates,
max_cost_usd=max_cost,
)
def validate_qa_sweep_run_id(run_id: str) -> str:
normalized = (run_id or "").strip()
if not QA_SWEEP_RUN_ID_RE.fullmatch(normalized):
raise ValueError("QA sweep run id must match [a-z0-9][a-z0-9_-]{0,47}")
return normalized
def qa_sweep_run_id_from_environment(environ: Optional[Mapping[str, str]] = None) -> Optional[str]:
env = environ if environ is not None else os.environ
raw = env.get(QA_SWEEP_RUN_ID_ENV, "").strip()
return validate_qa_sweep_run_id(raw) if raw else None
def validate_qa_sweep_environment(environ: Optional[Mapping[str, str]] = None) -> str:
"""Require the complete, closed-world override set for one QA sweep run."""
env = environ if environ is not None else os.environ
run_id = qa_sweep_run_id_from_environment(env)
if not run_id:
raise ValueError(f"{QA_SWEEP_RUN_ID_ENV} is required for a QA sweep run")
required = {
"OMI_ENV_STAGE": "dev",
"GOOGLE_CLOUD_PROJECT": QA_SWEEP_PROJECT,
"GCLOUD_PROJECT": QA_SWEEP_PROJECT,
"OMI_FIRESTORE_DATA_PLANE_PROJECT": QA_SWEEP_PROJECT,
"FIRESTORE_DATABASE_ID": QA_SWEEP_DATABASE,
"FIREBASE_AUTH_PROJECT_ID": "based-hardware",
"MEMORY_ENABLED": "on",
"OMI_JIT_QA_AUTH_ONLY": "true",
"OMI_JIT_QA_UID_ALLOWLIST": QA_SWEEP_UID,
QA_SWEEP_ADMISSION_ENV: "true",
DAILY_MEMORY_SWEEP_ENABLED_ENV: "true",
DAILY_MEMORY_SWEEP_KILL_SWITCH_ENV: "false",
DAILY_MEMORY_SWEEP_MODEL_ENABLED_ENV: "true",
DAILY_MEMORY_SWEEP_MODEL_NAME_ENV: QA_SWEEP_MODEL_NAME,
DAILY_MEMORY_SWEEP_MAX_MODEL_CANDIDATES_ENV: str(QA_SWEEP_MAX_MODEL_CANDIDATES),
DAILY_MEMORY_SWEEP_MAX_MODEL_COST_USD_ENV: f"{QA_SWEEP_MAX_MODEL_COST_USD:g}",
DAILY_MEMORY_SWEEP_COHORT_ENABLED_ENV: "true",
DAILY_MEMORY_SWEEP_COHORT_FLAG_ENV: QA_SWEEP_COHORT,
DAILY_MEMORY_SWEEP_TIMEZONE_RECONCILIATION_ENV: "false",
}
for name, expected in required.items():
if env.get(name, "").strip().casefold() != expected.casefold():
raise ValueError(f"QA sweep requires {name}={expected!r}")
if env.get("FIRESTORE_EMULATOR_HOST", "").strip():
raise ValueError("QA sweep proof must use named Cloud Firestore")
if env.get("SERVICE_ACCOUNT_JSON", "").strip() or env.get("FIREBASE_AUTH_CREDENTIALS_PATH", "").strip():
raise ValueError("QA sweep proof cannot select customer Firebase credentials")
return run_id
def qa_sweep_cohort_authorizer(uid: str, cohort_name: str = "") -> DailySweepCohortDecision:
"""Admit only the fixed QA account under the explicit QA capability gate."""
try:
validate_qa_sweep_environment()
except ValueError:
return DailySweepCohortDecision.unavailable
if uid != QA_SWEEP_UID or cohort_name != QA_SWEEP_COHORT:
return DailySweepCohortDecision.unavailable
return DailySweepCohortDecision.enabled
class SweepFenceBlocked(RuntimeError):
"""A durable deletion or generation fence closed during a transaction."""
class SweepAuthoritativeQueryUnavailable(RuntimeError):
"""A bounded canonical query could not prove the occupant set."""
class SweepAuthority(str, Enum):
direct_user_statement = "direct_user_statement"
agent_reusable_conclusion = "agent_reusable_conclusion"
sweep_inference = "sweep_inference"
@property
def rank(self) -> int:
return {
SweepAuthority.sweep_inference: 1,
SweepAuthority.agent_reusable_conclusion: 2,
SweepAuthority.direct_user_statement: 3,
}[self]
@property
def ledger_reason(self) -> LedgerWriteReason:
return {
SweepAuthority.direct_user_statement: LedgerWriteReason.direct_user_statement,
SweepAuthority.agent_reusable_conclusion: LedgerWriteReason.agent_reusable_conclusion,
SweepAuthority.sweep_inference: LedgerWriteReason.daily_reconciliation,
}[self]
class DailySweepCandidate(BaseModel):
"""One server-built, bounded candidate from a completed local day."""
model_config = ConfigDict(extra="forbid", frozen=True)
candidate_id: str
kind: Literal["fact", "trigger"]
operation: Literal["add", "amend", "repair"] = "add"
content: str
source_id: str
source_type: str
source_version: str = "v1"
source_refs: Tuple[str, ...] = ()
authority: SweepAuthority = SweepAuthority.sweep_inference
target_memory_id: Optional[str] = None
slot: Optional[str] = None
subject_scope: MemorySubjectScope = MemorySubjectScope.primary_user
subject_entity_id: Optional[str] = None
trigger_condition: Dict[str, Any] = Field(default_factory=dict)
@field_validator("candidate_id", "target_memory_id", "subject_entity_id")
@classmethod
def validate_ids(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return None
normalized = value.strip()
if not normalized or not _ID_RE.fullmatch(normalized.casefold()):
raise ValueError("candidate identifiers must be bounded canonical ids")
return normalized
@field_validator("content")
@classmethod
def validate_content(cls, value: str) -> str:
normalized = " ".join((value or "").split())
if not normalized:
raise ValueError("candidate content is required")
if len(normalized) > MAX_CONTENT_CHARACTERS:
raise ValueError("candidate content exceeds the daily sweep budget")
if any(marker in normalized.casefold() for marker in _FORBIDDEN_SOURCE_MARKERS):
raise ValueError("raw image/pixel payloads are not valid sweep content")
return normalized
@field_validator("source_id", "source_type", "source_version")
@classmethod
def validate_source_identity(cls, value: str, info) -> str:
normalized = (value or "").strip()
limit = MAX_SOURCE_ID_CHARACTERS if info.field_name == "source_id" else 64
if not normalized or len(normalized) > limit:
raise ValueError("source identity is missing or oversized")
lowered = normalized.casefold()
if any(marker in lowered for marker in _FORBIDDEN_SOURCE_MARKERS):
raise ValueError("raw image/pixel payloads are not valid sweep sources")
if info.field_name == "source_type" and normalized not in _ALLOWED_SOURCE_TYPES:
raise ValueError("unsupported sweep source type")
return normalized
@field_validator("source_refs")
@classmethod
def validate_source_refs(cls, value: Tuple[str, ...]) -> Tuple[str, ...]:
normalized = tuple(sorted({ref.strip() for ref in value if ref and ref.strip()}))
if len(normalized) > MAX_SOURCE_REFS:
raise ValueError("source_refs exceed the daily sweep budget")
for ref in normalized:
lowered = ref.casefold()
if len(ref) > MAX_SOURCE_REF_CHARACTERS or any(marker in lowered for marker in _FORBIDDEN_SOURCE_MARKERS):
raise ValueError("source_refs must be bounded metadata-only references")
return normalized
@field_validator("slot")
@classmethod
def validate_slot(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return None
normalized = "_".join(value.strip().lower().replace("-", "_").split())
if not normalized or len(normalized) > 64:
raise ValueError("slot must be a bounded non-empty name")
return normalized
@field_validator("trigger_condition")
@classmethod
def validate_trigger_condition(cls, value: Dict[str, Any]) -> Dict[str, Any]:
_reject_payload(value)
if len(value) > MAX_TRIGGER_CONDITION_KEYS:
raise ValueError("trigger condition exceeds the daily sweep budget")
return value
@model_validator(mode="after")
def validate_semantics(self) -> "DailySweepCandidate":
if self.subject_scope == MemorySubjectScope.third_party and not self.subject_entity_id:
raise ValueError("third-party sweep facts require subject_entity_id")
if self.kind == "fact" and self.trigger_condition:
raise ValueError("fact candidates cannot carry trigger conditions")
if self.kind == "trigger" and self.operation != "repair":
raise ValueError("the daily sweep may repair existing triggers but never invent them")
if self.operation in {"amend", "repair"} and not self.target_memory_id:
raise ValueError("amend/repair candidates require target_memory_id")
if self.authority == SweepAuthority.direct_user_statement and self.source_type not in {
"explicit_user_statement",
"onboarding",
}:
raise ValueError("direct authority requires an explicit-user-statement or onboarding source")
if self.kind == "trigger":
# Compile at the boundary, then persist the normalized strict schema
# so a future evaluator never receives an unvalidated ad-hoc map.
object.__setattr__(
self, "trigger_condition", compile_trigger_condition(self.trigger_condition).as_condition()
)
return self
@property
def source_key(self) -> str:
return f"{self.source_type}:{self.source_id}:{self.candidate_id}"
def digest(self) -> str:
return deterministic_contract_id("daily-memory-sweep-candidate", self.model_dump(mode="json"))
class DailySweepInput(BaseModel):
"""Immutable input packet for one completed user-local date."""
model_config = ConfigDict(extra="forbid", frozen=True)
schema_version: str = SCHEMA_VERSION
uid: str
local_date: date
account_generation: int
source_generation: int
# Sweep-owned receipt namespace. ``source_generation`` remains the live
# canonical fence; this generation must not be advanced by a timezone
# preference change in the global canonical control document.
sweep_generation: int = 1
timezone_name: str
window_id: str
window_start_utc: datetime
window_end_utc: datetime
window_kind: Literal["local_day", "timezone_transition"] = "local_day"
complete: bool
candidates: Tuple[DailySweepCandidate, ...] = ()
# The producer attests the onboarding sources represented by this packet,
# including sources that yielded zero candidates. Consumption is done
# after all candidate receipts commit, never once per candidate.
onboarding_source_keys: Tuple[str, ...] = ()
onboarding_source_progress: Dict[str, int] = Field(default_factory=dict)
eligibility_proof: Literal["completed_transcript_v1", "none"] = "none"
@field_validator("uid")
@classmethod
def validate_uid(cls, value: str) -> str:
normalized = (value or "").strip()
if not normalized:
raise ValueError("uid is required")
return normalized
@field_validator("account_generation", "source_generation", "sweep_generation")
@classmethod
def validate_generations(cls, value: int) -> int:
if value < 0:
raise ValueError("generation must be nonnegative")
return value
@field_validator("window_start_utc", "window_end_utc")
@classmethod
def validate_window_timestamp(cls, value: datetime) -> datetime:
if value.tzinfo is None or value.utcoffset() is None:
raise ValueError("input window timestamps must be timezone-aware")
return value.astimezone(timezone.utc)
@field_validator("candidates")
@classmethod
def validate_candidate_count(cls, value: Tuple[DailySweepCandidate, ...]) -> Tuple[DailySweepCandidate, ...]:
if len(value) > MAX_CANDIDATES_PER_DAY:
raise ValueError("daily sweep candidate window exceeded")
return value
@field_validator("onboarding_source_keys")
@classmethod
def validate_onboarding_source_keys(cls, value: Tuple[str, ...]) -> Tuple[str, ...]:
normalized = tuple(sorted({item.strip() for item in value if item.strip()}))
if len(normalized) > MAX_CANDIDATES_PER_DAY:
raise ValueError("daily sweep onboarding source budget exceeded")
if any(not item.startswith("onboarding:") or len(item) > MAX_SOURCE_ID_CHARACTERS for item in normalized):
raise ValueError("invalid onboarding source key")
return normalized
@field_validator("onboarding_source_progress")
@classmethod
def validate_onboarding_source_progress(cls, value: Dict[str, int]) -> Dict[str, int]:
normalized = {str(key).strip(): int(offset) for key, offset in value.items()}
if len(normalized) > MAX_CANDIDATES_PER_DAY or any(
not key.startswith("onboarding:") or offset < 0 for key, offset in normalized.items()
):
raise ValueError("invalid onboarding source progress")
return normalized
@model_validator(mode="after")
def validate_schema(self) -> "DailySweepInput":
if self.schema_version != SCHEMA_VERSION:
raise ValueError("unsupported daily sweep input schema")
try:
ZoneInfo(self.timezone_name)
except (ZoneInfoNotFoundError, ValueError) as exc:
raise ValueError("input timezone must be an installed IANA timezone") from exc
expected = completed_local_day_window(self.local_date, self.timezone_name)
exact_window = (
self.window_id == expected.window_id
and self.window_start_utc == expected.start_utc
and self.window_end_utc == expected.end_utc
)
transition_window = False
if self.window_kind == "timezone_transition" and self.window_start_utc < self.window_end_utc:
try:
transition = timezone_transition_window(
self.local_date,
self.timezone_name,
coverage_start_utc=self.window_start_utc,
)
transition_window = self.window_id == transition.window_id and self.window_end_utc == transition.end_utc
except ValueError:
transition_window = False
if not self.complete or not (exact_window if self.window_kind == "local_day" else transition_window):
raise ValueError("input must be an immutable complete exact local-day packet")
return self
class DailySweepSkip(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
candidate_id: str
reason: Literal[
"duplicate_candidate",
"lower_authority",
"missing_target",
"target_not_active",
"target_kind_mismatch",
"target_not_explicit_trigger",
"source_key_conflict",
"invalid_candidate",
"existing_active_slot",
"existing_active_subject",
]
class DailySweepPlan(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
schema_version: str = SCHEMA_VERSION
uid: str
local_date: date
idempotency_key: str
candidates: Tuple[DailySweepCandidate, ...] = ()
skipped: Tuple[DailySweepSkip, ...] = ()
class DailySweepCursor(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
schema_version: str = CURSOR_SCHEMA_VERSION
uid: str
account_generation: int
source_generation: int
sweep_generation: int = 1
generation: int = 0
timezone_name: Optional[str] = None
last_completed_local_date: Optional[date] = None
last_completed_window_id: Optional[str] = None
last_completed_window_start_utc: Optional[datetime] = None
last_completed_window_end_utc: Optional[datetime] = None
pending_transition_local_date: Optional[date] = None
pending_transition_window_id: Optional[str] = None
pending_transition_start_utc: Optional[datetime] = None
pending_transition_end_utc: Optional[datetime] = None
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
@field_validator(
"updated_at",
"last_completed_window_start_utc",
"last_completed_window_end_utc",
"pending_transition_start_utc",
"pending_transition_end_utc",
)
@classmethod
def validate_timestamp(cls, value: Optional[datetime]) -> Optional[datetime]:
if value is None:
return None
if value.tzinfo is None or value.utcoffset() is None:
raise ValueError("cursor timestamps must be timezone-aware")
return value.astimezone(timezone.utc)
@field_validator("timezone_name")
@classmethod
def validate_timezone_name(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return None
try:
ZoneInfo(value)
except ZoneInfoNotFoundError as exc:
raise ValueError("cursor timezone must be an installed IANA timezone") from exc
return value
@model_validator(mode="after")
def validate_window_identity(self) -> "DailySweepCursor":
if self.last_completed_local_date is None:
if any(
(
self.last_completed_window_id,
self.last_completed_window_start_utc,
self.last_completed_window_end_utc,
)
):
raise ValueError("cursor window identity requires a completed local date")
elif not (
self.timezone_name
and self.last_completed_window_id
and self.last_completed_window_start_utc
and self.last_completed_window_end_utc
):
raise ValueError("completed cursor rows require an exact UTC window identity")
transition_values = (
self.pending_transition_local_date,
self.pending_transition_window_id,
self.pending_transition_start_utc,
self.pending_transition_end_utc,
)
if any(value is not None for value in transition_values) and not all(
value is not None for value in transition_values
):
raise ValueError("timezone transition cursor rows require an exact pending window identity")
if (
self.pending_transition_start_utc is not None
and self.pending_transition_end_utc is not None
and self.pending_transition_end_utc <= self.pending_transition_start_utc
):
raise ValueError("timezone transition window must advance in UTC")
if any(value is not None for value in transition_values):
if self.last_completed_window_end_utc is None:
raise ValueError("timezone transition requires a completed UTC coverage anchor")
if self.pending_transition_start_utc != self.last_completed_window_end_utc:
raise ValueError("timezone transition must begin at the completed UTC coverage end")
pending_local_date = self.pending_transition_local_date
pending_start_utc = self.pending_transition_start_utc
if pending_local_date is None or pending_start_utc is None or self.timezone_name is None:
raise ValueError("timezone transition cursor window is incomplete")
try:
expected_transition = timezone_transition_window(
pending_local_date,
self.timezone_name,
coverage_start_utc=pending_start_utc,
)
except (TypeError, ValueError) as exc:
raise ValueError("timezone transition cursor window is invalid") from exc
if (
self.pending_transition_window_id != expected_transition.window_id
or self.pending_transition_end_utc != expected_transition.end_utc
):
raise ValueError("timezone transition cursor window identity mismatch")
return self
class DailySweepOutput(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
schema_version: str = SCHEMA_VERSION
uid: str
status: Literal["disabled", "not_due", "blocked", "committed"]
completed_local_dates: Tuple[date, ...] = ()
committed_count: int = 0
idempotent_count: int = 0
skipped_count: int = 0
blocked_reason: Optional[str] = None
telemetry: Dict[str, int | str] = Field(default_factory=dict)
@dataclass(frozen=True)
class CompletedLocalDayWindow:
start_utc: datetime
end_utc: datetime
window_id: str
def completed_local_day_window(local_date: date, timezone_name: str) -> CompletedLocalDayWindow:
"""Return the exact UTC half-open window for one local calendar day.
ZoneInfo conversion intentionally preserves 23-hour spring-forward and
25-hour fall-back days. A timezone change while a cursor is non-empty is
fail-closed by the runner: an operator must reconcile/reset the cursor, so
overlap is never double-processed and a gap is never silently skipped.
"""
try:
zone = ZoneInfo(timezone_name)
except (ZoneInfoNotFoundError, ValueError) as exc:
raise ValueError("timezone_name must be a valid IANA timezone") from exc
start = datetime.combine(local_date, time.min, tzinfo=zone).astimezone(timezone.utc)
end = datetime.combine(local_date + timedelta(days=1), time.min, tzinfo=zone).astimezone(timezone.utc)
if end <= start:
raise ValueError("local-day window must advance in UTC")
window_id = deterministic_contract_id(
"daily-memory-sweep-window",
{
"local_date": local_date.isoformat(),
"timezone": timezone_name,
"start_utc": start.isoformat(),
"end_utc": end.isoformat(),
},
)
return CompletedLocalDayWindow(start_utc=start, end_utc=end, window_id=window_id)
def timezone_transition_window(
local_date: date,
timezone_name: str,
*,
coverage_start_utc: datetime,
) -> CompletedLocalDayWindow:
"""Build the one bounded bridge window after a timezone preference change.
The new zone's local day ending at ``local_date + 1 midnight`` can begin
before or after the prior zone's UTC coverage end. Clipping its start to
that prior end gives the first post-change packet a half-open interval
contiguous with the already completed history; subsequent new-zone days
use ordinary exact local-day windows.
"""
expected = completed_local_day_window(local_date, timezone_name)
if coverage_start_utc.tzinfo is None or coverage_start_utc.utcoffset() is None:
raise ValueError("coverage_start_utc must be timezone-aware")
start = coverage_start_utc.astimezone(timezone.utc)