Repository navigation
Expand file tree
/
Copy pathhttp_server.py
More file actions
1596 lines (1347 loc) · 61.6 KB
/
Copy pathhttp_server.py
File metadata and controls
1596 lines (1347 loc) · 61.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Persistent HTTP server for SessionFlow MCP system.
Runs as a long-lived process serving MCP via StreamableHTTP.
The current project comes from the client's MCP roots, else the X-Project-Root header.
All projects share a single global DB at ~/.sessionflow/milvus.db.
Start: ./sessionflow-server.sh
Health: curl http://127.0.0.1:7102/health
"""
import asyncio
import concurrent.futures
import contextlib
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
import json
import logging
import os
import re
import signal
import sys
import threading
import time
import traceback
from pathlib import Path
import uvicorn
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route
from mcp.server import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
import client_roots
import rag_engine
import reranker
import transcript_parser
import file_watcher
import fts_hybrid
from provider_adapters import LEGAL_PROVIDERS, is_valid_issue_token
from backfill_manager import BackfillManager
from embedding_control import EmbeddingIdentity, get_embedding_budget
from provider_antigravity import AntigravityAdapter
from provider_claude import ClaudeCodeCliAdapter, ClaudeCoworkLegacyAdapter
from provider_codex import CodexAdapter
from provider_opencode import OpenCodeAdapter
from provider_ingestion import ProviderIngestionService, process_startup_provider_backfill
from file_watcher import register_project, get_global_watcher
from tools import register_tools, set_current_project_root, set_memory_service
import memory_store
import secret_redaction
import socket
from version import __version__
logger = logging.getLogger("sessionflow")
# --- Configuration ---
HOST = os.getenv("SESSIONFLOW_HOST", "127.0.0.1")
PORT = int(os.getenv("SESSIONFLOW_PORT", "7102"))
AUTO_EXPIRE_DAYS = int(os.getenv("SESSIONFLOW_EXPIRE_DAYS", "365"))
_EXPIRE_CHECK_INTERVAL = 86400 # Check once per day
_SERVER_DIR = Path.home() / ".sessionflow"
PID_FILE = _SERVER_DIR / "server.pid"
LOG_FILE = _SERVER_DIR / "server.log"
def _parse_backfill_drain_interval() -> float:
raw_interval = os.getenv("SESSIONFLOW_BACKFILL_DRAIN_INTERVAL_SECONDS", "30")
try:
interval = float(raw_interval)
except ValueError as exc:
raise ValueError(
"SESSIONFLOW_BACKFILL_DRAIN_INTERVAL_SECONDS must be a number"
) from exc
return interval
BACKFILL_DRAIN_INTERVAL = _parse_backfill_drain_interval()
if BACKFILL_DRAIN_INTERVAL <= 0:
raise ValueError("SESSIONFLOW_BACKFILL_DRAIN_INTERVAL_SECONDS must be > 0")
# Upper bound on the FTS heal exponential backoff. The schedule
# escalates as ``BACKFILL_DRAIN_INTERVAL * 2**(n-1)`` per consecutive failure and
# is held at this cap so the heal loop retries forever without runaway delays.
FTS_HEAL_BACKOFF_CAP = 300.0
# Milvus backend: remote Standalone URI or local Lite file path.
MILVUS_URI = os.getenv("SESSIONFLOW_MILVUS_URI", str(_SERVER_DIR / "milvus.db"))
HEARTBEAT_FILE = _SERVER_DIR / "heartbeat"
# --- Heartbeat ---
class HeartbeatThread:
"""Daemon thread that writes a JSON heartbeat file at fixed intervals.
File I/O releases the GIL, so this runs even when MLX Metal holds
the GIL during embedding computation.
"""
def __init__(self, path: Path, interval: float = 30.0):
"""
Initialize a HeartbeatThread that periodically writes a JSON heartbeat to the given file.
Parameters:
path (Path): Destination file path where heartbeat JSON will be written.
interval (float): Seconds between heartbeat writes (defaults to 30.0). The thread will attempt a write at this interval.
Detailed behavior:
- Creates an internal stop event used to signal the background thread to exit.
- Initializes the thread placeholder; the background thread is started by calling start().
"""
self._path = path
self._interval = interval
self._stop_event = threading.Event()
self._thread = None
def _get_activity(self) -> str:
"""
Return the current file-watcher activity label.
Queries the global file watcher status and returns "processing" if the watcher reports active processing; on any error or if not processing, returns "idle".
Returns:
activity (str): "processing" if the watcher is processing, "idle" otherwise.
"""
try:
status = file_watcher.get_watcher_status()
if status.get('global', {}).get('processing', False):
return "processing"
except Exception:
pass
return "idle"
def _write_heartbeat(self):
"""
Write the heartbeat JSON file to the configured path using an atomic replace.
The file contains `timestamp` (current epoch time), `pid` (current process id), and `activity` (value from `_get_activity()`). Data is written to a temporary file in the target directory and then moved into place with `os.replace`. Failures are caught and logged as a warning.
"""
data = {
"timestamp": time.time(),
"pid": os.getpid(),
"activity": self._get_activity(),
}
tmp_path = self._path.parent / f".heartbeat.{os.getpid()}.tmp"
try:
tmp_path.write_text(json.dumps(data))
os.replace(str(tmp_path), str(self._path))
except Exception as e:
logger.warning("Heartbeat write failed: %s", e)
def _run(self):
"""
Run the thread's main loop, writing the heartbeat file periodically until stopped.
This method repeatedly writes a heartbeat and then waits for the configured interval (or until a stop is requested). It exits when the thread's stop event is set.
"""
while not self._stop_event.is_set():
self._write_heartbeat()
self._stop_event.wait(self._interval)
def start(self):
"""
Start the heartbeat background thread.
Initiates a daemon thread that runs the heartbeat loop until the thread is stopped via stop().
"""
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def stop(self):
"""
Signal the heartbeat thread to stop and wait briefly for it to finish.
If the heartbeat thread was started, this sets the stop event and blocks up to 2 seconds for the thread to join. If the thread was not started, this returns immediately.
"""
self._stop_event.set()
if self._thread is not None:
self._thread.join(timeout=2.0)
# --- FTS heal state ---
@dataclass
class FtsHealState:
"""Worker-owned backoff + log-once state for the FTS heal loop.
Implements the bounded-backoff schedule (``BACKFILL_DRAIN_INTERVAL * 2**(n-1)``
capped at ``FTS_HEAL_BACKOFF_CAP``) and the log-once latch (signature =
exception type + stable message prefix) so a persistent failure warns once per
distinct signature. Owned by the heal worker in http_server. This worker state
(``consecutive_failures`` / ``last_error``) is exposed only via ``/health``;
``rag_engine.get_stats`` carries the static lag fields (fts_row_count, fts_lag,
fts_backfill_required) and never this worker state.
"""
consecutive_failures: int = 0
last_error_signature: str | None = None
current_backoff_seconds: float = BACKFILL_DRAIN_INTERVAL
@staticmethod
def _signature(exc) -> str:
"""Derive a stable log-once signature from an exception.
Combines the exception type name with a stable message prefix. The clean
message payload is preferred (Milvus exceptions expose ``.message``), with
``str(exc)`` as the fallback. A trailing parenthetical suffix (request id,
timestamp) is stripped so it does not churn the latch, while distinct
message bodies and exception types remain distinct signatures.
Args:
exc: The exception raised by a heal attempt.
Returns:
A ``"<TypeName>:<stable message prefix>"`` signature string.
"""
message = getattr(exc, "message", None)
if not isinstance(message, str):
message = str(exc)
stable_prefix = re.sub(r"\s*\([^()]*\)\s*$", "", message).strip()
return f"{type(exc).__name__}:{stable_prefix}"
def record_failure(self, exc: Exception) -> None:
"""Record a transient heal failure and escalate the bounded backoff.
Increments the consecutive-failure streak and sets the current backoff to
``BACKFILL_DRAIN_INTERVAL * 2**(n-1)`` capped at ``FTS_HEAL_BACKOFF_CAP``.
Never raises and never signals a terminal "give up": the heal loop keeps
retrying at the capped delay.
Args:
exc: The exception raised by the failed heal attempt.
"""
self.consecutive_failures += 1
raw = BACKFILL_DRAIN_INTERVAL * (2 ** (self.consecutive_failures - 1))
self.current_backoff_seconds = min(raw, FTS_HEAL_BACKOFF_CAP)
def record_success(self) -> None:
"""Reset backoff and log-once state after a successful heal.
Zeroes the failure streak, restores the backoff to the base drain
interval, and clears the error signature so a later failure warns again.
"""
self.consecutive_failures = 0
self.current_backoff_seconds = BACKFILL_DRAIN_INTERVAL
self.last_error_signature = None
def next_delay(self) -> float:
"""Return the next backoff delay in seconds.
Yields the base drain interval when there have been no failures since the
last reset, otherwise the current (escalated, capped) backoff.
Returns:
The delay in seconds before the next heal attempt.
"""
if self.consecutive_failures == 0:
return BACKFILL_DRAIN_INTERVAL
return self.current_backoff_seconds
def should_warn(self, exc: Exception) -> bool:
"""Decide whether to emit a warning for ``exc`` under log-once dedup.
Returns ``True`` on the first sighting of a signature and whenever the
signature changes, ``False`` while the same signature repeats. Records the
signature as a side effect so a repeat is suppressed.
Args:
exc: The exception raised by the failed heal attempt.
Returns:
``True`` to log a warning, ``False`` to suppress a duplicate.
"""
signature = self._signature(exc)
if signature == self.last_error_signature:
return False
self.last_error_signature = signature
return True
# --- Project middleware ---
class ProjectMiddleware:
"""ASGI middleware that extracts X-Project-Root header and sets ContextVar."""
def __init__(self, app):
"""Wrap the downstream ASGI ``app``."""
self.app = app
async def __call__(self, scope, receive, send):
"""Set the project root from the X-Project-Root header, then delegate."""
if scope["type"] == "http":
headers = dict(scope.get("headers", []))
project_root = headers.get(b"x-project-root", b"").decode("utf-8").strip()
set_current_project_root(project_root if project_root else None)
try:
await self.app(scope, receive, send)
except Exception as exc:
logger.error("ASGI handler error: %s\n%s", exc, traceback.format_exc())
if scope["type"] == "http":
body = json.dumps({"error": "internal_server_error", "detail": str(exc)}).encode()
await send({"type": "http.response.start", "status": 500, "headers": [
[b"content-type", b"application/json"],
[b"content-length", str(len(body)).encode()],
]})
await send({"type": "http.response.body", "body": body})
# --- Health endpoint ---
_model_loaded = False
_server_mode_ready = False
# "starting" until _background_startup finishes, then "ready". The
# port binds before the model and Milvus are up, and /health answers 503
# while this is "starting".
_startup_state = "starting"
_BACKFILL_STATE = _SERVER_DIR / "backfill_state.json"
_backfill_manager = BackfillManager(_BACKFILL_STATE)
_backfill_drain_event: asyncio.Event | None = None
_backfill_drain_lock: asyncio.Lock | None = None
# FTS heal worker primitives. The heal loop reuses the drain cadence
# but owns a dedicated single-thread executor so a long blocking backfill never
# competes with MLX embedding work on rag_engine's _embed_executor.
_fts_heal_event: asyncio.Event | None = None
_fts_heal_state: "FtsHealState | None" = None
_fts_heal_executor: concurrent.futures.ThreadPoolExecutor | None = None
# TTL cache for provider health — avoid expensive I/O on every /health probe.
_PROVIDER_HEALTH_TTL = 30 # seconds
_provider_health_cache: dict | None = None
_provider_health_cache_ts: float = 0.0
_provider_scan: asyncio.Future | None = None # touched only on the event loop
# TTL cache for the FTS-lag block — a full Milvus count on every /health probe
# would be wasteful, so cache it for a few seconds (mirrors provider health).
_FTS_LAG_TTL = 5 # seconds
_fts_lag_cache: dict | None = None
_fts_lag_cache_ts: float = 0.0
def _ensure_backfill_drain_primitives() -> None:
"""Create loop-bound primitives lazily inside the running event loop."""
global _backfill_drain_event, _backfill_drain_lock
if _backfill_drain_event is None:
_backfill_drain_event = asyncio.Event()
if _backfill_drain_lock is None:
_backfill_drain_lock = asyncio.Lock()
def _wake_backfill_drain() -> None:
"""Wake the background drain worker after queue-changing HTTP actions."""
if _backfill_drain_event is not None:
# Current callers are async HTTP handlers on the event-loop thread.
_backfill_drain_event.set()
async def _drain_backfill_once(skip_if_locked: bool = True) -> dict:
"""Drain queued provider jobs once without overlapping another drain."""
_ensure_backfill_drain_primitives()
lock = _backfill_drain_lock
if lock is None:
return {"jobs": 0, "processed_sources": 0, "indexed_turns": 0, "errors": 0}
if skip_if_locked and lock.locked():
return {"jobs": 0, "processed_sources": 0, "indexed_turns": 0, "errors": 0, "skipped": 1}
async with lock:
status = _backfill_manager.status()
if status.paused or not status.jobs:
return {"jobs": 0, "processed_sources": 0, "indexed_turns": 0, "errors": 0}
return await ProviderIngestionService(_backfill_manager, MILVUS_URI).process_queued_jobs()
async def _backfill_drain_worker(interval: float = BACKFILL_DRAIN_INTERVAL) -> None:
"""Poll and drain durable backfill jobs while the HTTP server is alive."""
_ensure_backfill_drain_primitives()
event = _backfill_drain_event
if event is None:
return
while True:
event.clear()
try:
await _drain_backfill_once()
except asyncio.CancelledError:
raise
except Exception:
logger.exception("Backfill drain worker failed")
try:
await asyncio.wait_for(event.wait(), timeout=interval)
except asyncio.TimeoutError:
pass
def _ensure_fts_heal_primitives() -> None:
"""Create the heal Event, state, and dedicated executor lazily.
Mirrors ``_ensure_backfill_drain_primitives`` so the loop-bound ``asyncio``
primitive and the heal worker's single-thread ThreadPoolExecutor are built
inside the running event loop on first use. The executor is kept SEPARATE
from rag_engine's MLX ``_embed_executor`` so a blocking FTS
backfill never contends with embedding work.
"""
global _fts_heal_event, _fts_heal_state, _fts_heal_executor
if _fts_heal_event is None:
_fts_heal_event = asyncio.Event()
if _fts_heal_state is None:
_fts_heal_state = FtsHealState()
if _fts_heal_executor is None:
_fts_heal_executor = concurrent.futures.ThreadPoolExecutor(
max_workers=1, thread_name_prefix="fts-heal"
)
async def _fts_heal_run_once(state: "FtsHealState", *, first_tick: bool) -> None:
"""Make and attempt one FTS heal decision for a single cadence tick.
On the first tick the backfill runs unconditionally (preserving the startup
catch-up of the old one-shot ``_fts_backfill``); on later ticks it runs only
when ``fts_hybrid.fts_backfill_required()`` reports the sentinel is set. The
backfill itself is dispatched on the dedicated heal executor so it never
blocks the event loop. A ``FtsBackfillTransientError`` is recorded on
``state`` (with a log-once WARN) instead of crashing the loop.
Args:
state: The worker-owned ``FtsHealState`` carrying backoff + log-once state.
first_tick: ``True`` only on the very first tick of the heal loop.
"""
if not first_tick and not fts_hybrid.fts_backfill_required():
return
_ensure_fts_heal_primitives()
executor = _fts_heal_executor
db_path = MILVUS_URI
loop = asyncio.get_running_loop()
try:
backfilled = await loop.run_in_executor(
executor, lambda: rag_engine.backfill_fts(db_path=db_path)
)
except rag_engine.FtsBackfillTransientError as exc:
if state.should_warn(exc):
logger.warning("FTS heal backfill failed (transient): %s", exc)
state.record_failure(exc)
return
state.record_success()
if backfilled:
logger.info("FTS heal backfill: %s records", backfilled)
async def _fts_heal_worker() -> None:
"""Run the recurring FTS heal loop for the life of the HTTP server.
Calls ``_fts_heal_run_once`` once per cadence tick — ``first_tick=True`` on
the very first iteration only — then waits on the heal Event with a bounded
timeout of ``state.next_delay()`` (the bounded-backoff schedule). The loop
only ever exits on cancellation; transient failures are absorbed by
``_fts_heal_run_once`` and surfaced through the backoff schedule.
"""
_ensure_fts_heal_primitives()
event = _fts_heal_event
state = _fts_heal_state
if event is None or state is None:
return
first_tick = True
while True:
event.clear()
try:
await _fts_heal_run_once(state, first_tick=first_tick)
except asyncio.CancelledError:
raise
except Exception:
logger.exception("FTS heal worker tick failed")
first_tick = False
try:
await asyncio.wait_for(event.wait(), timeout=state.next_delay())
except asyncio.TimeoutError:
pass
# --- Memory index sync loop ---
# Seconds between memory sync ticks; each tick applies every pending acknowledgement.
MEMORY_SYNC_INTERVAL = float(os.getenv("SESSIONFLOW_MEMORY_SYNC_INTERVAL", "5"))
# The full index-versus-Postgres reconcile runs on the first tick and then at
# most this often.
MEMORY_RECONCILE_INTERVAL = 6 * 3600
# After a failed or timed-out reconcile, passes only tick until this many
# seconds have passed, so a hanging reconcile cannot slow every pass.
MEMORY_RECONCILE_RETRY_INTERVAL = 300
# A tick or reconcile still running after this many seconds is cancelled and
# reported. A full batch of 256 Milvus embeds fits well inside it.
MEMORY_TICK_TIMEOUT = float(os.getenv("SESSIONFLOW_MEMORY_TICK_TIMEOUT", "600"))
# /health calls the loop stale once its last tick is older than the tick
# timeout plus this many sync intervals.
MEMORY_STALE_INTERVALS = 3
@dataclass
class MemorySyncState:
"""State of the memory sync loop, reported in ``/health``.
Attributes:
index: The ``MemoryIndex`` (or any object with async ``tick`` and ``reconcile``).
clock: Monotonic clock, injectable for tests.
last_reconcile: Clock value of the last successful reconcile, or None.
last_reconcile_attempt: Clock value of the last reconcile attempt, or None.
last_error: Text of the last tick or reconcile failure, or None.
tick_timeout: Seconds a tick or reconcile may run before it is cancelled.
"""
index: object
clock: object = field(default=time.monotonic)
last_reconcile: float | None = None
last_reconcile_attempt: float | None = None
last_error: str | None = None
tick_timeout: float = MEMORY_TICK_TIMEOUT
def _await_chain(task: asyncio.Task) -> list[str]:
"""Return the coroutine frames a task is suspended in, outermost first, ending at its future."""
lines = []
obj = task.get_coro()
while obj is not None:
frame = (getattr(obj, "cr_frame", None) or getattr(obj, "gi_frame", None)
or getattr(obj, "ag_frame", None))
if frame is None:
lines.append(f" awaiting {type(obj).__name__}: {repr(obj)[:160]}")
break
code = frame.f_code
lines.append(f" {code.co_qualname} ({os.path.basename(code.co_filename)}:{frame.f_lineno})")
obj = (getattr(obj, "cr_await", None) or getattr(obj, "gi_yieldfrom", None)
or getattr(obj, "ag_await", None))
return lines
def format_async_tasks() -> str:
"""Return every pending asyncio task on the running loop with the chain it is awaiting.
Thread profilers cannot see suspended coroutines; this can.
"""
out = []
for task in sorted(asyncio.all_tasks(), key=lambda t: t.get_name()):
out.append(f"Task {task.get_name()}:")
out.extend(_await_chain(task))
return "\n".join(out)
def log_async_tasks(reason: str) -> None:
"""Log every pending asyncio task and what it awaits, at WARNING."""
logger.warning("Asyncio tasks (%s):\n%s", reason, format_async_tasks())
def install_task_dump_handler() -> bool:
"""Log the asyncio tasks on SIGUSR1 (`kill -USR1 <pid>`); returns False where unsupported."""
sig = getattr(signal, "SIGUSR1", None)
if sig is None:
return False
try:
asyncio.get_running_loop().add_signal_handler(sig, log_async_tasks, "SIGUSR1")
except (NotImplementedError, RuntimeError, ValueError):
return False
return True
async def _run_bounded(awaitable, timeout: float, what: str):
"""Await ``awaitable`` for at most ``timeout`` seconds.
On timeout, log where every task is waiting before cancelling the work, then
raise TimeoutError. Cancelling the caller cancels the work too.
"""
task = asyncio.ensure_future(awaitable)
try:
done, _ = await asyncio.wait({task}, timeout=timeout)
except asyncio.CancelledError:
task.cancel()
raise
if done:
return task.result()
message = f"memory sync {what} timed out after {timeout:g} s"
log_async_tasks(message)
task.cancel()
await asyncio.wait({task}, timeout=5)
if task.done() and not task.cancelled():
task.exception()
raise TimeoutError(message)
def _scrub(exc: BaseException) -> str:
"""Return the exception text with any secret value redacted."""
redacted, _ = secret_redaction.redact(str(exc), mode="enforce")
return redacted
def _store_workers_saturated() -> str | None:
"""Return a pause message while all but one memory-db worker are busy, else None."""
busy = memory_store.db_calls_in_flight()
if busy < memory_store.DB_WORKERS - 1:
return None
return (f"memory sync paused: {busy} of {memory_store.DB_WORKERS} store workers "
"are busy, likely with calls left running by a timeout")
async def _memory_sync_run_once(state: MemorySyncState, *, first_tick: bool) -> None:
"""Run one memory sync tick: the reconcile when due, then the pending-acknowledgement pass.
The tick runs even when the reconcile fails. A failed reconcile stays due
and runs again once ``MEMORY_RECONCILE_RETRY_INTERVAL`` has passed. Each
step is bounded by ``state.tick_timeout``. Worker capacity is checked
before the pass and again before the tick, and the work stops while all
but one memory-db worker are busy, so calls left running by a timeout
cannot take the last worker from search. A failure, timeout or pause is
recorded on ``state`` and never ends the loop.
"""
paused = _store_workers_saturated()
if paused:
if state.last_error != paused:
logger.warning("%s", paused)
state.last_error = paused
return
now = state.clock()
errors: list[str] = []
retry_wait = (
not first_tick
and state.last_reconcile_attempt is not None
and state.last_reconcile_attempt != state.last_reconcile
and now - state.last_reconcile_attempt < MEMORY_RECONCILE_RETRY_INTERVAL
)
if not retry_wait and (first_tick or state.last_reconcile is None or (
now - state.last_reconcile >= MEMORY_RECONCILE_INTERVAL
)):
reconciled = False
try:
reset = await _run_bounded(state.index.reconcile(), state.tick_timeout, "reconcile")
reconciled = True
if reset:
logger.info("Memory reconcile reset %d acknowledgements", reset)
except asyncio.CancelledError:
raise
except Exception as exc:
errors.append(_scrub(exc))
logger.warning("Memory reconcile failed: %s", errors[-1])
finally:
# Stamped when the attempt ends: a timeout can take longer than the retry delay.
# On success both stamps are equal, which is how retry_wait tells success from failure.
state.last_reconcile_attempt = state.clock()
if reconciled:
state.last_reconcile = state.last_reconcile_attempt
paused = _store_workers_saturated()
if paused:
logger.warning("%s", paused)
errors.append(paused)
state.last_error = "; ".join(errors)
return
try:
await _run_bounded(state.index.tick(), state.tick_timeout, "tick")
except asyncio.CancelledError:
raise
except Exception as exc:
errors.append(_scrub(exc))
logger.warning("Memory sync tick failed: %s", errors[-1])
state.last_error = "; ".join(errors) or None
# Memory start-up runs after the transcript side is ready, on its own threads,
# so a slow DSN fetch or Postgres outage never touches transcript readiness.
_memory_status: dict = {"ready": False, "error": None}
_memory_runtime: dict = {}
MEMORY_FTS_FILE = _SERVER_DIR / "memories_fts.db"
def _memory_host() -> str:
return os.getenv("SESSIONFLOW_HOST_NAME") or socket.gethostname().split(".")[0].lower()
def _open_memory_store():
"""Fetch the DSN, open the store and apply migrations; runs on a startup thread."""
dsn = memory_store.fetch_dsn()
store = memory_store.MemoryStore(dsn)
try:
store.migrate()
except Exception:
store.close()
raise
return store
async def _start_memory(executor: concurrent.futures.Executor,
tasks: dict[str, asyncio.Task]) -> None:
"""Start the memory store, its indexes, the tools and the sync loop.
Any failure is reported as memory readiness ``False`` with the reason;
transcript search keeps working.
"""
loop = asyncio.get_running_loop()
try:
import memory_index
import memory_service
store = await loop.run_in_executor(executor, _open_memory_store)
_memory_runtime["store"] = store
client = await loop.run_in_executor(
executor, rag_engine._get_persistent_client, MILVUS_URI
)
index = memory_index.MemoryIndex(
store=store, milvus=client, fts_path=MEMORY_FTS_FILE, host=_memory_host(),
milvus_uri=MILVUS_URI,
)
await index.start()
_, _, allowlist_path = rag_engine._redaction_settings()
async def embed_query(text: str) -> list[float]:
vectors = await loop.run_in_executor(
rag_engine._embed_executor, lambda: rag_engine.embed_texts([text], is_query=True)
)
return vectors[0]
service = memory_service.MemoryService(
store=store, index=index, embed_query=embed_query,
allowlist=rag_engine.load_allowlist(allowlist_path),
)
_memory_runtime["index"] = index
state = MemorySyncState(index=index)
_memory_runtime["sync"] = state
tasks["memory_sync"] = asyncio.create_task(_memory_sync_worker(state))
set_memory_service(service)
_memory_status.update(ready=True, error=None)
print("[HTTP] Memory store ready.", file=sys.stderr)
except asyncio.CancelledError:
raise
except Exception as exc:
_memory_status.update(ready=False, error=_scrub(exc))
print(f"[HTTP] Warning: memory store unavailable: {_memory_status['error']}",
file=sys.stderr)
def jsonable(value):
"""Return ``value`` with datetimes turned into ISO strings, for JSONResponse."""
if isinstance(value, dict):
return {k: jsonable(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [jsonable(v) for v in value]
if hasattr(value, "isoformat"):
return value.isoformat()
return value
def _sync_staleness(last_tick: str | None, sync: MemorySyncState | None) -> dict:
"""Return the age of the last finished tick and whether the loop counts as stale."""
if not last_tick:
return {"last_tick_age_s": None, "stale": False}
age = (datetime.now(timezone.utc) - datetime.fromisoformat(last_tick)).total_seconds()
timeout = sync.tick_timeout if sync is not None else MEMORY_TICK_TIMEOUT
limit = timeout + MEMORY_STALE_INTERVALS * MEMORY_SYNC_INTERVAL
return {"last_tick_age_s": round(age, 1), "stale": age > limit}
def _memory_health_payload() -> dict:
"""Return memory readiness, the start-up error, acknowledgement lag and dump status."""
payload = {"ready": _memory_status["ready"], "error": _memory_status["error"],
"ack_lag": None, "dump": None, "index": None, "sync_error": None}
store = _memory_runtime.get("store")
index = _memory_runtime.get("index")
sync = _memory_runtime.get("sync")
if index is not None:
payload["index"] = index.health()
payload["index"].update(_sync_staleness(payload["index"].get("last_tick"), sync))
if sync is not None:
payload["sync_error"] = sync.last_error
if store is not None and _memory_status["ready"]:
try:
payload["ack_lag"] = store.ack_lag()
payload["dump"] = store.dump_status()
except Exception as exc:
payload["error"] = f"memory store unreachable: {_scrub(exc)}"
return payload
async def restore_check_endpoint(request: Request) -> JSONResponse:
"""Index a restored memory database into temporary targets and compare it with its manifest.
``memory_cli restore-check`` calls this after restoring a dump. The
production collection, FTS file, rows and acknowledgements are not touched.
"""
client_host = request.client.host if request.client else ""
if client_host not in ("127.0.0.1", "::1", "localhost", "testclient"):
return JSONResponse({"ok": False, "error": "loopback only"}, status_code=403)
index = _memory_runtime.get("index")
if not _memory_status["ready"] or index is None:
return JSONResponse({"ok": False, "error": "memory store not ready"}, status_code=503)
body = await request.json()
try:
target_dsn, manifest = body["target_dsn"], body["manifest"]
timeout_s = float(body.get("timeout_s", 600))
except (KeyError, TypeError, ValueError):
return JSONResponse({"ok": False, "error": "target_dsn and manifest are required"},
status_code=400)
import memory_index
try:
result = await memory_index.run_restore_check(
target_dsn=target_dsn, manifest=manifest, milvus=index.milvus,
fts_dir=_SERVER_DIR, embed=memory_index.embed_for_index,
model_name=rag_engine.get_model_name(), timeout_s=timeout_s,
)
except Exception as exc:
return JSONResponse({"ok": False, "error": _scrub(exc)}, status_code=500)
return JSONResponse(jsonable(result))
async def _memory_sync_worker(state: MemorySyncState) -> None:
"""Run the memory sync loop for the life of the server."""
first_tick = True
while True:
await _memory_sync_run_once(state, first_tick=first_tick)
first_tick = False
await asyncio.sleep(MEMORY_SYNC_INTERVAL)
async def _process_startup_provider_backfill_locked(
db_path: str,
enabled_providers: list[str],
mode: str,
startup_delay: float,
) -> dict:
"""Run startup provider backfill under the shared drain lock."""
_ensure_backfill_drain_primitives()
lock = _backfill_drain_lock
if lock is None:
return {}
if startup_delay > 0:
await asyncio.sleep(startup_delay)
async with lock:
return await process_startup_provider_backfill(
_backfill_manager,
db_path,
enabled_providers=enabled_providers,
mode=mode,
startup_delay=0,
)
def _provider_health(deep: bool = False) -> dict:
global _provider_health_cache, _provider_health_cache_ts
now = time.monotonic()
if not deep and _provider_health_cache is not None and (now - _provider_health_cache_ts) < _PROVIDER_HEALTH_TTL:
return _provider_health_cache
providers = [
ClaudeCodeCliAdapter(),
ClaudeCoworkLegacyAdapter(),
CodexAdapter(),
OpenCodeAdapter(),
AntigravityAdapter(source_kind="cli"),
AntigravityAdapter(source_kind="desktop"),
]
health = {}
for provider in providers:
try:
status = provider.health()
health[status.provider] = asdict(status)
except Exception as exc:
name = getattr(provider, "provider", provider.__class__.__name__)
health[name] = {"provider": name, "status": "error", "error": str(exc)}
_provider_health_cache = health
_provider_health_cache_ts = now
return health
async def _shared_provider_health(deep: bool) -> dict:
"""Run ``_provider_health`` on an executor; concurrent non-deep calls share one scan.
The default executor also runs query-less listings, so a burst of cache
misses must not fill it. ``shield`` keeps the scan alive for other waiters
when one caller is cancelled.
"""
global _provider_scan
loop = asyncio.get_running_loop()
if deep:
return await loop.run_in_executor(None, _provider_health, True)
if _provider_scan is None:
scan = loop.run_in_executor(None, _provider_health, False)
def _clear_scan(_done: asyncio.Future) -> None:
global _provider_scan
_provider_scan = None
scan.add_done_callback(_clear_scan)
_provider_scan = scan
return await asyncio.shield(_provider_scan)
def _backfill_status_payload() -> dict:
status = _backfill_manager.status()
return {
"paused": status.paused,
"jobs": [asdict(job) for job in status.jobs],
"providers": {
provider: asdict(provider_status)
for provider, provider_status in status.providers.items()
},
}
def _embedding_status_payload() -> dict:
try:
identity = EmbeddingIdentity.current_local()
identity_data = asdict(identity)
except Exception as exc:
identity_data = {"status": "error", "message": str(exc)}
try:
fingerprint = rag_engine.embedding_stamp_status()
except Exception as exc:
fingerprint = {"status": "error", "message": str(exc)}
return {
"identity": identity_data,
"fingerprint": fingerprint,
"budget": get_embedding_budget().status(),
}
def _fts_lag_payload() -> dict:
"""Return the FTS-vs-Milvus lag block for ``/health``.
Combines the static, server-wide lag from ``rag_engine.fts_lag_status`` with
the heal worker's standing-failure state (``consecutive_failures`` and the
last error signature) from the module-global ``_fts_heal_state``. The whole
computation is wrapped in try/except so a Milvus/FTS count failure under
persistent drift returns an ``{"status": "error", ...}`` marker instead of
raising — ``/health`` must never 500. The result is cached for a few seconds
to avoid a full Milvus scan on every probe.
Returns:
dict: static lag keys (``milvus_turn_count``, ``fts_row_count``,
``fts_lag``, ``fts_backfill_required``) plus ``consecutive_failures`` and
``last_error``; or ``{"status": "error", "message": ...}`` on failure.
"""
global _fts_lag_cache, _fts_lag_cache_ts
now = time.monotonic()
if _fts_lag_cache is not None and (now - _fts_lag_cache_ts) < _FTS_LAG_TTL:
return _fts_lag_cache
try:
payload = dict(rag_engine.fts_lag_status(db_path=MILVUS_URI, project_root=None))
state = _fts_heal_state
payload["consecutive_failures"] = (
state.consecutive_failures if state is not None else 0
)
payload["last_error"] = (
state.last_error_signature if state is not None else None
)
except Exception as exc:
payload = {"status": "error", "message": str(exc)}
_fts_lag_cache = payload
_fts_lag_cache_ts = now
return payload
_fts_lag_cache = payload
_fts_lag_cache_ts = now
return payload
async def health(request: Request) -> JSONResponse:
"""Return server health JSON; ``?deep=1`` bypasses the provider-status cache.
While background startup is still running this answers 503 with
``status: "starting"`` and skips the FTS-lag scan, which needs Milvus.
"""
deep = request is not None and request.query_params.get("deep") == "1"
watchers = file_watcher.get_watcher_status()
starting = _startup_state != "ready"
if starting:
fts_payload = {"status": "pending"}
else:
# _fts_lag_payload does synchronous Milvus/SQLite I/O on a cache miss; offload
# it to the loop's default executor so the scan never blocks the event loop.
loop = asyncio.get_running_loop()
fts_payload = await loop.run_in_executor(None, _fts_lag_payload)
memory_payload = await asyncio.get_running_loop().run_in_executor(
None, _memory_health_payload
)
providers_payload = await _shared_provider_health(deep)
return JSONResponse({
"memory": jsonable(memory_payload),
"status": "starting" if starting else "ok",
"startup": _startup_state,
"server": "sessionflow",
"version": __version__,
"port": PORT,
"model_name": rag_engine.get_model_name(),
"model_loaded": _model_loaded,
"milvus": _server_mode_ready,
"milvus_backend": "standalone" if MILVUS_URI.startswith("http") else "lite",