Codebase Mapdev
Class-by-class map of Luxir internals, oriented toward contributors and
coding agents. For the engine design overview and the reasoning behind it,
see ../design/architecture.md. For exact file
locations, browse src/luxir/<area>/.
Core Components
Section titled “Core Components”-
Server Layer (
src/luxir/server/)GRPCServer: Manages gRPC services and thread poolHttpServer: JSON/HTTP API (Boost.Beast), including NDJSON streaming ingestLuxirNode: Central coordinator wiring collections and servicesStats: The one mapping from engine state (IndexWriter/ReaderManager::stats, RAM budgets, allocator,util/Metrics.hservice counters,SystemStatsprocfs/cgroup readers) intoapi::StatsResponse;Prometheusrenders that response as text for/metricsand_stats?format=prometheusCollections: Owns the name -> collection map and every transition of it (startup discovery, creation, activation, rename, swap, removal), announced in order throughCollectionEvents; a multi-name mapping is one event and atomic per-name lookup changesReplicationFollower: Discovery and transfer protocol, with work keyed by tenant/incarnation. Stages missing data, then applies each tenant mapping throughCollectionsfor ready bindings, leaving dependent names unavailable when their old data now belongs to another nameScrubber: Paced background re-verification of published snapshot files; a mismatch fails the collection (Collections::fail) and a follower repairs itReplicationSource: Local discovery catalog, cursors, follower liveness and acknowledgments, fed by the orderedCollectionEventsinterface.CommitWaits: Node-local publication floors and replica barriers; owns deadlines, cancellation and captured follower expiry. Satisfied floors retain their exact collection.ProtoUpdateMessage::Completion: Owning local result plus copied replica-wait specification; transports release indexing bodies before waiting for visibility.
-
Search Engine (
src/luxir/search/)ReaderManager: Per-collection snapshot publication, reader refresh, and filter cache; searches do not require anIndexWriter. Schema-only snapshots share physical cores.ResolvedSchema.cpp: Declared representations and segment-generation coverageIndexReaderis for reading a whole index and contains aPostingsReaderper index segment; a reopen shares each unchanged segment’sPostingsReaderand live docs with the previous snapshot, and the writer’s open segments in both directions- Physical field catalog records available columns and stored resources; logical retrieval discovery is cached per reader and schema identity
SearchEngine: Coordinates query parsing, execution, and result collection- Implements parallel segment searching using TBB
- Ordinary preparation is shared with HTTP
?explain=resolved;?explain=requestonly parses and serializes
EmitDocs:ReturnFieldseparates the requested output key from the physical read source; wildcard discovery returns logical primaries only
-
Segment Reading (
src/luxir/reader/)PostingsReaderreads a single segment and owns the open files for that segment, plus views derived from its immutable bytes (numeric leaf metadata), which therefore live exactly as long as the mapped filesFieldReaderfinds metadata for a field in the segment (SegFieldInfo)TermsEnumenumerates or finds indexed terms for a field found byFieldReaderDocsEnumreturns the documents for a term found with theTermsEnum. Optionally returns term positions for each document.IntColReaderreads the doc-order numeric column (all numeric field classes store an order-preserving encoded int64)PointsReaderreads the optional 1-D sorted-leaf points index of aRANGE-indexed numeric field (value-sorted leaves + fence directory; exact ordinal counts).BKDReaderreads the 2-D int32 BKD of aGEO_POINTfield. Absence of either =SegFieldInfo.pointsMetaOff == 0.
-
Query System (
src/luxir/query/)Query execution flows from an index-independent
Querythrough a cross-segmentWeight, then through a per-segmentScorerSupplierthat resolves retained construction plans for the cursor, docs-only, bulk, or constant-count product the consumer will execute. The Overview inQuery.his the authoritative hierarchy and planning-contract description.Each query defines
createWeight(aMultiTermQuerysubclass,createFilteredEnum) out of line. That virtual is the class’s key function, so its vtable and the Weight and scorer code reached from it compile once rather than in every translation unit that constructs the query.BooleanQueryandKnnQuerydefine it in their own.cpp; the other queries shareQueryWeights.cpprather than each paying a translation unit’s header parsing for a few lines of code.BooleanQuery’s Weight and scorers are inBooleanWeight.h, which onlyBooleanQuery.cppand white-box tests include.- Supports Term, Boolean, Phrase, and All queries
NumericRangeQueryexecutes through the points index when present (direct materialization or complement), else zone-map pruned or full column scans;GeoBoxQueryexecutes through the BKD. Both share thePointsMaterializescorer/bitset primitives and keep a sparse two-phase column verify for small lead costs.ProtobufQueryParserlowers the wire tree (luxir::api::Query) viaQueryBuilder(the single place query-time analysis is applied);ParseContextcarries the request pool, schema, warnings sink, and shared nesting budgetFieldResolver: Parse-local handles cached by spelling and operation class, with one mutable analysis/normalization chain per field descriptor; lowering retains the resolved physical target- String parsers emit
api::Querysubtrees and lower through the same path:SimpleQueryParser(lenient search-box input that never fails to parse) andExprParser(the strictexprquery language;Cursoris its bounds-checked input,ExprFunctions.hthe reflection-driven function-form registry)
-
Indexing (
src/luxir/index/)IndexWriter: Handles multi-threaded indexing with TBB flow graph pipeline.- Manages
Inverterinstances, flushing, merging, and commits. - Atomically pins schema at update admission; stale inverters flush at checkout or release, keeping one schema per segment
- Manages
CommitSnapshotRegistry: Shard-owned current snapshot and commit-ID pins, lazy idle expiry, and retained-byte eviction. Publishes into its ReaderManager; accepts retirement from a writer or installer independently. Retirement preserves both snapshot pins and writer/merge ownership.Inverter: Single-threaded document processing under one pinned schema.InputHandler: One logical dispatcher per document key; stores source once when the primary enables it and sends the submitted value to every branchIndexHandler: One physical representation, owned byindexHandlers; finish/flush visits each once in global physical-name order
PostingsWriter: used by an Inverter on flush to write a new segment.PointsWriter(1-D sorted leaves) andBKDWriter(2-D geo) build the optional points indexes at flush;SegmentMergercarries 1-D points forward by run-merging and rebuilds geo BKDs from the merged column.
-
Vector Search (
src/luxir/index/,src/luxir/reader/)VectorReader: reads column-stored vectors for exact flat KNNVectorIndexBuilder/VectorAuxReader: per-segment FAISS IVF (RaBitQ by default, or explicit PQ) aux overlays for ANNutil/VectorRotation.h: seeded orthogonal FHT-Kac transform shared by ANN builders, readers and queries; parameters define the rotation disk contract.- Reuses column storage for exact search, cosine raw-column normalization, and full-precision rescoring
- See ../guide/vector-search.md for the user contract (query knobs, scoring, recall) and ../design/vector-search.md for the overlay/build/query internals
-
Storage (
src/luxir/store/)Directory: abstract storage interface. Implementations:RAMDir(in-memory, used by tests),FSDirectory(on-disk, mmap reads),CheckedDirectory(validation wrapper)InputStream/OutputStream: segment I/O primitives; thechecked*reads decode segment info and the field catalog without trusting the fileIndexFormat: the on-disk format version, recorded in each manifest and in every data file’s header. Bump it with any change to written bytes (IndexFormatTestflags one); manifests of another version fail to load withIndexFormatErrorFileVerifier: size + xxh3 checks of files against manifestFileDescriptors overDirectory::openChecksum(pread, optional O_DIRECT; never mmap): verify-on-open, scrubCorruptionMarker:corrupted_<id>files naming suspect index files, re-verified at openDirectoryFactory: storage backends (RAMDirFactory,FSDirFactory) and wrappers (CheckedDirFactory,ReadOnlyDirFactory); opens path views under authoritative and node-private roots.server/TenantCatalogowns names, timestamp incarnation allocation, and reservation/activation/retirement through catalog CAS. RAM storage accounts are keyed by tenant/incarnation; names select accountsstore/IncarnationState: per-incarnation writer epochs and tip CAS. Catalog reservation creates STATE; deleting STATE fences prior writers.Manifestloads the STATE-selected candidate; filenames carry the creating writer epoch, including later live-doc and overlay generationsStorageRegistry(StorageRegistry.h): named backends and layers resolved byCollectionsfromstore.backend/store.layers, with scoped options validated throughParamReader;DelegatingDirectory/DelegatingDirFactoryforward everything for plugin layers. CheckedDirectory and the read-only wrappers implement the bare interfaces; CheckedDirFactory delegates.DirectoryFactory::find<T>()reaches per-node storage state through the wrappers;Directory::capabilities()(HARD_LINK,ATOMIC_RENAME,DURABLE_SYNC,MEMORY_MAPPED,REMOTE) lets callers fall back (reuseFilescopies when links are unavailable)- Note: segment readers/writers live in
reader/(PostingsReader) andindex/(PostingsWriter), not instore/.
-
Schema (
src/luxir/schema/)LogicalField: Primary, variants, and search/value bindings;FieldTypedescribes one physical representationResolvedFieldHandle: Logical owner, role, descriptor, and owned logical/physical names; dynamic roots reference immutable template prototypesSchema: Separate logical input, operation-based request, and physical lookup; authored source stays sparse, resolved HTTP view exposes effective settings and introduction/segment generations for conservative coverageFieldSignature: Effective properties for schema introduction history and the resolved view; immutableSchemaInfofiles persist authored definitions and structured introduction versionsSchemaBinding: Tenant scope, shared name and major/minor/local/epoch version; manifests reference a schema file, segments record historical bindingsSchemaCache: Node-wide weak cache by location/version; snapshots and readers share parsed schemas and their tenant memory charge- Analysis (
src/luxir/analysis/):AnalysisRegistry(name -> maker for tokenizers, token filters, char filters, plus named analyzers) is the only path from an authoredAnalyzerDefto stages; its constructor seeds built-ins, plugins add more before the registry freezes.Analyzer::compileexpands a named analyzer into its definition (the canonical JSON, and so segment metadata, never names the preset) and builds an immutable plan;createChaininstantiates a per-threadTokenChain(char filters, tokenizer, token filters). All callers feed text throughTokenChain::setValue, which runs the char filters;sourceOffsetmaps token offsets back
-
Plugins (
src/luxir/plugin/,cmake/LuxirPlugins.cmake)Plugin/PluginRegistry/Registries: compiled-in extensions registered once byinitPlugins()at startup, then frozen. Plugins are CMake targets added withluxir_add_pluginand selected at build time viaLUXIR_PLUGIN_DIRS.- Extension registries:
QueryRegistry(src/luxir/query/, thepluginQuery arm),SearchOpRegistry(src/luxir/search/, thepluginSearchOp arm) andHttpRouteRegistry(src/luxir/server/);ParamReaderreads plugin arm params. - See plugins.md.
Data Organization
Section titled “Data Organization”- Collection: Logical document group with schema; its storage is a sequence of incarnations (identities), one active in the tenant catalog
- Shard: Physical collection partition, consists of a single Index
- Segment: Immutable index unit
- Flush records the pinned schema binding; merge records the oldest input version, preserving the no-backfill contract. Historical segment bindings do not require opening old schema definitions
Request Flow
Section titled “Request Flow”Search: gRPC/HTTP Request -> SearchEngine -> Query Parsing -> Weight Creation -> Per-Segment Plan Resolution and Execution -> Result Collection -> Response
Indexing: gRPC/HTTP Request -> IndexWriter -> Document Processing (Inverter) -> Segment Writing -> optional Commit
HTTP update bodies are not decoded on the connection’s I/O shard thread. A
buffered JSON body is decoded in the task-arena task that submits it. An
NDJSON stream is only framed on the shard: records that may be control
records ({} or a first key shaped "_name_") are decoded there, in stream
order, and document records stay where the body was read: NdjsonFramer
reads the body straight into chunks and returns views, and the batch
(HttpStreamBatchState::records) holds the chunks until it has decoded them. StreamingUpdateMessage::handle decodes
them on the update graph’s process node, after startUpdateNode has fixed
the batch’s update version, so batches of one connection decode in parallel.
Key Design Patterns
Section titled “Key Design Patterns”- TBB flow graph for asynchronous indexing pipeline
- Custom memory pools (
MemPool) for efficient single-threaded allocation that can be rolled back - For multi-thread safe arena allocation with destructor support, use protobuf’s Arena
- Parallel processing with work-stealing
- Streaming APIs for large result sets
Proto Files
Section titled “Proto Files”Protocol buffer definitions are in protos/:
- luxir.proto: Public service definitions only
- luxir_types.proto: Public request, response, and value definitions
- luxir_index.proto: Internal on-disk commit manifest, excluded from gRPC reflection
The public and internal wire structs are handwritten in src/luxir/api/.
hpp-proto generates their binary and JSON metadata into the build directory.