Skip to content
Development documentation for unreleased code on main. Behavior can change before a release. Latest release docs

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>/.

  1. Server Layer (src/luxir/server/)

    • GRPCServer: Manages gRPC services and thread pool
    • HttpServer: JSON/HTTP API (Boost.Beast), including NDJSON streaming ingest
    • LuxirNode: Central coordinator wiring collections and services
    • Stats: The one mapping from engine state (IndexWriter/ReaderManager::stats, RAM budgets, allocator, util/Metrics.h service counters, SystemStats procfs/cgroup readers) into api::StatsResponse; Prometheus renders that response as text for /metrics and _stats?format=prometheus
    • Collections: Owns the name -> collection map and every transition of it (startup discovery, creation, activation, rename, swap, removal), announced in order through CollectionEvents; a multi-name mapping is one event and atomic per-name lookup changes
    • ReplicationFollower: Discovery and transfer protocol, with work keyed by tenant/incarnation. Stages missing data, then applies each tenant mapping through Collections for ready bindings, leaving dependent names unavailable when their old data now belongs to another name
    • Scrubber: Paced background re-verification of published snapshot files; a mismatch fails the collection (Collections::fail) and a follower repairs it
    • ReplicationSource: Local discovery catalog, cursors, follower liveness and acknowledgments, fed by the ordered CollectionEvents interface.
    • 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.
  2. Search Engine (src/luxir/search/)

    • ReaderManager: Per-collection snapshot publication, reader refresh, and filter cache; searches do not require an IndexWriter. Schema-only snapshots share physical cores.
    • ResolvedSchema.cpp: Declared representations and segment-generation coverage
    • IndexReader is for reading a whole index and contains a PostingsReader per index segment; a reopen shares each unchanged segment’s PostingsReader and 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=request only parses and serializes
    • EmitDocs: ReturnField separates the requested output key from the physical read source; wildcard discovery returns logical primaries only
  3. Segment Reading (src/luxir/reader/)

    • PostingsReader reads 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 files
    • FieldReader finds metadata for a field in the segment (SegFieldInfo)
    • TermsEnum enumerates or finds indexed terms for a field found by FieldReader
    • DocsEnum returns the documents for a term found with the TermsEnum. Optionally returns term positions for each document.
    • IntColReader reads the doc-order numeric column (all numeric field classes store an order-preserving encoded int64)
    • PointsReader reads the optional 1-D sorted-leaf points index of a RANGE-indexed numeric field (value-sorted leaves + fence directory; exact ordinal counts). BKDReader reads the 2-D int32 BKD of a GEO_POINT field. Absence of either = SegFieldInfo.pointsMetaOff == 0.
  4. Query System (src/luxir/query/)

    Query execution flows from an index-independent Query through a cross-segment Weight, then through a per-segment ScorerSupplier that resolves retained construction plans for the cursor, docs-only, bulk, or constant-count product the consumer will execute. The Overview in Query.h is the authoritative hierarchy and planning-contract description.

    Each query defines createWeight (a MultiTermQuery subclass, 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. BooleanQuery and KnnQuery define it in their own .cpp; the other queries share QueryWeights.cpp rather than each paying a translation unit’s header parsing for a few lines of code. BooleanQuery’s Weight and scorers are in BooleanWeight.h, which only BooleanQuery.cpp and white-box tests include.

    • Supports Term, Boolean, Phrase, and All queries
    • NumericRangeQuery executes through the points index when present (direct materialization or complement), else zone-map pruned or full column scans; GeoBoxQuery executes through the BKD. Both share the PointsMaterialize scorer/bitset primitives and keep a sparse two-phase column verify for small lead costs.
    • ProtobufQueryParser lowers the wire tree (luxir::api::Query) via QueryBuilder (the single place query-time analysis is applied); ParseContext carries the request pool, schema, warnings sink, and shared nesting budget
    • FieldResolver: 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::Query subtrees and lower through the same path: SimpleQueryParser (lenient search-box input that never fails to parse) and ExprParser (the strict expr query language; Cursor is its bounds-checked input, ExprFunctions.h the reflection-driven function-form registry)
  5. Indexing (src/luxir/index/)

    • IndexWriter: Handles multi-threaded indexing with TBB flow graph pipeline.
      • Manages Inverter instances, flushing, merging, and commits.
      • Atomically pins schema at update admission; stale inverters flush at checkout or release, keeping one schema per segment
    • 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 branch
      • IndexHandler: One physical representation, owned by indexHandlers; 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) and BKDWriter (2-D geo) build the optional points indexes at flush; SegmentMerger carries 1-D points forward by run-merging and rebuilds geo BKDs from the merged column.
  6. Vector Search (src/luxir/index/, src/luxir/reader/)

    • VectorReader: reads column-stored vectors for exact flat KNN
    • VectorIndexBuilder / VectorAuxReader: per-segment FAISS IVF (RaBitQ by default, or explicit PQ) aux overlays for ANN
    • util/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
  7. 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; the checked* reads decode segment info and the field catalog without trusting the file
    • IndexFormat: the on-disk format version, recorded in each manifest and in every data file’s header. Bump it with any change to written bytes (IndexFormatTest flags one); manifests of another version fail to load with IndexFormatError
    • FileVerifier: size + xxh3 checks of files against manifest FileDescriptors over Directory::openChecksum (pread, optional O_DIRECT; never mmap): verify-on-open, scrub
    • CorruptionMarker: corrupted_<id> files naming suspect index files, re-verified at open
    • DirectoryFactory: storage backends (RAMDirFactory, FSDirFactory) and wrappers (CheckedDirFactory, ReadOnlyDirFactory); opens path views under authoritative and node-private roots. server/TenantCatalog owns names, timestamp incarnation allocation, and reservation/activation/retirement through catalog CAS. RAM storage accounts are keyed by tenant/incarnation; names select accounts
    • store/IncarnationState: per-incarnation writer epochs and tip CAS. Catalog reservation creates STATE; deleting STATE fences prior writers. Manifest loads the STATE-selected candidate; filenames carry the creating writer epoch, including later live-doc and overlay generations
    • StorageRegistry (StorageRegistry.h): named backends and layers resolved by Collections from store.backend / store.layers, with scoped options validated through ParamReader; DelegatingDirectory / DelegatingDirFactory forward 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 (reuseFiles copies when links are unavailable)
    • Note: segment readers/writers live in reader/ (PostingsReader) and index/ (PostingsWriter), not in store/.
  8. Schema (src/luxir/schema/)

    • LogicalField: Primary, variants, and search/value bindings; FieldType describes one physical representation
    • ResolvedFieldHandle: Logical owner, role, descriptor, and owned logical/physical names; dynamic roots reference immutable template prototypes
    • Schema: 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 coverage
    • FieldSignature: Effective properties for schema introduction history and the resolved view; immutable SchemaInfo files persist authored definitions and structured introduction versions
    • SchemaBinding: Tenant scope, shared name and major/minor/local/epoch version; manifests reference a schema file, segments record historical bindings
    • SchemaCache: 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 authored AnalyzerDef to stages; its constructor seeds built-ins, plugins add more before the registry freezes. Analyzer::compile expands a named analyzer into its definition (the canonical JSON, and so segment metadata, never names the preset) and builds an immutable plan; createChain instantiates a per-thread TokenChain (char filters, tokenizer, token filters). All callers feed text through TokenChain::setValue, which runs the char filters; sourceOffset maps token offsets back
  9. Plugins (src/luxir/plugin/, cmake/LuxirPlugins.cmake)

    • Plugin / PluginRegistry / Registries: compiled-in extensions registered once by initPlugins() at startup, then frozen. Plugins are CMake targets added with luxir_add_plugin and selected at build time via LUXIR_PLUGIN_DIRS.
    • Extension registries: QueryRegistry (src/luxir/query/, the plugin Query arm), SearchOpRegistry (src/luxir/search/, the plugin SearchOp arm) and HttpRouteRegistry (src/luxir/server/); ParamReader reads plugin arm params.
    • See plugins.md.
  • 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

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.

  • 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

Protocol buffer definitions are in protos/:

The public and internal wire structs are handwritten in src/luxir/api/. hpp-proto generates their binary and JSON metadata into the build directory.