-
Notifications
You must be signed in to change notification settings - Fork 1
Module llm wiki Architecture
The LLM wiki module is a standalone semantic knowledge core within ThemisDB. It provides plugin-based integration for external knowledge sources (Confluence, Notion, internal wikis) into ThemisDB's LLM workflow, and it is strongly coupled to llm for orchestration and to llama_cpp for local inference-backed retrieval, summarization, and generation support. The module enables controlled knowledge base access with guardrails, access policies, and dynamic workspace isolation.
-
llmfor orchestration, prompt planning, and response assembly -
llama_cppfor local inference-backed retrieval and summarization flows -
prompt_engineeringfor retrieval planning and prompt enhancement handoff -
retrievalfor semantic search and ranking support -
metadatafor provenance, revision, and audit integration - RocksDB for persistent workspace state and Phase B cache support
- Plugin Architecture: Multiple wiki backends supported through standardized interface
- Workspace Isolation: Separate knowledge bases per tenant/workspace; no cross-contamination
- Access Control: Hierarchical permission model (public, authenticated, role-based)
- Query Optimization: Caching and indexing for efficient knowledge retrieval
- Guardrails: LLM-specific safety checks and rate limiting
- Audit Trail: All knowledge access logged for compliance and debugging
The LLM Wiki schema is intentionally extensible, but evolution must be controlled to preserve determinism, compatibility, and auditability.
Stable core fields are mandatory for all persisted wiki entities:
schema_versionentity_typeprovenanceconfidencecreated_atupdated_at
All non-core additions must live in an extensions object and must not redefine core semantics.
- Extensions must use namespaced keys to avoid collisions.
- Unknown extensions are ignored by readers by default (forward compatibility).
- Writers may emit only extension namespaces enabled by policy for the current edition and workspace.
- Security-sensitive extensions require explicit allowlist approval in governance policy.
- Any extension that affects retrieval ranking, confidence, or allow-deny behavior must be auditable.
- Minor schema versions may add optional fields and extension namespaces.
- Major schema versions may change semantics and require explicit migration plans.
- Every migration must provide:
- deterministic transformation rules
- backward-read behavior definition
- rollback behavior
- migration audit events
- Migrations must be idempotent and safe to rerun.
- Legacy compatibility shims are forbidden unless explicitly human-approved and time-bounded.
Schema evolution is governed through capability declarations:
- Reader capability: which schema versions and extension namespaces can be interpreted.
- Writer capability: which schema versions and extension namespaces may be emitted.
- Governance capability: which policy packs are required for sensitive extensions.
Capabilities are evaluated at startup and on policy refresh to prevent partial-rollout inconsistencies.
Validation must fail closed for:
- missing core fields
- malformed provenance
- invalid confidence domain
- unauthorized extension namespaces
- extension payloads that violate policy constraints
Validation may soft-ignore unknown but policy-safe extensions while preserving the raw payload for future-compatible reads.
The reference schema for persisted wiki entities is defined in:
src/llm_wiki/schema/llm_wiki_entity.schema.json
This artifact is the canonical contract for stable-core fields, extension namespace constraints, provenance structure, and governance payload shape.
The module should adapt using a scientific control loop:
- Observe: collect request, retrieval, governance, and re-anchor telemetry.
- Hypothesize: derive candidate policy or weighting adjustments.
- Experiment: evaluate on shadow or canary traffic within bounded risk.
- Validate: require measurable gain without governance regression.
- Deploy: promote the new policy and capture rollback handles.
- answer utility feedback
- correction or override frequency
- re-anchor frequency
- provenance confidence drift
- deny-path and guardrail trigger rates
- No adaptation may bypass entitlement, guardrail, or provenance validation gates.
- Adaptive ranking changes must remain explainable via persisted decision metadata.
- Confidence threshold changes require policy versioning and audit traceability.
LLM Wiki process execution is orchestrated through a versioned YAML policy so adaptation behavior can be changed without code edits.
- Policy artifact:
src/llm_wiki/process/llm_wiki_process_policy.yaml - Policy schema:
src/llm_wiki/schema/llm_wiki_process_policy.schema.json
- Load YAML policy at startup and on controlled refresh points.
- Validate policy against schema and governance constraints.
- Materialize stage plan (
ingest,extract,synthesize,validate,re_anchor). - Execute stage gates according to schedule class (interactive, near-real-time, batch).
- Emit decision telemetry for each request and adaptation cycle.
The ML controller does not rewrite arbitrary process logic. It optimizes only approved knobs inside policy-defined hard bounds.
- Observe outcomes: utility, latency, deny rate, re-anchor rate, confidence drift.
- Propose knob updates (for example evidence size or confidence thresholds).
- Apply in
shadoworcanarymode first. - Promote only if policy goals improve and security metrics do not regress.
- Roll back automatically when rollback thresholds are violated.
-
second_planner_allowedmust remainfalse. - Fail-closed validation must stay enabled.
- Entitlement and guardrail gates are never tunable by ML.
- Policy snapshots and reason codes are mandatory for auditable decisions.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LLM Inference Request β
β β’ Query requiring external knowledge β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WikiContextManager (Main API) β
β β’ Coordinate wiki access and guardrails β
β β’ Manage workspace isolation β
β β’ Apply access policies β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββΌβββββββββββββββ
β β β
βΌ βΌ βΌ
ββββββββββββ ββββββββββββ ββββββββββββββββ
βConfluenceβ βNotion β βInternal Wiki β
βPlugin β βPlugin β βPlugin β
β β β β β β
ββββββ¬ββββββ ββββββ¬ββββββ ββββββββ¬ββββββββ
β β β
ββββββββββββββΌβββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββ
β AccessControl β
β β’ Permission checks β
β β’ Workspace isolation β
β β’ Rate limiting β
ββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββ
β Guardrails & Filters β
β β’ Content validation β
β β’ Sensitivity checks β
β β’ Token counting β
ββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββ
β Result Cache β
β β’ Query results β
β β’ TTL-based eviction β
β β’ Per-workspace keys β
ββββββββββββββββββββββββββ
Purpose: Unified interface for retrieving contextual knowledge from configured wiki sources.
Responsibilities:
- Route queries to appropriate wiki backend(s)
- Apply access control policies
- Enforce guardrails (token limits, content filters)
- Cache results for efficiency
- Track usage for rate limiting and audit
Public API:
class WikiContextManager {
Result<WikiContext> getContext(
const LLMQuery& query,
const WorkspaceId& workspace,
const UserId& user
);
Result<std::vector<WikiArticle>> search(
const std::string& query_text,
const WorkspaceId& workspace
);
};Purpose: Standardized contract for wiki backend implementations.
Responsibilities:
- Connect to wiki source (API, database, file system)
- Execute queries/searches
- Return article/document results
- Handle authentication with wiki system
- Implement caching and rate limiting
Plugin Abstraction:
class WikiPlugin {
virtual Result<std::vector<Article>> search(
const std::string& query
) = 0;
virtual Result<Article> getArticle(const ArticleId& id) = 0;
virtual Result<> authenticate(const Credentials& creds) = 0;
};Purpose: Enforce permission policies and workspace isolation.
Access Model:
- Workspace-Level: Separate knowledge bases per tenant
- Document-Level: Granular permissions (public, authenticated, role-based)
- User-Level: Identity and role tracking
- Query-Level: Rate limiting per user/workspace
Permission Checks:
Can user access document?
βββΊ Is document public? β YES
βββΊ Is user authenticated? β Check workspace
βββΊ Does user have required role? β Check document ACL
Purpose: Prevent sensitive content leakage and enforce LLM safety.
Enforcement Points:
-
Content Sensitivity Filtering
- Detect and filter: credentials, PII, confidential markings
- Signature-based (regex patterns, keyword lists)
- Configurable per workspace
-
Token Counting
- Measure context tokens before including
- Respect LLM context window limits
- Graceful truncation if over limit
-
Rate Limiting
- Per-user, per-workspace rate limits
- Query quota management
- Token consumption tracking
-
Audit Logging
- All access logged with: user, workspace, documents, timestamp
- Enables compliance and forensics
Purpose: Reduce repeated queries to wiki backends.
Strategy:
- Key:
<workspace_id, query_hash> - Value: cached results with TTL
- LRU eviction when capacity exceeded
- Configurable TTL per workspace
Configuration:
- Max cache size: configurable (default: 1 GB)
- TTL: configurable (default: 1 hour)
- Enable/disable per workspace
LLM Query (+ workspace + user)
β
βββΊ Query Cache Lookup
β βββΊ Cache hit β Return cached results
β βββΊ Cache miss β Continue
β
βββΊ Identify wiki sources
β
βββΊ For each wiki source:
β βββΊ Check access permissions (user)
β βββΊ Execute search query
β βββΊ Get ranked results
β
βββΊ Apply Guardrails:
β βββΊ Filter sensitive content
β βββΊ Count tokens
β βββΊ Rank by relevance
β
βββΊ Query Cache Store
β βββΊ Cache results with TTL
β
βββΊ Return context to LLM
βββΊ Ranked articles
βββΊ Token count
βββΊ Audit event logged
ThemisDB Cluster
β
βββΊ Workspace A
β βββΊ Users: alice, bob
β βββΊ Wiki Sources: Internal Wiki A, Confluence
β βββΊ Cache: isolated L1 (workspace A only)
β βββΊ Audit Log: workspace A events only
β
βββΊ Workspace B
β βββΊ Users: charlie, diana
β βββΊ Wiki Sources: Notion, GitHub Wiki
β βββΊ Cache: isolated L1 (workspace B only)
β βββΊ Audit Log: workspace B events only
β
βββΊ Global
βββΊ Shared Cache L2 (cross-workspace, anonymous)
βββΊ Central Audit Log (all events, workspace-tagged)
-
Confluence Plugin
- Atlassian Confluence API integration
- Authentication: API tokens, OAuth
- Search: CQL (Confluence Query Language)
- Caching: REST API rate limit aware
-
Notion Plugin
- Notion API (v1) integration
- Authentication: ******
- Search: Notion database queries
- Caching: TTL-aware
-
Internal Wiki Plugin
- Custom markdown/JSON file system
- No authentication required
- Full-text search via indexing
- File-system watcher for dynamic updates
To implement a custom wiki plugin:
- Extend
WikiPluginbase class - Implement
search()andgetArticle()methods - Handle authentication and credentials
- Implement local caching where appropriate
- Return results in standardized Article format
Example:
class CustomWikiPlugin : public WikiPlugin {
Result<std::vector<Article>> search(const std::string& query) override {
// Connect to custom wiki API
// Execute search
// Parse results into Article objects
// Apply local caching
// Return results
}
};-
Per-Workspace Access: Multiple readers allowed
- Search operations don't modify wiki state
- Read-write lock per workspace
- Enables concurrent queries
-
Cache Updates: Atomic with compare-and-swap
- Prevents race conditions during cache write
- Minimal lock contention
-
Plugin Access: Thread-safe plugin calls
- Plugins responsible for own synchronization
- Context manager serializes plugin invocations
-
std::shared_mutexfor per-workspace access control -
std::atomic<>for cache counters -
std::condition_variablefor plugin coordination
- Cache Hit: < 1 ms
- Single Plugin Query: < 500 ms (depends on wiki backend)
- Multi-Plugin Query: < 1000 ms (parallel queries)
- Context Retrieval End-to-End: < 2 seconds
- Queries/sec: > 10 concurrent queries
- Cache Capacity: > 10k documents
- Plugin Concurrency: > 5 concurrent plugin operations
- Per-Workspace Memory: < 100 MB (caches + state)
- Cache Memory: ~10 KB per cached result
- Total Memory: < 1 GB for typical deployment
- Plugin Unavailable β Skip that source; continue with others
- Query Timeout β Return partial results from other sources
- Access Denied β Return empty results; log audit event
- Cache Corruption β Bypass cache; recompute results
- Token Limit Exceeded β Truncate results to fit limit
- E9600: Wiki plugin not found
- E9601: Authentication failed with wiki backend
- E9602: Query timeout
- E9603: Access denied for user/workspace
- E9604: Content sensitivity filter blocked result
Wiki context is fetched and injected into LLM prompt:
- LLM query received
- WikiContextManager retrieves relevant context
- Context injected into system prompt
- LLM generates response with context
When documents reference wiki articles:
- Extract article references
- Validate user access to articles
- Pre-fetch and cache for RAG pipeline
- [[
ROADMAP.md|Module-llm-wiki-Roadmap]] β Implementation phases and deliverables -
README.mdβ Module overview - [[
FUTURE_ENHANCEMENTS.md|Module-llm-wiki-Future]] β Planned features -
../../include/llm_wiki/wiki_context_manager.hβ Public API
ThemisDB 1.9.0-beta Β· Home Β· Module-Index Β· GitHub Β· Issues
ThemisDB 1.9.0-beta Β· Home Β· Wiki-Index Β· Module-Index Β· FAQ Β· Quick-Reference Β· GitHub Β· Issues Β· Discussions Β· License
- Batch Operations
- Best Practices
- CRUD Tutorial
- Custom Document Ingestion
- Getting Started Tutorial
- Interactive Examples
- Schema Design
- Video Tutorials
- AQL Reference
- AQL Examples
- AQL Overview
- AQL Feature Roadmap
- AQL Geospatial Guide
- AQL LLM Migration Guide
- AQL API
- AQL Grammar (EBNF)
- AQL Root Overview
- AQL Examples (root)
- API Reference
- API Module README
- OpenAPI Overview
- Client SDK Overview
- SDK Overview
- Operations
- Operations Overview
- Operations Runbook
- Operations Handbook
- ThemisCtl Admin Guide
- Pipeline E2E SOPs
- Deploy Overview
- Docker Overview
- Docker Hub README
- Helm Overview
- Packaging Overview
- Operator Overview
- Security Policy
- Production Hardening Checklist
- Security Hardening Guide
- Encryption Key Management
- Access Control Framework
- Zero Trust Policy
- API Authentication & Authorization
- HSM Production Setup
- PKCS11 Integration
- DSGVO / SOC2 Checklist
- Access Model Runbooks
- Access Model Dashboard
- Maturity Automation Runbook
- Access Review Automation
- Access Model Dashboard
- Access Model Runbooks
- Rights Revocation
- Dr Checklists
- Dr Testing
- Incident Response Playbook
- Incident Response Testing
- GPU Oom Recovery
- Grammar Debugging
- Metrics Scrape Troubleshooting
- Model Swap Procedure
- Quota Tuning
- Subagent Deployment
- Logging Configuration
- Content Model
- Crypto & Keys
- Feature Flags Reference
- Modular Architecture Roadmap
- Modularization Guide
- Module Architecture Index
- PostgreSQL Wire Protocol
- Query Scheduling
- Raft Consensus Design
- Resource Pooling
- Source Directory Guide
- Unified Access Model
- E1 001 Layered Retrieval Design
- E1 002 Ann Abstraction Strategy
- E1 003 Tensor Summary Types
- E1 004 Lora Package Distinction
- E1 005 Model Switch Compatibility
- E1 006 Federated Tensor Summaries
- E2 001 Evaluation Framework Design
- E2 002 Hardware Profile Strategy
- E2 003 Query Planner Routing Model
- E2 004 Approximation Governance Rules
- E2 005 Cross Layer Fallback Confidence Policy
- E3 001 Distributed Tensor Design
- E3 002 Manifest Coordination Strategy
- E3 003 Recovery And Erasure Choice
- E3 004 Tensor Fabric Infrastructure
- Contributing
- Contributing (root)
- Code of Conduct
- Support
- Maintainers
- CTest Guide
- Build Quick Reference
- Developer Wiki Index
- Build / Test / CI
- Module Index
- Branching Strategy
- Disabled Stub Policy
- Docs PR Policy
- GA Promotion Sign Off
- Github Milestones Setup
- Maturity Claim Verification Checklist
- Maturity Evidence Registry
- Merge Gate Bot Config
- Merge Gate Status Live
- Phase 1 Closure Report
- Phase Closure Policy
- Phase Dependency Graph
- Phase3 Enforcement Runbook
- Plugin Submodule Rollback
- PR Version Targeting
- PR Version Targeting Backfill
- Production Ready 2026 Delivery Plan
- Query Module Status
- Readme
- Release Promotion Gate Policy
- Release Validation Checklist
- Security Module 5671 Evidence Summary
- Sharding P6 Residual Risk Acceptance
- Sourcecode Compliance Governance
- Updates Development Status Sign Off
- Wave C Implementation Complete
- Blob Storage
- Cuda
- Ethics Ai
- Exporters
- Huggingface
- Image Analysis
- Importers
- RPC
- Scraper
- Themisdb Ai Watermark Detector
- User Storage Encrypted
- Chimera Architecture
- Chimera Future
- Chimera Readme
- Chimera Roadmap
- Covina Fastapi Ingestion Architecture
- Covina Fastapi Ingestion Future
- Covina Fastapi Ingestion Roadmap
- Vcc Base Architecture
- Vcc Base Future
- Vcc Base Roadmap
- Vcc Clara Ingestion Architecture
- Vcc Clara Ingestion Future
- Vcc Clara Ingestion Roadmap
- Vcc Veritas Architecture
- Vcc Veritas Future
- Vcc Veritas Roadmap
- 01 Hello World
- 02 Todo App
- 03 Contact Manager
- 04 Inventory System
- 05 Time Series Monitor
- 06 Graph Social Network
- 07 Vector Search Documents
- 08 Dms Erp System
- 09 Iot Sensor Network
- 10 Drone Image Analysis
- 11 Blog Wiki
- 12 Expense Tracker
- 13 Recipe Manager
- 14 Ecommerce Catalog
- 15 Event Management
- 16 Kanban Board
- 17 Crm
- 18 Realtime Chat
- 19 Recommendation Engine
- 20 Smart Home
- 21 Coding Platform
- 22 AQL Diagram Tool
- 23 Traveling Salesman
- 24 Moral Philosophy Debates
- API Versioning
- Distributed Sharding
- Feedback Plugins
- Geo
- Gnn
- Image Analysis
- Legal Lora Training
- LLM
- Lora Sync
- Migration
- Nlp
- Performance
- Railway
- Replication
- Rope Visualization
- Sample Product Config
- Security
- Client SDK Overview
- Quickstart
- Sdk Enhancements
- Sdk Implementation Summary
- Test Suite Readme
- Go
- Java
- Javascript
- Php
- Python
- Ruby
- Rust
- Typescript
- 01 Grundlegende Operationen
- 02 AQL Queries
- 03 Graph Daten
- 04 Multimodell Anwendung
- 01 Quickstart Guide
- 02 AQL Referenz Kurzuebersicht
- 03 Datenmodellierung Guide
- 04 Uebungsaufgaben
- 05 Best Practices Guide
- Training Documents
- Training Overview
- 01 Einfuehrung Und Uebersicht
- 02 Datenmodelle Und Architektur
- 03 AQL Abfragesprache
- 04 Installation Und Setup
- 05 Anwendungsbeispiele
- Training Presentations
- Dependencies Readme
- Processmonitor Readme
- Themis.admintools.shared Readme
- Themis.aqlquerybuilder Readme
- Themis.aqlquerybuilder Roadmap
- Themis.auditlogviewer Readme
- Themis.auditlogviewer Roadmap
- Themis.classificationdashboard Readme
- Themis.classificationdashboard Roadmap
- Themis.compliancereports Readme
- Themis.compliancereports Roadmap
- Themis.gisviewer.controlpanel Readme
- Themis.gisviewer.controlpanel Roadmap
- Themis.impactanalysisviewer Readme
- Themis.impactanalysisviewer Roadmap
- Themis.ingestiontool Readme
- Themis.ingestiontool Roadmap
- Themis.keyrotationdashboard Readme
- Themis.keyrotationdashboard Roadmap
- Themis.piimanager Readme
- Themis.piimanager Roadmap
- Themis.retentionmanager Readme
- Themis.retentionmanager Roadmap
- Themis.sagaverifier Readme
- Themis.sagaverifier Roadmap
- Themis.usbadmintool Readme
- Themis.usbadmintool Roadmap
- CI Readme
- CI Roadmap
- Compiler Diagnostics Readme
- Compiler Diagnostics Roadmap
- Completion Readme
- Copilot Ollama Router Readme
- Copilot Ollama Router Roadmap
- Gnn Readme
- Gnn Roadmap
- Rope Visualizer Readme
- Rope Visualizer Roadmap
- Tco Calculator Readme
- Tco Calculator Roadmap
- Tests Readme
- Tests Roadmap
- Themis Config Wx Readme
- Themis Docs Builder Readme
- Wikipedia Ingestion Readme