Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

atlas-core: the engine as a library

Source: crates/atlas-core/src/lib.rs and the module files under crates/atlas-core/src/ (including src/shards/), with call sites in crates/atlas-search/src/main.rs, in https://github.com/developing-today/code/blob/main/pkgs/atlas-search/ — provenance only; this chapter is complete without following it.

atlas-core is Atlas with the process removed. Everything the binaries do that is not argument parsing, printing or HTTP lives here: the search pipeline, both data backends, the shard fan-out, staging and promotion, classification, evaluation, traces and feedback. Its crate documentation states the shape plainly: a SearchBackend — the Turso HTTPS pipeline API, or a local SQLite publish file — gathers a full-text pool and a vector pool with the caller’s sensitivity ceiling and filters applied inside the branch queries, before any ranking, and run_search fuses the pools with reciprocal rank fusion under the versioned query-parameter contract.

The library is synchronous. Backends are Send + Sync behind interior locks. The query embedder is the one exception: ONNX sessions take a mutable reference, so serve mode holds one embedder, or a small pool, behind a mutex — a loaded session is about 1.6 GB of resident memory, and it is shared state, not per-request state.

The crate is a semantics-exact port of the Python reference — see atlas_search.py: the Python reference implementation. JSON shapes, field order, note placement and fatal messages mirror the Python, and the parity tests diff rendered envelopes and SQL strings against fixtures recorded from the production Python module.

The 33 public modules, grouped by job

lib.rs declares 33 public modules. Grouped by the job they do:

Retrieval

ModuleJob
searchSearch orchestration and envelope rendering: run_search, run_get_chunk, the search options and modes
fusionThe FTS match expression and reciprocal rank fusion over the two branch pools
filtersThe filter set, the sensitivity ceiling type, and the branch and detail SQL builders. The SQL strings are the contract with the database; parity fixtures record them byte for byte
joinThe span join and reconstruction assembler: assembling a paragraph of a version from its span occurrences, byte for byte, with cold and retired (tombstone) rendering

Embedding

ModuleJob
embedQuery and document embedding at the library boundary: the query: prompt, truncation and renormalisation on the query side; prompt-free embedding on the document side
embed_cacheThe query-embedding cache: an in-memory tier plus an optional shared Turso tier, keyed by model identity and normalised query text. See Data stores and schemas

Corpus

ModuleJob
shardsThe core tier as a set of scan shards: discovery, naming, tiers, manifests, fan-out scan, content stores and the local-file transport (submodules shards::scan, shards::content, shards::local)
tursoThe Turso backend: the libsql HTTPS pipeline against the hosted DB with a read-only token. Every statement it builds is a SELECT
localThe local backend: a SQLite publish file, schema-normalising temporary views, and vector side stores joined by content hash with an in-process cosine scan
backendThe SearchBackend seam both backends implement: branch pools, chunk details, neighbours and message reads, with the ceiling enforced inside branch construction
manifestThe classification manifest: schema, validation and loader for the table that declares the filterable dimensions, with the built-in manifest as fallback and validation reference
boundarySource-boundary-safe embed splitting: the splitter and the classifier share source offsets, every declared boundary splits, and uncertain text becomes one secret-bearing chunk
disclosureDisclosure contexts: the destination-side half of the classification model. The caller ceiling and the destination context’s ceiling intersect; neither widens the other, and enforcement happens at the final output boundary in search

Ingest

ModuleJob
stageStaging databases and the staging-unit registry: provisioning, staged artifacts, classified staging, and the promotion transition
gateThe staging-shard ingest gate’s durable record and state machine: five ordered stages (write, classify, dedup, provenance check, publish), enumerated reason codes, and a strike limit of 3 per reason before a batch needs review
sweepThe source sweep: candidate filtering, guardrails, headroom, state, locking and run reporting for periodic ingest scheduling
github_commentsGitHub comments as a corpus source: comment documents, provenance marks and watermarks
trace_ingestQuery traces as a searchable corpus source, plus trace retention and compaction

Classification

ModuleJob
classificationThe classification record model: records, provenance, and the effective classification composed from records. Unknown, missing or malformed sensitivity fails closed to secret-bearing. The one module with no module-doc header and no lib.rs re-export — reach it as atlas_core::classification
classifyThe classification operating procedure: the unclassified-remainder sweep and schema-change review. The atlas-classify binary is its front end
detectSource detection: passes over plain trees, git trees and row stores, producing a versioned ledger of per-path and per-table verdicts
c8_fingerprintThe C8 error-investigation fingerprint core: error-string normalisation, fingerprints, occurrence grouping and evidence bundles. Pure types and derivations; no telemetry search
c8_profileThe C8 report and page metadata profile: source and page records, typed links and URL sanitising. Likewise seam-independent

