-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1690 lines (1474 loc) · 58.9 KB
/
Copy pathmain.py
File metadata and controls
1690 lines (1474 loc) · 58.9 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
"""
HybridMind FastAPI Application Entry Point.
Local dense, sparse, and graph retrieval service for controlled experiments.
The service has bounded caching, authentication/rate controls, and health
endpoints. Production suitability and retrieval quality are deployment- and
benchmark-dependent; this module does not claim either by itself.
"""
import asyncio
import hashlib
import json
import logging
import time
import os
import psutil
import secrets
import ipaddress
from collections import defaultdict, deque
from contextlib import asynccontextmanager
from typing import Dict, List, Optional
from dotenv import load_dotenv
load_dotenv()
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware
from pydantic import BaseModel, Field
from config import settings
from api.nodes import router as nodes_router
from api.edges import router as edges_router
from api.search import router as search_router
from api.bulk import router as bulk_router
from api.comparison import router as comparison_router
from api.dependencies import coordinate_mutation, get_db_manager
from engine.cache import get_query_cache
from engine.device import gpu_info as _gpu_info
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# Track startup time for metrics
_startup_time: Optional[float] = None
_model_loaded: bool = False
def _validate_api_security_configuration() -> None:
"""Refuse a network bind that would expose an unauthenticated API."""
host = settings.host.strip().lower()
try:
local_bind = ipaddress.ip_address(host).is_loopback
except ValueError:
local_bind = host == "localhost"
if (
not local_bind
and not settings.api_key.strip()
and not settings.allow_unauthenticated_private_networks
):
raise RuntimeError("A non-loopback HYBRIDMIND_HOST requires HYBRIDMIND_API_KEY")
def verify_integrity(mind_path: str) -> str:
from storage.mindfile import MindFile
from pathlib import Path
mind = MindFile(mind_path)
if not mind.exists:
return "New database"
try:
MindFile._validate_sqlite(mind.sqlite_path)
return "PASSED (SQLite source of truth)"
except Exception:
logger.error("Live SQLite integrity check failed; searching verified backups")
backup_dir = Path(settings.backup_dir)
for backup in reversed(sorted(backup_dir.glob("snapshot_*.mind.zip"))):
try:
MindFile.validate_archive(str(backup))
if mind.restore_from_archive(str(backup)):
return "PASSED (restored from verified backup)"
except Exception:
logger.warning("Rejected invalid snapshot backup: %s", backup.name)
# Never delete or replace live data when no verified backup exists.
return "FAILED (live data preserved)"
async def _memory_compression_worker(db_manager) -> None:
"""Periodically create lossy derived summaries when explicitly enabled."""
interval = max(60, settings.memory_compression_interval_seconds)
while True:
await asyncio.sleep(interval)
try:
from engine.consolidation import consolidate_sessions
result = await asyncio.to_thread(
consolidate_sessions,
db_manager,
min_facts=settings.memory_compression_min_facts,
max_age_hours=settings.memory_compression_max_age_hours,
model=settings.consolidation_model,
archive_sources=settings.memory_compression_archive_sources,
)
logger.info(f"memory compression cycle: {result}")
except asyncio.CancelledError:
raise
except Exception as exc:
logger.error("Memory compression cycle failed type=%s", type(exc).__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Application lifespan handler for startup and shutdown.
Initializes and validates local storage. A remote embedding warm-up is
opt-in because it can wake billable infrastructure; use the budget-gated
preflight before enabling it for an evaluation deployment.
"""
global _startup_time, _model_loaded
_validate_api_security_configuration()
startup_start = time.perf_counter()
logger.info("Warming up HybridMind...")
# Step 0: Integrity Check
integrity_status = verify_integrity(settings.mind_file_path)
# Step 1: Get database manager (triggers all component initialization)
logger.info(" Initializing storage components...")
db_manager = get_db_manager()
# Step 2: Resolve the embedding backend. Network warm-up is opt-in.
logger.info(" Resolving embedding backend...")
warmup_start = time.perf_counter()
embedding_engine = db_manager.embedding_engine
if embedding_engine.model is not None:
_model_loaded = True
warmup_vec = None
if settings.startup_embedding_warmup_enabled:
try:
if hasattr(embedding_engine, "warmup"):
warmup_vec = embedding_engine.warmup(
timeout_s=settings.startup_embedding_warmup_seconds
)
else:
warmup_vec = embedding_engine.embed(
"warmup query for model initialization"
)
warmup_time = (time.perf_counter() - warmup_start) * 1000
logger.info(" Embedding endpoint warmed in %.0fms", warmup_time)
except Exception as exc:
logger.error(
"Embedding endpoint not ready at startup type=%s; the first "
"real call will fail closed.",
type(exc).__name__,
)
else:
logger.info(
" Remote embedding warm-up skipped (run budget-gated preflight first)"
)
# Step 2.1: Hard-fail on embedding/FAISS dimension mismatch.
# A silent mismatch corrupts every similarity score in the index — never allow it.
# Only checkable when warmup actually returned a vector.
if warmup_vec is not None and (actual_dim := int(warmup_vec.shape[-1])) != (
index_dim := db_manager.vector_index.dimension
):
raise RuntimeError(
f"Embedding/FAISS dimension mismatch: the resolved embedding backend "
f"({type(embedding_engine).__name__}) outputs {actual_dim}-dim vectors, "
f"but the FAISS index at {settings.mind_file_path} was built with "
f"{index_dim} dims. This corrupts every similarity score. Fix by either "
f"(a) setting RUNPOD_TEI_EMBEDDING_URL to a TEI endpoint serving a "
f"{index_dim}-dim model, or (b) re-indexing the existing corpus for the "
f"current embedder with `python scripts/reindex_embeddings.py`."
)
else:
raise RuntimeError(
"The embedding backend did not initialize. HybridMind requires an exact "
"4096-dimensional backend and has no mock/local fallback."
)
# Step 2.5: BUG-1 — Verify FAISS index is in sync with SQLite
sqlite_count = db_manager.sqlite_store.count_retrievable_nodes()
faiss_count = db_manager.vector_index.size
if abs(sqlite_count - faiss_count) > 0:
logger.warning(
f"Index mismatch detected: SQLite={sqlite_count}, FAISS={faiss_count}. "
"Rebuilding indexes from SQLite..."
)
db_manager._rebuild_indexes()
logger.info(
f"Index rebuild complete: {db_manager.vector_index.size} vectors, "
f"{db_manager.graph_index.node_count} graph nodes"
)
else:
logger.info(f"Index sync verified: SQLite={sqlite_count}, FAISS={faiss_count}")
# Step 3: Initialize query cache
logger.info(" Initializing query cache...")
cache = get_query_cache(
maxsize=settings.cache_size,
ttl=300, # 5 minute TTL
)
# Step 4: Log stats summary
stats = db_manager.get_stats()
total_startup = (time.perf_counter() - startup_start) * 1000
_startup_time = time.time()
manifest = db_manager.mind_file.read_manifest() or {}
version = manifest.get("snapshot_version", 0)
timestamp = manifest.get("modified", "Unknown")
soft_deleted = db_manager.sqlite_store.get_deleted_nodes_count()
graph_embeddings_enabled = getattr(
settings, "use_graph_conditioned_embeddings", False
)
print(f"\nHybridMind starting up")
print(f"- Nodes: {stats['total_nodes']} ({soft_deleted} pending compaction)")
print(f"- Edges: {stats['total_edges']}")
print(f"- FAISS index: {stats['vector_index_size']} vectors")
print(f"- Graph nodes: {stats['graph_node_count']}")
print(f"- Snapshot manifest: v{version} @ {timestamp}")
print(f"- Checksum verification: {integrity_status}")
print(
f"- Graph-conditioned embeddings: {'ENABLED' if graph_embeddings_enabled else 'DISABLED'}"
)
from engine.llm_client import provider_chain
providers = provider_chain()
print(
"- Fact Extractor LLM: "
+ (
" -> ".join(providers)
if providers
else "DISABLED (no policy-allowed provider)"
)
)
print("\n")
compression_task = None
if settings.memory_compression_enabled:
compression_task = asyncio.create_task(_memory_compression_worker(db_manager))
logger.info(
"Derived-summary consolidation enabled: interval=%ss archive_sources=%s",
settings.memory_compression_interval_seconds,
settings.memory_compression_archive_sources,
)
yield
# Shutdown
logger.info("Shutting down HybridMind...")
if compression_task is not None:
compression_task.cancel()
try:
await compression_task
except asyncio.CancelledError:
pass
db_manager.save_indexes()
db_manager.close(save=False)
logger.info("HybridMind shutdown complete")
# Create FastAPI application
app = FastAPI(
title="HybridMind",
description="""
## Local dense, sparse, and graph retrieval service
HybridMind exposes controlled retrieval paths over SQLite-backed memory records.
Quality and latency must be established by an evidence-ID benchmark for the
specific corpus and deployment.
### Key Features
- **Vector Search**: Semantic similarity using cosine distance with FAISS
- **Graph Search**: Relationship traversal using NetworkX
- **Hybrid Search**: weighted reciprocal-rank fusion with optional reranking
- **Query Caching**: Fast repeated queries with TTL-based cache
- **Rate Limiting**: Protection against abuse
### Default fusion
```
RRF(d) = Σ weight(signal) / (k + rank(signal, d))
```
Request controls can isolate vector, sparse, graph, or combined paths. A
cross-encoder may rerank the bounded fusion pool when configured; responses
expose whether it was attempted and applied.
""",
version="1.0.0",
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=[
origin.strip()
for origin in settings.cors_allowed_origins.split(",")
if origin.strip()
],
allow_credentials=False,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-HybridMind-API-Key"],
)
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=[
host.strip() for host in settings.trusted_hosts.split(",") if host.strip()
],
www_redirect=False,
)
_request_windows = defaultdict(deque)
_rate_lock = asyncio.Lock()
_public_paths = {"/live"}
_expensive_prefixes = (
"/ingest/",
"/bulk/",
"/snapshot",
"/database/export",
"/admin/",
"/health",
)
def _is_local_client(request: Request) -> bool:
host = request.client.host if request.client else ""
if host == "testclient":
return True
try:
address = ipaddress.ip_address(host)
return address.is_loopback or (
settings.allow_unauthenticated_private_networks and address.is_private
)
except ValueError:
return False
@app.middleware("http")
async def authenticate_and_limit(request: Request, call_next):
"""Require a constant-time API-key check off loopback and cap costly calls."""
if request.method != "OPTIONS" and request.url.path not in _public_paths:
configured = settings.api_key
supplied = request.headers.get("X-HybridMind-API-Key", "")
authorization = request.headers.get("Authorization", "")
if authorization.startswith("Bearer "):
supplied = authorization[7:]
local_bypass = settings.allow_unauthenticated_localhost and _is_local_client(
request
)
if configured:
if not supplied or not secrets.compare_digest(supplied, configured):
return JSONResponse(status_code=401, content={"detail": "Unauthorized"})
elif not local_bypass:
return JSONResponse(
status_code=503,
content={"detail": "API authentication is not configured"},
)
expensive = request.url.path.startswith(_expensive_prefixes)
limit = (
settings.expensive_rate_limit_per_minute
if expensive
else settings.request_rate_limit_per_minute
)
# Starlette's synthetic test client is not a network principal and is
# shared across the entire test process; do not let one test module
# exhaust another module's window.
if limit > 0 and (not request.client or request.client.host != "testclient"):
key = (
(request.client.host if request.client else "unknown"),
"expensive" if expensive else "standard",
)
now = time.monotonic()
async with _rate_lock:
window = _request_windows[key]
while window and now - window[0] >= 60:
window.popleft()
if len(window) >= limit:
return JSONResponse(
status_code=429, content={"detail": "Rate limit exceeded"}
)
window.append(now)
return await call_next(request)
# Request timing middleware
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""Add processing time to response headers."""
start_time = time.perf_counter()
response = await call_next(request)
process_time = (time.perf_counter() - start_time) * 1000
response.headers["X-Process-Time-Ms"] = f"{process_time:.2f}"
return response
# Global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""Handle unexpected exceptions."""
logger.error(
"Unexpected request failure path=%s type=%s",
request.url.path,
type(exc).__name__,
)
return JSONResponse(
status_code=500,
content={
"detail": "Internal server error",
"error": "An unexpected error occurred",
},
)
# Include routers
app.include_router(nodes_router)
app.include_router(edges_router)
app.include_router(search_router)
app.include_router(bulk_router)
app.include_router(comparison_router)
# ==================== Health & Utility Endpoints ====================
# Response models for health endpoints
class HealthResponse(BaseModel):
"""Comprehensive health check response."""
status: str
timestamp: float
uptime_seconds: float
components: dict
metrics: dict
class ReadinessResponse(BaseModel):
"""Kubernetes readiness probe response."""
status: str
model_loaded: bool
nodes_loaded: int
edges_loaded: int
class LivenessResponse(BaseModel):
"""Kubernetes liveness probe response."""
status: str
@app.get("/", tags=["Utility"])
async def root():
"""Welcome endpoint with API overview."""
return {
"name": "HybridMind",
"version": "1.0.0",
"description": "Local dense, sparse, and graph retrieval service",
"docs": "/docs",
"endpoints": {
"nodes": "/nodes",
"edges": "/edges",
"search": {
"vector": "/search/vector",
"graph": "/search/graph",
"hybrid": "/search/hybrid",
"compare": "/search/compare",
},
"bulk": {
"nodes": "/bulk/nodes",
"edges": "/bulk/edges",
"import": "/bulk/import",
},
"health": {"full": "/health", "ready": "/ready", "live": "/live"},
"stats": "/search/stats",
"cache": "/cache/stats",
},
}
@app.get("/health", response_model=HealthResponse, tags=["Health"])
async def health_check():
"""
Comprehensive health check endpoint.
Returns detailed status of all components:
- Embedding model status and latency
- Vector index status and size
- Graph index status and size
- Database connectivity
- System metrics (CPU, memory, disk)
"""
components = {}
try:
db_manager = get_db_manager()
# Do not make a billable/remote provider call from a probe by default.
components["embedding"] = {
"status": "configured",
"model": settings.embedding_model,
"remote_probe_enabled": settings.health_remote_checks,
}
if settings.health_remote_checks:
try:
start = time.perf_counter()
db_manager.embedding_engine.embed("health check")
components["embedding"].update(
{
"status": "healthy",
"latency_ms": round((time.perf_counter() - start) * 1000, 2),
}
)
except Exception:
components["embedding"] = {
"status": "unhealthy",
"error": "Remote embedding probe failed",
}
# Check vector index
components["vector_index"] = {
"status": "healthy",
"size": db_manager.vector_index.size,
"dimension": db_manager.vector_index.dimension,
}
# Check graph index
components["graph_index"] = {
"status": "healthy",
"nodes": db_manager.graph_index.node_count,
"edges": db_manager.graph_index.edge_count,
}
# Check database
try:
node_count = db_manager.sqlite_store.count_nodes()
components["database"] = {
"status": "healthy",
"nodes": node_count,
"size_bytes": db_manager.sqlite_store.get_database_size(),
}
except Exception:
components["database"] = {
"status": "unhealthy",
"error": "Database check failed",
}
# Check cache
cache = get_query_cache()
components["cache"] = {"status": "healthy", **cache.stats}
# GPU / device info
components["gpu"] = _gpu_info()
except Exception:
components["system"] = {
"status": "unhealthy",
"error": "Component initialization failed",
}
# System metrics
metrics = {
"cpu_percent": psutil.cpu_percent(),
"memory_percent": psutil.virtual_memory().percent,
"memory_available_mb": round(psutil.virtual_memory().available / (1024 * 1024)),
}
# Try to get disk usage (may fail on some systems)
try:
disk = psutil.disk_usage("/")
metrics["disk_percent"] = disk.percent
except:
pass
# Calculate uptime
uptime = time.time() - _startup_time if _startup_time else 0
# Determine overall status
unhealthy_components = [
name
for name, info in components.items()
if isinstance(info, dict) and info.get("status") == "unhealthy"
]
if not unhealthy_components:
status = "healthy"
elif len(unhealthy_components) < len(components):
status = "degraded"
else:
status = "unhealthy"
return HealthResponse(
status=status,
timestamp=time.time(),
uptime_seconds=round(uptime, 1),
components=components,
metrics=metrics,
)
@app.get("/ready", response_model=ReadinessResponse, tags=["Health"])
async def readiness_check():
"""
Kubernetes readiness probe.
Returns ready status only when:
- Database manager is initialized
- Embedding model is loaded
- Data is loaded from disk
"""
try:
db_manager = get_db_manager()
stats = db_manager.get_stats()
return {
"status": "online",
"model_loaded": db_manager.embedding_engine.model is not None,
"nodes_loaded": stats.get("total_nodes", 0),
"edges_loaded": stats.get("total_edges", 0),
"graph_nodes": stats.get("graph_node_count", 0),
"vector_nodes": stats.get("vector_index_size", 0),
"settings": {
"graph_conditioned_embeddings": getattr(
settings, "use_graph_conditioned_embeddings", False
),
"dimensions": getattr(settings, "embedding_dimension", 4096),
},
}
except Exception:
return JSONResponse(
status_code=503,
content={
"status": "not_ready",
"model_loaded": False,
"nodes_loaded": 0,
"edges_loaded": 0,
},
)
@app.get("/live", response_model=LivenessResponse, tags=["Health"])
async def liveness_check():
"""
Kubernetes liveness probe.
Simple check that the application is running.
Always returns success if the server is responding.
"""
return LivenessResponse(status="alive")
@app.get("/cache/stats", tags=["Utility"])
async def cache_stats():
"""Get query cache statistics."""
cache = get_query_cache()
return cache.stats
@app.post("/cache/clear", tags=["Utility"])
async def clear_cache():
"""Clear the query cache."""
cache = get_query_cache()
cache.invalidate_all()
return {"status": "success", "message": "Cache cleared"}
@app.post("/snapshot", tags=["Utility"])
async def create_snapshot():
"""Create a persistence snapshot of indexes."""
try:
db_manager = get_db_manager()
snapshot = db_manager.save_indexes()
return {
"status": "success",
"message": "Verified snapshot created",
"snapshot": snapshot.name,
}
except Exception:
return JSONResponse(
status_code=500,
content={"status": "error", "message": "Snapshot creation failed"},
)
@app.get("/database", tags=["Utility"])
async def get_database_info():
"""
Get information about the .mind database file.
HybridMind uses the `.mind` extension as its native database format.
A .mind file is a directory containing:
- store.db: SQLite database
- vectors.faiss: FAISS vector index
- graph.nx: NetworkX graph
- manifest.json: Metadata and stats
"""
try:
db_manager = get_db_manager()
return db_manager.mind_file.get_info()
except Exception:
return JSONResponse(
status_code=500, content={"error": "Database information unavailable"}
)
@app.post("/database/export", tags=["Utility"])
async def export_database(compress: bool = True):
"""
Export the .mind database to a portable archive.
Creates a .mind.zip file that can be shared and imported elsewhere.
"""
try:
db_manager = get_db_manager()
if not compress:
return JSONResponse(
status_code=400,
content={"error": "Only verified compressed exports are supported"},
)
result = db_manager.save_indexes()
return {
"status": "success",
"snapshot": result.name,
"message": "Verified database snapshot exported successfully",
}
except Exception:
return JSONResponse(status_code=500, content={"error": "Export failed"})
@app.post("/admin/compact", tags=["Admin"])
async def compact_database():
"""
Compact the database by rebuilding FAISS index and hard-deleting soft-deleted nodes.
"""
try:
db_manager = get_db_manager()
# Preserve one verified, internally consistent recovery point before the
# irreversible history purge. save_indexes owns the process mutation
# guard, so run it before taking the async guard below.
await asyncio.to_thread(db_manager.save_indexes)
async with db_manager.mutation_async():
try:
with db_manager.sqlite_store.transaction():
deleted_count = (
db_manager.sqlite_store.hard_delete_soft_deleted_nodes()
)
db_manager._rebuild_indexes()
except Exception:
# SQL has rolled back. Replace every derived index from that
# authoritative pre-compaction state before reporting failure.
db_manager._rebuild_indexes()
raise
from engine.cache import invalidate_cache
invalidate_cache()
return {
"status": "success",
"message": "Database compacted successfully",
"compacted_nodes": deleted_count,
}
except Exception:
return JSONResponse(
status_code=500,
content={"status": "error", "message": "Database compaction failed"},
)
@app.post("/admin/clear", tags=["Admin"])
async def clear_database():
"""Clear all data from the database."""
db_manager = None
try:
db_manager = get_db_manager()
async with db_manager.mutation_async():
try:
with db_manager.sqlite_store.transaction():
with db_manager.sqlite_store._cursor() as cursor:
cursor.execute("DELETE FROM edges")
# Clear/forget is an erasure boundary. Immutable history
# must not retain text after current nodes are deleted.
cursor.execute("DELETE FROM node_versions")
cursor.execute("DELETE FROM nodes")
db_manager.vector_index.clear()
db_manager.graph_index.clear()
db_manager.bm25_index.clear()
if getattr(db_manager, "visual_store", None) is not None:
db_manager.visual_store.clear()
if getattr(db_manager, "colbert_store", None) is not None:
db_manager.colbert_store.clear()
except Exception:
db_manager._rebuild_indexes()
raise
from engine.cache import invalidate_cache
invalidate_cache()
clear_fact_cache()
return {"status": "success", "message": "Database cleared"}
except Exception as exc:
logger.error("Database clear failed type=%s", type(exc).__name__)
return JSONResponse(status_code=500, content={"error": "Database clear failed"})
# ==================== Admin: Memory Lifecycle ====================
class ConsolidateRequest(BaseModel):
min_facts: int = settings.memory_compression_min_facts
max_age_hours: int = settings.memory_compression_max_age_hours
model: Optional[str] = None
archive_sources: bool = settings.memory_compression_archive_sources
@app.post("/admin/consolidate", tags=["Admin"])
async def consolidate_memory(request: ConsolidateRequest = ConsolidateRequest()):
"""
Consolidate old session memories into summary nodes.
Groups extracted_fact nodes by session_id, summarizes sessions with
>= min_facts facts that are older than max_age_hours. Idempotent.
"""
try:
db_manager = get_db_manager()
from engine.consolidation import consolidate_sessions
result = await asyncio.to_thread(
consolidate_sessions,
db_manager,
min_facts=request.min_facts,
max_age_hours=request.max_age_hours,
model=request.model,
archive_sources=request.archive_sources,
)
status = "partial" if result.get("failures") else "success"
return {"status": status, **result}
except ValueError:
return JSONResponse(
status_code=409,
content={
"status": "error",
"message": "Unsafe consolidation request rejected",
},
)
except Exception:
return JSONResponse(
status_code=500,
content={"status": "error", "message": "Consolidation failed"},
)
class PruneRequest(BaseModel):
threshold: float = Field(default=0.3, ge=0.0, le=1.0)
@app.post("/admin/prune-low-importance", tags=["Admin"])
async def prune_low_importance(request: PruneRequest = PruneRequest()):
"""
Soft-delete low-importance memory nodes.
Computes importance_score() for every node (recency + centrality +
access frequency). Nodes with score < threshold are soft-deleted.
Runs compaction automatically after pruning.
"""
db_manager = None
try:
db_manager = get_db_manager()
from engine.consolidation import importance_score
async with db_manager.mutation_async():
# Score one stable graph/SQL view, then apply the complete mutation
# as a transaction. A single projection failure aborts the request.
with db_manager.sqlite_store._cursor() as cursor:
cursor.execute("SELECT id FROM nodes WHERE deleted_at IS NULL")
all_ids = [row["id"] for row in cursor.fetchall()]
graph = db_manager.graph_index.graph
max_graph_degree = max(
(float(degree) for _, degree in graph.degree()),
default=1.0,
)
to_prune = [
node_id
for node_id in all_ids
if importance_score(
node_id,
db_manager,
max_graph_degree=max_graph_degree,
)
< request.threshold
]
try:
with db_manager.sqlite_store.transaction():
for node_id in to_prune:
if not db_manager.sqlite_store.soft_delete_node(node_id):
raise RuntimeError("node disappeared during pruning")
db_manager.vector_index.remove(node_id)
db_manager.graph_index.remove_node(node_id)
db_manager.bm25_index.remove(node_id)
except Exception:
db_manager._rebuild_indexes()
raise
from engine.cache import invalidate_cache
invalidate_cache()
pruned = len(to_prune)
logger.info(
f"prune-low-importance: pruned {pruned}/{len(all_ids)} nodes (threshold={request.threshold})"
)
return {
"status": "success",
"threshold": request.threshold,
"nodes_evaluated": len(all_ids),
"nodes_pruned": pruned,
}
except Exception as exc:
logger.error("Pruning failed type=%s", type(exc).__name__)
return JSONResponse(
status_code=500, content={"status": "error", "message": "Pruning failed"}
)
@app.post("/admin/detect-communities", tags=["Admin"])
async def detect_communities(
mutation_guard: None = Depends(coordinate_mutation),
):
"""
Run Louvain community detection and create community summary nodes.
Detects clusters in the memory graph and creates a summary node for
each community with >= 3 members. Idempotent per run.
"""
try:
db_manager = get_db_manager()
from engine.community_detector import run_community_detection
result = await asyncio.to_thread(run_community_detection, db_manager)
return {"status": "success", **result}
except Exception:
return JSONResponse(
status_code=500,
content={"status": "error", "message": "Community detection failed"},
)
# ==================== Ingest Helpers ====================
class SessionTurn(BaseModel):
"""A single conversation turn for fact extraction."""
speaker: str = ""
text: str
date: str = ""
class SessionFactsRequest(BaseModel):
"""Request body for /ingest/session-facts."""
session_id: str
turns: List[SessionTurn]
container_tag: Optional[str] = None
class SessionFactsResponse(BaseModel):
"""Response from /ingest/session-facts."""
session_id: str
facts_extracted: int
node_ids: List[str]