contextsynapse 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- contextsynapse/__init__.py +107 -0
- contextsynapse/__main__.py +9 -0
- contextsynapse/a2a/__init__.py +28 -0
- contextsynapse/a2a/client.py +120 -0
- contextsynapse/a2a/discovery.py +128 -0
- contextsynapse/a2a/handlers.py +164 -0
- contextsynapse/a2a/models.py +246 -0
- contextsynapse/a2a/streaming.py +92 -0
- contextsynapse/a2a/task_manager.py +275 -0
- contextsynapse/adapters/__init__.py +98 -0
- contextsynapse/adapters/_base.py +298 -0
- contextsynapse/adapters/autogen/__init__.py +4 -0
- contextsynapse/adapters/autogen/tools.py +34 -0
- contextsynapse/adapters/crewai/__init__.py +4 -0
- contextsynapse/adapters/crewai/tools.py +63 -0
- contextsynapse/adapters/langchain/__init__.py +19 -0
- contextsynapse/adapters/langchain/message_history.py +17 -0
- contextsynapse/adapters/langchain/retriever.py +158 -0
- contextsynapse/adapters/langchain/tools.py +43 -0
- contextsynapse/adapters/langgraph/__init__.py +21 -0
- contextsynapse/adapters/langgraph/checkpoint.py +223 -0
- contextsynapse/adapters/langgraph/context_tools.py +341 -0
- contextsynapse/adapters/langgraph/message_history.py +138 -0
- contextsynapse/adapters/langgraph/tools.py +43 -0
- contextsynapse/adapters/llamaindex/__init__.py +4 -0
- contextsynapse/adapters/llamaindex/tools.py +64 -0
- contextsynapse/adapters/openai/__init__.py +24 -0
- contextsynapse/adapters/openai/tools.py +206 -0
- contextsynapse/adapters/pydantic_ai/__init__.py +4 -0
- contextsynapse/adapters/pydantic_ai/tools.py +36 -0
- contextsynapse/adapters/swarm/__init__.py +4 -0
- contextsynapse/adapters/swarm/tools.py +44 -0
- contextsynapse/agents/__init__.py +6 -0
- contextsynapse/agents/auto_capture.py +80 -0
- contextsynapse/agents/dispatcher.py +299 -0
- contextsynapse/agents/notifications.py +112 -0
- contextsynapse/aiql/__init__.py +71 -0
- contextsynapse/aiql/cache.py +341 -0
- contextsynapse/aiql/compiler/__init__.py +62 -0
- contextsynapse/aiql/compiler/optimizer.py +126 -0
- contextsynapse/aiql/compiler/planner.py +366 -0
- contextsynapse/aiql/compiler/statistics.py +235 -0
- contextsynapse/aiql/compiler/validator.py +425 -0
- contextsynapse/aiql/engine/__init__.py +11 -0
- contextsynapse/aiql/engine/chunk_storage.py +2584 -0
- contextsynapse/aiql/engine/executor.py +7737 -0
- contextsynapse/aiql/engine/extraction_integration.py +442 -0
- contextsynapse/aiql/engine/graph_builder.py +405 -0
- contextsynapse/aiql/engine/node_creation_from_normalized.py +691 -0
- contextsynapse/aiql/engine/performance_monitor.py +289 -0
- contextsynapse/aiql/engine/postprocessing.py +365 -0
- contextsynapse/aiql/engine/ray_stage_executors.py +918 -0
- contextsynapse/aiql/engine/redis_cache.py +106 -0
- contextsynapse/aiql/engine/streaming_json.py +366 -0
- contextsynapse/aiql/engine/streaming_parquet.py +568 -0
- contextsynapse/aiql/engine/streaming_ray_chunking.py +419 -0
- contextsynapse/aiql/grammar/__init__.py +14 -0
- contextsynapse/aiql/grammar/aiql_grammar.py +1822 -0
- contextsynapse/aiql/grammar/base.py +71 -0
- contextsynapse/aiql/parser/__init__.py +46 -0
- contextsynapse/aiql/parser/aiql_parser.py +11330 -0
- contextsynapse/aiql/parser/base_parser.py +47 -0
- contextsynapse/api/__init__.py +5 -0
- contextsynapse/api/a2a_router.py +233 -0
- contextsynapse/api/admin_router.py +140 -0
- contextsynapse/api/agent_worker_router.py +978 -0
- contextsynapse/api/algorithms_router.py +317 -0
- contextsynapse/api/api.py +4144 -0
- contextsynapse/api/audit.py +204 -0
- contextsynapse/api/auth.py +441 -0
- contextsynapse/api/auth_router.py +537 -0
- contextsynapse/api/billing.py +261 -0
- contextsynapse/api/billing_router.py +275 -0
- contextsynapse/api/boundary_router.py +452 -0
- contextsynapse/api/cognition_router.py +116 -0
- contextsynapse/api/connector_router.py +237 -0
- contextsynapse/api/context_router.py +1619 -0
- contextsynapse/api/dashboard_router.py +11367 -0
- contextsynapse/api/errors.py +183 -0
- contextsynapse/api/events.py +88 -0
- contextsynapse/api/experiment_bootstrap.py +321 -0
- contextsynapse/api/experiment_orchestrator.py +1078 -0
- contextsynapse/api/experiment_router.py +2089 -0
- contextsynapse/api/feature_gate.py +89 -0
- contextsynapse/api/federation_router.py +108 -0
- contextsynapse/api/integrations.py +567 -0
- contextsynapse/api/integrations_router.py +461 -0
- contextsynapse/api/intelligence_router.py +1028 -0
- contextsynapse/api/metering.py +155 -0
- contextsynapse/api/metrics.py +112 -0
- contextsynapse/api/models.py +38 -0
- contextsynapse/api/monitoring_router.py +174 -0
- contextsynapse/api/pipeline_router.py +1437 -0
- contextsynapse/api/playground_conn.py +116 -0
- contextsynapse/api/projects_router.py +131 -0
- contextsynapse/api/queries_router.py +282 -0
- contextsynapse/api/quota.py +95 -0
- contextsynapse/api/rate_limit.py +64 -0
- contextsynapse/api/search_router.py +261 -0
- contextsynapse/api/shield_router.py +447 -0
- contextsynapse/api/tenant_guard.py +103 -0
- contextsynapse/api/tenant_quotas.py +231 -0
- contextsynapse/api/tenants.py +305 -0
- contextsynapse/api/users.py +646 -0
- contextsynapse/api/v1.py +167 -0
- contextsynapse/api/vertical_builder_router.py +387 -0
- contextsynapse/benchmark/__init__.py +15 -0
- contextsynapse/benchmark/__main__.py +64 -0
- contextsynapse/benchmark/agents.py +338 -0
- contextsynapse/benchmark/live_ab.py +338 -0
- contextsynapse/benchmark/reporter.py +149 -0
- contextsynapse/benchmark/runner.py +264 -0
- contextsynapse/benchmark/savings.py +266 -0
- contextsynapse/benchmark/token_counter.py +212 -0
- contextsynapse/benchmark/workloads.py +289 -0
- contextsynapse/buffer/__init__.py +154 -0
- contextsynapse/buffer/base.py +257 -0
- contextsynapse/buffer/duckdb_buffer.py +246 -0
- contextsynapse/buffer/file_buffer.py +229 -0
- contextsynapse/buffer/lmdb_buffer.py +286 -0
- contextsynapse/buffer/local_buffer.py +154 -0
- contextsynapse/buffer/redis_buffer.py +211 -0
- contextsynapse/buffer/sqlite_buffer.py +266 -0
- contextsynapse/cache.py +2 -0
- contextsynapse/cli/__init__.py +40 -0
- contextsynapse/cli/cli.py +475 -0
- contextsynapse/cli/config_cli.py +177 -0
- contextsynapse/cli/scaffold.py +465 -0
- contextsynapse/cognition/__init__.py +31 -0
- contextsynapse/cognition/derivation.py +55 -0
- contextsynapse/cognition/events.py +135 -0
- contextsynapse/cognition/feedback.py +52 -0
- contextsynapse/cognition/hallucination.py +90 -0
- contextsynapse/cognition/invalidation.py +70 -0
- contextsynapse/cognition/read_tracker.py +50 -0
- contextsynapse/collaboration.py +2 -0
- contextsynapse/comparison.py +2 -0
- contextsynapse/config/__init__.py +10 -0
- contextsynapse/config/connectors/amfi_nav.yaml +18 -0
- contextsynapse/config/connectors/auto_sector.yaml +20 -0
- contextsynapse/config/connectors/banking_sector.yaml +20 -0
- contextsynapse/config/connectors/energy_sector.yaml +20 -0
- contextsynapse/config/connectors/fmcg_sector.yaml +20 -0
- contextsynapse/config/connectors/nsdl_fpi.yaml +9 -0
- contextsynapse/config/connectors/nse_price.yaml +61 -0
- contextsynapse/config/connectors/pharma_sector.yaml +20 -0
- contextsynapse/config/connectors/rbi_dbie.yaml +12 -0
- contextsynapse/config/context_presets/ai_research.json +25 -0
- contextsynapse/config/context_presets/chatgpt_conversations.json +19 -0
- contextsynapse/config/context_presets/claude_conversations.json +19 -0
- contextsynapse/config/context_presets/legal_compliance.json +21 -0
- contextsynapse/config/context_presets/meeting_notes.json +21 -0
- contextsynapse/config/context_presets/slack_engineering.json +21 -0
- contextsynapse/config/context_presets/tech_climate.json +24 -0
- contextsynapse/config/context_presets/toi_politics.json +25 -0
- contextsynapse/config/database_config.py +453 -0
- contextsynapse/config/deployment.py +221 -0
- contextsynapse/config/gpt_action_schema.json +164 -0
- contextsynapse/config/indicators/india_macro.yaml +213 -0
- contextsynapse/config/logging_config.py +88 -0
- contextsynapse/config/mode_config.py +223 -0
- contextsynapse/config/schemas/api_spec.yaml +48 -0
- contextsynapse/config/schemas/architecture_doc.yaml +51 -0
- contextsynapse/config/schemas/chat_history.yaml +90 -0
- contextsynapse/config/schemas/chatgpt_conversation.yaml +101 -0
- contextsynapse/config/schemas/claude_conversation.yaml +148 -0
- contextsynapse/config/schemas/contract.yaml +48 -0
- contextsynapse/config/schemas/conversation.yaml +167 -0
- contextsynapse/config/schemas/database.yaml +74 -0
- contextsynapse/config/schemas/decision.yaml +72 -0
- contextsynapse/config/schemas/ecommerce.yaml +56 -0
- contextsynapse/config/schemas/education.yaml +42 -0
- contextsynapse/config/schemas/healthcare.yaml +133 -0
- contextsynapse/config/schemas/hr_document.yaml +48 -0
- contextsynapse/config/schemas/invoice.yaml +40 -0
- contextsynapse/config/schemas/knowledge_base.yaml +75 -0
- contextsynapse/config/schemas/legal.yaml +42 -0
- contextsynapse/config/schemas/marketing_content.yaml +48 -0
- contextsynapse/config/schemas/meeting_notes.yaml +51 -0
- contextsynapse/config/schemas/news_article.yaml +61 -0
- contextsynapse/config/schemas/real_estate.yaml +49 -0
- contextsynapse/config/schemas/requirements_doc.yaml +48 -0
- contextsynapse/config/schemas/research_paper.yaml +56 -0
- contextsynapse/config/schemas/resume.yaml +49 -0
- contextsynapse/config/schemas/retail.yaml +42 -0
- contextsynapse/config/schemas/rule_meta.yaml +173 -0
- contextsynapse/config/schemas/rules.yaml +72 -0
- contextsynapse/config/schemas/screener_meta.yaml +236 -0
- contextsynapse/config/schemas/sdlc.yaml +103 -0
- contextsynapse/config/schemas/session_graph.yaml +172 -0
- contextsynapse/config/schemas/support_ticket.yaml +48 -0
- contextsynapse/config/schemas/web.yaml +64 -0
- contextsynapse/config/sensors/earnings_calendar.yaml +52 -0
- contextsynapse/config/sensors/global_risk.yaml +53 -0
- contextsynapse/config/sensors/government_policy.yaml +54 -0
- contextsynapse/config/sensors/supply_chain.yaml +50 -0
- contextsynapse/config/sensors/templates/behavioral.yaml +56 -0
- contextsynapse/config/sensors/templates/equity_sentiment.yaml +48 -0
- contextsynapse/config/sensors/templates/global_macro.yaml +47 -0
- contextsynapse/config/sensors/templates/market_data.yaml +118 -0
- contextsynapse/config/sensors/templates/sector_technical.yaml +47 -0
- contextsynapse/config/sensors/weather.yaml +52 -0
- contextsynapse/config/storage_strategy.py +202 -0
- contextsynapse/config/templates/competitive_intel.yaml +39 -0
- contextsynapse/config/templates/geopolitical_risk.yaml +46 -0
- contextsynapse/config/templates/market_analysis.yaml +58 -0
- contextsynapse/connectors/__init__.py +15 -0
- contextsynapse/connectors/api_router.py +121 -0
- contextsynapse/connectors/base.py +357 -0
- contextsynapse/connectors/financial/audio.py +170 -0
- contextsynapse/connectors/financial/youtube.py +272 -0
- contextsynapse/connectors/github.py +164 -0
- contextsynapse/connectors/jira.py +120 -0
- contextsynapse/connectors/kafka_connector.py +124 -0
- contextsynapse/connectors/pipeline_connector.py +747 -0
- contextsynapse/connectors/registry.py +116 -0
- contextsynapse/connectors/scheduler.py +87 -0
- contextsynapse/connectors/universal.py +360 -0
- contextsynapse/context/__init__.py +96 -0
- contextsynapse/context/__main__.py +4 -0
- contextsynapse/context/acl.py +125 -0
- contextsynapse/context/agent_card.py +201 -0
- contextsynapse/context/agent_memory.py +814 -0
- contextsynapse/context/agents.py +472 -0
- contextsynapse/context/agents_redis.py +391 -0
- contextsynapse/context/assembled.py +204 -0
- contextsynapse/context/attribution.py +113 -0
- contextsynapse/context/blob.py +184 -0
- contextsynapse/context/boundaries.py +187 -0
- contextsynapse/context/boundary.py +507 -0
- contextsynapse/context/bundle.py +155 -0
- contextsynapse/context/cli.py +519 -0
- contextsynapse/context/collaboration.py +165 -0
- contextsynapse/context/compiler.py +604 -0
- contextsynapse/context/composite.py +536 -0
- contextsynapse/context/compression.py +147 -0
- contextsynapse/context/context_manager.py +888 -0
- contextsynapse/context/context_schema.py +90 -0
- contextsynapse/context/context_schema.yaml +105 -0
- contextsynapse/context/context_units.py +891 -0
- contextsynapse/context/conversation.py +488 -0
- contextsynapse/context/dedup.py +207 -0
- contextsynapse/context/document_processor.py +698 -0
- contextsynapse/context/embedding_hooks.py +338 -0
- contextsynapse/context/execution_schema.py +274 -0
- contextsynapse/context/fan_out.py +138 -0
- contextsynapse/context/frozen.py +80 -0
- contextsynapse/context/gravity.py +227 -0
- contextsynapse/context/hub.py +1401 -0
- contextsynapse/context/ingest.py +391 -0
- contextsynapse/context/injection.py +226 -0
- contextsynapse/context/interaction_graphifier.py +562 -0
- contextsynapse/context/layers.py +574 -0
- contextsynapse/context/projection.py +1195 -0
- contextsynapse/context/promotion.py +634 -0
- contextsynapse/context/proof.py +131 -0
- contextsynapse/context/propagation.py +577 -0
- contextsynapse/context/pubsub.py +135 -0
- contextsynapse/context/quality.py +1054 -0
- contextsynapse/context/quality_tracker.py +270 -0
- contextsynapse/context/scoping.py +370 -0
- contextsynapse/context/seed.py +992 -0
- contextsynapse/context/session.py +1142 -0
- contextsynapse/context/session_graph.py +593 -0
- contextsynapse/context/session_memory.py +309 -0
- contextsynapse/context/session_resolver.py +111 -0
- contextsynapse/context/skill_learning.py +237 -0
- contextsynapse/context/smart_budget.py +129 -0
- contextsynapse/context/source_policy.py +242 -0
- contextsynapse/context/store_factory.py +53 -0
- contextsynapse/context/sync.py +648 -0
- contextsynapse/context/token.py +236 -0
- contextsynapse/context/vector_integration.py +297 -0
- contextsynapse/context/webhooks.py +194 -0
- contextsynapse/context/working_memory.py +224 -0
- contextsynapse/core/__init__.py +18 -0
- contextsynapse/core/archiver.py +237 -0
- contextsynapse/core/change_stream.py +282 -0
- contextsynapse/core/checkpoint.py +310 -0
- contextsynapse/core/cloud_storage.py +387 -0
- contextsynapse/core/context_state.py +651 -0
- contextsynapse/core/cron.py +324 -0
- contextsynapse/core/datasource.py +643 -0
- contextsynapse/core/db.py +289 -0
- contextsynapse/core/federation.py +283 -0
- contextsynapse/core/graph_coordinator.py +201 -0
- contextsynapse/core/graph_intelligence.py +388 -0
- contextsynapse/core/graph_structures.py +106 -0
- contextsynapse/core/graph_sync.py +157 -0
- contextsynapse/core/hybrid_graph_storage.py +2998 -0
- contextsynapse/core/lifecycle.py +691 -0
- contextsynapse/core/multiworker.py +378 -0
- contextsynapse/core/pruning.py +312 -0
- contextsynapse/core/redis_registry.py +524 -0
- contextsynapse/core/registry.py +1043 -0
- contextsynapse/core/registry_factory.py +51 -0
- contextsynapse/core/registry_metadata.py +294 -0
- contextsynapse/core/replay.py +354 -0
- contextsynapse/core/replication.py +339 -0
- contextsynapse/core/time_travel.py +260 -0
- contextsynapse/core/write_behind.py +152 -0
- contextsynapse/core/write_context.py +39 -0
- contextsynapse/db/__init__.py +1 -0
- contextsynapse/db/postgres.py +267 -0
- contextsynapse/db/profile.py +236 -0
- contextsynapse/db/rules.py +328 -0
- contextsynapse/demo/__init__.py +0 -0
- contextsynapse/demo/report.py +147 -0
- contextsynapse/demo/runner.py +520 -0
- contextsynapse/demo/scenario.py +165 -0
- contextsynapse/demo/session_demo.py +280 -0
- contextsynapse/demo/session_report.py +143 -0
- contextsynapse/demo/universal_runner.py +257 -0
- contextsynapse/engine/__init__.py +15 -0
- contextsynapse/engine/core.py +555 -0
- contextsynapse/extraction/__init__.py +69 -0
- contextsynapse/extraction/cli.py +274 -0
- contextsynapse/extraction/config.py +107 -0
- contextsynapse/extraction/examples/example_usage.py +118 -0
- contextsynapse/extraction/examples/sample_manifest.json +53 -0
- contextsynapse/extraction/examples/sample_normalized.json +185 -0
- contextsynapse/extraction/extract_engine.py +440 -0
- contextsynapse/extraction/extractors/__init__.py +37 -0
- contextsynapse/extraction/extractors/chat_export_extractor.py +189 -0
- contextsynapse/extraction/extractors/csv_extractor.py +83 -0
- contextsynapse/extraction/extractors/docx_extractor.py +129 -0
- contextsynapse/extraction/extractors/excel_extractor.py +152 -0
- contextsynapse/extraction/extractors/html_extractor.py +146 -0
- contextsynapse/extraction/extractors/pdf_extractor.py +635 -0
- contextsynapse/extraction/extractors/pdf_extractor_layoutparser.py +408 -0
- contextsynapse/extraction/extractors/register_extractors.py +63 -0
- contextsynapse/extraction/extractors/text_extractor.py +65 -0
- contextsynapse/extraction/extractors/txt_extractor.py +120 -0
- contextsynapse/extraction/extractors/website_extractor.py +246 -0
- contextsynapse/extraction/fact_extractor.py +236 -0
- contextsynapse/extraction/file_manager.py +353 -0
- contextsynapse/extraction/hierarchy.py +239 -0
- contextsynapse/extraction/id_generator.py +450 -0
- contextsynapse/extraction/layout_detector.py +409 -0
- contextsynapse/extraction/llm_entity_extractor.py +301 -0
- contextsynapse/extraction/normalized_store.py +480 -0
- contextsynapse/extraction/normalizer.py +594 -0
- contextsynapse/extraction/parquet_writer.py +598 -0
- contextsynapse/extraction/post_processors/__init__.py +40 -0
- contextsynapse/extraction/post_processors/column_reorganizer.py +507 -0
- contextsynapse/extraction/ray_normalization.py +233 -0
- contextsynapse/extraction/ray_runner.py +207 -0
- contextsynapse/extraction/redis_schema_registry.py +222 -0
- contextsynapse/extraction/registry.py +204 -0
- contextsynapse/extraction/schema_loader.py +663 -0
- contextsynapse/extraction/schema_registry.py +230 -0
- contextsynapse/extraction/semantic_normalizer.py +245 -0
- contextsynapse/extraction/version_manager.py +314 -0
- contextsynapse/gateway/__init__.py +24 -0
- contextsynapse/gateway/action_emitter.py +212 -0
- contextsynapse/gateway/cost_tracker.py +508 -0
- contextsynapse/gateway/gateway.py +377 -0
- contextsynapse/gateway/policy.py +303 -0
- contextsynapse/governance/__init__.py +13 -0
- contextsynapse/governance/layer.py +513 -0
- contextsynapse/ingestion/__init__.py +15 -0
- contextsynapse/ingestion/amplifier.py +288 -0
- contextsynapse/ingestion/async_ingest.py +463 -0
- contextsynapse/ingestion/chunker.py +303 -0
- contextsynapse/ingestion/chunking.py +58 -0
- contextsynapse/ingestion/cleaner.py +190 -0
- contextsynapse/ingestion/cleanse.py +252 -0
- contextsynapse/ingestion/connectors/__init__.py +38 -0
- contextsynapse/ingestion/connectors/base.py +300 -0
- contextsynapse/ingestion/connectors/chatgpt_memory.py +247 -0
- contextsynapse/ingestion/connectors/claude_memory.py +274 -0
- contextsynapse/ingestion/connectors/sap_ingestor.py +208 -0
- contextsynapse/ingestion/content_detector.py +80 -0
- contextsynapse/ingestion/content_monitor.py +502 -0
- contextsynapse/ingestion/dedup.py +106 -0
- contextsynapse/ingestion/feed.py +640 -0
- contextsynapse/ingestion/filters.py +461 -0
- contextsynapse/ingestion/graph_builder.py +705 -0
- contextsynapse/ingestion/input_classifier.py +307 -0
- contextsynapse/ingestion/job_manager.py +571 -0
- contextsynapse/ingestion/llm_extractor.py +610 -0
- contextsynapse/ingestion/orchestrator.py +116 -0
- contextsynapse/ingestion/parsers/__init__.py +19 -0
- contextsynapse/ingestion/parsers/graph_parser_registry.py +103 -0
- contextsynapse/ingestion/parsers/graphml_parser.py +141 -0
- contextsynapse/ingestion/parsers/jsonld_parser.py +171 -0
- contextsynapse/ingestion/parsers/rdf_parser.py +150 -0
- contextsynapse/ingestion/pipeline_context.py +228 -0
- contextsynapse/ingestion/pipeline_store.py +1195 -0
- contextsynapse/ingestion/queue.py +133 -0
- contextsynapse/ingestion/reprocess.py +179 -0
- contextsynapse/ingestion/scenario_router.py +224 -0
- contextsynapse/ingestion/schema_extractor.py +759 -0
- contextsynapse/ingestion/schema_validator.py +274 -0
- contextsynapse/ingestion/sdlc_ingest.py +87 -0
- contextsynapse/ingestion/smart_ingest.py +2451 -0
- contextsynapse/ingestion/source_connector.py +171 -0
- contextsynapse/ingestion/stage_executor.py +2095 -0
- contextsynapse/ingestion/stages/__init__.py +9 -0
- contextsynapse/ingestion/stages/tabular_to_graph.py +289 -0
- contextsynapse/ingestion/strategies.py +386 -0
- contextsynapse/ingestion/universal/__init__.py +4 -0
- contextsynapse/ingestion/universal/_operator_registry.py +59 -0
- contextsynapse/ingestion/universal/ingest_content.py +32 -0
- contextsynapse/ingestion/universal/operators/__init__.py +1 -0
- contextsynapse/ingestion/universal/operators/base.py +19 -0
- contextsynapse/ingestion/universal/operators/build_edges.py +75 -0
- contextsynapse/ingestion/universal/operators/cluster_topics.py +397 -0
- contextsynapse/ingestion/universal/operators/deduplicate.py +45 -0
- contextsynapse/ingestion/universal/operators/detect_signals.py +90 -0
- contextsynapse/ingestion/universal/operators/embed.py +80 -0
- contextsynapse/ingestion/universal/operators/extract_entities.py +253 -0
- contextsynapse/ingestion/universal/operators/extract_preferences.py +117 -0
- contextsynapse/ingestion/universal/operators/filter_content.py +69 -0
- contextsynapse/ingestion/universal/operators/index_bm25.py +52 -0
- contextsynapse/ingestion/universal/operators/infer_domains.py +69 -0
- contextsynapse/ingestion/universal/operators/link_cross_reference.py +210 -0
- contextsynapse/ingestion/universal/operators/parse_records.py +66 -0
- contextsynapse/ingestion/universal/operators/resolve_entities.py +261 -0
- contextsynapse/ingestion/universal/operators/scanners/__init__.py +16 -0
- contextsynapse/ingestion/universal/operators/scanners/edges.py +173 -0
- contextsynapse/ingestion/universal/operators/scanners/git.py +187 -0
- contextsynapse/ingestion/universal/operators/scanners/github.py +135 -0
- contextsynapse/ingestion/universal/operators/scanners/github_api.py +509 -0
- contextsynapse/ingestion/universal/operators/scanners/helpers.py +67 -0
- contextsynapse/ingestion/universal/operators/scanners/jira.py +65 -0
- contextsynapse/ingestion/universal/operators/scanners/llm_enrichment.py +82 -0
- contextsynapse/ingestion/universal/operators/scanners/repo.py +149 -0
- contextsynapse/ingestion/universal/operators/sdlc_scan.py +213 -0
- contextsynapse/ingestion/universal/operators/spec_scanner.py +149 -0
- contextsynapse/ingestion/universal/operators/store_documents.py +72 -0
- contextsynapse/ingestion/universal/operators/synthesize_cu.py +180 -0
- contextsynapse/ingestion/universal/operators/validate_gate.py +65 -0
- contextsynapse/ingestion/universal/parsers/__init__.py +5 -0
- contextsynapse/ingestion/universal/parsers/record_parser.py +203 -0
- contextsynapse/ingestion/universal/parsers/turn_parser.py +329 -0
- contextsynapse/ingestion/universal/shared_signals.py +161 -0
- contextsynapse/ingestion/universal/stage_executor.py +219 -0
- contextsynapse/ingestion/web_crawler.py +265 -0
- contextsynapse/intelligence/__init__.py +53 -0
- contextsynapse/intelligence/alerts.py +198 -0
- contextsynapse/intelligence/collector.py +655 -0
- contextsynapse/intelligence/comparison.py +198 -0
- contextsynapse/intelligence/config.py +56 -0
- contextsynapse/intelligence/conflict_detector.py +182 -0
- contextsynapse/intelligence/context_gaps.py +192 -0
- contextsynapse/intelligence/context_radar.py +135 -0
- contextsynapse/intelligence/correlation_engine.py +416 -0
- contextsynapse/intelligence/correlation_template.py +120 -0
- contextsynapse/intelligence/dedup.py +296 -0
- contextsynapse/intelligence/event_bus.py +91 -0
- contextsynapse/intelligence/feedback_loop.py +101 -0
- contextsynapse/intelligence/freshness.py +307 -0
- contextsynapse/intelligence/fundamental_feed.py +551 -0
- contextsynapse/intelligence/geo_data.py +170 -0
- contextsynapse/intelligence/geo_reference.py +112 -0
- contextsynapse/intelligence/graph_fusion.py +465 -0
- contextsynapse/intelligence/heuristics.py +176 -0
- contextsynapse/intelligence/impact_tracker.py +336 -0
- contextsynapse/intelligence/macro_indicators.py +319 -0
- contextsynapse/intelligence/ocr.py +104 -0
- contextsynapse/intelligence/persistence.py +267 -0
- contextsynapse/intelligence/pipeline_health.py +130 -0
- contextsynapse/intelligence/price_feed.py +221 -0
- contextsynapse/intelligence/rate_limiter.py +130 -0
- contextsynapse/intelligence/reactive.py +411 -0
- contextsynapse/intelligence/runtime_context.py +390 -0
- contextsynapse/intelligence/sentiment_decay.py +426 -0
- contextsynapse/intelligence/session.py +277 -0
- contextsynapse/intelligence/signal_hierarchy.py +438 -0
- contextsynapse/intelligence/signals.py +185 -0
- contextsynapse/intelligence/source_watcher.py +132 -0
- contextsynapse/intelligence/table_enricher.py +256 -0
- contextsynapse/intelligence/tagger.py +319 -0
- contextsynapse/intelligence/timeseries.py +209 -0
- contextsynapse/intelligence/tracker.py +318 -0
- contextsynapse/intelligence/watchdog.py +392 -0
- contextsynapse/intelligence/watchdog_manager.py +263 -0
- contextsynapse/intelligence/webhook_receiver.py +165 -0
- contextsynapse/intelligence/weight_learner.py +234 -0
- contextsynapse/llm/__init__.py +8 -0
- contextsynapse/llm/client.py +348 -0
- contextsynapse/llm/rate_limiter.py +166 -0
- contextsynapse/logging_config.py +2 -0
- contextsynapse/marketplace/__init__.py +7 -0
- contextsynapse/marketplace/registry.py +173 -0
- contextsynapse/mcp/__init__.py +11 -0
- contextsynapse/mcp/__main__.py +4 -0
- contextsynapse/mcp/auth_middleware.py +212 -0
- contextsynapse/mcp/connection_pool.py +128 -0
- contextsynapse/mcp/server.py +986 -0
- contextsynapse/mcp/session_context.py +67 -0
- contextsynapse/memory/__init__.py +34 -0
- contextsynapse/memory/engine.py +475 -0
- contextsynapse/memory/temporal.py +327 -0
- contextsynapse/metadata/__init__.py +12 -0
- contextsynapse/metadata/metadata_db.py +272 -0
- contextsynapse/metadata/metadata_query_tool.py +300 -0
- contextsynapse/metadata/metadata_tracker.py +425 -0
- contextsynapse/models/__init__.py +27 -0
- contextsynapse/models/embedding_service.py +360 -0
- contextsynapse/models/model_registry.py +228 -0
- contextsynapse/multiworker.py +2 -0
- contextsynapse/pipelines/__init__.py +1 -0
- contextsynapse/pipelines/executor.py +851 -0
- contextsynapse/pipelines/filters.py +189 -0
- contextsynapse/pipelines/models.py +176 -0
- contextsynapse/pipelines/scheduler.py +268 -0
- contextsynapse/playground/__init__.py +1 -0
- contextsynapse/playground/templates.py +85 -0
- contextsynapse/plugins/__init__.py +43 -0
- contextsynapse/plugins/api.py +66 -0
- contextsynapse/plugins/base.py +350 -0
- contextsynapse/plugins/domain_interface.py +508 -0
- contextsynapse/plugins/domain_loader.py +241 -0
- contextsynapse/plugins/loader.py +148 -0
- contextsynapse/plugins/registry.py +265 -0
- contextsynapse/project/__init__.py +11 -0
- contextsynapse/project/code_context.py +807 -0
- contextsynapse/project/connectors/__init__.py +4 -0
- contextsynapse/project/connectors/github_connector.py +113 -0
- contextsynapse/project/connectors/jira_connector.py +160 -0
- contextsynapse/project/graph.py +1023 -0
- contextsynapse/project/project_context.py +545 -0
- contextsynapse/project/scanner_registry.py +61 -0
- contextsynapse/project/schema_manager.py +322 -0
- contextsynapse/project/schemas/knowledge.yaml +59 -0
- contextsynapse/project/schemas/sdlc.yaml +369 -0
- contextsynapse/project/sdlc_schema.py +172 -0
- contextsynapse/project/spec_parser.py +85 -0
- contextsynapse/project/task_lock.py +181 -0
- contextsynapse/project/task_stream.py +203 -0
- contextsynapse/project/team_tools.py +537 -0
- contextsynapse/py.typed +0 -0
- contextsynapse/realtime/__init__.py +6 -0
- contextsynapse/realtime/collaboration.py +147 -0
- contextsynapse/rules/__init__.py +10 -0
- contextsynapse/rules/engine.py +116 -0
- contextsynapse/rules/evaluators/__init__.py +6 -0
- contextsynapse/rules/evaluators/aggregate.py +205 -0
- contextsynapse/rules/evaluators/custom.py +170 -0
- contextsynapse/rules/evaluators/pre_action.py +125 -0
- contextsynapse/rules/evaluators/temporal.py +129 -0
- contextsynapse/rules/loader.py +52 -0
- contextsynapse/rules/models.py +124 -0
- contextsynapse/rules/universal.py +393 -0
- contextsynapse/scheduler.py +229 -0
- contextsynapse/schema/__init__.py +42 -0
- contextsynapse/schema/compiler.py +252 -0
- contextsynapse/schema/composer.py +158 -0
- contextsynapse/schema/dedup.py +73 -0
- contextsynapse/schema/derivation.py +172 -0
- contextsynapse/schema/sdl.py +326 -0
- contextsynapse/schema/validation_gate.py +124 -0
- contextsynapse/sdk/__init__.py +63 -0
- contextsynapse/sdk/agent.py +214 -0
- contextsynapse/sdk/client.py +269 -0
- contextsynapse/sdk/exceptions.py +23 -0
- contextsynapse/sdk/models.py +78 -0
- contextsynapse/sdk/session.py +408 -0
- contextsynapse/sdk/tracked.py +218 -0
- contextsynapse/sdk/worker.py +266 -0
- contextsynapse/sdk/workspace_client.py +98 -0
- contextsynapse/sdk/ws.py +41 -0
- contextsynapse/search/__init__.py +20 -0
- contextsynapse/search/embedding_cache.py +140 -0
- contextsynapse/search/enhanced_search.py +152 -0
- contextsynapse/search/fulltext.py +130 -0
- contextsynapse/search/graph_search.py +634 -0
- contextsynapse/search/lmdb_index.py +1218 -0
- contextsynapse/search/nl_to_aiql.py +199 -0
- contextsynapse/search/rag.py +1346 -0
- contextsynapse/search/rag_cache.py +167 -0
- contextsynapse/search/reasoning_chain.py +231 -0
- contextsynapse/search/redis_search.py +207 -0
- contextsynapse/search/retrieval_quality.py +314 -0
- contextsynapse/search/semantic_query.py +455 -0
- contextsynapse/search/text_resolver.py +159 -0
- contextsynapse/search/whoosh_search.py +373 -0
- contextsynapse/security/__init__.py +17 -0
- contextsynapse/security/audit.py +297 -0
- contextsynapse/security/audit_logger.py +97 -0
- contextsynapse/security/audit_trail.py +270 -0
- contextsynapse/security/auth_unified.py +284 -0
- contextsynapse/security/auto_tagger.py +230 -0
- contextsynapse/security/data_security.py +218 -0
- contextsynapse/security/encryption.py +207 -0
- contextsynapse/security/identity.py +447 -0
- contextsynapse/security/jwt_identity.py +59 -0
- contextsynapse/security/middleware.py +336 -0
- contextsynapse/security/pii.py +233 -0
- contextsynapse/security/rbac.py +96 -0
- contextsynapse/security/rls.py +205 -0
- contextsynapse/security/sanitize.py +233 -0
- contextsynapse/security/scoped_encryption.py +131 -0
- contextsynapse/security/tenant.py +401 -0
- contextsynapse/shield/__init__.py +21 -0
- contextsynapse/shield/anomaly.py +56 -0
- contextsynapse/shield/permissions.py +99 -0
- contextsynapse/shield/profile.py +103 -0
- contextsynapse/shield/shield.py +108 -0
- contextsynapse/shield/trust_engine.py +69 -0
- contextsynapse/skills/__init__.py +14 -0
- contextsynapse/skills/engine.py +233 -0
- contextsynapse/skills/loader.py +59 -0
- contextsynapse/skills/models.py +139 -0
- contextsynapse/storage/__init__.py +7 -0
- contextsynapse/storage/cache.py +208 -0
- contextsynapse/storage/columnar_store_v2.py +178 -0
- contextsynapse/storage/csr_graph_storage.py +587 -0
- contextsynapse/storage/csr_store.py +388 -0
- contextsynapse/storage/document_store.py +491 -0
- contextsynapse/storage/hnsw_index.py +294 -0
- contextsynapse/storage/hybrid_store_v2.py +278 -0
- contextsynapse/storage/lmdb_graph_storage.py +366 -0
- contextsynapse/storage/migration.py +279 -0
- contextsynapse/storage/namespace_store.py +346 -0
- contextsynapse/storage/pure_graph_storage.py +185 -0
- contextsynapse/storage/redis_graph_adapter.py +186 -0
- contextsynapse/storage/redis_graph_storage.py +375 -0
- contextsynapse/storage/router/__init__.py +29 -0
- contextsynapse/storage/router/duckdb_store.py +398 -0
- contextsynapse/storage/router/factory.py +83 -0
- contextsynapse/storage/router/interface.py +125 -0
- contextsynapse/storage/router/postgres_store.py +339 -0
- contextsynapse/storage/router/resolver.py +192 -0
- contextsynapse/storage/router/router.py +300 -0
- contextsynapse/storage/single_file_storage.py +391 -0
- contextsynapse/storage/storage_manager.py +214 -0
- contextsynapse/storage/storage_query_optimizer.py +314 -0
- contextsynapse/storage/wal.py +359 -0
- contextsynapse/temporal/__init__.py +0 -0
- contextsynapse/temporal/storage.py +106 -0
- contextsynapse/tests/__init__.py +11 -0
- contextsynapse/tests/regression/__init__.py +1 -0
- contextsynapse/tests/regression/add_metadata.py +395 -0
- contextsynapse/tests/regression/add_skip_flags.py +85 -0
- contextsynapse/tests/regression/cases/test_basic_create_node.yaml +20 -0
- contextsynapse/tests/regression/cases/test_basic_select.yaml +21 -0
- contextsynapse/tests/regression/cases/test_blockchain_audit_trail.yaml +37 -0
- contextsynapse/tests/regression/cases/test_blockchain_audit_trail_filtered.yaml +39 -0
- contextsynapse/tests/regression/cases/test_blockchain_blocks_range.yaml +39 -0
- contextsynapse/tests/regression/cases/test_blockchain_get_block.yaml +35 -0
- contextsynapse/tests/regression/cases/test_blockchain_latest_block.yaml +35 -0
- contextsynapse/tests/regression/cases/test_blockchain_length.yaml +37 -0
- contextsynapse/tests/regression/cases/test_blockchain_merkle_root.yaml +37 -0
- contextsynapse/tests/regression/cases/test_blockchain_verify.yaml +35 -0
- contextsynapse/tests/regression/cases/test_blockchain_verify_block.yaml +35 -0
- contextsynapse/tests/regression/cases/test_create_edge.yaml +28 -0
- contextsynapse/tests/regression/cases/test_delete_edge_basic.yaml +29 -0
- contextsynapse/tests/regression/cases/test_delete_node_basic.yaml +29 -0
- contextsynapse/tests/regression/cases/test_evaluation_mrr.yaml +40 -0
- contextsynapse/tests/regression/cases/test_evaluation_ndcg.yaml +40 -0
- contextsynapse/tests/regression/cases/test_evaluation_precision.yaml +40 -0
- contextsynapse/tests/regression/cases/test_evaluation_recall.yaml +40 -0
- contextsynapse/tests/regression/cases/test_group_by_basic.yaml +56 -0
- contextsynapse/tests/regression/cases/test_match_node_basic.yaml +29 -0
- contextsynapse/tests/regression/cases/test_match_node_with_order_limit.yaml +31 -0
- contextsynapse/tests/regression/cases/test_namespace_switch.yaml +18 -0
- contextsynapse/tests/regression/cases/test_pipeline_cascaded.yaml +61 -0
- contextsynapse/tests/regression/cases/test_pipeline_fixed_size_chunking.yaml +48 -0
- contextsynapse/tests/regression/cases/test_pipeline_gpt4_chunking.yaml +54 -0
- contextsynapse/tests/regression/cases/test_pipeline_hybrid_indexing.yaml +57 -0
- contextsynapse/tests/regression/cases/test_pipeline_large_embedding.yaml +52 -0
- contextsynapse/tests/regression/cases/test_pipeline_paragraph_chunking.yaml +49 -0
- contextsynapse/tests/regression/cases/test_pipeline_recursive_chunking.yaml +47 -0
- contextsynapse/tests/regression/cases/test_pipeline_run_pipeline.yaml +56 -0
- contextsynapse/tests/regression/cases/test_pipeline_section_based_chunking.yaml +53 -0
- contextsynapse/tests/regression/cases/test_pipeline_semantic_chunking.yaml +51 -0
- contextsynapse/tests/regression/cases/test_pipeline_with_entity_extraction.yaml +57 -0
- contextsynapse/tests/regression/cases/test_pipeline_with_relationships.yaml +62 -0
- contextsynapse/tests/regression/cases/test_rag_evaluation.yaml +38 -0
- contextsynapse/tests/regression/cases/test_rag_graph_bfs_with_eval.yaml +48 -0
- contextsynapse/tests/regression/cases/test_rag_graph_centrality.yaml +40 -0
- contextsynapse/tests/regression/cases/test_rag_graph_centrality_eval.yaml +35 -0
- contextsynapse/tests/regression/cases/test_rag_graph_community.yaml +40 -0
- contextsynapse/tests/regression/cases/test_rag_graph_community_eval.yaml +35 -0
- contextsynapse/tests/regression/cases/test_rag_graph_dfs_with_eval.yaml +35 -0
- contextsynapse/tests/regression/cases/test_rag_graph_multi_hop_eval.yaml +35 -0
- contextsynapse/tests/regression/cases/test_rag_graph_path.yaml +40 -0
- contextsynapse/tests/regression/cases/test_rag_graph_search_basic.yaml +38 -0
- contextsynapse/tests/regression/cases/test_rag_graph_search_bfs.yaml +52 -0
- contextsynapse/tests/regression/cases/test_rag_graph_search_dfs.yaml +41 -0
- contextsynapse/tests/regression/cases/test_rag_graph_search_multi_hop.yaml +43 -0
- contextsynapse/tests/regression/cases/test_rag_graph_search_shortest_path.yaml +41 -0
- contextsynapse/tests/regression/cases/test_rag_graph_search_weighted.yaml +43 -0
- contextsynapse/tests/regression/cases/test_rag_graph_shortest_path_eval.yaml +35 -0
- contextsynapse/tests/regression/cases/test_rag_graph_traversal.yaml +30 -0
- contextsynapse/tests/regression/cases/test_rag_graph_weighted_eval.yaml +35 -0
- contextsynapse/tests/regression/cases/test_rag_hybrid_search.yaml +33 -0
- contextsynapse/tests/regression/cases/test_rag_hybrid_with_prompt_embedding.yaml +44 -0
- contextsynapse/tests/regression/cases/test_rag_keyword_search.yaml +32 -0
- contextsynapse/tests/regression/cases/test_rag_multi_hop_graph.yaml +32 -0
- contextsynapse/tests/regression/cases/test_rag_path_based.yaml +34 -0
- contextsynapse/tests/regression/cases/test_rag_profile_based.yaml +32 -0
- contextsynapse/tests/regression/cases/test_rag_vector_search.yaml +32 -0
- contextsynapse/tests/regression/cases/test_rag_weighted_graph.yaml +34 -0
- contextsynapse/tests/regression/cases/test_rag_weighted_hybrid.yaml +31 -0
- contextsynapse/tests/regression/cases/test_semantic_boundary_chunking.yaml +57 -0
- contextsynapse/tests/regression/cases/test_semantic_boundary_detection.yaml +33 -0
- contextsynapse/tests/regression/cases/test_semantic_hash_function.yaml +30 -0
- contextsynapse/tests/regression/cases/test_semantic_hash_with_model.yaml +31 -0
- contextsynapse/tests/regression/cases/test_tcs_ingestion_fixed_size.yaml +44 -0
- contextsynapse/tests/regression/cases/test_tcs_ingestion_recursive.yaml +46 -0
- contextsynapse/tests/regression/cases/test_tcs_ingestion_section.yaml +46 -0
- contextsynapse/tests/regression/cases/test_tcs_ingestion_semantic.yaml +44 -0
- contextsynapse/tests/regression/cases/test_time_travel_as_of.yaml +35 -0
- contextsynapse/tests/regression/cases/test_time_travel_at_commit.yaml +33 -0
- contextsynapse/tests/regression/cases/test_time_travel_at_timestamp.yaml +33 -0
- contextsynapse/tests/regression/cases/test_time_travel_for_system_time_all.yaml +37 -0
- contextsynapse/tests/regression/cases/test_time_travel_versions_between.yaml +39 -0
- contextsynapse/tests/regression/cases/test_traverse_basic.yaml +31 -0
- contextsynapse/tests/regression/cases/test_traverse_max_depth.yaml +34 -0
- contextsynapse/tests/regression/cases/test_update_edge_basic.yaml +29 -0
- contextsynapse/tests/regression/evaluation_metrics.py +227 -0
- contextsynapse/tests/regression/regression_runner.py +1081 -0
- contextsynapse/tests/regression/setup_regression_data.py +212 -0
- contextsynapse/tests/regression/test_basic_only.py +84 -0
- contextsynapse/tests/regression/test_namespace_creation.py +29 -0
- contextsynapse/tests/regression/test_single_fix.py +61 -0
- contextsynapse/tests/regression/test_single_query.py +20 -0
- contextsynapse/tests/regression/validate_test_syntax.py +179 -0
- contextsynapse/tests/test_advanced_features.py +347 -0
- contextsynapse/tests/test_aiql_summary.py +283 -0
- contextsynapse/tests/test_all_aiql_queries.py +948 -0
- contextsynapse/tests/test_all_create_queries.py +213 -0
- contextsynapse/tests/test_api_vs_native.py +280 -0
- contextsynapse/tests/test_chunking_dedup.py +199 -0
- contextsynapse/tests/test_connectors.py +171 -0
- contextsynapse/tests/test_edges_and_match.py +202 -0
- contextsynapse/tests/test_extraction_pipeline_integration.py +581 -0
- contextsynapse/tests/test_name_property.py +224 -0
- contextsynapse/tests/test_node_edge_metadata.py +250 -0
- contextsynapse/tests/test_playground_conn.py +114 -0
- contextsynapse/tests/test_query_cache.py +213 -0
- contextsynapse/tests/test_source_policy_auth.py +348 -0
- contextsynapse/tests/test_temporal_and_domain.py +224 -0
- contextsynapse/tests/test_time_travel_e2e.py +571 -0
- contextsynapse/tests/test_traversal_and_aggregation.py +275 -0
- contextsynapse/tools/__init__.py +36 -0
- contextsynapse/tools/a2a_tools.py +106 -0
- contextsynapse/tools/cognition_tools.py +118 -0
- contextsynapse/tools/context.py +905 -0
- contextsynapse/tools/formatting.py +92 -0
- contextsynapse/tools/gateway_tools.py +186 -0
- contextsynapse/tools/graph.py +1700 -0
- contextsynapse/tools/intelligence.py +235 -0
- contextsynapse/tools/memory.py +118 -0
- contextsynapse/tools/registry.py +373 -0
- contextsynapse/tools/shield_tools.py +159 -0
- contextsynapse/tools/tasks.py +341 -0
- contextsynapse/tools/workspace_tools.py +124 -0
- contextsynapse/utils/__init__.py +15 -0
- contextsynapse/utils/config_loader.py +198 -0
- contextsynapse/utils/env_loader.py +156 -0
- contextsynapse/utils/file_utils.py +288 -0
- contextsynapse/utils/logging_optimizer.py +119 -0
- contextsynapse/vector/__init__.py +30 -0
- contextsynapse/vector/chroma_vector_store.py +152 -0
- contextsynapse/vector/custom_vector_store.py +537 -0
- contextsynapse/vector/faiss_vector_store.py +296 -0
- contextsynapse/vector/qdrant_vector_store.py +163 -0
- contextsynapse/vector/vector_db.py +953 -0
- contextsynapse/vector/vector_db_manager.py +197 -0
- contextsynapse/workspace/__init__.py +27 -0
- contextsynapse/workspace/base.py +94 -0
- contextsynapse/workspace/git.py +228 -0
- contextsynapse/workspace/github.py +78 -0
- contextsynapse/workspace/local.py +73 -0
- contextsynapse/workspace/tools.py +222 -0
- contextsynapse-1.0.0.dist-info/METADATA +847 -0
- contextsynapse-1.0.0.dist-info/RECORD +776 -0
- contextsynapse-1.0.0.dist-info/WHEEL +5 -0
- contextsynapse-1.0.0.dist-info/entry_points.txt +4 -0
- contextsynapse-1.0.0.dist-info/licenses/LICENSE +200 -0
- contextsynapse-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1218 @@
|
|
|
1
|
+
"""LMDB-backed keyword and BM25 index for microsecond search.
|
|
2
|
+
|
|
3
|
+
Replaces the in-memory keyword index (60s rebuild cycle) and Whoosh BM25
|
|
4
|
+
with persistent, memory-mapped indexes that survive restarts and update
|
|
5
|
+
incrementally.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
idx = LMDBIndex("contextcore_data/lmdb_index/my_graph")
|
|
9
|
+
idx.index_node(node_id, label, {"name": "Netanyahu", "statement": "..."})
|
|
10
|
+
results = idx.search("netanyahu", limit=10)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import math
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import time
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Dict, List, Optional, Set, Tuple
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
import lmdb
|
|
26
|
+
except ImportError:
|
|
27
|
+
lmdb = None
|
|
28
|
+
logger.warning("lmdb not installed — falling back to in-memory index")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# Fields to index and their weights
|
|
32
|
+
_FIELD_WEIGHTS = {"name": 2.0, "title": 2.0, "content": 1.0, "statement": 1.5, "description": 1.0}
|
|
33
|
+
|
|
34
|
+
# Labels whose nodes are meaningful search results (used in hybrid_search neighbour expansion)
|
|
35
|
+
_CONTENT_LABELS: frozenset = frozenset({
|
|
36
|
+
"Person", "Organization", "Location", "Event",
|
|
37
|
+
"Fact", "Passage", "Finding", "Insight",
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
# Labels to exclude from indexing
|
|
41
|
+
_NOISE_LABELS = frozenset({
|
|
42
|
+
# Agent mechanics — not knowledge
|
|
43
|
+
"AgentThought", "AgentAction", "AgentMessage", "AgentPresence",
|
|
44
|
+
"Task", "Action",
|
|
45
|
+
# Conversation structure — search entities/topics/signals, not raw turns
|
|
46
|
+
"Turn", "Session",
|
|
47
|
+
# System/experiment infrastructure
|
|
48
|
+
"ExperimentRun", "ExperimentScore", "PipelineRun",
|
|
49
|
+
"VectorIndex", "BM25Index", "ContextRef",
|
|
50
|
+
"Context", "Project", "ContextIntelligence",
|
|
51
|
+
"CodeBase", "SystemStore", "UserStore", "WebStore",
|
|
52
|
+
"GeneratedStore", "MemoryStore", "ArtifactStore", "ToolStore",
|
|
53
|
+
"KnowledgeBase",
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
# Stop words — skip these terms
|
|
57
|
+
_STOP_WORDS = frozenset({
|
|
58
|
+
"the", "a", "an", "is", "are", "was", "were", "be", "been", "being",
|
|
59
|
+
"have", "has", "had", "do", "does", "did", "will", "would", "shall",
|
|
60
|
+
"should", "may", "might", "can", "could", "of", "in", "to", "for",
|
|
61
|
+
"with", "on", "at", "by", "from", "as", "into", "through", "during",
|
|
62
|
+
"and", "or", "but", "not", "no", "if", "then", "than", "that", "this",
|
|
63
|
+
"it", "its", "he", "she", "his", "her", "we", "they", "them", "our",
|
|
64
|
+
"said", "also", "one", "two", "who", "what", "when", "where",
|
|
65
|
+
"how", "all", "each", "every", "both", "few", "more", "most", "other",
|
|
66
|
+
"some", "such", "only", "own", "same", "so", "very", "just", "about",
|
|
67
|
+
"https", "http", "www", "com", "org", "html", "htm",
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Pre-compiled tokenization patterns (module-level for zero per-call overhead)
|
|
72
|
+
# Splits on whitespace and common punctuation boundaries
|
|
73
|
+
_PUNCT_RE = re.compile(r"[\s\-_/.,;:!?()\[\]{}\"|]+")
|
|
74
|
+
# Inserts a split at camelCase boundaries:
|
|
75
|
+
# lower→UPPER: "graphNode" → "graph Node"
|
|
76
|
+
# UPPER sequence → "UIContext" → "UI Context"
|
|
77
|
+
_CAMEL_RE = re.compile(r"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
|
|
78
|
+
|
|
79
|
+
_VOWELS = frozenset("aeiou")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _stem(word: str) -> str:
|
|
83
|
+
"""Minimal suffix-stripping stemmer (English). Zero dependencies.
|
|
84
|
+
|
|
85
|
+
Handles the highest-value, lowest-error suffix rules only:
|
|
86
|
+
-ies → -y : "queries" → "query"
|
|
87
|
+
-ing : "searching" → "search", "processing" → "process"
|
|
88
|
+
-ed : "indexed" → "index", "processed" → "process"
|
|
89
|
+
-s : "nodes" → "node", "graphs" → "graph"
|
|
90
|
+
(blocked when stem ends in "ss": "class", "process")
|
|
91
|
+
|
|
92
|
+
Deliberately omits doubled-consonant undoing to avoid "process" → "proces"
|
|
93
|
+
false-positives. "running" → "runn" is an acceptable imprecision for a
|
|
94
|
+
knowledge-graph workload where uninflected root queries are rare.
|
|
95
|
+
"""
|
|
96
|
+
n = len(word)
|
|
97
|
+
if n <= 3:
|
|
98
|
+
return word
|
|
99
|
+
if word.endswith("ies") and n > 4:
|
|
100
|
+
return word[:-3] + "y"
|
|
101
|
+
if word.endswith("ing") and n > 5:
|
|
102
|
+
return word[:-3]
|
|
103
|
+
if word.endswith("ed") and n > 4:
|
|
104
|
+
return word[:-2]
|
|
105
|
+
if word.endswith("s") and not word.endswith("ss") and n > 3:
|
|
106
|
+
return word[:-1]
|
|
107
|
+
return word
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _tokenize(text: str, max_token_len: int = 100) -> List[str]:
|
|
111
|
+
"""Tokenize text into stemmed lowercase terms, skipping stop words.
|
|
112
|
+
|
|
113
|
+
Pipeline:
|
|
114
|
+
1. Split camelCase on original text ("GraphNode" → "Graph Node").
|
|
115
|
+
2. Lowercase and split on whitespace + punctuation.
|
|
116
|
+
3. Filter by length and stop words.
|
|
117
|
+
4. Stem each token (-ing/-ed/-s/-ies).
|
|
118
|
+
5. Re-filter stemmed form (stem may produce a stop word or be too short).
|
|
119
|
+
"""
|
|
120
|
+
# Step 1: camelCase split on original casing, then lowercase
|
|
121
|
+
text = _CAMEL_RE.sub(" ", text).lower()
|
|
122
|
+
result = []
|
|
123
|
+
for t in _PUNCT_RE.split(text):
|
|
124
|
+
if not (2 <= len(t) <= max_token_len) or t in _STOP_WORDS:
|
|
125
|
+
continue
|
|
126
|
+
stemmed = _stem(t)
|
|
127
|
+
if 2 <= len(stemmed) <= max_token_len and stemmed not in _STOP_WORDS:
|
|
128
|
+
result.append(stemmed)
|
|
129
|
+
return result
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _bigrams(tokens: List[str]) -> List[str]:
|
|
133
|
+
"""Generate consecutive token pair strings from a token list.
|
|
134
|
+
|
|
135
|
+
Pairs are joined with '__' (double underscore) — a separator that
|
|
136
|
+
cannot appear in real tokens since _PUNCT_RE splits on underscores.
|
|
137
|
+
Stored in the same 'terms' LMDB database as unigrams; their low df
|
|
138
|
+
(rare occurrence) gives them high IDF, boosting phrase precision.
|
|
139
|
+
"""
|
|
140
|
+
return [f"{tokens[i]}__{tokens[i + 1]}" for i in range(len(tokens) - 1)]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _char_trigrams(token: str) -> List[str]:
|
|
144
|
+
"""Generate character trigrams from a token string.
|
|
145
|
+
|
|
146
|
+
Used for typo-tolerant fuzzy search: tokens with ≥50% shared
|
|
147
|
+
trigrams are considered likely matches for the same term despite
|
|
148
|
+
spelling errors.
|
|
149
|
+
|
|
150
|
+
Examples:
|
|
151
|
+
"graph" → ["gra", "rap", "aph"]
|
|
152
|
+
"ab" → ["ab"] (too short, return as-is)
|
|
153
|
+
"abc" → ["abc"]
|
|
154
|
+
"""
|
|
155
|
+
if len(token) < 3:
|
|
156
|
+
return [token]
|
|
157
|
+
return [token[i:i + 3] for i in range(len(token) - 2)]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _compute_node_terms(
|
|
161
|
+
label: str,
|
|
162
|
+
props: Dict[str, Any],
|
|
163
|
+
) -> Tuple[Dict[str, float], List[str], bytes]:
|
|
164
|
+
"""Compute BM25 terms, term list, and node metadata bytes for one node.
|
|
165
|
+
|
|
166
|
+
Returns (terms, term_list, node_data):
|
|
167
|
+
- terms: {token: weight} — accumulated field-weighted token weights,
|
|
168
|
+
including bigram phrase tokens (joined with '__')
|
|
169
|
+
- term_list: list of token strings (same keys as terms, includes bigrams)
|
|
170
|
+
- node_data: JSON-encoded node metadata bytes ready for LMDB storage
|
|
171
|
+
Returns ({}, [], b"") for noise labels so callers can skip.
|
|
172
|
+
|
|
173
|
+
Called by both index_node (in-memory path) and index_batch (LMDB path)
|
|
174
|
+
to guarantee identical term computation in both paths.
|
|
175
|
+
"""
|
|
176
|
+
if label in _NOISE_LABELS:
|
|
177
|
+
return {}, [], b""
|
|
178
|
+
|
|
179
|
+
# Auto-resolve thin nodes with _ref pointers
|
|
180
|
+
if props.get("_ref", "").startswith("duckdb:"):
|
|
181
|
+
try:
|
|
182
|
+
from contextsynapse.storage.router import get_content_resolver
|
|
183
|
+
node_id = props.get("id", "")
|
|
184
|
+
resolved_text = get_content_resolver().get_text(node_id) if node_id else ""
|
|
185
|
+
if resolved_text:
|
|
186
|
+
props = {**props, "content": resolved_text}
|
|
187
|
+
except Exception:
|
|
188
|
+
pass
|
|
189
|
+
|
|
190
|
+
name = props.get("name", "")
|
|
191
|
+
snippet = (
|
|
192
|
+
props.get("statement") or props.get("content") or props.get("text")
|
|
193
|
+
or props.get("description") or name
|
|
194
|
+
)[:200]
|
|
195
|
+
created_at = props.get("_created_at", "")
|
|
196
|
+
updated_at = props.get("_updated_at", "")
|
|
197
|
+
|
|
198
|
+
terms: Dict[str, float] = {}
|
|
199
|
+
for field, weight in _FIELD_WEIGHTS.items():
|
|
200
|
+
val = str(props.get(field, ""))
|
|
201
|
+
if not val:
|
|
202
|
+
continue
|
|
203
|
+
field_tokens = _tokenize(val)
|
|
204
|
+
for term in field_tokens:
|
|
205
|
+
terms[term] = terms.get(term, 0) + weight
|
|
206
|
+
# Phrase signals: consecutive token pairs with boosted weight
|
|
207
|
+
for bigram in _bigrams(field_tokens):
|
|
208
|
+
terms[bigram] = terms.get(bigram, 0) + weight * 1.5
|
|
209
|
+
|
|
210
|
+
# term_count counts only unigrams — bigrams must not inflate BM25 dl
|
|
211
|
+
unigram_count = sum(1 for t in terms if "__" not in t)
|
|
212
|
+
term_list = list(terms.keys())
|
|
213
|
+
|
|
214
|
+
node_data = json.dumps({
|
|
215
|
+
"label": label,
|
|
216
|
+
"name": name[:120],
|
|
217
|
+
"snippet": snippet,
|
|
218
|
+
"_created_at": created_at,
|
|
219
|
+
"_updated_at": updated_at,
|
|
220
|
+
"term_count": unigram_count, # BM25 dl: unigrams only
|
|
221
|
+
}).encode()
|
|
222
|
+
|
|
223
|
+
return terms, term_list, node_data
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# Reserved key in the nodes DB for corpus-level BM25 statistics.
|
|
227
|
+
# Tilde prefix sorts after all hex UUID characters — won't collide.
|
|
228
|
+
_CORPUS_STATS_KEY = b"~corpus_stats"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class LMDBIndex:
|
|
232
|
+
"""Persistent keyword + BM25 index backed by LMDB.
|
|
233
|
+
|
|
234
|
+
Two LMDB databases in one environment:
|
|
235
|
+
- ``terms``: term → JSON list of (node_id, weight) pairs
|
|
236
|
+
- ``nodes``: node_id → JSON {label, name, snippet}
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
def __init__(self, path: str, map_size: int = 256 * 1024 * 1024):
|
|
240
|
+
"""Open or create the index at ``path``.
|
|
241
|
+
|
|
242
|
+
Parameters
|
|
243
|
+
----------
|
|
244
|
+
path : str
|
|
245
|
+
Directory for the LMDB environment.
|
|
246
|
+
map_size : int
|
|
247
|
+
Max DB size in bytes (default 256MB, auto-grows on write).
|
|
248
|
+
"""
|
|
249
|
+
import threading as _threading_local
|
|
250
|
+
self._path = path
|
|
251
|
+
self._map_size = map_size
|
|
252
|
+
self._env = None
|
|
253
|
+
self._local = _threading_local.local() # per-thread state (e.g. grow_depth counter)
|
|
254
|
+
|
|
255
|
+
if lmdb is None:
|
|
256
|
+
logger.debug("[LMDB] lmdb not installed — using in-memory fallback")
|
|
257
|
+
self._mem_terms: Dict[str, List[Tuple[str, float]]] = {}
|
|
258
|
+
self._mem_nodes: Dict[str, Dict] = {}
|
|
259
|
+
self._mem_node_terms: Dict[str, List[str]] = {} # reverse index: node_id → [terms]
|
|
260
|
+
self._mem_corpus_stats: Dict[str, int] = {"total_term_count": 0, "doc_count": 0}
|
|
261
|
+
return
|
|
262
|
+
|
|
263
|
+
Path(path).mkdir(parents=True, exist_ok=True)
|
|
264
|
+
try:
|
|
265
|
+
self._env = lmdb.open(path, map_size=map_size, max_dbs=7)
|
|
266
|
+
# Pre-open named databases (must be done in a write txn)
|
|
267
|
+
with self._env.begin(write=True) as txn:
|
|
268
|
+
self._terms_db_handle = self._env.open_db(b"terms", txn=txn, create=True)
|
|
269
|
+
self._nodes_db_handle = self._env.open_db(b"nodes", txn=txn, create=True)
|
|
270
|
+
self._passages_db_handle = self._env.open_db(b"passages", txn=txn, create=True) # node_id → full text
|
|
271
|
+
self._edges_db_handle = self._env.open_db(b"edges", txn=txn, create=True) # node_id → [{target, label, name}]
|
|
272
|
+
self._neighbors_db_handle = self._env.open_db(b"neighbors", txn=txn, create=True) # node_id → [similar_ids] (semantic)
|
|
273
|
+
self._node_terms_db_handle = self._env.open_db(b"node_terms", txn=txn, create=True) # reverse: node_id → [terms]
|
|
274
|
+
self._trigrams_db_handle = self._env.open_db(b"trigrams", txn=txn, create=True)
|
|
275
|
+
except Exception as e:
|
|
276
|
+
logger.warning("[LMDB] Failed to open %s: %s — using in-memory", path, e)
|
|
277
|
+
self._env = None
|
|
278
|
+
self._trigrams_db_handle = None
|
|
279
|
+
self._mem_terms = {}
|
|
280
|
+
self._mem_nodes = {}
|
|
281
|
+
self._mem_node_terms = {}
|
|
282
|
+
self._mem_corpus_stats = {"total_term_count": 0, "doc_count": 0}
|
|
283
|
+
|
|
284
|
+
def _terms_db(self, txn=None):
|
|
285
|
+
return self._terms_db_handle
|
|
286
|
+
|
|
287
|
+
def _nodes_db(self, txn=None):
|
|
288
|
+
return self._nodes_db_handle
|
|
289
|
+
|
|
290
|
+
def _node_terms_db(self, txn=None):
|
|
291
|
+
return self._node_terms_db_handle
|
|
292
|
+
|
|
293
|
+
def _trigrams_db(self, txn=None):
|
|
294
|
+
return self._trigrams_db_handle
|
|
295
|
+
|
|
296
|
+
# ── Write ──────────────────────────────────────────────────
|
|
297
|
+
|
|
298
|
+
def index_node(self, node_id: str, label: str, props: Dict[str, Any]):
|
|
299
|
+
"""Index a single node. Call after node creation or update."""
|
|
300
|
+
terms, term_list, node_data = _compute_node_terms(label, props)
|
|
301
|
+
if not node_data: # noise label — _compute_node_terms returned empty
|
|
302
|
+
return
|
|
303
|
+
|
|
304
|
+
if not self._env:
|
|
305
|
+
# In-memory fallback
|
|
306
|
+
old = self._mem_nodes.get(node_id)
|
|
307
|
+
if old:
|
|
308
|
+
# Re-index: subtract old contribution from corpus stats
|
|
309
|
+
self._mem_corpus_stats["total_term_count"] -= old.get("term_count", 0)
|
|
310
|
+
self._mem_corpus_stats["doc_count"] = max(0, self._mem_corpus_stats["doc_count"] - 1)
|
|
311
|
+
# Prune stale terms: remove node from posting lists it no longer belongs to
|
|
312
|
+
old_terms = set(self._mem_node_terms.get(node_id, []))
|
|
313
|
+
stale_terms = old_terms - set(terms.keys())
|
|
314
|
+
for stale_term in stale_terms:
|
|
315
|
+
if stale_term in self._mem_terms:
|
|
316
|
+
self._mem_terms[stale_term] = [
|
|
317
|
+
(nid, w) for nid, w in self._mem_terms[stale_term] if nid != node_id
|
|
318
|
+
]
|
|
319
|
+
if not self._mem_terms[stale_term]:
|
|
320
|
+
del self._mem_terms[stale_term]
|
|
321
|
+
self._mem_nodes[node_id] = json.loads(node_data)
|
|
322
|
+
self._mem_node_terms[node_id] = term_list # reverse index
|
|
323
|
+
self._mem_corpus_stats["total_term_count"] += sum(1 for t in term_list if "__" not in t)
|
|
324
|
+
self._mem_corpus_stats["doc_count"] += 1
|
|
325
|
+
for term, weight in terms.items():
|
|
326
|
+
if term not in self._mem_terms:
|
|
327
|
+
self._mem_terms[term] = []
|
|
328
|
+
# Use dict for O(1) lookup/update, then convert back to list
|
|
329
|
+
postings_dict = {nid: w for nid, w in self._mem_terms[term]}
|
|
330
|
+
postings_dict[node_id] = weight
|
|
331
|
+
self._mem_terms[term] = list(postings_dict.items())
|
|
332
|
+
return
|
|
333
|
+
|
|
334
|
+
# LMDB write — delegate to shared helper, handle map-full here
|
|
335
|
+
try:
|
|
336
|
+
with self._env.begin(write=True) as txn:
|
|
337
|
+
self._write_node_to_txn(txn, node_id, node_data, terms, term_list)
|
|
338
|
+
except lmdb.MapFullError:
|
|
339
|
+
# Auto-grow and retry (bounded to prevent infinite recursion).
|
|
340
|
+
# _local.grow_depth is per-thread so concurrent writers don't
|
|
341
|
+
# interfere with each other's retry count.
|
|
342
|
+
depth = getattr(self._local, 'grow_depth', 0)
|
|
343
|
+
if depth >= 4:
|
|
344
|
+
logger.warning("[LMDB] map full after %d grow attempts, giving up", depth)
|
|
345
|
+
return
|
|
346
|
+
self._local.grow_depth = depth + 1
|
|
347
|
+
self._map_size *= 2
|
|
348
|
+
self._env.set_mapsize(self._map_size)
|
|
349
|
+
self.index_node(node_id, label, props)
|
|
350
|
+
self._local.grow_depth = max(0, getattr(self._local, 'grow_depth', 1) - 1)
|
|
351
|
+
|
|
352
|
+
def _write_node_to_txn(
|
|
353
|
+
self,
|
|
354
|
+
txn: Any,
|
|
355
|
+
node_id: str,
|
|
356
|
+
node_data: bytes,
|
|
357
|
+
terms: Dict[str, float],
|
|
358
|
+
term_list: List[str],
|
|
359
|
+
) -> None:
|
|
360
|
+
"""Write one node's index data into an open LMDB write transaction.
|
|
361
|
+
|
|
362
|
+
Shared by index_node (single-node txn) and index_batch (batch txn)
|
|
363
|
+
so that corpus stats, stale-term pruning, and posting-list updates
|
|
364
|
+
are identical in both paths.
|
|
365
|
+
"""
|
|
366
|
+
terms_db = self._terms_db()
|
|
367
|
+
nodes_db = self._nodes_db()
|
|
368
|
+
node_terms_db = self._node_terms_db()
|
|
369
|
+
|
|
370
|
+
# Update corpus stats (subtract old term count first on re-index)
|
|
371
|
+
stats_raw = txn.get(_CORPUS_STATS_KEY, db=nodes_db)
|
|
372
|
+
corpus = json.loads(stats_raw) if stats_raw else {"total_term_count": 0, "doc_count": 0}
|
|
373
|
+
old_node_raw = txn.get(node_id.encode(), db=nodes_db)
|
|
374
|
+
if old_node_raw:
|
|
375
|
+
try:
|
|
376
|
+
old_node = json.loads(old_node_raw)
|
|
377
|
+
corpus["total_term_count"] -= old_node.get("term_count", 0)
|
|
378
|
+
corpus["doc_count"] = max(0, corpus["doc_count"] - 1)
|
|
379
|
+
except Exception:
|
|
380
|
+
pass
|
|
381
|
+
corpus["total_term_count"] += sum(1 for t in term_list if "__" not in t)
|
|
382
|
+
corpus["doc_count"] += 1
|
|
383
|
+
txn.put(_CORPUS_STATS_KEY, json.dumps(corpus).encode(), db=nodes_db)
|
|
384
|
+
|
|
385
|
+
# Store node metadata (includes term_count for BM25 dl)
|
|
386
|
+
txn.put(node_id.encode(), node_data, db=nodes_db)
|
|
387
|
+
|
|
388
|
+
# Prune stale posting-list entries for terms that no longer apply
|
|
389
|
+
old_term_list_raw = txn.get(node_id.encode(), db=node_terms_db)
|
|
390
|
+
if old_term_list_raw:
|
|
391
|
+
try:
|
|
392
|
+
old_terms = set(json.loads(old_term_list_raw))
|
|
393
|
+
stale_terms = old_terms - set(term_list)
|
|
394
|
+
for stale_term in stale_terms:
|
|
395
|
+
stale_key = stale_term.encode()
|
|
396
|
+
existing = txn.get(stale_key, db=terms_db)
|
|
397
|
+
if existing:
|
|
398
|
+
postings = [[nid, w] for nid, w in json.loads(existing) if nid != node_id]
|
|
399
|
+
if postings:
|
|
400
|
+
txn.put(stale_key, json.dumps(postings).encode(), db=terms_db)
|
|
401
|
+
else:
|
|
402
|
+
txn.delete(stale_key, db=terms_db)
|
|
403
|
+
except Exception:
|
|
404
|
+
pass # stale-term pruning must never block indexing
|
|
405
|
+
|
|
406
|
+
# Store reverse index: node_id → [terms] for O(K) delete
|
|
407
|
+
txn.put(node_id.encode(), json.dumps(term_list).encode(), db=node_terms_db)
|
|
408
|
+
|
|
409
|
+
# Update inverted index for each term — O(1) update via dict
|
|
410
|
+
for term, weight in terms.items():
|
|
411
|
+
key = term.encode()
|
|
412
|
+
existing = txn.get(key, db=terms_db)
|
|
413
|
+
if existing:
|
|
414
|
+
postings_dict = {nid: w for nid, w in json.loads(existing)}
|
|
415
|
+
postings_dict[node_id] = weight
|
|
416
|
+
postings = [[nid, w] for nid, w in postings_dict.items()]
|
|
417
|
+
else:
|
|
418
|
+
postings = [[node_id, weight]]
|
|
419
|
+
txn.put(key, json.dumps(postings).encode(), db=terms_db)
|
|
420
|
+
|
|
421
|
+
# Trigram index: character 3-grams of each unigram token → node_id membership
|
|
422
|
+
# Used by fuzzy_candidates() for typo-tolerant search.
|
|
423
|
+
trigrams_db = self._trigrams_db()
|
|
424
|
+
if trigrams_db is not None:
|
|
425
|
+
written_trigrams: Set[str] = set()
|
|
426
|
+
for term in term_list:
|
|
427
|
+
if "__" in term:
|
|
428
|
+
continue # skip bigrams — trigrams index unigrams only
|
|
429
|
+
for tg in _char_trigrams(term):
|
|
430
|
+
if tg in written_trigrams:
|
|
431
|
+
continue
|
|
432
|
+
written_trigrams.add(tg)
|
|
433
|
+
tg_key = tg.encode()
|
|
434
|
+
existing_raw = txn.get(tg_key, db=trigrams_db)
|
|
435
|
+
node_set: List[str] = json.loads(existing_raw) if existing_raw else []
|
|
436
|
+
if node_id not in node_set:
|
|
437
|
+
node_set.append(node_id)
|
|
438
|
+
txn.put(tg_key, json.dumps(node_set).encode(), db=trigrams_db)
|
|
439
|
+
|
|
440
|
+
def index_batch(self, nodes: list):
|
|
441
|
+
"""Index multiple nodes in a single LMDB transaction (N× faster than N calls).
|
|
442
|
+
|
|
443
|
+
Pre-computes all node data outside the transaction to minimise lock
|
|
444
|
+
hold time, then writes everything in one atomic commit. Falls back
|
|
445
|
+
to per-node indexing on MapFullError (map grow + retry).
|
|
446
|
+
"""
|
|
447
|
+
if not self._env:
|
|
448
|
+
# In-memory path has no transaction overhead — delegate normally
|
|
449
|
+
for n in nodes:
|
|
450
|
+
node_id = n.get("id", "")
|
|
451
|
+
label = n.get("label", "")
|
|
452
|
+
props = n.get("properties", {})
|
|
453
|
+
if node_id and label:
|
|
454
|
+
self.index_node(node_id, label, props)
|
|
455
|
+
return
|
|
456
|
+
|
|
457
|
+
# Pre-compute outside the transaction to minimise write-lock hold time
|
|
458
|
+
batch: List[Tuple[str, bytes, Dict[str, float], List[str]]] = []
|
|
459
|
+
for n in nodes:
|
|
460
|
+
node_id = n.get("id", "")
|
|
461
|
+
label = n.get("label", "")
|
|
462
|
+
props = n.get("properties", {})
|
|
463
|
+
if not node_id or not label:
|
|
464
|
+
continue
|
|
465
|
+
terms, term_list, node_data = _compute_node_terms(label, props)
|
|
466
|
+
if not node_data: # noise label
|
|
467
|
+
continue
|
|
468
|
+
batch.append((node_id, node_data, terms, term_list))
|
|
469
|
+
|
|
470
|
+
if not batch:
|
|
471
|
+
return
|
|
472
|
+
|
|
473
|
+
try:
|
|
474
|
+
with self._env.begin(write=True) as txn:
|
|
475
|
+
for node_id, node_data, terms, term_list in batch:
|
|
476
|
+
self._write_node_to_txn(txn, node_id, node_data, terms, term_list)
|
|
477
|
+
except lmdb.MapFullError:
|
|
478
|
+
# Grow map and fall back to per-node on map-full (rare)
|
|
479
|
+
self._map_size *= 2
|
|
480
|
+
self._env.set_mapsize(self._map_size)
|
|
481
|
+
for n in nodes:
|
|
482
|
+
node_id = n.get("id", "")
|
|
483
|
+
label = n.get("label", "")
|
|
484
|
+
props = n.get("properties", {})
|
|
485
|
+
if node_id and label:
|
|
486
|
+
self.index_node(node_id, label, props)
|
|
487
|
+
|
|
488
|
+
# ── Read ───────────────────────────────────────────────────
|
|
489
|
+
|
|
490
|
+
def search(self, query: str, limit: int = 10, label_filter: str = "") -> List[Dict]:
|
|
491
|
+
"""Search the index. Returns list of {node_id, label, name, snippet, score}."""
|
|
492
|
+
query_terms = list(dict.fromkeys(_tokenize(query))) # deduplicate, preserve order
|
|
493
|
+
if not query_terms:
|
|
494
|
+
return []
|
|
495
|
+
|
|
496
|
+
scores: Dict[str, float] = {}
|
|
497
|
+
|
|
498
|
+
if not self._env:
|
|
499
|
+
# In-memory fallback
|
|
500
|
+
for term in query_terms:
|
|
501
|
+
for node_id, weight in self._mem_terms.get(term, []):
|
|
502
|
+
scores[node_id] = scores.get(node_id, 0) + weight
|
|
503
|
+
results = []
|
|
504
|
+
for nid, score in sorted(scores.items(), key=lambda x: -x[1])[:limit * 2]:
|
|
505
|
+
node = self._mem_nodes.get(nid, {})
|
|
506
|
+
if label_filter and node.get("label") != label_filter:
|
|
507
|
+
continue
|
|
508
|
+
results.append({
|
|
509
|
+
"node_id": nid, "label": node.get("label", ""),
|
|
510
|
+
"name": node.get("name", ""), "snippet": node.get("snippet", ""),
|
|
511
|
+
"score": round(score, 3),
|
|
512
|
+
})
|
|
513
|
+
if len(results) >= limit:
|
|
514
|
+
break
|
|
515
|
+
return results
|
|
516
|
+
|
|
517
|
+
# LMDB read — no locks on readers
|
|
518
|
+
try:
|
|
519
|
+
with self._env.begin() as txn:
|
|
520
|
+
terms_db = self._terms_db()
|
|
521
|
+
nodes_db = self._nodes_db()
|
|
522
|
+
|
|
523
|
+
# Aggregate term scores
|
|
524
|
+
for term in query_terms:
|
|
525
|
+
raw = txn.get(term.encode(), db=terms_db)
|
|
526
|
+
if raw:
|
|
527
|
+
for nid, weight in json.loads(raw):
|
|
528
|
+
scores[nid] = scores.get(nid, 0) + weight
|
|
529
|
+
|
|
530
|
+
# Resolve top-k nodes (deduplicated by node_id)
|
|
531
|
+
results = []
|
|
532
|
+
seen_ids: Set[str] = set()
|
|
533
|
+
for nid, score in sorted(scores.items(), key=lambda x: -x[1])[:limit * 3]:
|
|
534
|
+
if nid in seen_ids:
|
|
535
|
+
continue
|
|
536
|
+
node_raw = txn.get(nid.encode(), db=nodes_db)
|
|
537
|
+
if not node_raw:
|
|
538
|
+
continue
|
|
539
|
+
node = json.loads(node_raw)
|
|
540
|
+
if label_filter and node.get("label") != label_filter:
|
|
541
|
+
continue
|
|
542
|
+
seen_ids.add(nid)
|
|
543
|
+
name = node.get("name", "")
|
|
544
|
+
results.append({
|
|
545
|
+
"node_id": nid, "label": node.get("label", ""),
|
|
546
|
+
"name": name, "snippet": node.get("snippet", ""),
|
|
547
|
+
"score": round(score, 3),
|
|
548
|
+
})
|
|
549
|
+
if len(results) >= limit:
|
|
550
|
+
break
|
|
551
|
+
|
|
552
|
+
return results
|
|
553
|
+
except Exception as e:
|
|
554
|
+
logger.debug("[LMDB] Search failed: %s", e)
|
|
555
|
+
return []
|
|
556
|
+
|
|
557
|
+
def search_bm25(self, query: str, limit: int = 10, label_filter: str = "",
|
|
558
|
+
k1: float = 1.5, b: float = 0.75) -> List[Dict]:
|
|
559
|
+
"""BM25-scored search. Uses term postings + doc frequency for ranking.
|
|
560
|
+
|
|
561
|
+
Parameters
|
|
562
|
+
----------
|
|
563
|
+
k1 : float
|
|
564
|
+
Term frequency saturation (default 1.5).
|
|
565
|
+
b : float
|
|
566
|
+
Length normalization (default 0.75).
|
|
567
|
+
"""
|
|
568
|
+
query_terms = list(dict.fromkeys(_tokenize(query))) # deduplicate, preserve order
|
|
569
|
+
if not query_terms:
|
|
570
|
+
return []
|
|
571
|
+
|
|
572
|
+
if not self._env:
|
|
573
|
+
return self.search(query, limit, label_filter) # fallback
|
|
574
|
+
|
|
575
|
+
# Extend query with bigrams so phrase matches score higher
|
|
576
|
+
query_bigrams = _bigrams(query_terms)
|
|
577
|
+
all_query_terms = list(dict.fromkeys(query_terms + query_bigrams))
|
|
578
|
+
|
|
579
|
+
try:
|
|
580
|
+
with self._env.begin() as txn:
|
|
581
|
+
terms_db = self._terms_db()
|
|
582
|
+
nodes_db = self._nodes_db()
|
|
583
|
+
|
|
584
|
+
# Read real corpus stats for accurate avg_dl
|
|
585
|
+
# total_docs excludes the reserved ~corpus_stats key
|
|
586
|
+
stats_raw = txn.get(_CORPUS_STATS_KEY, db=nodes_db)
|
|
587
|
+
if stats_raw:
|
|
588
|
+
corpus = json.loads(stats_raw)
|
|
589
|
+
total_docs = max(corpus.get("doc_count", 1), 1)
|
|
590
|
+
total_terms = corpus.get("total_term_count", total_docs * 5)
|
|
591
|
+
avg_dl = max(total_terms / total_docs, 1.0) # guard against 0 → ZeroDivisionError
|
|
592
|
+
else:
|
|
593
|
+
total_docs = max(txn.stat(nodes_db)["entries"] - 1, 1) # -1 for corpus_stats key
|
|
594
|
+
avg_dl = 5.0 # fallback when stats not yet built
|
|
595
|
+
|
|
596
|
+
# Collect postings and compute BM25 with correct per-term saturation.
|
|
597
|
+
# BM25(d,Q) = Σ_t IDF_t * (tf_t*(k1+1)) / (tf_t + k1*(1-b+b*dl/avgdl))
|
|
598
|
+
# Saturation must be applied per-term before summing, not to the aggregate.
|
|
599
|
+
#
|
|
600
|
+
# node_cache stores the full node dict (or None if not found) so that
|
|
601
|
+
# the result-building pass below never needs a second LMDB read.
|
|
602
|
+
bm25_scores: Dict[str, float] = {}
|
|
603
|
+
node_cache: Dict[str, Optional[Dict]] = {}
|
|
604
|
+
for term in all_query_terms:
|
|
605
|
+
raw = txn.get(term.encode(), db=terms_db)
|
|
606
|
+
if not raw:
|
|
607
|
+
continue
|
|
608
|
+
postings = json.loads(raw)
|
|
609
|
+
df = len(postings)
|
|
610
|
+
# Clamp to 0: IDF goes negative when df > total_docs (stale corpus stats).
|
|
611
|
+
idf = max(0.0, math.log((total_docs - df + 0.5) / (df + 0.5) + 1.0))
|
|
612
|
+
|
|
613
|
+
for nid, tf in postings:
|
|
614
|
+
if nid not in node_cache:
|
|
615
|
+
node_raw = txn.get(nid.encode(), db=nodes_db)
|
|
616
|
+
try:
|
|
617
|
+
node_cache[nid] = json.loads(node_raw) if node_raw else None
|
|
618
|
+
except Exception:
|
|
619
|
+
node_cache[nid] = None
|
|
620
|
+
node = node_cache[nid]
|
|
621
|
+
if node is None:
|
|
622
|
+
continue # stale posting — node deleted but not yet pruned
|
|
623
|
+
dl = node.get("term_count", avg_dl)
|
|
624
|
+
# Per-term BM25 contribution with length normalization
|
|
625
|
+
tf_norm = (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * dl / avg_dl))
|
|
626
|
+
bm25_scores[nid] = bm25_scores.get(nid, 0.0) + idf * tf_norm
|
|
627
|
+
|
|
628
|
+
# Resolve top-k — reuse node_cache to avoid second LMDB reads
|
|
629
|
+
results = []
|
|
630
|
+
seen_ids: Set[str] = set()
|
|
631
|
+
for nid, score in sorted(bm25_scores.items(), key=lambda x: -x[1])[:limit * 3]:
|
|
632
|
+
if nid in seen_ids:
|
|
633
|
+
continue
|
|
634
|
+
node = node_cache.get(nid)
|
|
635
|
+
if node is None:
|
|
636
|
+
continue
|
|
637
|
+
if label_filter and node.get("label") != label_filter:
|
|
638
|
+
continue
|
|
639
|
+
seen_ids.add(nid)
|
|
640
|
+
results.append({
|
|
641
|
+
"node_id": nid, "label": node.get("label", ""),
|
|
642
|
+
"name": node.get("name", ""), "snippet": node.get("snippet", ""),
|
|
643
|
+
"score": round(score, 4),
|
|
644
|
+
})
|
|
645
|
+
if len(results) >= limit:
|
|
646
|
+
break
|
|
647
|
+
|
|
648
|
+
return results
|
|
649
|
+
except Exception as e:
|
|
650
|
+
logger.debug("[LMDB] BM25 search failed: %s", e)
|
|
651
|
+
return self.search(query, limit, label_filter)
|
|
652
|
+
|
|
653
|
+
def get_node(self, node_id: str) -> Optional[Dict]:
|
|
654
|
+
"""Get node metadata by ID."""
|
|
655
|
+
if not self._env:
|
|
656
|
+
return self._mem_nodes.get(node_id)
|
|
657
|
+
try:
|
|
658
|
+
with self._env.begin() as txn:
|
|
659
|
+
raw = txn.get(node_id.encode(), db=self._nodes_db())
|
|
660
|
+
return json.loads(raw) if raw else None
|
|
661
|
+
except Exception:
|
|
662
|
+
return None
|
|
663
|
+
|
|
664
|
+
# ── Passage storage ─────────────────────────────────────
|
|
665
|
+
|
|
666
|
+
def store_passage(self, node_id: str, full_text: str):
|
|
667
|
+
"""Store full passage text for a node."""
|
|
668
|
+
if not self._env:
|
|
669
|
+
return
|
|
670
|
+
try:
|
|
671
|
+
with self._env.begin(write=True) as txn:
|
|
672
|
+
# Truncate string (not bytes) to avoid splitting multi-byte UTF-8 sequences
|
|
673
|
+
stored = full_text[:5000].encode()
|
|
674
|
+
txn.put(node_id.encode(), stored, db=self._passages_db_handle)
|
|
675
|
+
except Exception:
|
|
676
|
+
pass
|
|
677
|
+
|
|
678
|
+
def get_passage(self, node_id: str) -> Optional[str]:
|
|
679
|
+
"""Get full passage text for a node."""
|
|
680
|
+
if not self._env:
|
|
681
|
+
return None
|
|
682
|
+
try:
|
|
683
|
+
with self._env.begin() as txn:
|
|
684
|
+
raw = txn.get(node_id.encode(), db=self._passages_db_handle)
|
|
685
|
+
return raw.decode() if raw else None
|
|
686
|
+
except Exception:
|
|
687
|
+
return None
|
|
688
|
+
|
|
689
|
+
# ── Edge/graph storage ─────────────────────────────────
|
|
690
|
+
|
|
691
|
+
def store_edges(self, node_id: str, edges: List[Dict]):
|
|
692
|
+
"""Store edges for a node: [{target_id, label, target_name, target_type}]."""
|
|
693
|
+
if not self._env:
|
|
694
|
+
return
|
|
695
|
+
try:
|
|
696
|
+
with self._env.begin(write=True) as txn:
|
|
697
|
+
txn.put(node_id.encode(), json.dumps(edges).encode(), db=self._edges_db_handle)
|
|
698
|
+
except Exception:
|
|
699
|
+
pass
|
|
700
|
+
|
|
701
|
+
def get_edges(self, node_id: str) -> List[Dict]:
|
|
702
|
+
"""Get stored edges for a node."""
|
|
703
|
+
if not self._env:
|
|
704
|
+
return []
|
|
705
|
+
try:
|
|
706
|
+
with self._env.begin() as txn:
|
|
707
|
+
raw = txn.get(node_id.encode(), db=self._edges_db_handle)
|
|
708
|
+
return json.loads(raw) if raw else []
|
|
709
|
+
except Exception:
|
|
710
|
+
return []
|
|
711
|
+
|
|
712
|
+
# ── Semantic neighbor storage ──────────────────────────
|
|
713
|
+
|
|
714
|
+
def store_neighbors(self, node_id: str, neighbor_ids: List[str]):
|
|
715
|
+
"""Store pre-computed semantic neighbors for a node."""
|
|
716
|
+
if not self._env:
|
|
717
|
+
return
|
|
718
|
+
try:
|
|
719
|
+
with self._env.begin(write=True) as txn:
|
|
720
|
+
txn.put(node_id.encode(), json.dumps(neighbor_ids).encode(), db=self._neighbors_db_handle)
|
|
721
|
+
except Exception:
|
|
722
|
+
pass
|
|
723
|
+
|
|
724
|
+
def get_neighbors(self, node_id: str) -> List[str]:
|
|
725
|
+
"""Get semantic neighbors for a node."""
|
|
726
|
+
if not self._env:
|
|
727
|
+
return []
|
|
728
|
+
try:
|
|
729
|
+
with self._env.begin() as txn:
|
|
730
|
+
raw = txn.get(node_id.encode(), db=self._neighbors_db_handle)
|
|
731
|
+
return json.loads(raw) if raw else []
|
|
732
|
+
except Exception:
|
|
733
|
+
return []
|
|
734
|
+
|
|
735
|
+
# ── Hybrid search (all signals) ────────────────────────
|
|
736
|
+
|
|
737
|
+
def hybrid_search(self, query: str, limit: int = 10, label_filter: str = "") -> List[Dict]:
|
|
738
|
+
"""Full hybrid search: BM25 + graph expansion + passages.
|
|
739
|
+
|
|
740
|
+
Returns rich results with full text, connected entities, and relevance scores.
|
|
741
|
+
All from LMDB — no network calls, microseconds per signal.
|
|
742
|
+
"""
|
|
743
|
+
# Signal 1: BM25 keyword relevance + quality + relevance filter
|
|
744
|
+
bm25_results = self.search_bm25(query, limit=limit * 3, label_filter=label_filter)
|
|
745
|
+
|
|
746
|
+
if not bm25_results:
|
|
747
|
+
return []
|
|
748
|
+
|
|
749
|
+
# Filter: require meaningful query term overlap (not just one common word like "US").
|
|
750
|
+
# Use the same stemmed tokens as BM25 so "searching" matches a node indexed with "search".
|
|
751
|
+
query_stems = set(_tokenize(query))
|
|
752
|
+
meaningful_stems = {t for t in query_stems if len(t) > 3}
|
|
753
|
+
min_matches = max(1, len(meaningful_stems) // 2)
|
|
754
|
+
filtered = []
|
|
755
|
+
for r in bm25_results:
|
|
756
|
+
text_stems = set(_tokenize(r.get("name", "") + " " + r.get("snippet", "")))
|
|
757
|
+
meaningful_matching = sum(1 for t in meaningful_stems if t in text_stems)
|
|
758
|
+
if meaningful_matching >= min_matches:
|
|
759
|
+
r["_relevance"] = sum(1 for t in query_stems if t in text_stems)
|
|
760
|
+
filtered.append(r)
|
|
761
|
+
# Sort filtered by relevance then BM25 score
|
|
762
|
+
filtered.sort(key=lambda r: (r.get("_relevance", 0), r.get("score", 0)), reverse=True)
|
|
763
|
+
bm25_results = filtered or bm25_results[:limit]
|
|
764
|
+
|
|
765
|
+
# Signal 2: Graph expansion — find connected entities for top results
|
|
766
|
+
expanded_entities: Dict[str, Dict] = {} # name → {label, node_id}
|
|
767
|
+
for r in bm25_results[:5]:
|
|
768
|
+
edges = self.get_edges(r["node_id"])
|
|
769
|
+
for edge in edges[:10]:
|
|
770
|
+
ename = edge.get("target_name", "")
|
|
771
|
+
if ename and ename not in expanded_entities:
|
|
772
|
+
expanded_entities[ename] = {
|
|
773
|
+
"node_id": edge.get("target_id", ""),
|
|
774
|
+
"label": edge.get("target_type", ""),
|
|
775
|
+
"name": ename,
|
|
776
|
+
"via": edge.get("label", ""),
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
# Signal 3: Enrich with full passage text
|
|
780
|
+
for r in bm25_results:
|
|
781
|
+
passage = self.get_passage(r["node_id"])
|
|
782
|
+
if passage:
|
|
783
|
+
r["full_text"] = passage
|
|
784
|
+
# Also enrich snippet if it's short
|
|
785
|
+
if not r.get("snippet") or len(r.get("snippet", "")) < 30:
|
|
786
|
+
r["snippet"] = (passage or r.get("name", ""))[:200]
|
|
787
|
+
|
|
788
|
+
# Signal 4: Semantic neighbors — find similar nodes (filter out noise)
|
|
789
|
+
neighbor_results = []
|
|
790
|
+
existing_names = {r.get("name", "").lower() for r in bm25_results}
|
|
791
|
+
for r in bm25_results[:3]:
|
|
792
|
+
neighbors = self.get_neighbors(r["node_id"])
|
|
793
|
+
for nid in neighbors[:3]:
|
|
794
|
+
node = self.get_node(nid)
|
|
795
|
+
if not node:
|
|
796
|
+
continue
|
|
797
|
+
# Filter: only content nodes (not Document/Link/system noise)
|
|
798
|
+
if node.get("label", "") not in _CONTENT_LABELS:
|
|
799
|
+
continue
|
|
800
|
+
# Dedup
|
|
801
|
+
if node.get("name", "").lower() in existing_names:
|
|
802
|
+
continue
|
|
803
|
+
existing_names.add(node.get("name", "").lower())
|
|
804
|
+
# Semantic neighbors are pre-validated by Qdrant — no keyword filter needed
|
|
805
|
+
neighbor_results.append({
|
|
806
|
+
"node_id": nid, "label": node.get("label", ""),
|
|
807
|
+
"name": node.get("name", ""), "snippet": node.get("snippet", ""),
|
|
808
|
+
"score": 0.1, "via": "semantic_neighbor",
|
|
809
|
+
})
|
|
810
|
+
|
|
811
|
+
# Merge: BM25 results + expanded entities + semantic neighbors
|
|
812
|
+
final = []
|
|
813
|
+
seen_names: Set[str] = set()
|
|
814
|
+
|
|
815
|
+
# Primary: BM25 results (highest relevance)
|
|
816
|
+
for r in bm25_results:
|
|
817
|
+
name_key = r.get("name", "").strip().lower()[:60]
|
|
818
|
+
if name_key not in seen_names:
|
|
819
|
+
seen_names.add(name_key)
|
|
820
|
+
final.append(r)
|
|
821
|
+
|
|
822
|
+
# Secondary: Connected entities (graph expansion) — show actual name + relationship
|
|
823
|
+
for ename, edata in list(expanded_entities.items())[:5]:
|
|
824
|
+
name_key = ename.strip().lower()[:60]
|
|
825
|
+
if name_key not in seen_names and len(ename) > 3:
|
|
826
|
+
seen_names.add(name_key)
|
|
827
|
+
# Get full node data for richer display
|
|
828
|
+
enode = self.get_node(edata["node_id"])
|
|
829
|
+
esnippet = ""
|
|
830
|
+
if enode:
|
|
831
|
+
esnippet = enode.get("snippet", "")
|
|
832
|
+
passage = self.get_passage(edata["node_id"])
|
|
833
|
+
display = passage[:200] if passage else esnippet or ename
|
|
834
|
+
final.append({
|
|
835
|
+
"node_id": edata["node_id"], "label": edata["label"],
|
|
836
|
+
"name": ename, "snippet": display,
|
|
837
|
+
"full_text": passage if passage else None,
|
|
838
|
+
"score": 0.3, "via": f"connected ({edata['via']})",
|
|
839
|
+
})
|
|
840
|
+
|
|
841
|
+
# Tertiary: Semantic neighbors
|
|
842
|
+
for r in neighbor_results:
|
|
843
|
+
name_key = r.get("name", "").strip().lower()[:60]
|
|
844
|
+
if name_key not in seen_names:
|
|
845
|
+
seen_names.add(name_key)
|
|
846
|
+
final.append(r)
|
|
847
|
+
|
|
848
|
+
# Quaternary: fuzzy candidates (typo tolerance) — add any not already seen
|
|
849
|
+
fuzzy = self.fuzzy_candidates(query, limit=limit)
|
|
850
|
+
for r in fuzzy:
|
|
851
|
+
name_key = r.get("name", "").strip().lower()[:60]
|
|
852
|
+
if name_key not in seen_names:
|
|
853
|
+
seen_names.add(name_key)
|
|
854
|
+
final.append({
|
|
855
|
+
"node_id": r["node_id"], "label": r["label"],
|
|
856
|
+
"name": r["name"], "snippet": r["snippet"],
|
|
857
|
+
"score": r["similarity"] * 0.5, # lower than BM25 results
|
|
858
|
+
"via": "fuzzy_match",
|
|
859
|
+
})
|
|
860
|
+
|
|
861
|
+
return final[:limit]
|
|
862
|
+
|
|
863
|
+
def get_idf(self, terms: List[str]) -> Dict[str, float]:
|
|
864
|
+
"""Get IDF scores for terms directly from the index. O(K) not O(N).
|
|
865
|
+
|
|
866
|
+
Uses the same Robertson-Sparck Jones formula as search_bm25:
|
|
867
|
+
IDF = max(0, log((N - df + 0.5) / (df + 0.5) + 1))
|
|
868
|
+
Terms not in the index are treated as df=0 (maximum IDF).
|
|
869
|
+
"""
|
|
870
|
+
result = {}
|
|
871
|
+
if not self._env:
|
|
872
|
+
total = max(len(self._mem_nodes), 1)
|
|
873
|
+
for t in terms:
|
|
874
|
+
df = len(self._mem_terms.get(t, []))
|
|
875
|
+
result[t] = max(0.0, math.log((total - df + 0.5) / (df + 0.5) + 1.0))
|
|
876
|
+
return result
|
|
877
|
+
try:
|
|
878
|
+
with self._env.begin() as txn:
|
|
879
|
+
stats_raw = txn.get(_CORPUS_STATS_KEY, db=self._nodes_db())
|
|
880
|
+
if stats_raw:
|
|
881
|
+
total = max(json.loads(stats_raw).get("doc_count", 1), 1)
|
|
882
|
+
else:
|
|
883
|
+
total = max(txn.stat(self._nodes_db())["entries"] - 1, 1)
|
|
884
|
+
terms_db = self._terms_db()
|
|
885
|
+
for t in terms:
|
|
886
|
+
raw = txn.get(t.encode(), db=terms_db)
|
|
887
|
+
df = len(json.loads(raw)) if raw else 0
|
|
888
|
+
result[t] = max(0.0, math.log((total - df + 0.5) / (df + 0.5) + 1.0))
|
|
889
|
+
except Exception:
|
|
890
|
+
for t in terms:
|
|
891
|
+
result[t] = 2.0
|
|
892
|
+
return result
|
|
893
|
+
|
|
894
|
+
def fuzzy_candidates(
|
|
895
|
+
self,
|
|
896
|
+
query: str,
|
|
897
|
+
limit: int = 10,
|
|
898
|
+
min_similarity: float = 0.5,
|
|
899
|
+
) -> List[Dict]:
|
|
900
|
+
"""Return nodes whose indexed tokens share ≥ min_similarity trigrams with query tokens.
|
|
901
|
+
|
|
902
|
+
Similarity per token pair = shared_trigrams / query_token_trigrams.
|
|
903
|
+
A node is included if any of its tokens reaches min_similarity against
|
|
904
|
+
any query token. Results are ordered by descending max similarity.
|
|
905
|
+
|
|
906
|
+
Used to augment BM25 results with typo-tolerant candidates.
|
|
907
|
+
"""
|
|
908
|
+
query_terms = list(dict.fromkeys(_tokenize(query)))
|
|
909
|
+
if not query_terms or not self._env:
|
|
910
|
+
return []
|
|
911
|
+
|
|
912
|
+
# Build query trigram sets per token
|
|
913
|
+
query_tg_sets: Dict[str, Set[str]] = {
|
|
914
|
+
t: set(_char_trigrams(t)) for t in query_terms
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
try:
|
|
918
|
+
with self._env.begin() as txn:
|
|
919
|
+
trigrams_db = self._trigrams_db()
|
|
920
|
+
if trigrams_db is None:
|
|
921
|
+
return []
|
|
922
|
+
nodes_db = self._nodes_db()
|
|
923
|
+
|
|
924
|
+
# Count how many query trigrams each candidate node matches
|
|
925
|
+
candidate_scores: Dict[str, float] = {} # node_id → best similarity
|
|
926
|
+
for qt, qt_tgs in query_tg_sets.items():
|
|
927
|
+
qt_count = len(qt_tgs)
|
|
928
|
+
if qt_count == 0:
|
|
929
|
+
continue
|
|
930
|
+
matches_per_node: Dict[str, int] = {}
|
|
931
|
+
for tg in qt_tgs:
|
|
932
|
+
raw = txn.get(tg.encode(), db=trigrams_db)
|
|
933
|
+
if raw:
|
|
934
|
+
for nid in json.loads(raw):
|
|
935
|
+
matches_per_node[nid] = matches_per_node.get(nid, 0) + 1
|
|
936
|
+
for nid, match_count in matches_per_node.items():
|
|
937
|
+
sim = match_count / qt_count
|
|
938
|
+
if sim >= min_similarity:
|
|
939
|
+
candidate_scores[nid] = max(candidate_scores.get(nid, 0.0), sim)
|
|
940
|
+
|
|
941
|
+
# Resolve node metadata for top candidates
|
|
942
|
+
results = []
|
|
943
|
+
for nid, sim in sorted(candidate_scores.items(), key=lambda x: -x[1])[:limit * 2]:
|
|
944
|
+
node_raw = txn.get(nid.encode(), db=nodes_db)
|
|
945
|
+
if not node_raw:
|
|
946
|
+
continue
|
|
947
|
+
node = json.loads(node_raw)
|
|
948
|
+
results.append({
|
|
949
|
+
"node_id": nid,
|
|
950
|
+
"label": node.get("label", ""),
|
|
951
|
+
"name": node.get("name", ""),
|
|
952
|
+
"snippet": node.get("snippet", ""),
|
|
953
|
+
"similarity": round(sim, 3),
|
|
954
|
+
})
|
|
955
|
+
if len(results) >= limit:
|
|
956
|
+
break
|
|
957
|
+
return results
|
|
958
|
+
except Exception as e:
|
|
959
|
+
logger.debug("[LMDB] fuzzy_candidates failed: %s", e)
|
|
960
|
+
return []
|
|
961
|
+
|
|
962
|
+
def delete_node(self, node_id: str) -> bool:
|
|
963
|
+
"""Remove a node and all its term postings from the index.
|
|
964
|
+
|
|
965
|
+
O(K) where K = number of terms in the node, using the reverse index
|
|
966
|
+
(node_terms db) to find only the affected posting lists.
|
|
967
|
+
Previously O(total_terms) full scan — catastrophic under cascade invalidation.
|
|
968
|
+
|
|
969
|
+
Returns True if the node was present and removed, False if not found.
|
|
970
|
+
"""
|
|
971
|
+
if not self._env:
|
|
972
|
+
# In-memory fallback
|
|
973
|
+
if node_id not in self._mem_nodes:
|
|
974
|
+
return False
|
|
975
|
+
old = self._mem_nodes.pop(node_id)
|
|
976
|
+
self._mem_corpus_stats["total_term_count"] -= old.get("term_count", 0)
|
|
977
|
+
self._mem_corpus_stats["doc_count"] = max(0, self._mem_corpus_stats["doc_count"] - 1)
|
|
978
|
+
node_term_list = self._mem_node_terms.pop(node_id, [])
|
|
979
|
+
for term in node_term_list:
|
|
980
|
+
if term in self._mem_terms:
|
|
981
|
+
self._mem_terms[term] = [
|
|
982
|
+
(nid, w) for nid, w in self._mem_terms[term] if nid != node_id
|
|
983
|
+
]
|
|
984
|
+
if not self._mem_terms[term]:
|
|
985
|
+
del self._mem_terms[term]
|
|
986
|
+
return True
|
|
987
|
+
|
|
988
|
+
try:
|
|
989
|
+
with self._env.begin(write=True) as txn:
|
|
990
|
+
nodes_db = self._nodes_db()
|
|
991
|
+
terms_db = self._terms_db()
|
|
992
|
+
node_terms_db = self._node_terms_db()
|
|
993
|
+
|
|
994
|
+
# Check node exists and read metadata (need term_count for corpus stats)
|
|
995
|
+
node_raw = txn.get(node_id.encode(), db=nodes_db)
|
|
996
|
+
if node_raw is None:
|
|
997
|
+
return False
|
|
998
|
+
|
|
999
|
+
# Decrement corpus stats
|
|
1000
|
+
try:
|
|
1001
|
+
node_meta = json.loads(node_raw)
|
|
1002
|
+
stats_raw = txn.get(_CORPUS_STATS_KEY, db=nodes_db)
|
|
1003
|
+
corpus = json.loads(stats_raw) if stats_raw else {"total_term_count": 0, "doc_count": 0}
|
|
1004
|
+
corpus["total_term_count"] -= node_meta.get("term_count", 0)
|
|
1005
|
+
corpus["doc_count"] = max(0, corpus["doc_count"] - 1)
|
|
1006
|
+
txn.put(_CORPUS_STATS_KEY, json.dumps(corpus).encode(), db=nodes_db)
|
|
1007
|
+
except Exception:
|
|
1008
|
+
pass
|
|
1009
|
+
|
|
1010
|
+
# Look up this node's term list from the reverse index — O(1)
|
|
1011
|
+
node_terms_raw = txn.get(node_id.encode(), db=node_terms_db)
|
|
1012
|
+
if node_terms_raw:
|
|
1013
|
+
term_list = json.loads(node_terms_raw)
|
|
1014
|
+
else:
|
|
1015
|
+
# No reverse index entry (node was indexed before this feature).
|
|
1016
|
+
# Fall back to full scan for this node only.
|
|
1017
|
+
term_list = None
|
|
1018
|
+
|
|
1019
|
+
# Remove from nodes and reverse-index DBs
|
|
1020
|
+
txn.delete(node_id.encode(), db=nodes_db)
|
|
1021
|
+
txn.delete(node_id.encode(), db=node_terms_db)
|
|
1022
|
+
|
|
1023
|
+
if term_list is not None:
|
|
1024
|
+
# Fast path: only touch the K terms this node contributed to
|
|
1025
|
+
for term in term_list:
|
|
1026
|
+
key = term.encode()
|
|
1027
|
+
raw = txn.get(key, db=terms_db)
|
|
1028
|
+
if not raw:
|
|
1029
|
+
continue
|
|
1030
|
+
try:
|
|
1031
|
+
postings = json.loads(raw)
|
|
1032
|
+
new_postings = [p for p in postings if p[0] != node_id]
|
|
1033
|
+
if new_postings:
|
|
1034
|
+
txn.put(key, json.dumps(new_postings).encode(), db=terms_db)
|
|
1035
|
+
else:
|
|
1036
|
+
txn.delete(key, db=terms_db)
|
|
1037
|
+
except Exception:
|
|
1038
|
+
pass
|
|
1039
|
+
|
|
1040
|
+
# Remove node from trigram postings
|
|
1041
|
+
trigrams_db = self._trigrams_db()
|
|
1042
|
+
if trigrams_db is not None:
|
|
1043
|
+
removed_tgs: Set[str] = set()
|
|
1044
|
+
for term in term_list:
|
|
1045
|
+
if "__" in term:
|
|
1046
|
+
continue
|
|
1047
|
+
for tg in _char_trigrams(term):
|
|
1048
|
+
if tg in removed_tgs:
|
|
1049
|
+
continue
|
|
1050
|
+
removed_tgs.add(tg)
|
|
1051
|
+
tg_key = tg.encode()
|
|
1052
|
+
existing_raw = txn.get(tg_key, db=trigrams_db)
|
|
1053
|
+
if existing_raw:
|
|
1054
|
+
node_set = [n for n in json.loads(existing_raw) if n != node_id]
|
|
1055
|
+
if node_set:
|
|
1056
|
+
txn.put(tg_key, json.dumps(node_set).encode(), db=trigrams_db)
|
|
1057
|
+
else:
|
|
1058
|
+
txn.delete(tg_key, db=trigrams_db)
|
|
1059
|
+
else:
|
|
1060
|
+
# Legacy fallback: full scan (only for pre-reverse-index nodes)
|
|
1061
|
+
logger.debug("[LMDB] delete_node %s: no reverse index, doing full terms scan", node_id)
|
|
1062
|
+
cursor = txn.cursor(db=terms_db)
|
|
1063
|
+
to_update: List[Tuple[bytes, bytes]] = []
|
|
1064
|
+
to_delete_keys: List[bytes] = []
|
|
1065
|
+
if cursor.first():
|
|
1066
|
+
while True:
|
|
1067
|
+
key = cursor.key()
|
|
1068
|
+
raw = cursor.value()
|
|
1069
|
+
try:
|
|
1070
|
+
postings = json.loads(raw)
|
|
1071
|
+
new_postings = [p for p in postings if p[0] != node_id]
|
|
1072
|
+
if len(new_postings) != len(postings):
|
|
1073
|
+
if new_postings:
|
|
1074
|
+
to_update.append((key, json.dumps(new_postings).encode()))
|
|
1075
|
+
else:
|
|
1076
|
+
to_delete_keys.append(key)
|
|
1077
|
+
except Exception:
|
|
1078
|
+
pass
|
|
1079
|
+
if not cursor.next():
|
|
1080
|
+
break
|
|
1081
|
+
for key, val in to_update:
|
|
1082
|
+
txn.put(key, val, db=terms_db)
|
|
1083
|
+
for key in to_delete_keys:
|
|
1084
|
+
txn.delete(key, db=terms_db)
|
|
1085
|
+
|
|
1086
|
+
return True
|
|
1087
|
+
except Exception as e:
|
|
1088
|
+
logger.warning("[LMDB] delete_node(%s) failed: %s", node_id, e)
|
|
1089
|
+
return False
|
|
1090
|
+
|
|
1091
|
+
def stats(self) -> Dict:
|
|
1092
|
+
"""Return index statistics."""
|
|
1093
|
+
if not self._env:
|
|
1094
|
+
return {"nodes": len(self._mem_nodes), "terms": len(self._mem_terms), "backend": "memory"}
|
|
1095
|
+
try:
|
|
1096
|
+
with self._env.begin() as txn:
|
|
1097
|
+
terms_stat = txn.stat(self._terms_db())
|
|
1098
|
+
nodes_stat = txn.stat(self._nodes_db())
|
|
1099
|
+
raw_node_entries = nodes_stat["entries"]
|
|
1100
|
+
# Subtract the reserved ~corpus_stats key so the count reflects real nodes
|
|
1101
|
+
node_count = max(0, raw_node_entries - 1) if raw_node_entries > 0 else 0
|
|
1102
|
+
# Read corpus stats for avg_dl if available
|
|
1103
|
+
stats_raw = txn.get(_CORPUS_STATS_KEY, db=self._nodes_db())
|
|
1104
|
+
corpus = json.loads(stats_raw) if stats_raw else {}
|
|
1105
|
+
return {
|
|
1106
|
+
"nodes": node_count,
|
|
1107
|
+
"terms": terms_stat["entries"],
|
|
1108
|
+
"backend": "lmdb",
|
|
1109
|
+
"path": self._path,
|
|
1110
|
+
"map_size_mb": self._map_size // (1024 * 1024),
|
|
1111
|
+
"avg_dl": round(corpus.get("total_term_count", 0) / max(corpus.get("doc_count", 1), 1), 1),
|
|
1112
|
+
"doc_count": corpus.get("doc_count", 0),
|
|
1113
|
+
}
|
|
1114
|
+
except Exception:
|
|
1115
|
+
return {"backend": "lmdb", "error": "stats unavailable"}
|
|
1116
|
+
|
|
1117
|
+
def close(self):
|
|
1118
|
+
"""Close the LMDB environment."""
|
|
1119
|
+
if self._env:
|
|
1120
|
+
self._env.close()
|
|
1121
|
+
self._env = None
|
|
1122
|
+
|
|
1123
|
+
|
|
1124
|
+
# ── Module-level cache of LMDBIndex instances ─────────────────
|
|
1125
|
+
|
|
1126
|
+
import threading as _threading
|
|
1127
|
+
_lmdb_indexes: Dict[str, LMDBIndex] = {}
|
|
1128
|
+
_lmdb_index_lock = _threading.Lock()
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def get_lmdb_index(graph_name: str) -> LMDBIndex:
|
|
1132
|
+
"""Get or create an LMDBIndex for a graph. Thread-safe."""
|
|
1133
|
+
# Fast path — no lock needed for reads once entry exists
|
|
1134
|
+
idx = _lmdb_indexes.get(graph_name)
|
|
1135
|
+
if idx is not None:
|
|
1136
|
+
return idx
|
|
1137
|
+
# Slow path — serialize creation to avoid TOCTOU race
|
|
1138
|
+
with _lmdb_index_lock:
|
|
1139
|
+
idx = _lmdb_indexes.get(graph_name)
|
|
1140
|
+
if idx is None:
|
|
1141
|
+
path = f"contextcore_data/lmdb_index/{graph_name}"
|
|
1142
|
+
idx = LMDBIndex(path)
|
|
1143
|
+
_lmdb_indexes[graph_name] = idx
|
|
1144
|
+
return idx
|
|
1145
|
+
|
|
1146
|
+
|
|
1147
|
+
def build_lmdb_index(db, graph_name: str) -> LMDBIndex:
|
|
1148
|
+
"""Build LMDB index from a graph (full rebuild). Returns the index."""
|
|
1149
|
+
idx = get_lmdb_index(graph_name)
|
|
1150
|
+
start = time.time()
|
|
1151
|
+
|
|
1152
|
+
try:
|
|
1153
|
+
all_nodes = db.get_all_nodes()
|
|
1154
|
+
except Exception:
|
|
1155
|
+
all_nodes = []
|
|
1156
|
+
|
|
1157
|
+
batch = []
|
|
1158
|
+
for node in all_nodes:
|
|
1159
|
+
if isinstance(node, dict):
|
|
1160
|
+
batch.append(node)
|
|
1161
|
+
else:
|
|
1162
|
+
batch.append({
|
|
1163
|
+
"id": str(getattr(node, "id", "")),
|
|
1164
|
+
"label": getattr(node, "label", getattr(node, "node_type", "")),
|
|
1165
|
+
"properties": getattr(node, "properties", {}) or {},
|
|
1166
|
+
})
|
|
1167
|
+
|
|
1168
|
+
if batch:
|
|
1169
|
+
idx.index_batch(batch)
|
|
1170
|
+
|
|
1171
|
+
elapsed = (time.time() - start) * 1000
|
|
1172
|
+
stats = idx.stats()
|
|
1173
|
+
logger.info("[LMDB] Built index for '%s': %d nodes, %d terms in %.0fms",
|
|
1174
|
+
graph_name, stats.get("nodes", 0), stats.get("terms", 0), elapsed)
|
|
1175
|
+
return idx
|
|
1176
|
+
|
|
1177
|
+
|
|
1178
|
+
def lmdb_delete_node(namespace: str, node_id: str) -> None:
|
|
1179
|
+
"""Best-effort LMDB cleanup for a deleted graph node. Never raises."""
|
|
1180
|
+
try:
|
|
1181
|
+
if namespace:
|
|
1182
|
+
get_lmdb_index(namespace).delete_node(str(node_id))
|
|
1183
|
+
except Exception:
|
|
1184
|
+
pass
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
def lmdb_reindex_node(namespace: str, node_id: str, label: str, props: dict) -> None:
|
|
1188
|
+
"""Best-effort LMDB re-index after a node create or update. Never raises."""
|
|
1189
|
+
try:
|
|
1190
|
+
if namespace:
|
|
1191
|
+
get_lmdb_index(namespace).index_node(str(node_id), label, dict(props))
|
|
1192
|
+
except Exception:
|
|
1193
|
+
pass
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def remove_lmdb_index(graph_name: str) -> None:
|
|
1197
|
+
"""Close and delete the LMDB index for a dropped graph. Never raises.
|
|
1198
|
+
|
|
1199
|
+
Evicts the singleton, closes the LMDB environment, and deletes the
|
|
1200
|
+
directory on disk so a fresh graph reusing the same name starts clean.
|
|
1201
|
+
"""
|
|
1202
|
+
try:
|
|
1203
|
+
import shutil
|
|
1204
|
+
from pathlib import Path
|
|
1205
|
+
|
|
1206
|
+
with _lmdb_index_lock:
|
|
1207
|
+
idx = _lmdb_indexes.pop(graph_name, None)
|
|
1208
|
+
if idx is not None:
|
|
1209
|
+
try:
|
|
1210
|
+
idx.close()
|
|
1211
|
+
except Exception:
|
|
1212
|
+
pass
|
|
1213
|
+
|
|
1214
|
+
path = f"contextcore_data/lmdb_index/{graph_name}"
|
|
1215
|
+
if Path(path).exists():
|
|
1216
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
1217
|
+
except Exception:
|
|
1218
|
+
pass
|