Quality

ModuleJob
evalThe offline retrieval evaluation harness: saved rankings from any signal scored against judged qrels (nDCG@10, Recall@100, Recall@1000, MRR@10), with dev/test split discipline
feedbackFeedback capture in the atlas-feedback/v1 schema: votes attached to a query and chunk identity, the append-only JSONL sink, and the derived supersede view
feedback_normaliseThe normalisation pass over raw feedback: categories, summaries, self-feedback detection and requester weighting, emitted as derived records — the raw store is never rewritten
traceQuery-trace capture in the atlas-query-trace/v1 schema. Every executed search mints a query id and persists one trace record before the response is released; a sink failure is a search failure
trace_statsTrace statistics and the weekly report: windowed aggregation over traces and feedback votes, with the requester weights (the owner and users at 1.0, agents at 0.25, anonymous at 0.1)

Support

ModuleJob
typesThe shared value and row model between the Turso pipeline encoding and rusqlite: values, rows, statements, branch hits and pools, chunk details, and the canonical defaults (the default model and the default vector table, vec_snowflake_m_v2_768_f32)
errorThe error type and the crate’s Result alias; see the error vocabulary below
aggregateThe staging aggregator: embed-at-promotion. It reads one staging unit, embeds every chunk document-side, writes one new core scan shard, stamps provenance and promotes the unit through the registry
owner_inventoryThe owner inventory matcher (atlas-owner-inventory/v1): a narrow, fail-closed component whose findings carry a class and an opaque record id, never a matched value
shinglesToken shingles and the Jaccard rescore signal: a third signal applied only at rescore time over the fused candidate union, never a retrieval scorer. Off by default in the shipped parameters

Four binaries live in this crate’s src/bin/ — atlas-classify, atlas-eval, atlas-github-comments and atlas-sweep — each a thin front end over the module of the same job. Three examples (live_smoke, retrieval_proof, shard_bench) exercise the library against live stores.

Key public types

The types a caller actually constructs or matches on:

TypeModuleWhat it is
SearchOptionssearchOne search request: the query, the mode, k (default 10), the per-branch pool (default 100), grouping, expand (default 0), the model, the truncation width (0 = full), the vector backend (default scan), the query parameters, and the disclosure context (default PublicSurface — fail-closed at the library layer). Built with SearchOptions::new(query)
SearchModesearchFts, Vector or Hybrid (the default)
FiltersfiltersThe classification filters and the caller ceiling: kind, topic, project and client lists, the maximum sensitivity, and the since/until dates. Construction validates, with the Python’s fatal texts
SensitivityfiltersThe ceiling ladder Shareable < Personal < LocalOnly < SecretBearing; the ordering is the security ordering. Default Personal
DisclosureContextdisclosureThe destination context — FleetInternal, HostedPerUser, PublicSurface, LocalOwner — each with its own ceiling; effective_ceiling(grant) is the minimum of the two
SearchBackend (trait)backendThe data-source seam: branch_pools, chunk_details, neighbors, message_chunks, message. Implementations: TursoBackend and LocalBackend
QueryEmbedder / DocEmbedder (traits), AtlasEmbedderembedThe embedding seam. AtlasEmbedder wraps the atlas-embed embedder behind a mutex and implements both traits; fixed-vector embedders stand in for tests and fixtures
BranchPools, BranchHit, ChunkDetailtypesWhat a backend returns: the FTS and vector pools (a vector hit carries its cosine distance; an FTS hit carries none), and the resolved detail row for a chunk, including its effective sensitivity
Error, ResulterrorThe error vocabulary, below
Manifest, LoadedManifestmanifestThe classification manifest and its loaded form, with the source it came from
Registry, StagingUnitstageThe staging registry handle and one unit’s record
GateRecordgateOne batch’s gate audit record. The gate types are public in their module but are not re-exported at the crate root

Most workhorse types are re-exported at the crate root (atlas_core::run_search, atlas_core::Filters, atlas_core::TursoBackend and so on). The recorded exceptions are classification, the gate types, github_comments, sweep and the shards types, which are reached through their module paths.

