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

The service and the Worker

Source: written from pkgs/atlas-search/crates/atlas-search/src/server.rs, pkgs/atlas-search/crates/atlas-proto/src/lib.rs, pkgs/fleet/crates/fleet-search/src/serve.rs, and pkgs/atlas-search/worker/src/ (index.ts, search.ts, service.ts, cache_do.ts, hot_cache.ts, key.ts, space.ts, mcp.ts) in https://github.com/developing-today/code/blob/main/pkgs/atlas-search/, plus the binary/service design of record in doc/. Provenance only — this chapter is complete without following it.

Atlas has two serving halves, and they are not two copies of the same thing. The service is a long-lived process on Drew’s laptop that owns the corpus connection, the resident embedding model, and the search itself. The Worker is a small Cloudflare Worker that sits in front of that service as the hosted front door: it authenticates callers, caches whole query results, and forwards anything it has not seen before to the laptop. A local command-line search can bypass the Worker entirely; a hosted caller cannot bypass the service. Everything below keeps the two halves separate, because most confusion about Atlas serving — above all about caching — comes from merging them.

The laptop service

The service is the serve mode of the Atlas search binary: one process that holds the state a one-shot command would have to rebuild on every invocation. That state is a lazily loaded ONNX embedder session for the Snowflake model (about a second to load, a few hundred megabytes resident, against roughly 35 seconds of cold start for the old Python path), a connection pool to the corpus stores, a worker pool for branch execution, and the job registry described below. In production the systemd user unit atlas-search.service does not run the standalone binary: a home-manager flag re-points its ExecStart to fleet serve search, the serve half rehomed into the fleet binary. The unit name, the configuration, the port, and the wire protocol are unchanged by that rehoming, and rollback is the same single flag pointed back at atlas-search serve. The service binds 127.0.0.1:18760 on the laptop, with tailnet exposure layered in front of the loopback port; it is never a public listener in its own right.

Its configuration lives in ~/.local/state/atlas-search/service.json, a file with mode 0600 written by atlas-search init. That file holds the listen address and the per-client token table: each named client has its own bearer token and a ceiling cap, the highest sensitivity ceiling that client may ever search under. The clamp is the security property of the whole design, and it is computed server-side as effective = min(requested, token ceiling cap); the effective ceiling is recorded on the job and reported back in the result envelope, so a caller can always see the ceiling it actually got. Raising a cap is a local edit by Drew on the laptop, never something a request can do. The named clients and their caps are covered in Consumers: fleet, agents, memory and ID.

The job protocol: submit, wait, page

Search over a filtered corpus is slow enough — a filtered vector scan is seconds of server-side work — that the service speaks an asynchronous job protocol over HTTP and JSON, defined by the shared atlas-proto crate so the server and its clients cannot drift apart:

  1. The client submits with POST /v1/search/jobs and receives 202 with a job id and a per-job capability token. That token authorizes only that one job’s status, results, chunk, and delete endpoints; it is not a client credential.
  2. Workers inside the service run the full-text and vector branches concurrently, fuse the two pools once into a final ranking, and land that ranking in the temp store (below). Fetch-to-fill depth escalation, when the vector index path needs it, happens inside the job’s vector branch — never in client paging — precisely so that reciprocal rank fusion runs once, over complete branch pools.
  3. The client polls GET /v1/search/jobs/<id> for status, then pages the finished, immutable ranking with GET /v1/search/jobs/<id>/results using a cursor and a limit (default limit 100). GET /v1/search/jobs/<id>/chunk/<chunk_id> fetches one chunk from the job’s context, and DELETE /v1/search/jobs/<id> discards the job early.

There is also a one-shot POST /v1/search, which is the same machinery with the waiting done on the caller’s behalf, a POST /v1/embed endpoint that returns a query embedding in the pinned space (added for the Worker’s cache-miss path; any valid client may embed, because ceilings govern search, not embedding), feedback endpoints, and an open GET /health that reports liveness, embedder state, queue depth, and active job counts with no authentication and no corpus data. A client that only wants the finished answer — the command line’s one-shot mode sets the protocol’s wait flag — never has to handle the job states itself, but the states are the real protocol, not an implementation detail.

