Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
2828 lines (2439 loc) · 91.8 KB
/
Copy pathdatabase.py
File metadata and controls
2828 lines (2439 loc) · 91.8 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 argparse
import asyncio
import aiosqlite
import contextlib
import datetime
import json
import sqlite3
import logging
import os
import re
from dataclasses import dataclass
from typing import Any, Callable, Mapping, Optional
import numpy as np
from app.rag_embeddings import (
EmbeddingMetadata,
embed_text_with_metadata,
embed_texts_with_metadata,
get_runtime_embedding_metadata,
pack_embedding,
unpack_embedding,
)
from app.runtime_config import get_runtime_bool, get_runtime_int, get_runtime_value
DB_FILE = get_runtime_value("DB_FILE")
logger = logging.getLogger(__name__)
BOT_HISTORY_USERNAME = "mioo_bot"
DB_SCHEMA_VERSION = 4
DB_SCHEMA_VERSION_KEY = "schema_version"
REPLY_BACKFILL_MARKER_KEY = "reply_backfill_done"
SQLITE_BUSY_TIMEOUT_MS = 5000
def _db_file_path() -> str:
# Prefer runtime env override while preserving compatibility with test monkeypatching.
return get_runtime_value("DB_FILE") or DB_FILE
_ENSURED_DB_PARENT_DIRS: set[str] = set()
def _ensure_db_parent_dir(db_file: str) -> None:
parent_dir = os.path.dirname(db_file)
if not parent_dir:
return
# makedirs(exist_ok=True) on every DB call is pure syscall overhead; the
# directory only needs to be ensured once per path per process.
if parent_dir in _ENSURED_DB_PARENT_DIRS:
return
os.makedirs(parent_dir, exist_ok=True)
_ENSURED_DB_PARENT_DIRS.add(parent_dir)
def _get_env_int(name: str, default: int) -> int:
value = get_runtime_int(name, default)
if value == default:
raw = get_runtime_value(name)
if raw and raw != str(default):
logger.warning("Invalid %s=%r, using default=%d", name, raw, default)
return value
def _rag_top_k() -> int:
return _get_env_int("RAG_TOP_K", 12)
def _rag_enabled() -> bool:
return get_runtime_bool("RAG_ENABLED", True)
def _message_review_back() -> int:
return _get_env_int("MESSAGE_REVIEW_BACK", 80)
def _rag_keyword_scan_back() -> int:
return _get_env_int("RAG_KEYWORD_SCAN_BACK", 500)
def _recent_context_max_chars() -> int:
return _get_env_int("RECENT_CONTEXT_MAX_CHARS", 12000)
def _rag_context_max_chars() -> int:
return _get_env_int("RAG_CONTEXT_MAX_CHARS", 6000)
def _rag_vector_candidate_limit() -> int:
"""Upper bound on embedding rows loaded per vector search (0 = unlimited)."""
return _get_env_int("RAG_VECTOR_CANDIDATE_LIMIT", 50000)
@dataclass(frozen=True)
class MessageRow:
id: int
chat_id: int
username: str
content: str
timestamp: str
reply_to_username: Optional[str] = None
@dataclass(frozen=True)
class StickerReplyCandidate:
file_unique_id: str
file_id: str
emoji: Optional[str]
set_name: Optional[str]
description: str
description_source: str
tags: list[str]
mood: Optional[str]
safe_for_reply: bool = True
is_animated: bool = False
is_video: bool = False
use_count: int = 0
last_used_at: Optional[str] = None
@dataclass(frozen=True)
class UserMemoryRow:
telegram_user_key: str
latest_display_name: str
memory_text: str
last_refreshed_date: Optional[str] = None
@dataclass(frozen=True)
class UserMemoryFactRow:
id: int
telegram_user_key: str
fact_type: str
fact_text: str
confidence: float
evidence_message_ids: list[int]
first_observed_at: Optional[str] = None
last_confirmed_at: Optional[str] = None
@dataclass(frozen=True)
class GlobalMemoryFactRow:
id: int
chat_id: int
fact_type: str
fact_text: str
confidence: float
evidence_message_ids: list[int]
first_observed_at: Optional[str] = None
last_confirmed_at: Optional[str] = None
@dataclass(frozen=True)
class GlobalMemoryChatOverviewRow:
chat_id: int
message_count: int
global_fact_count: int
latest_message_at: Optional[str]
latest_message_username: Optional[str]
latest_message_preview: Optional[str]
@dataclass(frozen=True)
class WebAdminLoginTokenRow:
id: int
token_hash: str
admin_user_id: Optional[int]
admin_username: str
expires_at: str
used_at: Optional[str]
created_at: Optional[str]
@dataclass(frozen=True)
class WebAdminDashboardStats:
message_count: int
chat_count: int
user_memory_count: int
user_memory_fact_count: int
pending_candidate_count: int
global_memory_fact_count: int
db_schema_version: int
@dataclass(frozen=True)
class WebAdminMessageRow:
id: int
chat_id: int
username: str
content: str
timestamp: str
telegram_user_key: Optional[str]
telegram_message_id: Optional[int]
reply_to_telegram_message_id: Optional[int]
reply_to_db_message_id: Optional[int]
reply_to_username: Optional[str]
@dataclass(frozen=True)
class UserMemoryOverviewRow:
telegram_user_key: str
latest_display_name: str
memory_text: str
last_refreshed_date: Optional[str]
fact_count: int
latest_message_at: Optional[str]
@dataclass(frozen=True)
class UserMemorySearchRow:
telegram_user_key: str
latest_display_name: str
source: str
text: str
@dataclass(frozen=True)
class UserMemoryCandidateRow:
id: int
telegram_user_key: str
fact_type: str
fact_text: str
confidence: float
evidence_message_ids: list[int]
source_message_id: Optional[int]
priority: str
status: str
created_at: Optional[str]
updated_at: Optional[str]
def _format_message(row: MessageRow, *, max_chars: int = 800) -> str:
content = (row.content or "").replace("\r\n", "\n").strip()
if len(content) > max_chars:
content = content[: max_chars - 1] + "…"
if row.reply_to_username:
content = f"[reply to {row.reply_to_username}] {content}"
return f"[{row.timestamp}] {row.username}: {content}"
def _trim_context_lines(lines: list[str], *, max_chars: int, keep: str = "last") -> list[str]:
if max_chars <= 0 or not lines:
return lines
selected: list[str] = []
total = 0
source = reversed(lines) if keep == "last" else iter(lines)
for line in source:
text = str(line)
cost = len(text) + 1
if selected and total + cost > max_chars:
break
if cost > max_chars:
text = text[: max_chars - 1].rstrip() + "…"
cost = len(text) + 1
selected.append(text)
total += cost
if keep == "last":
selected.reverse()
return selected
_STICKER_SEARCH_STOPWORDS = {
"and",
"the",
"this",
"that",
"with",
"from",
"input_type",
"sticker",
"reply",
"message",
"user",
"true",
"false",
"none",
"current_date_utc",
"current_weekday_utc",
"sender_display",
"trigger_type",
"direct_addressed",
}
_STICKER_QUERY_EXPANSIONS = (
("haha", ("laugh", "smile", "happy", "joy")),
("lol", ("laugh", "smile", "happy", "joy")),
("lmao", ("laugh", "smile", "happy", "joy")),
("thanks", ("thanks", "thank", "heart", "happy")),
("thank you", ("thanks", "thank", "heart", "happy")),
("cute", ("cute", "happy", "smile")),
("angry", ("angry", "mad", "annoyed")),
("sad", ("sad", "cry", "tears")),
("cry", ("cry", "sad", "tears")),
("ok", ("ok", "yes", "thumb", "nod")),
("哈哈", ("laugh", "smile", "happy", "joy")),
("笑死", ("laugh", "smile", "happy", "joy")),
("开心", ("happy", "smile", "joy")),
("可爱", ("cute", "happy", "smile")),
("谢谢", ("thanks", "thank", "heart", "happy")),
("感谢", ("thanks", "thank", "heart", "happy")),
("生气", ("angry", "mad", "annoyed")),
("难过", ("sad", "cry", "tears")),
("哭", ("cry", "sad", "tears")),
)
def _sticker_search_terms(query_text: str, *, max_terms: int = 16) -> list[str]:
lowered = (query_text or "").lower()
terms: list[str] = []
for trigger, expanded_terms in _STICKER_QUERY_EXPANSIONS:
if trigger in lowered:
terms.extend(expanded_terms)
for token in re.findall(r"[\w\u4e00-\u9fff]+", lowered):
normalized = token.strip("_")
if len(normalized) < 2 or normalized in _STICKER_SEARCH_STOPWORDS:
continue
terms.append(normalized[:64])
unique_terms: list[str] = []
seen: set[str] = set()
for term in terms:
if term in seen:
continue
seen.add(term)
unique_terms.append(term)
if len(unique_terms) >= max_terms:
break
return unique_terms
def _sticker_reply_cooldown_minutes() -> int:
return _get_env_int("STICKER_REPLY_COOLDOWN_MINUTES", 30)
def _decode_sticker_tags(value: Any) -> list[str]:
try:
decoded = json.loads(value) if isinstance(value, str) else value
except json.JSONDecodeError:
decoded = value
if isinstance(decoded, str):
raw_tags = [part.strip() for part in decoded.replace(";", ",").split(",")]
elif isinstance(decoded, list):
raw_tags = [str(part).strip() for part in decoded]
else:
raw_tags = []
tags: list[str] = []
seen: set[str] = set()
for raw_tag in raw_tags:
tag = " ".join(raw_tag.lower().split())[:40]
if not tag or tag in seen:
continue
seen.add(tag)
tags.append(tag)
if len(tags) >= 8:
break
return tags
def _encode_sticker_tags(tags: Optional[list[str]]) -> str:
return json.dumps(_decode_sticker_tags(tags or []), ensure_ascii=False)
def _is_recent_sticker_use(last_used_at: Optional[str], *, cooldown_minutes: int) -> bool:
if not last_used_at or cooldown_minutes <= 0:
return False
cutoff = datetime.datetime.now(datetime.UTC) - datetime.timedelta(minutes=cooldown_minutes)
cutoff_text = cutoff.strftime("%Y-%m-%d %H:%M:%S")
return str(last_used_at) >= cutoff_text
def _score_sticker_candidate(candidate: StickerReplyCandidate, terms: list[str]) -> int:
description = (candidate.description or "").lower()
emoji = (candidate.emoji or "").lower()
set_name = (candidate.set_name or "").lower()
tags = " ".join(candidate.tags or []).lower()
mood = (candidate.mood or "").lower()
score = 0
for term in terms:
if term in description:
score += 4
if tags and term in tags:
score += 5
if mood and term in mood:
score += 3
if emoji and term in emoji:
score += 2
if set_name and term in set_name:
score += 1
if not candidate.safe_for_reply:
score -= 1000
score -= min(max(candidate.use_count, 0), 20)
if _is_recent_sticker_use(candidate.last_used_at, cooldown_minutes=_sticker_reply_cooldown_minutes()):
score -= 100
return score
def _sticker_candidate_from_row(row: tuple[Any, ...]) -> StickerReplyCandidate:
return StickerReplyCandidate(
file_unique_id=str(row[0]),
file_id=str(row[1]),
emoji=row[2] if isinstance(row[2], str) else None,
set_name=row[3] if isinstance(row[3], str) else None,
description=str(row[4] or ""),
description_source=str(row[5] or ""),
tags=_decode_sticker_tags(row[6]),
mood=row[7] if isinstance(row[7], str) and row[7].strip() else None,
safe_for_reply=bool(row[8]),
is_animated=bool(row[9]),
is_video=bool(row[10]),
use_count=int(row[11] or 0),
last_used_at=row[12] if isinstance(row[12], str) else None,
)
async def _enable_foreign_keys(db: aiosqlite.Connection) -> None:
try:
await db.execute("PRAGMA foreign_keys = ON")
except Exception:
# Best effort; if it fails, DB still works but cascade deletes won't.
pass
def _configure_sqlite_connection(db: sqlite3.Connection) -> None:
db.execute(f"PRAGMA busy_timeout = {SQLITE_BUSY_TIMEOUT_MS}")
db.execute("PRAGMA journal_mode = WAL")
db.execute("PRAGMA synchronous = NORMAL")
db.execute("PRAGMA foreign_keys = ON")
async def _configure_async_sqlite_connection(db: aiosqlite.Connection) -> None:
await db.execute(f"PRAGMA busy_timeout = {SQLITE_BUSY_TIMEOUT_MS}")
await db.execute("PRAGMA journal_mode = WAL")
await db.execute("PRAGMA synchronous = NORMAL")
await _enable_foreign_keys(db)
def _connect(db_file: str):
"""Open a configured aiosqlite connection.
Explicit factory instead of monkeypatching aiosqlite.connect globally:
every runtime data-access path goes through here so PRAGMAs are applied
exactly once per connection.
"""
return _ConfiguredAioSqliteConnection(aiosqlite.connect(db_file))
class _ConfiguredAioSqliteConnection:
def __init__(self, connection: aiosqlite.Connection):
self._connection = connection
async def __aenter__(self) -> aiosqlite.Connection:
db = await self._connection.__aenter__()
await _configure_async_sqlite_connection(db)
return db
async def __aexit__(self, exc_type, exc, tb):
return await self._connection.__aexit__(exc_type, exc, tb)
def _get_message_columns(db: sqlite3.Connection) -> set[str]:
cursor = db.execute("PRAGMA table_info(messages)")
return {str(row[1]) for row in cursor.fetchall()}
def _table_exists(db: sqlite3.Connection, table_name: str) -> bool:
row = db.execute(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
(table_name,),
).fetchone()
return row is not None
def _get_table_columns(db: sqlite3.Connection, table_name: str) -> set[str]:
cursor = db.execute(f"PRAGMA table_info({table_name})")
return {str(row[1]) for row in cursor.fetchall()}
def _init_db_metadata_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS db_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
'''
)
def _get_db_schema_version(db: sqlite3.Connection) -> int:
if not _table_exists(db, "db_metadata"):
return 0
row = db.execute(
"SELECT value FROM db_metadata WHERE key = ?",
(DB_SCHEMA_VERSION_KEY,),
).fetchone()
if not row:
return 0
try:
return int(row[0])
except (TypeError, ValueError):
return 0
def _set_db_schema_version(db: sqlite3.Connection, version: int) -> None:
db.execute(
'''
INSERT INTO db_metadata (key, value, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = CURRENT_TIMESTAMP
''',
(DB_SCHEMA_VERSION_KEY, str(version)),
)
def get_db_schema_version() -> int:
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
with contextlib.closing(sqlite3.connect(db_file)) as db:
_configure_sqlite_connection(db)
return _get_db_schema_version(db)
def _migrate_messages_table(db: sqlite3.Connection) -> None:
columns = _get_message_columns(db)
if "telegram_message_id" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN telegram_message_id INTEGER")
if "reply_to_telegram_message_id" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN reply_to_telegram_message_id INTEGER")
if "reply_to_db_message_id" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN reply_to_db_message_id INTEGER")
if "reply_to_username" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN reply_to_username TEXT")
if "telegram_user_key" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN telegram_user_key TEXT")
db.execute("CREATE INDEX IF NOT EXISTS idx_messages_chat_tg ON messages (chat_id, telegram_message_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_messages_reply_db ON messages (reply_to_db_message_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_messages_user_date ON messages (telegram_user_key, timestamp)")
db.execute("CREATE INDEX IF NOT EXISTS idx_messages_chat_id ON messages (chat_id, id)")
def _backfill_reply_metadata_from_content(db: sqlite3.Connection) -> None:
"""One-shot backfill for old rows that embedded reply target in content.
The UPDATE is a full table scan; without a completion marker it re-ran on
every startup forever. The marker makes it a no-op after the first success
and stays compatible with rollbacks to older code (which simply re-runs it).
"""
row = db.execute(
"SELECT 1 FROM db_metadata WHERE key = ?",
(REPLY_BACKFILL_MARKER_KEY,),
).fetchone()
if row:
return
db.execute(
'''
UPDATE messages
SET reply_to_username = TRIM(SUBSTR(content, 11, INSTR(SUBSTR(content, 11), ']') - 1))
WHERE reply_to_username IS NULL
AND content LIKE '[reply_to:%'
AND INSTR(SUBSTR(content, 11), ']') > 0
'''
)
db.execute(
'''
INSERT INTO db_metadata (key, value, updated_at)
VALUES (?, '1', CURRENT_TIMESTAMP)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = CURRENT_TIMESTAMP
''',
(REPLY_BACKFILL_MARKER_KEY,),
)
def _get_message_embedding_columns(db: sqlite3.Connection) -> set[str]:
cursor = db.execute("PRAGMA table_info(message_embeddings)")
return {str(row[1]) for row in cursor.fetchall()}
def _migrate_message_embeddings_table(db: sqlite3.Connection) -> None:
columns = _get_message_embedding_columns(db)
if "backend" not in columns:
db.execute("ALTER TABLE message_embeddings ADD COLUMN backend TEXT")
if "signature" not in columns:
db.execute("ALTER TABLE message_embeddings ADD COLUMN signature TEXT")
db.execute("CREATE INDEX IF NOT EXISTS idx_embed_chat_signature ON message_embeddings (chat_id, signature)")
def _get_sticker_columns(db: sqlite3.Connection) -> set[str]:
cursor = db.execute("PRAGMA table_info(sticker_descriptions)")
return {str(row[1]) for row in cursor.fetchall()}
def _migrate_stickers_table(db: sqlite3.Connection) -> None:
columns = _get_sticker_columns(db)
if "sticker_tags" not in columns:
db.execute("ALTER TABLE sticker_descriptions ADD COLUMN sticker_tags TEXT NOT NULL DEFAULT '[]'")
if "mood" not in columns:
db.execute("ALTER TABLE sticker_descriptions ADD COLUMN mood TEXT")
if "safe_for_reply" not in columns:
db.execute("ALTER TABLE sticker_descriptions ADD COLUMN safe_for_reply INTEGER NOT NULL DEFAULT 1")
if "use_count" not in columns:
db.execute("ALTER TABLE sticker_descriptions ADD COLUMN use_count INTEGER NOT NULL DEFAULT 0")
if "last_used_at" not in columns:
db.execute("ALTER TABLE sticker_descriptions ADD COLUMN last_used_at DATETIME")
def _init_stickers_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS sticker_descriptions (
file_unique_id TEXT PRIMARY KEY,
file_id TEXT,
emoji TEXT,
set_name TEXT,
description TEXT NOT NULL,
description_source TEXT NOT NULL DEFAULT 'fallback',
sticker_tags TEXT NOT NULL DEFAULT '[]',
mood TEXT,
safe_for_reply INTEGER NOT NULL DEFAULT 1,
is_animated INTEGER NOT NULL DEFAULT 0,
is_video INTEGER NOT NULL DEFAULT 0,
use_count INTEGER NOT NULL DEFAULT 0,
last_used_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
'''
)
_migrate_stickers_table(db)
db.execute("CREATE INDEX IF NOT EXISTS idx_sticker_set_name ON sticker_descriptions (set_name)")
db.execute("CREATE INDEX IF NOT EXISTS idx_sticker_file_id ON sticker_descriptions (file_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_sticker_updated_at ON sticker_descriptions (updated_at)")
db.execute("CREATE INDEX IF NOT EXISTS idx_sticker_safe_reply ON sticker_descriptions (safe_for_reply, last_used_at, use_count)")
def _init_user_memories_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS user_memories (
telegram_user_key TEXT PRIMARY KEY,
latest_display_name TEXT NOT NULL,
memory_text TEXT NOT NULL DEFAULT '',
last_refreshed_date TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
'''
)
def _init_user_memory_facts_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS user_memory_facts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
telegram_user_key TEXT NOT NULL,
fact_type TEXT NOT NULL,
fact_text TEXT NOT NULL,
confidence REAL NOT NULL DEFAULT 0.5,
evidence_message_ids TEXT NOT NULL DEFAULT '[]',
first_observed_at TEXT,
last_confirmed_at TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(telegram_user_key, fact_type, fact_text)
)
'''
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_user_memory_facts_user ON user_memory_facts "
"(telegram_user_key, is_active, fact_type, confidence)"
)
def _init_global_memory_facts_table(db: sqlite3.Connection) -> None:
legacy_backup_name: Optional[str] = None
if _table_exists(db, "global_memory_facts"):
columns = _get_table_columns(db, "global_memory_facts")
if "chat_id" not in columns:
base_backup_name = "global_memory_facts_unscoped_backup"
legacy_backup_name = base_backup_name
suffix = 1
while _table_exists(db, legacy_backup_name):
suffix += 1
legacy_backup_name = f"{base_backup_name}_{suffix}"
db.execute(f"ALTER TABLE global_memory_facts RENAME TO {legacy_backup_name}")
db.execute(
'''
CREATE TABLE IF NOT EXISTS global_memory_facts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
fact_type TEXT NOT NULL,
fact_text TEXT NOT NULL,
confidence REAL NOT NULL DEFAULT 0.5,
evidence_message_ids TEXT NOT NULL DEFAULT '[]',
first_observed_at TEXT,
last_confirmed_at TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(chat_id, fact_type, fact_text)
)
'''
)
if legacy_backup_name:
db.execute(
f'''
INSERT OR IGNORE INTO global_memory_facts (
chat_id,
fact_type,
fact_text,
confidence,
evidence_message_ids,
first_observed_at,
last_confirmed_at,
is_active,
created_at,
updated_at
)
SELECT
0,
fact_type,
fact_text,
confidence,
evidence_message_ids,
first_observed_at,
last_confirmed_at,
is_active,
created_at,
updated_at
FROM {legacy_backup_name}
'''
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_global_memory_facts_chat_active ON global_memory_facts "
"(chat_id, is_active, fact_type, confidence)"
)
def _init_user_memory_candidates_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS user_memory_candidates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
telegram_user_key TEXT NOT NULL,
fact_type TEXT NOT NULL,
fact_text TEXT NOT NULL,
confidence REAL NOT NULL DEFAULT 0.5,
evidence_message_ids TEXT NOT NULL DEFAULT '[]',
source_message_id INTEGER,
priority TEXT NOT NULL DEFAULT 'slow',
status TEXT NOT NULL DEFAULT 'pending',
review_note TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
reviewed_at DATETIME
)
'''
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_user_memory_candidates_user_status ON user_memory_candidates "
"(telegram_user_key, status, priority, id)"
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_user_memory_candidates_status ON user_memory_candidates "
"(status, priority, id)"
)
def _init_webadmin_login_tokens_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS webadmin_login_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_hash TEXT NOT NULL UNIQUE,
admin_user_id INTEGER,
admin_username TEXT NOT NULL DEFAULT '',
expires_at DATETIME NOT NULL,
used_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
'''
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_webadmin_login_tokens_expiry "
"ON webadmin_login_tokens (expires_at, used_at)"
)
async def _embed_message_content(username: str, content: str) -> tuple[np.ndarray, EmbeddingMetadata]:
return await embed_text_with_metadata(f"{username}: {content}")
def init_db():
"""Initializes the database and creates the messages table if it doesn't exist."""
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
# closing() fixes a connection handle leak: sqlite3's context manager only
# commits, it never closes, which on Windows keeps the file locked.
with contextlib.closing(sqlite3.connect(db_file)) as db:
_configure_sqlite_connection(db)
_init_db_metadata_table(db)
previous_schema_version = _get_db_schema_version(db)
db.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
username TEXT NOT NULL,
content TEXT NOT NULL,
telegram_message_id INTEGER,
reply_to_telegram_message_id INTEGER,
reply_to_db_message_id INTEGER,
reply_to_username TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
_migrate_messages_table(db)
db.execute('CREATE INDEX IF NOT EXISTS idx_chat_timestamp ON messages (chat_id, timestamp)')
db.execute('''
CREATE TABLE IF NOT EXISTS message_embeddings (
message_id INTEGER PRIMARY KEY,
chat_id INTEGER NOT NULL,
embedding BLOB NOT NULL,
dim INTEGER NOT NULL,
model TEXT,
backend TEXT,
signature TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(message_id) REFERENCES messages(id) ON DELETE CASCADE
)
''')
_migrate_message_embeddings_table(db)
db.execute('CREATE INDEX IF NOT EXISTS idx_embed_chat ON message_embeddings (chat_id)')
db.execute('CREATE INDEX IF NOT EXISTS idx_embed_chat_msg ON message_embeddings (chat_id, message_id)')
_init_stickers_table(db)
_init_user_memories_table(db)
_init_user_memory_facts_table(db)
_init_global_memory_facts_table(db)
_init_user_memory_candidates_table(db)
_init_webadmin_login_tokens_table(db)
_backfill_reply_metadata_from_content(db)
_set_db_schema_version(db, DB_SCHEMA_VERSION)
db.commit()
if previous_schema_version != DB_SCHEMA_VERSION:
logger.info("Database schema version updated: %s -> %s", previous_schema_version, DB_SCHEMA_VERSION)
logger.info("Database initialized: %s", db_file)
async def add_message(
chat_id: int,
username: str,
content: str,
*,
telegram_user_key: Optional[str] = None,
telegram_message_id: Optional[int] = None,
reply_to_telegram_message_id: Optional[int] = None,
reply_to_username: Optional[str] = None,
) -> Optional[int]:
"""Adds a message to the history with optional reply-chain metadata."""
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with _connect(db_file) as db:
# Add the new message
cursor = await db.execute(
"""
INSERT INTO messages (
chat_id,
username,
content,
telegram_user_key,
telegram_message_id,
reply_to_telegram_message_id,
reply_to_username
) VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(chat_id, username, content, telegram_user_key, telegram_message_id, reply_to_telegram_message_id, reply_to_username)
)
lastrowid = cursor.lastrowid
if lastrowid is None:
await db.commit()
return None
message_id = int(lastrowid)
# Resolve parent DB row for reply chain when Telegram parent id is known.
if reply_to_telegram_message_id is not None:
parent_cursor = await db.execute(
'''
SELECT id
FROM messages
WHERE chat_id = ? AND telegram_message_id = ?
ORDER BY id DESC
LIMIT 1
''',
(chat_id, reply_to_telegram_message_id),
)
parent_row = await parent_cursor.fetchone()
if parent_row:
await db.execute(
"UPDATE messages SET reply_to_db_message_id = ? WHERE id = ?",
(int(parent_row[0]), message_id),
)
await db.commit()
# Store local embedding best-effort after committing the message row. This
# keeps slow model work from holding a SQLite write transaction open.
try:
vec, metadata = await _embed_message_content(username, content)
blob, dim = pack_embedding(vec)
async with _connect(db_file) as db:
await db.execute(
"INSERT OR REPLACE INTO message_embeddings (message_id, chat_id, embedding, dim, model, backend, signature) VALUES (?, ?, ?, ?, ?, ?, ?)",
(message_id, chat_id, blob, dim, metadata.model, metadata.backend, metadata.signature),
)
await db.commit()
except Exception as e:
logger.warning("Embedding failed for message %s: %s", message_id, e)
return message_id
async def get_recent_messages(chat_id: int, *, limit: Optional[int] = None) -> list[MessageRow]:
effective_limit = _message_review_back() if limit is None else limit
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with _connect(db_file) as db:
cursor = await db.execute(
'''
SELECT id, chat_id, username, content, timestamp, reply_to_username FROM messages
WHERE chat_id = ?
ORDER BY id DESC
LIMIT ?
''',
(chat_id, effective_limit),
)
rows = list(await cursor.fetchall())
# reverse to chronological
rows.reverse()
return [MessageRow(*row) for row in rows]
async def get_oldest_messages(chat_id: int, *, limit: int) -> list[MessageRow]:
"""Return the oldest retained messages for an optional prompt-cache anchor."""
if limit <= 0:
return []
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with _connect(db_file) as db:
cursor = await db.execute(
'''
SELECT id, chat_id, username, content, timestamp, reply_to_username FROM messages
WHERE chat_id = ?
ORDER BY id ASC
LIMIT ?
''',
(chat_id, limit),
)
return [MessageRow(*row) for row in await cursor.fetchall()]
def _cosine_top_k(query_vec: np.ndarray, matrix: np.ndarray, *, top_k: int) -> np.ndarray:
q = np.asarray(query_vec, dtype=np.float32)
qn = np.linalg.norm(q) + 1e-8
mn = np.linalg.norm(matrix, axis=1) + 1e-8
sims = (matrix @ q) / (mn * qn)
if top_k <= 0:
top_k = 1
top_k = min(top_k, sims.shape[0])
# argpartition for speed, then sort selected
idx = np.argpartition(-sims, top_k - 1)[:top_k]
idx = idx[np.argsort(-sims[idx])]
return idx
async def vector_search_messages(
chat_id: int,
query: str,
*,