-
Notifications
You must be signed in to change notification settings - Fork 1
Module execution Architecture
The execution module provides the runtime execution substrate for ThemisDB query processing, combining deadline-driven query scheduling with adaptive work-stealing thread pooling. The architecture separates concerns between query scheduling (priority, deadlines, SLAs) and execution (worker threads, load balancing, resource utilization).
- Deadline-Driven Scheduling: Queries carry SLA deadlines; scheduler enforces deadline constraints through priority queuing and timeout mechanisms
- Work-Stealing Parallelism: Idle workers steal work from busy workers to balance load and maximize throughput
- Adaptive Resource Management: Thread pool sizing adapts dynamically to workload; memory and CPU constraints are enforced
- Fail-Closed Degradation: Resource exhaustion triggers structured errors, not undefined behavior
- Observable: All scheduling decisions and resource state changes are logged with diagnostic context
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Query Scheduler (SLA-Aware) β
β β’ Priority Queue: CRITICAL > HIGH > NORMAL > LOW β
β β’ Deadline Tracking: enqueue_time + sla_deadline_ms β
β β’ Backpressure: max_queue_depth enforcement β
β β’ Timeout Handling: on enqueue/dequeue operations β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Thread Pool Manager (Adaptive) β
β β’ Worker Threads: min_threads to max_threads β
β β’ Per-Thread Task Queue: work-stealing enabled β
β β’ Adaptive Spawning: scale workers based on queue depth β
β β’ Graceful Shutdown: complete in-flight work β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Work Distribution & Execution β
β β’ FIFO Dispatch: within priority level β
β β’ Work Stealing: idle workers steal from busy peers β
β β’ Resource Accounting: CPU, memory per query β
β β’ Timeout Enforcement: deadline-based cancellation β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Purpose: Manage query entry points with SLA deadline enforcement and priority-based dispatch.
Responsibilities:
- Enqueue queries with deadline computation (relative to SLA policy)
- Dequeue queries respecting priority order and deadline constraints
- Track queue depth and apply backpressure when limits exceeded
- Report deadline violations and queue saturation events
- Support graceful shutdown with remaining query completion
Key Contracts:
-
enqueue(query, sla_deadline_ms) β Result<QueueToken>- Computes absolute deadline = now() + sla_deadline_ms
- Returns error if queue full or deadline already expired
- Thread-safe; lock-free for query entry reads
-
dequeue() β Result<Query>- Returns highest-priority query within deadline
- Returns empty if queue empty or all queries expired
- Atomic state transition to "executing"
-
get_queue_depth() β size_t- Returns current queue size
- No locking required (atomic read)
Error Codes (E7100βE7199):
- E7100: Queue depth exceeded
- E7101: Enqueue timeout (deadline expired during wait)
- E7102: Thread spawn failure (max_threads limit)
- E7103: Work steal timeout
- E7104: Shutdown in progress
Purpose: Manage worker threads with adaptive scaling and work-stealing load balancing.
Responsibilities:
- Spawn and terminate worker threads based on queue depth
- Implement per-thread task queues with work-stealing capability
- Balance load across workers via work-stealing algorithm
- Track worker utilization and scale limits
- Support graceful shutdown with task completion
Key Contracts:
-
create(min_threads, max_threads) β ThreadPoolManager*- Creates thread pool with adaptive scaling bounds
- Initially spawns min_threads workers
-
schedule(task) β Result<TaskToken>- Submits task for execution
- Returns token for cancellation/monitoring
- May spawn new worker if queue depth exceeds threshold
-
shutdown(wait_ms) β Result<>- Stops accepting new tasks
- Completes in-flight work within wait_ms timeout
- Returns error if timeout exceeded
Scaling Strategy:
if queue_depth > high_watermark && active_threads < max_threads:
spawn_new_worker()
if queue_depth < low_watermark && active_threads > min_threads:
signal_worker_shutdown()
-
Query Queue: Protected by single spinlock for enqueue/dequeue operations
- Lock held only for queue state update (< 1 Β΅s)
- Query entries themselves are lock-free (atomic reads)
-
Thread Pool State: Atomic flags for shutdown and scaling decisions
- No mutex for thread count updates (atomic increment/decrement)
- Worker termination signaled via atomic flag
-
Per-Thread Task Queues: Lock-free with compare-and-swap operations
- Only touched by owning thread (no contention for common case)
- Work-stealing uses non-blocking dequeue for competing threads
-
std::atomic<size_t>for queue depth (reader-optimal) -
std::mutex+std::condition_variablefor queue notification - Per-thread
std::atomic<bool>for shutdown signals
- Enqueue: < 5 ms (99th percentile)
- Dequeue: < 100 Β΅s
- Work-Steal: < 200 Β΅s
- Thread Spawn: < 10 ms per worker
- Queue Throughput: β₯ 10k queries/sec at 16 threads
- Vertical Scaling: Nearly linear speedup up to available CPUs
- Horizontal Scaling: Supports cross-node coordination via distributed task queue (future)
- Per-Worker Memory: ~2 MB (task queue, TLS)
- Queue Overhead: O(queue_depth) memory
absolute_deadline = now_ms + sla_deadline_ms
if (absolute_deadline <= now_ms):
return error(E7101); // Deadline already expired
if (queue_depth >= max_queue_depth):
apply_backpressure();- Scheduler tracks deadline violations for reporting
- Violating queries are prioritized for execution or rejected
- Operator runbook: increase
min_threadsor reducemax_queue_depth
- [[
ROADMAP.md|Module-execution-Roadmap]] β Implementation phases and deliverables -
FUTURE_ENHANCEMENTS.mdβ Planned features -
../../include/execution/query_scheduler.hβ Public API -
../../include/execution/thread_pool_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