The temp store: ten minutes, in memory, gone on restart

A job’s fused ranking lands in a temp store that is deliberately perishable. It is in-memory only, held by the serve process. Entries carry a TTL of 10 minutes from completion, with a 60-minute hard cap from submit. Nothing in the temp store survives a restart, by requirement — a restart takes every in-flight and finished job’s stored ranking with it, and clients simply submit again.

That perishability is a security property, not a missing feature. Job results hold ceiling-gated snippets: text a particular client was allowed to see at a particular ceiling. The design considered and rejected the two obvious persistent alternatives on evidence. A scratch Turso or libsql database inherits the production writer’s stall behaviour (recorded at roughly 22 minutes per write in the incident that motivated the design). A local SQLite file would work mechanically, but its persistence is itself the liability — snippets would outlive the job, the session, and the reason they were fetched. In-memory storage with a short TTL is the only option that makes the snippets’ lifetime match their purpose. Backpressure follows the same bounded shape: a small number of concurrent branch executions globally, a per-client limit on concurrent jobs with a bounded queue behind it, and saturation answered with 429 and a retry hint rather than unbounded queueing; a job left queued far beyond its useful life fails as expired instead of running stale.

Hold this TTL story apart from the Worker’s, below. Both stores get called “the Atlas cache” in different documents. They are different stores, on different machines, with opposite lifetimes, for opposite reasons.

The Cloudflare Worker

The Worker (package name atlas-search, deployed on the fleet Cloudflare account’s workers.dev subdomain) is the hosted front door for callers that are not on the laptop: principally agents reaching Atlas through the MCP endpoint wired into mcpx, and any REST caller holding the gate token. Its public surface is five routes: GET /health (open, liveness only), POST /v1/search, GET /v1/cache/inspect, POST /v1/cache/purge, and POST /mcp. Everything else is a 404.

Two facts define what the Worker is not. First, it holds no database credentials at all — no Turso token, no shard list, no corpus connection. Shard discovery, fan-out, manifest reads, and merging all live in the laptop service; the Worker knows exactly one upstream, the service, reached through the tunnel hostname atlas-search.security.cab with a Cloudflare Access service token alongside its service token. If the laptop service is unreachable, the Worker degrades to 502 and caches nothing. Second, there is exactly one search execution path: a single executeSearch function that both the REST route and the MCP search tool call after their own gate and validation, so ceiling pinning and cache keying cannot drift between the two surfaces. An MCP search and a REST search for the same normalized query at the same depth are, by construction, the same search — and share one cache entry.

The gate, and the identity the Worker presents

Inbound, every gated route checks one shared secret, named GATE_TOKEN, presented as an Authorization: Bearer header. There are no per-route, per-caller, or per-agent tokens: a valid check yields a boolean and nothing else, so every gated caller is the same identity to the Worker. The comparison is built to be constant-time — both the presented token and the configured token are hashed with SHA-256, and the two 32-byte digests are XOR-folded; the tokens match exactly when the fold is zero. A missing token, a missing configuration, or any mismatch is a 401.

Outbound, the Worker presents exactly one client identity to the service: the cf-worker client, whose service-side ceiling cap is personal. This pinning is compile-time, not configuration. The Worker sends ceiling: "personal" and disclosure context hosted-per-user on every service search; no request field, header, or environment variable can change either value. After the service responds, the Worker verifies that the reported effective_ceiling is personal before anything is cached — a result computed above personal is refused with a 502 and can never enter the cache. The ceiling and context are also fields of the cache key itself, so a payload filtered for one ceiling could never be served to another even if the keying were reached by a different route. The embedding space is pinned the same way: model Snowflake/snowflake-arctic-embed-m-v2.0, 768 dimensions, one pinned model revision and vector table, validated on every cache miss before anything is stored. The full ceiling model is in Sensitivity tiers and client ceilings.

The Durable Object cache: check-and-fill, retained indefinitely