Two crate-level constants bound every caller: MAX_EXPAND_NEIGHBORS = 100, the ceiling on neighbour expansion and on get-chunk neighbours, and the message text cap of 50,000 characters applied to message payloads.

The error vocabulary

The library has exactly three errors, in atlas_core::Error:

VariantMeaningExit code at the atlas-search binary
Error::Fatal(String)A fatal that mirrors a Python die() text: validation failures, unresolvable configuration, a missing model or token. Constructed with Error::fatal(...)2
Error::Backend(String)A backend or transport failure: the pipeline request, the database, the local file. Constructed with Error::backend(...)1
Error::Embed(String)An embedding failure: the model, the runtime, a zero query vector1

atlas_core::Result<T> is the crate-wide alias over this error. The exit-code column is the binary crate’s mapping, not the library’s — the library returns the variant and the caller decides what it costs. One special case rides on top of it in the binary: a get-chunk not-found arrives as a Fatal with the exact message chunk <id> not found and is remapped to exit 1, matching the Python.

Embedding a search in another binary

The shape of the call, taken from the real call sites in the atlas-search crate’s main.rs: open a backend, build the filters, build the options, call run_search, and print or serve the returned JSON envelope. The envelope — not a result struct — is the return value: a serde_json::Value whose shape, field order and notes mirror the Python exactly.

#![allow(unused)]
fn main() {
use atlas_core::{Filters, LocalBackend, SearchOptions, TursoBackend, run_search};

// Standalone shape: a backend, an embedder, filters, options.
// The Turso backend resolves its read-only token itself:
let backend = TursoBackend::new(vec_table)?;
// …or the local publish file:
// let backend = LocalBackend::new(db_path, vecdb_arg, vec_table, trunc)?;

let filters = Filters::new(/* kind, topic, project and client lists,
    the max-sensitivity ceiling, and the since/until dates */)?;
// construction validates, and its fatals carry the Python's texts

let mut opts = SearchOptions::new(query.to_string());
opts.k = 10;          // defaults already: k 10, pool 100, expand 0,
opts.context = ctx;   // hybrid mode, scan vector backend

let envelope = run_search(&backend, &embedder, &filters, &opts)?;
// envelope is the JSON result document, ready to print or return.
}

What the call sites around that shape add:

  • The embedder is lazy. FTS-only searches and get-chunk never load the model. The binary builds the real embedder only when the mode uses the vector branch; library callers follow the same rule, passing a fixed or absent embedder where no vector work can occur.
  • One chunk, by id: run_get_chunk(&backend, chunk_id, neighbors) returns the chunk envelope with that many same-message neighbours attached (at most 100). run_get_chunk_with_context is the form that also applies a disclosure context.
  • Traced searches: run_search_traced (and run_search_with_executor_traced for a custom branch executor) take a TraceJob carrying the trace sink, the trace context and the query id, and persist the trace before the envelope is released. The one-shot binary always searches traced, through a JSONL sink; a sink failure fails the search.
  • Custom branch execution: run_search_with_executor accepts any BranchPoolExecutor in place of the backend’s own branch pools — the seam the shard fan-out composition uses, serving the vector branch from the shard set while the wrapped backend keeps FTS, details and neighbours.

Worked example — the smallest complete embedding, in the shape of the crate’s own examples: open a LocalBackend on a publish file, construct Filters with no dimension filters at the default personal ceiling, construct SearchOptions::new("backup retention"), and call run_search with a fixed embedder for an FTS-only mode so no model is needed. The returned envelope names the backend, the filters in force and the ranked results, exactly as the CLI would print it.

Failure shapes

  • expand above 100, a non-scan vector backend on a non-Turso backend, and hydration combined with grouped output are all Fatal before any branch runs.
  • In FTS mode, a query with no FTS-searchable terms (every word too short) is Fatal; in hybrid mode the same query simply runs the vector branch alone.
  • A shard fan-out in which the scanned shards carry mixed embedding models is Fatal: vectors from different embedding models are not comparable. A failing shard likewise fails the whole query — a partial answer that silently omits a shard is treated as worse than an error.
  • A missing or empty HOME environment variable panics loudly in the path expansion used by the Turso and local backends, by design; it is never silently replaced with a relative path.

For the workspace this crate sits in, see The crates. For the stores its backends read, see Data stores and schemas.