-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathstore.py
More file actions
1563 lines (1433 loc) · 65.4 KB
/
Copy pathstore.py
File metadata and controls
1563 lines (1433 loc) · 65.4 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
from __future__ import annotations
"""Immutable-first message store — the source of truth.
Every message is persisted durably in SQLite. The normal model is append-only,
with one narrow opt-in exception: already-externalized summarized tool-result
rows may be rewritten to compact GC tombstones while preserving the original
row identity (`store_id`) for DAG/source lookup.
"""
import json
import logging
import math
import sqlite3
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from .db_bootstrap import (
ExternalContentFtsSpec,
add_column_if_missing,
configure_connection,
ensure_external_content_fts,
refuse_schema_version_too_new,
run_versioned_migrations,
)
from .config import LCMConfig
from .ingest_protection import protect_message_for_ingest, protect_messages_for_ingest
from .search_query import (
build_snippet,
compute_search_candidate_cap,
compute_directness_rank_bonus_upper_bound,
compute_directness_score,
compute_like_fallback_fetch_limit,
compute_search_fetch_limit,
contains_risky_fts_ascii,
count_term_matches,
escape_like,
extract_quoted_phrases,
extract_search_terms,
normalize_search_sort,
requires_like_fallback,
sanitize_fts5_query,
sanitize_like_query,
AGE_DECAY_RATE,
should_apply_directness_rank_adjustment,
)
from .message_content import normalize_content_value as _normalize_content_value
from .tokens import count_message_tokens
logger = logging.getLogger(__name__)
_MESSAGE_ROLE_BIAS_SQL = "CASE m.role WHEN 'user' THEN 0 WHEN 'assistant' THEN 1 WHEN 'tool' THEN 2 ELSE 1 END"
_MESSAGE_SELECT_COLUMNS = (
"store_id, session_id, source, role, content, tool_call_id, "
"tool_calls, tool_name, timestamp, token_estimate, pinned, conversation_id, "
"ingested_at, observed_at, observed_at_source"
)
_MESSAGE_SELECT_COLUMN_COUNT = len(_MESSAGE_SELECT_COLUMNS.split(","))
_UNKNOWN_SOURCE = "unknown"
def _legacy_blank_source_clause(column: str) -> str:
# SQLite TRIM() only strips spaces unless given an explicit character set.
# Match Python's write-time `str.strip()` behavior for common ASCII whitespace
# so legacy tabs/newlines do not become a fake attributed source bucket.
whitespace_chars = "char(9) || char(10) || char(11) || char(12) || char(13) || char(32)"
return f"({column} IS NULL OR TRIM({column}, {whitespace_chars}) = '')"
def _normalize_source_value(source: str | None) -> str:
normalized = (source or "").strip()
return normalized or _UNKNOWN_SOURCE
def _normalize_conversation_id_value(conversation_id: str | None) -> str:
return (conversation_id or "").strip()
def _normalize_observed_at(value: Any) -> float | None:
"""Return a trustworthy host/source timestamp without inventing one.
Numeric Unix seconds and timezone-aware ISO-8601 strings are accepted.
Naive wall-clock strings, booleans, non-finite values, and non-positive
values are rejected so LCM write time is never silently relabelled as
source observation time.
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, (int, float)):
observed_at = float(value)
elif isinstance(value, str):
raw = value.strip()
if not raw:
return None
try:
observed_at = float(raw)
except ValueError:
try:
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
except ValueError:
return None
if parsed.tzinfo is None or parsed.utcoffset() is None:
return None
observed_at = parsed.timestamp()
else:
return None
if not math.isfinite(observed_at) or observed_at <= 0:
return None
try:
datetime.fromtimestamp(observed_at, tz=timezone.utc)
except (OSError, OverflowError, ValueError):
return None
return observed_at
def _source_filter_clause(column: str, source: str | None) -> tuple[str | None, list[str]]:
normalized = _normalize_source_value(source) if source is not None else ""
if not normalized:
return None, []
if normalized == _UNKNOWN_SOURCE:
return f"({column} = ? OR {_legacy_blank_source_clause(column)})", [_UNKNOWN_SOURCE]
return f"{column} = ?", [normalized]
def _conversation_filter_clause(column: str, conversation_id: str | None) -> tuple[str | None, list[str]]:
normalized = _normalize_conversation_id_value(conversation_id)
if not normalized:
return None, []
return f"{column} = ?", [normalized]
def _message_role_bias(role: str | None) -> float:
if role == "user":
return 0.0
if role == "assistant":
return 1.0
if role == "tool":
return 2.0
return 1.0
def _message_directness_score(role: str | None, content: str | None, terms: List[str], phrases: List[str] | None = None) -> float:
score = compute_directness_score(content or "", terms, phrases)
if role == "tool":
stripped = (content or "").lstrip()
if stripped.startswith("{") or stripped.startswith("["):
score -= 4.0
return score
def _build_search_order_by(
sort: str | None,
timestamp_expr: str,
role_penalty_expr: str | None = None,
) -> str:
normalized = normalize_search_sort(sort)
order_parts: list[str] = []
if normalized == "relevance":
if role_penalty_expr:
order_parts.extend(["rank ASC", f"{role_penalty_expr} ASC", f"{timestamp_expr} DESC"])
else:
order_parts.extend(["rank ASC", f"{timestamp_expr} DESC"])
return ", ".join(order_parts)
if normalized == "hybrid":
blended = f"(rank / (1 + (MAX(0.0, ((strftime('%s','now') - {timestamp_expr}) / 3600.0)) * {AGE_DECAY_RATE})))"
if role_penalty_expr:
order_parts.extend([f"{blended} ASC", f"{role_penalty_expr} ASC", f"{timestamp_expr} DESC"])
else:
order_parts.extend([f"{blended} ASC", f"{timestamp_expr} DESC"])
return ", ".join(order_parts)
order_parts.append(f"{timestamp_expr} DESC")
if role_penalty_expr:
order_parts.append(f"{role_penalty_expr} ASC")
order_parts.append("rank ASC")
return ", ".join(order_parts)
def _fallback_result_sort_key(result: Dict[str, Any], sort: str | None) -> tuple[float, float, float, float]:
normalized = normalize_search_sort(sort)
score = float(result.get("_fallback_score") or 0.0)
directness = float(result.get("_directness_score") or 0.0)
timestamp = float(result.get("timestamp") or 0.0)
role_bias = _message_role_bias(result.get("role"))
if normalized == "relevance":
return (-score, -directness, role_bias, -timestamp)
if normalized == "hybrid":
age_hours = max(0.0, (time.time() - timestamp) / 3600.0)
blended = score / (1 + (age_hours * AGE_DECAY_RATE))
return (-blended, -directness, role_bias, -timestamp)
return (-timestamp, role_bias, -score, -directness)
def _fts_result_sort_key(result: Dict[str, Any], sort: str | None) -> tuple[float, float, float, float]:
normalized = normalize_search_sort(sort)
rank = result.get("search_rank")
rank_value = float(rank) if rank is not None else float("inf")
directness = float(result.get("_directness_score") or 0.0)
timestamp = float(result.get("timestamp") or 0.0)
role_bias = _message_role_bias(result.get("role"))
if normalized == "relevance":
return (rank_value, -directness, role_bias, -timestamp)
if normalized == "hybrid":
age_hours = max(0.0, (time.time() - timestamp) / 3600.0)
blended = rank_value / (1 + (age_hours * AGE_DECAY_RATE)) if rank is not None else float("inf")
return (blended, -directness, role_bias, -timestamp)
return (-timestamp, role_bias, rank_value, 0.0)
def _fts_primary_value(result: Dict[str, Any], sort: str | None) -> float:
normalized = normalize_search_sort(sort)
rank = result.get("search_rank")
rank_value = float(rank) if rank is not None else float("inf")
if normalized == "hybrid":
timestamp = float(result.get("timestamp") or 0.0)
age_hours = max(0.0, (time.time() - timestamp) / 3600.0)
return rank_value / (1 + (age_hours * AGE_DECAY_RATE)) if rank is not None else float("inf")
return rank_value
def build_message_fts_spec() -> ExternalContentFtsSpec:
return ExternalContentFtsSpec(
table_name="messages_fts",
content_table="messages",
content_rowid="store_id",
indexed_column="content",
trigger_sqls=(
"""
CREATE TRIGGER IF NOT EXISTS msg_fts_insert
AFTER INSERT ON messages BEGIN
INSERT INTO messages_fts(rowid, content)
VALUES (new.store_id, new.content);
END;
""",
"""
CREATE TRIGGER IF NOT EXISTS msg_fts_delete
AFTER DELETE ON messages BEGIN
INSERT INTO messages_fts(messages_fts, rowid, content)
VALUES('delete', old.store_id, old.content);
END;
""",
"""
CREATE TRIGGER IF NOT EXISTS msg_fts_update
AFTER UPDATE OF content ON messages BEGIN
INSERT INTO messages_fts(messages_fts, rowid, content)
VALUES('delete', old.store_id, old.content);
INSERT INTO messages_fts(rowid, content)
VALUES (new.store_id, new.content);
END;
""",
),
)
class MessageStore:
"""SQLite-backed immutable message store."""
def __init__(self, db_path: str | Path, *, ingest_protection_config=None, hermes_home: str = ""):
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._ingest_protection_config = ingest_protection_config or LCMConfig(database_path=str(self.db_path))
self._hermes_home = hermes_home or str(self.db_path.parent)
self._conn: Optional[sqlite3.Connection] = None
# ``self._conn`` is shared across threads (the connection is opened with
# ``check_same_thread=False``). SQLite's own C-level mutex serializes
# statements at the engine layer, but the Python ``sqlite3`` module
# releases the GIL while the C call runs. Under heavy thread contention
# with concurrent HTTPS clients in the same process, downstream
# operators have observed on-disk corruption that is consistent with
# external bytes landing inside SQLite's write path (e.g. the first
# 28 bytes of the database file replaced with a TLS record header +
# ciphertext while the "SQLit" magic remains intact).
#
# This re-entrant lock is defense-in-depth: it forces all write call
# sites that use ``self._conn`` to be serialized at the Python layer,
# eliminating any window where Python-side buffer reuse or memory
# aliasing could intersect SQLite's flush of a write. It does not
# change semantics for single-threaded callers and adds only a single
# uncontended ``RLock.acquire``/``release`` pair per operation.
self._write_lock = threading.RLock()
self._init_db()
def _init_db(self):
self._conn = sqlite3.connect(str(self.db_path), timeout=5.0, check_same_thread=False)
refuse_schema_version_too_new(self._conn)
configure_connection(self._conn)
self._conn.executescript("""
CREATE TABLE IF NOT EXISTS messages (
store_id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
source TEXT DEFAULT '',
conversation_id TEXT DEFAULT '',
role TEXT NOT NULL,
content TEXT,
tool_call_id TEXT,
tool_calls TEXT,
tool_name TEXT,
timestamp REAL NOT NULL,
token_estimate INTEGER DEFAULT 0,
pinned INTEGER DEFAULT 0,
ingested_at REAL,
observed_at REAL,
observed_at_source TEXT
);
CREATE INDEX IF NOT EXISTS idx_msg_session
ON messages(session_id, store_id);
CREATE INDEX IF NOT EXISTS idx_msg_session_ts
ON messages(session_id, timestamp);
CREATE TABLE IF NOT EXISTS metadata (
key TEXT PRIMARY KEY,
value TEXT
);
""")
ensure_external_content_fts(
self._conn,
build_message_fts_spec(),
)
run_versioned_migrations(self._conn)
self._ensure_source_column()
self._ensure_conversation_id_column()
self._ensure_time_contract_columns()
self._conn.commit()
def _ensure_source_column(self) -> None:
columns = {
row[1] for row in self._conn.execute("PRAGMA table_info(messages)").fetchall()
}
add_column_if_missing(
self._conn, columns, "source",
"ALTER TABLE messages ADD COLUMN source TEXT DEFAULT ''",
)
self._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_msg_source_session ON messages(source, session_id, store_id)"
)
def _ensure_conversation_id_column(self) -> None:
columns = {
row[1] for row in self._conn.execute("PRAGMA table_info(messages)").fetchall()
}
add_column_if_missing(
self._conn, columns, "conversation_id",
"ALTER TABLE messages ADD COLUMN conversation_id TEXT DEFAULT ''",
)
self._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_msg_conversation_session ON messages(conversation_id, session_id, store_id)"
)
def _ensure_time_contract_columns(self) -> None:
"""Add the backward-compatible V4.2 source-time sidecar columns.
``timestamp`` remains the historical LCM write timestamp. Existing
rows receive only an ``ingested_at`` copy; their ``observed_at`` stays
NULL because no source timestamp can be recovered honestly.
"""
columns = {
row[1] for row in self._conn.execute("PRAGMA table_info(messages)").fetchall()
}
add_column_if_missing(
self._conn,
columns,
"ingested_at",
"ALTER TABLE messages ADD COLUMN ingested_at REAL",
)
add_column_if_missing(
self._conn,
columns,
"observed_at",
"ALTER TABLE messages ADD COLUMN observed_at REAL",
)
add_column_if_missing(
self._conn,
columns,
"observed_at_source",
"ALTER TABLE messages ADD COLUMN observed_at_source TEXT",
)
self._conn.execute(
"UPDATE messages SET ingested_at = timestamp WHERE ingested_at IS NULL"
)
# -- Write operations ---------------------------------------------------
def append(self, session_id: str, msg: Dict[str, Any],
token_estimate: int = 0, source: str = "",
conversation_id: str = "") -> int:
"""Persist a message and return its store_id."""
msg = protect_message_for_ingest(
msg,
config=self._ingest_protection_config,
hermes_home=self._hermes_home,
session_id=session_id,
)
tool_calls = msg.get("tool_calls")
tc_json = json.dumps(tool_calls) if tool_calls else None
observed_at = _normalize_observed_at(msg.get("timestamp"))
ingested_at = time.time()
with self._write_lock:
cur = self._conn.execute(
"""INSERT INTO messages
(session_id, source, conversation_id, role, content, tool_call_id, tool_calls,
tool_name, timestamp, token_estimate, pinned, ingested_at,
observed_at, observed_at_source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
session_id,
_normalize_source_value(source),
_normalize_conversation_id_value(conversation_id),
msg.get("role", "unknown"),
_normalize_content_value(msg.get("content")),
msg.get("tool_call_id"),
tc_json,
msg.get("tool_name"),
ingested_at,
token_estimate,
0,
ingested_at,
observed_at,
"host_message_timestamp" if observed_at is not None else None,
),
)
self._conn.commit()
return cur.lastrowid
def append_batch(self, session_id: str,
messages: List[Dict[str, Any]],
token_estimates: List[int] | None = None,
source: str = "",
conversation_id: str = "") -> List[int]:
"""Persist multiple messages in one transaction. Returns store_ids."""
protected_messages = protect_messages_for_ingest(
messages,
config=self._ingest_protection_config,
hermes_home=self._hermes_home,
session_id=session_id,
)
return self._append_protected_batch(
session_id,
protected_messages,
token_estimates,
source=source,
conversation_id=conversation_id,
)
def _append_protected_batch(self, session_id: str,
messages: List[Dict[str, Any]],
token_estimates: List[int] | None = None,
source: str = "",
conversation_id: str = "") -> List[int]:
"""Persist messages that already passed ingest protection.
This is an internal fast path for callers that need the protected form
before storage, for example to update active replay with raw-payload
stubs. Direct callers should use ``append_batch`` so storage-boundary
payload protection cannot be bypassed accidentally.
"""
if token_estimates is None:
token_estimates = [0] * len(messages)
ids = []
with self._write_lock, self._conn:
for msg, est in zip(messages, token_estimates):
tc = msg.get("tool_calls")
tc_json = json.dumps(tc) if tc else None
ts = time.time()
observed_at = _normalize_observed_at(msg.get("timestamp"))
cur = self._conn.execute(
"""INSERT INTO messages
(session_id, source, conversation_id, role, content, tool_call_id, tool_calls,
tool_name, timestamp, token_estimate, pinned, ingested_at,
observed_at, observed_at_source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
session_id,
_normalize_source_value(source),
_normalize_conversation_id_value(conversation_id),
msg.get("role", "unknown"),
_normalize_content_value(msg.get("content")),
msg.get("tool_call_id"),
tc_json,
msg.get("tool_name"),
ts,
est,
0,
ts,
observed_at,
"host_message_timestamp" if observed_at is not None else None,
),
)
ids.append(cur.lastrowid)
return ids
def reassign_session_messages(self, old_session_id: str, new_session_id: str) -> int:
"""Move all persisted messages from one session_id to another."""
if not old_session_id or not new_session_id or old_session_id == new_session_id:
return 0
with self._write_lock:
cur = self._conn.execute(
"UPDATE messages SET session_id = ? WHERE session_id = ?",
(new_session_id, old_session_id),
)
self._conn.commit()
return cur.rowcount if cur.rowcount is not None else 0
def delete_session_messages(self, session_id: str) -> int:
"""Delete all messages for a session. Returns count deleted."""
with self._write_lock:
cur = self._conn.execute(
"DELETE FROM messages WHERE session_id = ?",
(session_id,),
)
self._conn.commit()
deleted = cur.rowcount if cur.rowcount is not None else 0
return deleted
def gc_externalized_tool_result(
self,
store_id: int,
placeholder: str,
*,
before_commit: "Callable[[sqlite3.Connection, int], None] | None" = None,
) -> bool:
"""Rewrite one unpinned tool-result row to a compact GC placeholder.
When ``before_commit`` is given it runs on this store's connection AFTER
the content rewrite and BEFORE the single commit, so a caller can archive
the row's now-stale chunks in the SAME transaction as the rewrite. Without
that atomicity a recall landing between the content-rewrite commit and a
later batch archive would slice the new (short) content at the old chunk
offsets, returning a garbled fragment (F2).
"""
with self._write_lock:
row = self._conn.execute(
"SELECT role, pinned, content, tool_call_id FROM messages WHERE store_id = ?",
(store_id,),
).fetchone()
if row is None:
return False
role, pinned, current_content, tool_call_id = row
if role != "tool" or bool(pinned) or current_content == placeholder:
return False
placeholder_tokens = count_message_tokens(
{
"role": "tool",
"content": placeholder,
"tool_call_id": tool_call_id,
}
)
self._conn.execute(
"UPDATE messages SET content = ?, token_estimate = ? WHERE store_id = ?",
(placeholder, placeholder_tokens, store_id),
)
if before_commit is not None:
before_commit(self._conn, store_id)
self._conn.commit()
return True
def pin(self, store_id: int) -> None:
"""Mark a message as pinned (protected from pruning)."""
with self._write_lock:
self._conn.execute(
"UPDATE messages SET pinned = 1 WHERE store_id = ?", (store_id,)
)
self._conn.commit()
def unpin(self, store_id: int) -> None:
with self._write_lock:
self._conn.execute(
"UPDATE messages SET pinned = 0 WHERE store_id = ?", (store_id,)
)
self._conn.commit()
# -- Read operations ----------------------------------------------------
def get(self, store_id: int) -> Optional[Dict[str, Any]]:
"""Retrieve a single message by store_id."""
row = self._conn.execute(
f"SELECT {_MESSAGE_SELECT_COLUMNS} FROM messages WHERE store_id = ?", (store_id,)
).fetchone()
return self._row_to_dict(row) if row else None
def get_batch(self, store_ids: List[int]) -> Dict[int, Dict[str, Any]]:
"""Retrieve multiple messages by store_id in a single query.
Returns a dict mapping store_id → message dict.
"""
if not store_ids:
return {}
placeholders = ",".join("?" for _ in store_ids)
rows = self._conn.execute(
f"SELECT {_MESSAGE_SELECT_COLUMNS} FROM messages WHERE store_id IN ({placeholders})",
store_ids,
).fetchall()
return {row[0]: self._row_to_dict(row) for row in rows}
def scan_evidence_rows(self, *, limit: int = 4096) -> Dict[str, Any]:
"""Return one bounded, read-only whole-corpus evidence snapshot.
The window metadata and rows come from one SQLite statement, so a
caller cannot accidentally certify finite coverage from a count and a
row page taken at different corpus generations. This API deliberately
has no query or session filter: a narrower scan is not whole-corpus
coverage. Callers must treat ``truncated`` as an honest fallback.
"""
bounded_limit = min(4096, max(1, int(limit)))
rows = self._conn.execute(
f"""
WITH snapshot AS (
SELECT {_MESSAGE_SELECT_COLUMNS},
COUNT(*) OVER () AS snapshot_total_rows,
MAX(store_id) OVER () AS snapshot_max_store_id,
SUM(CASE WHEN observed_at IS NULL THEN 1 ELSE 0 END)
OVER () AS snapshot_observed_at_missing_rows
FROM messages
)
SELECT * FROM snapshot
ORDER BY store_id
LIMIT ?
""",
(bounded_limit,),
).fetchall()
if not rows:
return {
"rows": [],
"snapshot_max_store_id": 0,
"total_rows": 0,
"returned_rows": 0,
"truncated": False,
"observed_at_missing_rows": 0,
}
message_column_count = _MESSAGE_SELECT_COLUMN_COUNT
total_rows = int(rows[0][message_column_count] or 0)
snapshot_max_store_id = int(rows[0][message_column_count + 1] or 0)
observed_at_missing_rows = int(rows[0][message_column_count + 2] or 0)
messages = [self._row_to_dict(row[:message_column_count]) for row in rows]
return {
"rows": messages,
"snapshot_max_store_id": snapshot_max_store_id,
"total_rows": total_rows,
"returned_rows": len(messages),
"truncated": total_rows > len(messages),
"observed_at_missing_rows": observed_at_missing_rows,
}
def get_range(self, session_id: str, start_id: int = 0,
end_id: int | None = None,
limit: int = 1000,
conversation_id: str | None = None) -> List[Dict[str, Any]]:
"""Get messages in a store_id range for a session."""
where = ["session_id = ?", "store_id >= ?"]
args: list[Any] = [session_id, start_id]
conversation_clause, conversation_args = _conversation_filter_clause("conversation_id", conversation_id)
if conversation_clause:
where.append(conversation_clause)
args.extend(conversation_args)
if end_id is not None:
where.append("store_id <= ?")
args.append(end_id)
args.append(limit)
rows = self._conn.execute(
f"""SELECT {_MESSAGE_SELECT_COLUMNS} FROM messages
WHERE {' AND '.join(where)}
ORDER BY store_id LIMIT ?""",
args,
).fetchall()
return [self._row_to_dict(r) for r in rows]
def _session_load_where(
self,
session_id: str,
*,
roles: list[str] | None = None,
time_from: float | None = None,
time_to: float | None = None,
) -> tuple[list[str], list[Any]]:
where = ["session_id = ?"]
args: list[Any] = [session_id]
if roles:
placeholders = ",".join("?" for _ in roles)
where.append(f"role IN ({placeholders})")
args.extend(roles)
if time_from is not None:
where.append("timestamp >= ?")
args.append(time_from)
if time_to is not None:
where.append("timestamp <= ?")
args.append(time_to)
return where, args
def count_session_load_messages(
self,
session_id: str,
*,
roles: list[str] | None = None,
time_from: float | None = None,
time_to: float | None = None,
) -> int:
"""Count messages matching the lcm_load_session filter contract."""
where, args = self._session_load_where(
session_id,
roles=roles,
time_from=time_from,
time_to=time_to,
)
return int(
self._conn.execute(
f"SELECT COUNT(*) FROM messages WHERE {' AND '.join(where)}",
args,
).fetchone()[0]
)
def load_session_page(
self,
session_id: str,
*,
after_store_id: int = 0,
limit: int = 100,
roles: list[str] | None = None,
time_from: float | None = None,
time_to: float | None = None,
) -> List[Dict[str, Any]]:
"""Load one ordered raw-message page for a session.
``after_store_id`` is exclusive so callers can use the previous page's
``next_cursor`` without duplicating the cursor row.
"""
where, args = self._session_load_where(
session_id,
roles=roles,
time_from=time_from,
time_to=time_to,
)
where.append("store_id > ?")
args.extend([after_store_id, limit])
rows = self._conn.execute(
f"""SELECT {_MESSAGE_SELECT_COLUMNS} FROM messages
WHERE {' AND '.join(where)}
ORDER BY store_id LIMIT ?""",
args,
).fetchall()
return [self._row_to_dict(r) for r in rows]
def load_session_window(
self,
session_id: str,
*,
anchor_store_id: int,
before: int = 2,
after: int = 3,
) -> List[Dict[str, Any]]:
"""Load one bounded ordered window around an exact message anchor."""
before = min(12, max(0, int(before)))
after = min(12, max(0, int(after)))
prior = self._conn.execute(
f"""SELECT {_MESSAGE_SELECT_COLUMNS}
FROM messages
WHERE session_id = ? AND store_id < ?
ORDER BY store_id DESC LIMIT ?""",
(session_id, anchor_store_id, before),
).fetchall()
following = self._conn.execute(
f"""SELECT {_MESSAGE_SELECT_COLUMNS}
FROM messages
WHERE session_id = ? AND store_id >= ?
ORDER BY store_id LIMIT ?""",
(session_id, anchor_store_id, after + 1),
).fetchall()
rows = list(reversed(prior)) + list(following)
return [self._row_to_dict(row) for row in rows]
def get_session_messages(self, session_id: str,
limit: int = 10000) -> List[Dict[str, Any]]:
"""Get all messages for a session, ordered by store_id."""
rows = self._conn.execute(
f"""SELECT {_MESSAGE_SELECT_COLUMNS} FROM messages
WHERE session_id = ?
ORDER BY store_id LIMIT ?""",
(session_id, limit),
).fetchall()
return [self._row_to_dict(r) for r in rows]
def get_session_messages_after(self, session_id: str,
after_store_id: int = 0,
limit: int = 10000) -> List[Dict[str, Any]]:
"""Get session messages after a store_id, ordered by store_id."""
rows = self._conn.execute(
f"""SELECT {_MESSAGE_SELECT_COLUMNS} FROM messages
WHERE session_id = ? AND store_id > ?
ORDER BY store_id LIMIT ?""",
(session_id, after_store_id, limit),
).fetchall()
return [self._row_to_dict(r) for r in rows]
def get_session_tail(self, session_id: str, limit: int = 1000) -> List[Dict[str, Any]]:
"""Get the latest messages for a session, returned in store order."""
if limit <= 0:
return []
rows = self._conn.execute(
f"""SELECT {_MESSAGE_SELECT_COLUMNS}
FROM (
SELECT {_MESSAGE_SELECT_COLUMNS}
FROM messages
WHERE session_id = ?
ORDER BY store_id DESC
LIMIT ?
)
ORDER BY store_id""",
(session_id, limit),
).fetchall()
return [self._row_to_dict(r) for r in rows]
def get_session_count(self, session_id: str) -> int:
"""Count messages in a session."""
row = self._conn.execute(
"SELECT COUNT(*) FROM messages WHERE session_id = ?",
(session_id,),
).fetchone()
return row[0] if row else 0
def get_session_token_total(self, session_id: str) -> int:
"""Sum of token estimates for a session."""
row = self._conn.execute(
"SELECT COALESCE(SUM(token_estimate), 0) FROM messages WHERE session_id = ?",
(session_id,),
).fetchone()
return row[0] if row else 0
def get_source_stats(self, session_id: str | None = None) -> Dict[str, int]:
"""Return raw source-bucket counts for diagnostics."""
where = ""
args: list[Any] = []
if session_id is not None:
where = "WHERE session_id = ?"
args.append(session_id)
legacy_blank_clause = _legacy_blank_source_clause("source")
query = f"""
SELECT COUNT(*) AS messages_total,
COALESCE(SUM(CASE WHEN source = ? THEN 1 ELSE 0 END), 0) AS normalized_unknown_messages,
COALESCE(SUM(CASE WHEN {legacy_blank_clause} THEN 1 ELSE 0 END), 0) AS legacy_blank_source_messages,
COALESCE(SUM(CASE WHEN NOT {legacy_blank_clause} AND source != ? THEN 1 ELSE 0 END), 0) AS attributed_messages
FROM messages
{where}
"""
query_args: list[Any] = [_UNKNOWN_SOURCE, _UNKNOWN_SOURCE, *args]
row = self._conn.execute(query, query_args).fetchone()
messages_total = int(row[0] or 0) if row else 0
normalized_unknown = int(row[1] or 0) if row else 0
legacy_blank = int(row[2] or 0) if row else 0
attributed = int(row[3] or 0) if row else 0
return {
"messages_total": messages_total,
"attributed_messages": attributed,
"normalized_unknown_messages": normalized_unknown,
"legacy_blank_source_messages": legacy_blank,
"effective_unknown_messages": normalized_unknown + legacy_blank,
}
def scan_session_cleanup_stats(self) -> List[tuple]:
"""Per-session ``(session_id, message_count, token_total, node_count)``
rows across messages and summary nodes, for ``/lcm doctor clean``
candidate scanning. Callers own the pattern/protection policy."""
return self._conn.execute(
"""
WITH session_ids AS (
SELECT session_id FROM messages
UNION
SELECT session_id FROM summary_nodes
),
message_stats AS (
SELECT session_id,
COUNT(*) AS message_count,
COALESCE(SUM(token_estimate), 0) AS token_total
FROM messages
GROUP BY session_id
),
node_stats AS (
SELECT session_id, COUNT(*) AS node_count
FROM summary_nodes
GROUP BY session_id
)
SELECT s.session_id,
COALESCE(m.message_count, 0) AS message_count,
COALESCE(m.token_total, 0) AS token_total,
COALESCE(n.node_count, 0) AS node_count
FROM session_ids s
LEFT JOIN message_stats m ON m.session_id = s.session_id
LEFT JOIN node_stats n ON n.session_id = s.session_id
ORDER BY s.session_id
"""
).fetchall()
def scan_session_retention_stats(self, session_id: str) -> List[tuple]:
"""Per-session activity/token stats for one session (messages + summary
nodes), for ``/lcm doctor retention`` scanning. Callers own the
staleness/protection policy."""
return self._conn.execute(
"""
WITH session_ids AS (
SELECT session_id FROM messages
UNION
SELECT session_id FROM summary_nodes
),
message_stats AS (
SELECT session_id,
COUNT(*) AS message_count,
COALESCE(SUM(token_estimate), 0) AS token_total,
MIN(timestamp) AS first_message_at,
MAX(timestamp) AS last_message_at
FROM messages
GROUP BY session_id
),
node_stats AS (
SELECT session_id,
COUNT(*) AS node_count,
COALESCE(SUM(token_count), 0) AS node_token_total,
MIN(COALESCE(earliest_at, created_at)) AS first_node_at,
MAX(COALESCE(latest_at, created_at)) AS last_node_at
FROM summary_nodes
GROUP BY session_id
)
SELECT s.session_id,
COALESCE(m.message_count, 0) AS message_count,
COALESCE(m.token_total, 0) AS token_total,
COALESCE(n.node_count, 0) AS node_count,
COALESCE(n.node_token_total, 0) AS node_token_total,
m.first_message_at,
m.last_message_at,
n.first_node_at,
n.last_node_at
FROM session_ids s
LEFT JOIN message_stats m ON m.session_id = s.session_id
LEFT JOIN node_stats n ON n.session_id = s.session_id
WHERE s.session_id = ?
ORDER BY s.session_id
""",
(session_id,),
).fetchall()
def get_source_normalization_plan(self) -> Dict[str, Any]:
"""Return a dry-run plan for normalizing legacy blank source values."""
stats_before = self.get_source_stats()
blank_clause = _legacy_blank_source_clause("source")
row = self._conn.execute(
f"""
SELECT COUNT(*) AS would_update_messages,
COUNT(DISTINCT session_id) AS affected_sessions
FROM messages
WHERE {blank_clause}
"""
).fetchone()
would_update = int(row[0] or 0) if row else 0
affected_sessions = int(row[1] or 0) if row else 0
return {
"target_source": _UNKNOWN_SOURCE,
"would_update_messages": would_update,
"affected_sessions": affected_sessions,
"stats_before": stats_before,
}
def normalize_legacy_blank_sources(self) -> Dict[str, Any]:
"""Normalize legacy NULL/blank source rows to the explicit unknown bucket."""
stats_before = self.get_source_stats()
blank_clause = _legacy_blank_source_clause("source")
with self._write_lock, self._conn:
cur = self._conn.execute(
f"UPDATE messages SET source = ? WHERE {blank_clause}",
(_UNKNOWN_SOURCE,),
)
updated = cur.rowcount if cur.rowcount is not None else 0
stats_after = self.get_source_stats()
return {
"target_source": _UNKNOWN_SOURCE,
"updated_messages": int(updated),
"stats_before": stats_before,
"stats_after": stats_after,
}
def get_time_bounds(self, store_ids: List[int]) -> tuple[float | None, float | None]:
if not store_ids:
return None, None
placeholders = ",".join("?" * len(store_ids))
row = self._conn.execute(
f"SELECT MIN(timestamp), MAX(timestamp) FROM messages WHERE store_id IN ({placeholders})",
store_ids,
).fetchone()
if not row:
return None, None
return row[0], row[1]
# -- Metadata key/value JSON --------------------------------------------