Each distinct query gets its own Durable Object (DO), a small single-threaded Cloudflare object with its own SQLite storage, named by the query’s cache key. The key is the lowercase hex SHA-256 of a versioned JSON material string (key schema KEY_SCHEMA = 2, carried in the material’s v field) containing the normalized query (Unicode NFC, trimmed, whitespace runs collapsed to one space; case preserved), the pinned ceiling, the pinned context, the model revision, the vector table, and the clamped result depth k (default 10, clamped to 1–50; only a JSON number is honoured). One DO therefore owns exactly one (query, depth, ceiling, context, space) combination and exactly one stored row.

That ownership is what makes the cache correct under concurrency: the whole check-and-fill runs inside the DO’s fetch handler, so concurrent misses for the same key serialize on the DO’s single thread and the expensive laptop fan-out executes once. The entry moves through three states — absent, embedded, complete. On a miss the DO inserts the row, asks the service to embed the query, and persists the embedding before the search runs; if the search then fails, the entry stays embedded, the error propagates, and the next request retries the search without paying for the embedding again. On success the result JSON, timestamps, and the measured embed and search times are written, and every later request is a hit: the stored result is returned verbatim and a hit counter is incremented. The operator routes fit the same shape — inspect returns metadata only (presence, embedding dimensions and validity, result size, hit count, timings; never the result body or the vector), and purge deletes exactly one key’s row. There is no prefix or enumeration purge, by design: the key is a digest, and enumeration would need a separate index nobody has built.

This cache has no TTL. Entries are retained indefinitely — no expiry, no eviction, nothing deleted except by an explicit operator purge — by Drew’s order, and tracked as issue #6805. Deferred triggers for revisiting that policy exist on the record (add a corpus generation to the key after a large same-space re-ingest or a stale-result complaint; add a sweeper at a stated size), but they are triggers, not code: today, a cached answer survives any corpus change underneath it. This is the opposite end of the TTL spectrum from the service temp store’s ten minutes, and it is a cost decision — the cache exists so repeated agent queries never re-pay the laptop fan-out — where the temp store’s perishability is a sensitivity decision.

The D1 hot cache: a store that is not wired in

The Worker contains a second cache mechanism, and stating its status precisely matters. The D1 hot-cache tier (D1 is Cloudflare’s hosted SQLite database) is a tenant-keyed store designed as a cheaper tier in front of the Durable Objects: one shared database, rows keyed by (tenant, cache key), each holding an opaque payload blob, a payload class, a source watermark, fill and last-hit timestamps, and a hit count, with an index supporting least-recently-hit eviction order. Its storage module is complete and tested: get, put, touch, and evict primitives all exist and behave as designed.

It is not on the request path. Nothing in the Worker’s routing, search, MCP, service, or cache code calls the store; its only callers are its own tests. The master flag HOT_CACHE_ENABLED (committed value "false"; only the literal string "true" would enable it, and only when the database binding also exists) therefore changes nothing today either way — turning it on would not make a single read or write happen. Freshness evaluation, admission, and an eviction sweep are separate follow-on work, and read-path integration is issue #13105. Like the DO cache, the D1 tier as implemented has no TTL and no automatic eviction, so it too retains entries indefinitely (#6805) — but the operative fact for any reader today is simpler: when you ask where a hosted Atlas answer was cached, the answer is always the Durable Object, never D1.

Timeouts

There are no application-level timeouts anywhere in the Worker. No abort controller, no signal, no deadline, and no setTimeout appears in its source: the outbound calls to the service, the Durable Object stub calls, and the gate’s digest computation all run unbounded, subject only to Cloudflare platform limits that live outside this code. The only time values the Worker handles are measurements — the Date.now() durations it records as embed and search milliseconds — and stored timestamps. A slow laptop service means a slow hosted answer, not a Worker-side cutoff.

How the two halves fit

A hosted query, end to end: the caller passes the gate; the Worker normalizes the query, clamps k, and derives the cache key; the key’s Durable Object either serves its complete entry or runs the fill — embed, then search — against the laptop service, presenting the cf-worker identity, verifying the personal ceiling on the way back, and storing the result indefinitely. A local query skips the Worker entirely: the client speaks the job protocol to fleet serve search on the laptop, whose results live for ten minutes in memory and vanish on restart. Same engine, same corpus, same ceiling discipline — Architecture draws the whole picture — but two front doors with deliberately different memories.