# Layer — Full documentation Search endpoint: https://hevlayer.com/api/ask/pro # Agents Source: https://hevlayer.com/docs/pro/agents import Edition from "../../components/docs/Edition.astro"; import Callout from "../../components/docs/Callout.astro"; These docs are queryable from the command line. The same engine behind the `⌘K` search on this site ships as a CLI, so your coding agent can search, read, and cite the Layer docs directly — no scraping, no MCP server, no API key. The `layer` CLI also lets agents operate environments, indexes, pipelines, UDFs, and Function runs. The skill bodies below are plain `SKILL.md` files. Use your agent harness' native skill directory when it has one, or paste the same Markdown into `AGENTS.md` or the harness equivalent. ## 1. Install the CLIs ```sh go install github.com/hev/ask/cmd/ask@latest ``` The `ask` binary is self-contained; any agent harness that can run a shell command can use it. From a Layer checkout, build the `layer` CLI when the agent should operate Layer environments instead of only searching docs: ```sh go build -o layer ./apps/layer-cli ``` ## 2. Add the docs skill Set `AGENT_SKILL_HOME` to your harness's skill directory, such as `~/.codex/skills` for Codex or `~/.claude/skills` for Claude Code. ```sh AGENT_SKILL_HOME="${AGENT_SKILL_HOME:-${CODEX_HOME:-$HOME/.codex}/skills}" mkdir -p "$AGENT_SKILL_HOME/hevlayer-docs" cat > "$AGENT_SKILL_HOME/hevlayer-docs/SKILL.md" <<'EOF' --- name: hevlayer-docs description: >- Query the hev layer docs. Use when the user asks about Layer — the turbopuffer gateway, stable reads, the stable watermark, the document cache, warm jobs, scans (filter, full-text, and radius), snapshots, pipelines, UDFs, the Index/InfraRules/Pipeline/Function CRDs, compute pools, install via Terraform or Helm, failure modes, or the dashboard. --- # hev layer docs Answer Layer questions from the docs, not from memory. Every verb is a keyless read: ask --endpoint https://hevlayer.com/api/ask/pro search "" ask --endpoint https://hevlayer.com/api/ask/pro section get "" ask --endpoint https://hevlayer.com/api/ask/pro overview ask --endpoint https://hevlayer.com/api/ask/pro glossary get "" Start with `search`; fetch sections for detail; use `overview` when you need the full map. Section ids look like `api/query#stable-reads`. Cite sections in your answer as https://hevlayer.com plus the returned `url` field. If `ask` is missing, install it: `go install github.com/hev/ask/cmd/ask@latest` EOF ``` ## 3. Add the layer CLI skill Use this skill when an agent should inspect or operate Layer through the `layer` CLI. The skill keeps read-only inspection, docs lookup, and mutating operations separate. ```sh AGENT_SKILL_HOME="${AGENT_SKILL_HOME:-${CODEX_HOME:-$HOME/.codex}/skills}" mkdir -p "$AGENT_SKILL_HOME/hevlayer-layer-cli" cat > "$AGENT_SKILL_HOME/hevlayer-layer-cli/SKILL.md" <<'EOF' --- name: hevlayer-layer-cli description: >- Use the hevlayer layer CLI. Use when the user asks an agent to inspect Layer environments, query docs through layer ask, list or get indexes, pipelines, or UDFs, open the operations TUI, delete indexes, or run Function manifests with the layer CLI. --- # hevlayer layer CLI Use `layer` to operate hevlayer from the terminal. In a Layer checkout, prefer a repo-local binary: go build -o layer ./apps/layer-cli ./layer --help Use `./layer ...` for a repo-local binary and `layer ...` for one on `PATH`. Prefer `-o json` for agent parsing and do not print API keys. For docs questions, start with `layer ask` against the committed digest: layer ask grep "" layer ask cat "" layer ask tree layer ask glossary get "" For read-only operational inspection, prefer: layer -o json env ls layer -o json env show [NAME] layer -o json index list layer -o json index get NAME layer -o json pipeline list layer -o json pipeline get ID layer -o json udf list layer -o json udf get UDF_ID Only `layer run` needs Kubernetes access by default. It applies a Function CR, registers the UDF spec with the gateway, triggers discovery, and optionally watches until the queue drains. Confirm the target environment, gateway URL, kube context, and Kubernetes namespace before mutating state. Mutating commands include `layer env add`, `layer env use`, `layer env rm`, `layer index delete`, `layer run`, and `layer run --rm`. Resolve configuration in this order: explicit flags, `LAYER_*` or `HEVLAYER_*` environment variables, `--env` or `LAYER_ENV`, the active `~/.hevlayer/config.toml` environment, then the built-in base URL. EOF ``` ## 4. Ask ```sh ask --endpoint https://hevlayer.com/api/ask/pro search "cache is down" ``` ```json { "results": [ { "title": "Concepts", "heading": "Document cache", "url": "/docs/pro/concepts#document-cache", "group": "Overview", "snippet": "The document cache does two jobs: pull-through document reads..." } ] } ``` From here your agent typically runs `section get` on the winning id and answers with the citation. ## The verbs | Verb | Returns | | --- | --- | | `overview` | Orientation context plus the full section map with stable ids | | `search ""` | Ranked sections with snippets and deep links | | `section get ""` | One section: summary, exact identifiers, source URL | | `glossary get ""` | A product term resolved through its aliases (`watermark` → stable watermark) | ## Why answers stay grounded Search runs over a committed, reviewable digest of these docs — the same corpus, heading by heading, that renders on this site. Every anchor in it is verified against the rendered pages in CI, so a cited deep link like [/docs/api/query#stable-reads](/docs/pro/api/query#stable-reads) always resolves. When the docs change, the digest is rebuilt and recommitted with them. Every verb above is a read against the public docs. Nothing to sign up for, nothing to configure beyond the endpoint URL. The docs are also available as plain text for direct ingestion: [/docs/pro/llms.txt](/docs/pro/llms.txt) (index) and [/docs/pro/llms-full.txt](/docs/pro/llms-full.txt) (full corpus). The CLI is the better path for agents that can run commands — it ranks, resolves aliases, and costs a fraction of the tokens. # Dashboard Source: https://hevlayer.com/docs/pro/dashboard import Callout from "../../components/docs/Callout.astro"; The Layer dashboard is the operator UI that ships in-cluster alongside the gateway, as the `layer-dashboard` Deployment and Service. This page covers running it: the access it needs, how to reach it, how to gate it, and how to turn it off. ## Access it needs The dashboard is read-mostly and backed by three sources, each with its own grant: - **The gateway API** — the same endpoints customers use, plus the Prometheus-compatible metrics proxy at `/v2/metrics`. Authenticated with a gateway bearer (`LAYER_GATEWAY_API_KEY`). In `deriveFromStore` mode this is the default `VectorStore` credential; in `keys` mode it is the configured inbound worker key. It does not touch PostgreSQL, Aerospike, or VictoriaMetrics directly — metrics and cost arrive through the gateway proxy and `/v2/cost`. - **The Kubernetes API** — reads `hevlayer.com` CRDs (VectorStores, Indexes, InfraRules, Pipelines) and the workload objects behind them (pods, deployments/statefulsets, HPAs, KEDA ScaledObjects, nodes) through RBAC bound to its ServiceAccount. `dashboard.kubeAccess.enabled` grants the read role; with it off the dashboard still runs but the cluster/scaling views show a "kube access not configured" banner. `dashboard.writeAccess.enabled` adds the operator write role: Index spec patches, Karpenter NodePool disruption, VectorStore and Warehouse create/edit, and namespace-scoped Secret writes for credentials. Set it `false` for a read-only install. - **Cost data** — the cost view reads the gateway cost API. turbopuffer spend is metered from upstream billing counters; AWS spend is read by the gateway from Cost Explorer using the gateway IRSA role. The dashboard does not need direct AWS cost API permissions for the standard cost view. In a Terraform install, still pass `dashboard.serviceAccount.roleArn` from the `layer_dashboard_role_arn` output so the dashboard ServiceAccount is annotated with its cluster-specific IRSA role at first boot. ## Networking The dashboard is an operator tool. **Reach it over a port-forward** rather than exposing it publicly: ```sh kubectl port-forward -n svc/layer-dashboard 8081:8081 ``` Then open `http://localhost:8081`. Customer workloads only ever receive the gateway base URL and credentials — never the dashboard. ## Basic auth HTTP Basic auth sits in front of every dashboard route and is **required** — the dashboard refuses to start without it. Set credentials through the chart: ```yaml dashboard: basicAuth: user: ops password: ``` The chart render fails if either field is blank while the dashboard is enabled. ## Disabling the dashboard The dashboard is optional. Disable it and the Deployment, Service, RBAC, and ingress all skip rendering: ```yaml dashboard: enabled: false ``` The gateway and transform runtime run unchanged without it; you lose only the operator UI. ## Operational notes ### Pipeline queue states The pipeline overview combines gateway queue counters with the matching `Pipeline` resources and their operator-managed Deployments and KEDA ScaledObjects. A queue with pending work is presented as: - **PAUSED** when every matching `Pipeline` has `spec.paused: true`. Its workers are intentionally at zero replicas; pending documents remain queued. - **CRON-GATED** when its cron ScaledObject is inactive. The card shows the next UTC window, scaler activity, and managed worker replica counts. - **STALLED** when work is pending with no processing or indexing activity and neither an intentional pause nor a closed cron window explains the stop. Failed-document counts, operator condition messages, and missing or inactive managed workers appear as reason hints on the same card. A growing queue that is still processing remains **BACKLOG** rather than **STALLED**. The **data** tab is split into indexes, vector store, and warehouse views. Indexes come from `/v2/namespaces`; vector stores and warehouses come from the gateway's `/v2/vectorstores` and `/v2/warehouses` projections, so the dashboard shows the same credential-safe shape as the CLI and SDKs. When write access is enabled, the vector store and warehouse panes can create and edit those CRDs. Raw credentials are accepted only in the form submission; the dashboard writes them into Kubernetes Secrets first, then creates or patches the CR. The read views keep showing only Secret references. The dashboard is intentionally read-mostly. Mutating actions (UDF pause, InfraRules or scaling edits, data-supply CRD apply) are gated through CRD apply or explicit confirm dialogs, and write access is governed separately by `dashboard.writeAccess.enabled`. # Concepts Source: https://hevlayer.com/docs/pro/concepts import Edition from "../../components/docs/Edition.astro"; import Callout from "../../components/docs/Callout.astro"; import StoreNote from "../../components/docs/StoreNote.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; import StoreMatrixLink from "../../components/docs/StoreMatrixLink.astro"; ## Wire protocol matching Layer accepts the Turbopuffer HTTP wire protocol: the methods and paths a client calls, the JSON request fields it sends, and the response shapes and status codes it reads. For supported operations, an application can point its Turbopuffer client at Layer's base URL and keep the same request body. See the [API reference](/docs/pro/api/introduction) for authentication and client setup. With Turbopuffer as the store, Layer forwards native requests after gateway validation. With another store, Layer translates supported operations into that store's native calls. A valid but unsupported feature should return `422 UnsupportedByStore`, naming the store, route, and feature, rather than silently dropping part of the request. Matching the wire does not promise identical index internals, latency, scores, or ranking across stores. In particular, full-text ranking is backend-specific. Layer's additional request fields, routes, and response metadata are documented as gateway enhancements. ### How we validate it - **API and client contracts.** The SDK harness compares the gateway OpenAPI operations and generated Python client with the upstream API, and checks captured HTTP requests against documented examples using a mock server. These checks catch route, field, and serialization drift; they do not prove that a real backend returns the right results. - **Backend acceptance.** Store-specific suites send requests through a real gateway and backend using generated clients. They check supported operations and explicit rejection of unsupported requests. - **Documented examples.** A committed selection of upstream examples runs against a real gateway and store. Each request is classified as **ok**, **unsupported**, **fail**, or **blocked** by a prerequisite. A baseline change fails the check for review; matching a baseline can still preserve known failures. This is a selected test corpus, not proof that every upstream request or combination works. The capability matrix is generated from backend declarations and checked for source drift. It states the contract; acceptance results are evidence of behavior. Both are needed to assess compatibility. ## Gateway enhancements Layer adds retrieval operations around the store while keeping one client endpoint. [Hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion) combines retrieval legs, [query routing](/docs/pro/api/query#query-routing) selects a strategy, [scans](/docs/pro/api/scans) select or count matching rows, and [federated queries](/docs/pro/api/federated-query) combine named namespaces. The API reference calls out each backend's limits at the relevant feature. The [Layer clients](/docs/pro/api/introduction#install) expose these additions; plain HTTP can call the same API. Native requests and enhanced requests can share the gateway endpoint. Where Layer needs bookkeeping attributes, it reserves the `_hevlayer_*` prefix. Treat these fields as read-only; the [document model](/docs/pro/document-model) defines the contract. ## Control loops Layer uses a control loop as a core primitive for managing your indexes. It reconciles index state against metrics emitted by the search system, which is how Layer applies row-level transformations ([UDFs](/docs/pro/kubernetes/function-crd)) and keeps an index's stable view current. Related: [UDFs](/docs/pro/kubernetes/function-crd), [snapshots](/docs/pro/api/snapshots), stable watermark. ## Kubernetes autoscaling Because Layer is stateless, you can autoscale every tier independently. Karpenter handles node-level scaling, and KEDA scales pods against signals from an embedded PostgreSQL queue. The data in that queue is used for scaling decisions only — it carries no non-recoverable system state. ## Scatter/gather Layer can partition a single namespace into hash buckets, called shards, by assigning each row a reserved `_hevlayer_shard` attribute (xxh64 of its id, modulo the shard count). The gateway then scatters a query to every bucket in parallel, one `_hevlayer_shard`-filtered query per shard, and gathers the results: it merges and re-ranks the combined rows down to your requested `top_k` before returning them. Sharding stays invisible to the client — you issue one query and get one ranked result set. The same scatter/gather path backs [scans](/docs/pro/api/scans) (filter, full-text, and radius) and [UDF](/docs/pro/kubernetes/function-crd) discovery scans. For an existing turbopuffer namespace adopted by Layer, initialize sharding with `POST /v2/namespaces/{namespace}/init` and a `shard_count`. The gateway writes a reserved namespace marker, stamps new writes immediately, and runs an embedded scan-and-patch backfill for rows that do not yet have `_hevlayer_shard`. Scatter/gather activates only after namespace metadata reports `layer.shard_lag_rows: 0`; until then queries and scans use the single-namespace path so unstamped rows are not missed. Run `layer init --shards N` to create the namespace shard marker, start the backfill, and watch `shard_lag_rows` drain until scatter/gather activates. ## Document cache The Layer document cache does two jobs. Document [reads](/docs/pro/api/query#fetch) are served pull-through: the gateway checks the cache first, and on a miss reads through to turbopuffer (or S3 for snapshots), returns the row, and backfills the cache best-effort. [Pipeline](/docs/pro/api/pipelines) chunk handoff uses the same store as the queue between CPU and GPU workers. Neither job makes it a hard dependency: document reads fall through to origin if the cache is unavailable, and chunk reads fall back to S3 backing (see [Failure modes](/docs/pro/failure-modes)). One logical cache serves every path, with different uses (document fetch, pipeline chunks, snapshot field-values) separated into dedicated cache sets. ## Glossary | Concept | Meaning | | --- | --- | | Wire protocol | The HTTP methods, paths, request fields, response shapes, and status codes exchanged by client and server. | | Wire feature | An individual operation or option whose backend support is declared in the capability matrix. | | Gateway | The Layer service that receives client requests, validates them, and executes them against the configured stores. | | [VectorStore](/docs/pro/api/vectorstores) | A serving connection to the backend that stores and queries rows. | | [Warehouse](/docs/pro/api/warehouses) | An upstream source connection, separate from the store serving retrieval requests. | | Namespace | A named collection of rows addressed through `/v2/namespaces/{namespace}`. | | Document / row | An ID and application attributes, optionally including vectors. | | [Scan](/docs/pro/api/scans) | Row selection that returns matching IDs, field values, or a count; supported selectors depend on the backend. | | Shard | A hash bucket within a namespace, identified by the reserved `_hevlayer_shard` attribute. | | Scatter/gather | Running subqueries across shards or namespaces and combining their results into one response. | | Leg | One subquery contributing to a hybrid or federated result. | | RRF | Reciprocal rank fusion: combining ranked lists using each result's position in its input lists. | | Tokenizer policy | The rules that turn input text into retrieval tokens, including word boundaries, case normalization, and token limits. | | Route | A retrieval strategy, such as `hybrid_text`, `semantic`, or `fused`, selected by the query router where supported. | | Routing policy | The deterministic, versioned rules used to select an `Auto` route. | | Deferral | An `Auto` response with `executed: false`: the application must supply an embedding before the selected route can execute. | ### Pro runtime terms | Concept | Meaning | | --- | --- | | Document cache | Layer-managed hot records keyed by namespace and document id, plus cache sets for pipeline chunks and snapshots. | | Stable watermark | Epoch-ms cut tracked by the consistency watcher when turbopuffer reports up-to-date, or when a backing store without an index watermark settles its `row_count` across consecutive polls. | | Ready signal | Whether a namespace is fully indexed: `indexed` / `index_lag_rows` on [namespace metadata](/docs/pro/api/namespace-metadata), reconciled from the latest snapshot when every row's vector is indexed. | | [Pipeline](/docs/pro/api/pipelines) | A PostgreSQL-backed state machine for CPU extraction and GPU embedding work. | | [Snapshot](/docs/pro/api/snapshots) | A content-addressed S3 facet histogram written after a namespace is observed stable. | | Facet listing | The distinct values for a field, precomputed in snapshots as `fields[].values[].v` or computed on demand by a values scan. | | Facet count | The document count for a facet value, returned as `fields[].values[].n` in snapshots and `values[].n` in values scan results. | | [UDF](/docs/pro/kubernetes/function-crd) | A stateless worker the gateway coordinates over existing rows to enrich, fan out, or re-upsert data. | | [Operator](/docs/pro/kubernetes/operator) | The Kubernetes operator that reconciles Layer's CRDs — functions, pipelines, scaling, and cluster config. | | CRD | Custom Resource Definition: the Kubernetes-native resources the operator reconciles — [functions](/docs/pro/kubernetes/function-crd), [pipelines](/docs/pro/kubernetes/pipeline-crd), [scaling](/docs/pro/kubernetes/scaling-crd), and [indexes](/docs/pro/kubernetes/index-crd). | | PromQL | The Prometheus query language. The gateway proxies it to the embedded VictoriaMetrics so you can query metrics without a separate scraper. | # Layer CLI Source: https://hevlayer.com/docs/pro/cli import Edition from "../../components/docs/Edition.astro"; import StoreNote from "../../components/docs/StoreNote.astro"; The `layer` CLI operates hevlayer from the terminal. It manages named environments, initializes adopted namespaces for sharding, observes index, pipeline, and UDF state from the gateway, mints and revokes API keys, shows VectorStore and Warehouse health, and runs Function manifests. Every read goes through the gateway API with an API key; besides the [`install` lifecycle](#install-an-aws-environment), only `run` touches Kubernetes — it applies the Function CR, registers the UDF spec with the gateway, triggers discovery, and optionally watches until the queue drains. `run` is the only command that needs a kube context: set it on the environment with `--kube-context`/`--kube-namespace` or per invocation with `--context`/`--kube-namespace`. ## Install From the repository root: ```sh go build -o layer ./apps/layer-cli ``` ## Install An AWS Environment `layer install` provisions a full AWS environment — Terraform (VPC, EKS, IAM/IRSA, S3, ECR) followed by the Helm release — as a single shot. `--profile demo` (the default) installs the lean footprint; `--profile indexing` adds the dedicated document-cache node pool. `layer install status` reports release and workload health, and `layer install uninstall` tears the environment down. The command runs from a `hev/layer` source checkout, which carries the Terraform configuration and the Helm chart it drives: ```sh git clone https://github.com/hev/layer cd layer go build -o layer ./apps/layer-cli ./layer install ``` Missing required inputs prompt interactively on a TTY; the command prints the resolved plan and asks for confirmation before provisioning anything. The [Install](/docs/pro/install) page is the reference for every flag, profile, and value it sets. ## Configuration `layer` reads named environments from `~/.hevlayer/config.toml`. The directory is created with mode `0700`; the config file is written with mode `0600`. ```toml active = "partner" [envs.partner] base_url = "https://aws-us-east-1.hevlayer.com" api_key = "..." kube_context = "partner-cluster" kube_namespace = "hevlayer" [envs.local] base_url = "http://localhost:8080" api_key = "dev" kube_context = "kind-hevlayer" ``` Resolution order is: | Priority | Source | | --- | --- | | 1 | Explicit flags such as `--base-url`, `--api-key`, `--context`, and `--kube-namespace` | | 2 | `LAYER_BASE_URL`, `LAYER_API_KEY`, and the `HEVLAYER_` twins | | 3 | Environment selected by `--env` or `LAYER_ENV` | | 4 | Active environment in `~/.hevlayer/config.toml` | | 5 | Built-in base URL default | A shell exporting `LAYER_BASE_URL` or `LAYER_API_KEY` keeps the env-var-only behavior and does not need a config file. `--env` and `LAYER_ENV` select an environment for one invocation without changing the active environment. | Flag | Environment | Default | | --- | --- | --- | | `--base-url` | `LAYER_BASE_URL`, `HEVLAYER_BASE_URL` | `https://aws-us-east-1.hevlayer.com` | | `--api-key` | `LAYER_API_KEY`, `HEVLAYER_API_KEY` | none | | `--env` | `LAYER_ENV` | active config env | | `-o`, `--output` | none | `table` | Output formats are `table`, `json`, and `names`. ## Environments ```sh layer env add partner --base-url https://aws-us-east-1.hevlayer.com \ --api-key "$LAYER_API_KEY" --kube-context partner-cluster \ --kube-namespace hevlayer layer env use partner layer env ls layer env show partner -o json layer env rm partner ``` `env add` prompts for missing values on a TTY. On a non-TTY, the required values must be supplied by flags. API keys are masked in `env ls` and `env show`. ## Initialize a Namespace ```sh layer init products --shards 8 layer init products --shards 8 --watch=false layer init products --shards 8 --poll-interval 5s ``` `init` calls `POST /v2/namespaces/{namespace}/init` through the selected gateway environment. The command creates or reattaches to the namespace shard marker, starts the shard backfill, and watches by default until `shard_lag_rows` reaches `0` and scatter/gather is active. Re-running with the same shard count is idempotent; requesting a different shard count returns a conflict message instead of changing the marker. ## Run A Function ```sh layer run -f tag-products.yaml layer run -f tag-products.yaml --index amazon-products-staging layer run -f tag-products.yaml --detach layer run -f tag-products.yaml --rm ``` The input is a Kubernetes `Function` manifest. `--index` overrides `spec.targetNamespaces` with one target. `--context` selects a kubeconfig context; `--kube-namespace` selects the Kubernetes namespace for the Function CR. `--no-apply` skips the Kubernetes apply step for workers managed outside the operator. `spec.version` is registered with the gateway as the Function completion marker version. Bump it before re-running a Function after changing a model, prompt, taxonomy, or worker write contract. `--detach` returns after registration and discovery. Without `--detach`, the CLI polls UDF status until discovery has completed and `pending_count` and `processing_count` are both zero. A drained queue with failures exits non-zero. `--rm` deletes the gateway registration and, unless `--no-apply` is set, the Function CR after the queue drains cleanly. A drain with failures leaves both in place so you can inspect them. Watch a run from another terminal: ```sh layer udf list layer udf get product-tags --watch ``` `udf list` lists registered UDFs with pending, processing, failed, discovery sweep count, and indexed rate. `udf get` shows those fields for one UDF; `--watch` polls until `pending_count` and `processing_count` are both zero. ## TUI Bare `layer` on a TTY opens the read-only operations TUI (`layer browse` is the explicit spelling); on a non-TTY it prints usage and exits `2`. Press `i`/`f`/`p`/`k`/`e` to switch between indexes, functions, pipelines, keys, and environments from any view, `enter` to open a detail view, and `esc`/`q` to back out. Every view has a non-interactive command twin with the same data — the TUI humanizes timestamps and sizes; the commands emit raw values for scripting. | TUI view | Command | | --- | --- | | Environments | `layer env ls` | | Functions | `layer udf list` | | Function detail | `layer udf get UDF_ID [--watch]` | | Indexes | `layer index list` | | Index detail | `layer index get NAME` | | Pipelines | `layer pipeline list` | | Pipeline detail | `layer pipeline get ID` | | Keys | `layer keys ls` | | Key detail | `layer keys get KEY_ID` | The keys views are read-only like the rest of the TUI: minting and revoking stay in the commands. ## Keys ```sh layer keys mint cohort-reader --owner acme \ --entitle vectorstore.prod-turbopuffer=read \ --namespaces "cohort-*" \ --claim warehouse.prod-snowflake="notes:cohort:*:read" layer keys ls layer keys get cohort-reader layer keys revoke cohort-reader layer keys rm cohort-reader ``` `keys mint` creates the key through the gateway and prints the token once — alone on stdout, so `layer keys mint … | pbcopy` captures it; the metadata table goes to stderr. There is no way to print it again. `keys revoke` is the default way to retire a key and keeps its audit record. `keys rm` is rare permanent cleanup and accepts only a key already in the `Revoked` phase. | Flag | Shape | | --- | --- | | `--entitle` | `TARGET[=SCOPE[+SCOPE]]`, repeatable. Targets are `vectorstore.`, `warehouse.`, `agent.`, or `layer`. | | `--namespaces` | Upstream-namespace globs for the vectorstore entitlement, comma-separated. | | `--claim` | `TARGET=STRING`, repeatable. Appends an opaque claim string to that target's entitlement. | | `--expires-after` | Duration or `never`; defaults to `365d`. | For agent invocation, use `--entitle agent.` without scopes; the entitlement is an empty object and does not accept namespace restrictions. `--entitle layer=admin` mints an admin key. For anything longer than a couple of flags, write the object instead: `layer keys mint -f key.yaml` takes the same `ApiKey` manifest `kubectl apply` does. `keys ls` and `keys get` show metadata only — key id, owner, phase, entitlement targets, expiry, last seen — never tokens or hashes. `revoke` is idempotent and keeps the record; `rm` hard-deletes it. All `keys` commands call the gateway key routes, which require a key with the `layer` entitlement at `admin` scope (or the bootstrap gateway key); no kube access is involved. ## Vector Store And Warehouse ```sh layer vectorstore list layer vectorstore get layer vectorstore get prod-turbopuffer -o json layer warehouse list layer warehouse get prod-snowflake ``` `vectorstore list` shows declared stores with kind, default marker, region, reachability, and turbopuffer org id. `vectorstore get` prints endpoint, credential Secret reference, inbound auth mode, reachability, observed generation, and the turbopuffer dashboard link when the store has `spec.turbopuffer.orgId`. Without a name, `vectorstore get` selects the default-marked store, or the only store when exactly one exists. `warehouse list` leads with name, kind, phase, verification time, and consumer counts. `warehouse get NAME` shows the Snowflake source identity, credential Secret reference, verification status, failure reason, and what still depends on the warehouse. These commands are read-only and gateway-backed; they never read or print Secret contents. ## Ask The Docs `layer ask` queries the committed docs digest with the `ask` CLI. It is keyless and local by default: from a checkout, it finds `site/.hev-ask`, prefers a sibling `../ask` source checkout, and falls back to the docs site's installed `@hevmind/ask` package or an `ask` binary on `PATH`. ```sh layer ask tree layer ask grep "warm cache" layer ask cat api/query layer ask glossary get watermark layer -o json ask tree ``` Use `--endpoint` to query a deployed hev ask endpoint instead of the local digest: ```sh layer ask --endpoint https://hevlayer.com/api/ask tree ``` ## Inspect An Index ```sh layer index get shop-products layer index get shop-products -o json ``` `index get` reports row count, size, schema summary, last write, stable watermark and lag, and index (WAL) and cache state on any gateway. The RECENT SNAPSHOTS table (and `index list`'s last-snapshot column) additionally need snapshot history, which is served only by a managed/pro gateway; timestamps and sizes are raw (epoch-ms, bytes) and `-o json` carries the full snapshot list where available. `PURGE` reports `pending` while the gateway has discovered an outstanding namespace cleanup intent, `none` when its backlog is empty for this name, or `unknown` if the gateway's `/metrics` endpoint cannot be read or S3 intent discovery has not succeeded. A deleted index with a pending purge remains inspectable by name through `index get`; it does not reappear in `index list`. ## Manage Snapshots ```sh layer index snapshot shop-products --field category layer index policy shop-products --facet-field category --facet-field brand --interval 5m --retention 30d ``` `index snapshot` creates an on-demand snapshot job and waits for it to complete; `index policy` writes the same `facetFields`, `interval`, and `retention` shape used by `Index.spec.snapshot`, so shared-gateway namespaces can enable the automatic writer without applying a Kubernetes resource. Neither command requires an operator or license, but both require S3-compatible object storage; the default CE Compose bundle does not configure it. Snapshot jobs also require a source that supports scanning. `--source` accepts `auto`, `stored`, `cache`, or `origin` (the default). `snapshot` is an alias for `stored`. ## Delete An Index ```sh layer index delete shop-products layer index delete shop-products shop-products-staging layer index delete --prefix shop- layer index delete --prefix shop- --yes ``` `index delete` works without object storage, including the default CE Compose bundle. When S3 is configured, it first writes a durable cleanup intent. If that write fails, it returns an error without deleting upstream; retry the command. After deleting the upstream namespace, the gateway clears its in-memory state and returns HTTP 200 with `namespace deleted; snapshot and cache purge continues in the background and may take a few minutes`. Document cache rows, snapshot mirrors, S3 snapshots/checkpoints/search history/clickstream/shard metadata, and the operator-discovered Index CR are cleaned up in the background. Incomplete cleanup retries with exponential backoff (1 second up to 60 seconds). With S3 configured, intent records survive gateway restarts and are removed only after cleanup succeeds. Without S3, cleanup retries live in memory and do not survive a gateway restart. Recovery checks that the upstream namespace is absent before purging; an intent whose upstream delete failed remains pending until the client retries the delete. `layer_namespace_purge_pending{namespace="NAME"}` on `/metrics` reports outstanding intents discovered by that gateway; restart discovery runs at startup and every 30 seconds. Do not reuse a namespace name until its purge has drained, since its cache and S3 paths are shared with the deleted index. Pass one or more names, or `--prefix` to delete every index whose name starts with that prefix — name arguments and `--prefix` are mutually exclusive, and the prefix must be non-empty. The prefix form lists the matched indexes for confirmation before deleting; on a TTY it prompts, and `--yes` skips the prompt. `--yes` is required when stdin is not a TTY. A prefix that matches nothing exits `0` without deleting. ## Pipelines ```sh layer pipeline list layer pipeline get product-images ``` `pipeline list` reads registered pipelines and fans out to the [pipeline status API](/docs/pro/api/pipelines#wait-for-completion) for each one's live queue depth (`pending`, `processing`, `failed`, `rate/min`); `pipeline get` adds target namespace, distance metric, and created-at. A pipeline with no worker staged into it yet renders without queue counts rather than erroring. Reads need only an API key — no kube access. `layer push` is deferred to the managed build/dev-loop milestone. # Document model Source: https://hevlayer.com/docs/pro/document-model import Edition from "../../components/docs/Edition.astro"; import StoreNote from "../../components/docs/StoreNote.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; Layer reserves the `_hevlayer_*` attribute prefix for its own bookkeeping. **These attributes are read-only.** The gateway stamps and maintains them; your writes and [UDF](/docs/pro/kubernetes/function-crd) completion patches must not set or change them. The gateway rejects or overwrites any `_hevlayer_*` value you send, and editing one directly breaks Layer's guarantees. The reserved set depends on the engine backing the namespace.
| Attribute | Type | Purpose | | --- | --- | --- | | `_hevlayer_upserted_at` | integer (epoch ms) | Server-stamped on every write. The watermark Layer's [stable reads](/docs/pro/api/query#stable-reads) are taken against. | | `_hevlayer_shard` | integer | Hash bucket assigned at write time (`xxh64(id) % shard_count`), present only on sharded namespaces. Lets the gateway [scatter/gather](/docs/pro/concepts#scattergather) a query across the shards of one namespace. | | `_hevlayer_udf__v` | string | Function completion marker. The gateway stamps the Function's `spec.version` here when a worker completes a row. Hyphens in the Function id are normalized to underscores. | | `_hevlayer_udf__stale_after` | integer or null | Function invalidation marker. Discovery reclaims rows once this epoch-ms timestamp expires; completion clears the marker. |
The `_hevlayer_` prefix also namespaces internal cache sets (snapshot field-values and search-history clickstream), but those are cache keys, not part of your document schema. # Failure Modes Source: https://hevlayer.com/docs/pro/failure-modes import Edition from "../../components/docs/Edition.astro"; import Callout from "../../components/docs/Callout.astro"; import StoreNote from "../../components/docs/StoreNote.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; Layer strives to degrade gracefully: queries and document fetch served from turbopuffer keep functioning when components around them fail. This page details the scenarios where that does not apply. ## Read A gateway outage returns a connection error to the client. SDKs do not retry directly against the backing store. Check gateway health and connectivity; store failures remain visible through the gateway response. The document cache is stateless and can scale to zero with no disruption: document fetches fall through to origin (turbopuffer, or S3 for snapshots) on a miss or cache outage, so a cache failure degrades latency, not availability. ## Write Successful writes require success from the backing store. If the gateway is unreachable, the client returns the connection error. Cache warming is best-effort and does not replace the durable store write. ### Pipeline stop-writes The primary failure mode for writes through a healthy gateway is Aerospike stop-writes during a multi-stage pipeline job: staged documents stay warm in the cache but carry no vector data yet, and once that data exceeds the Aerospike drive allocation the cache rejects further writes. The pipeline does not stall. Each stage persists its chunk bodies to S3 before it touches the cache, and pipeline state lives in PostgreSQL, so the Aerospike write is best-effort: on stop-writes the gateway logs the skipped write and the stage still completes. Downstream chunk reads degrade to the S3 backing for as long as the cache is rejecting writes. Recovery is automatic. The Helm document cache restarts on stop-writes by default (`documentCache.autoRestartOnStopWrites: true`) and clears its Aerospike backing file on pod start (`documentCache.storage.resetOnStart: true`); the gateway reconnects in the background and refills the cache from S3 on demand. No pipeline work is lost — S3 and PostgreSQL are the durable recovery boundary and must stay healthy. Operator signals: - `layer_aerospike_op_duration_seconds{status="aerospike_stop_writes"}` — the stop-writes condition itself, the same series the [dashboard](/docs/pro/dashboard) charts. - `hevlayer_cache_cold_responses_total` — reads being served from S3 backing instead of the cache while it recovers. - `hevlayer_document_cache_cold_starts_total` and `hevlayer_document_cache_cold_start_seconds` — the demand-triggered reconnect-and-refill cycle after the cache restarts. - Gateway warn logs `Aerospike chunk write failed (best-effort)` and `Aerospike chunk read failed; falling back to S3 backing`. ## Client failures When the gateway is unreachable, the SDKs return the gateway connection error. They do not retry directly against a backing store. That keeps the client surface backend-neutral: a namespace may be backed by turbopuffer or another store selected by `VectorStore`, and callers should not need a store-specific credential or fallback path. # FAQ Source: https://hevlayer.com/docs/pro/faq import Edition from "../../components/docs/Edition.astro"; import StoreNote from "../../components/docs/StoreNote.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; This page answers the questions the rest of the docs don't: licensing, pricing, trials, and where the project is headed. ## What is the licensing for hev layer? The standalone gateway is source-available under the Business Source License 1.1 in [hev/layer](https://github.com/hev/layer). It is free to self-host at any scale and converts to Apache-2.0 on the change date in its `LICENSE`. The operator, function runtime, and dashboard require a commercial license. Licensed installs use signed license keys for trial and commercial access. The key is supplied to Helm as `license.token` or through a referenced Kubernetes Secret. See [licensing](/docs/pro/licensing) for the install and lifecycle details. ## How much will it cost? Layer is licensed per operator deployment: one license per operator install, so a production, staging, and DR cluster each carry their own. Replicas within an install do not count. Pricing is not final for the design-partner cut. Start with a trial license; commercial terms are handled directly with each design partner. ## How do I start a trial? Use the [trial signup](/#start-trial). Submit your work email and hev layer emails a signed trial key plus the current install instructions. ## How do I know whether my license is healthy? Call [`GET /v2/license`](/docs/pro/licensing#license-states) on your gateway. The gateway reports `licensed`, `grace`, or `floor` from the key configured in the install. Operator and dashboard license surfaces use the same state model when their enforcement surfaces ship. ## Who built hev layer? [Adam Hevenor](https://hevmind.com/about). hev layer is a [hev mind](https://hevmind.com) product. # Introduction Source: https://hevlayer.com/docs/pro import Edition from "../../components/docs/Edition.astro"; import Diagram from "../../components/docs/Diagram.astro"; import { layerMapDiagram, layerMapDiagramNarrow, ceGatewayDiagram, ceGatewayDiagramNarrow, ceGatewayDiagramLabel } from "../../lib/diagrams"; import StoreNote from "../../components/docs/StoreNote.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; Layer provides a set of drop-in enhancements to your favorite retrieval systems. One install gives you two products: a **retrieval gateway** you adopt without changing client code, and a **function runtime** that runs your own code across every row of your index. {layerMapDiagram} You run two server components in your own cluster: a Rust **gateway** and a Kubernetes **operator**. The **gateway** is a transparent proxy in front of turbopuffer. It extends native clients with [fetch](/docs/pro/api/query#fetch), [scans](/docs/pro/api/scans), [snapshots](/docs/pro/api/snapshots), and operator-facing semantics around the cache, write path, and [pipelines](/docs/pro/api/pipelines) — you swap in Layer's drop-in client and change nothing else. It also lets you scale your own compute over multi-stage pipelines, reason about the [state of your index](/docs/pro/api/namespace-metadata), observe [clickstream](/docs/pro/api/search-history), and track [cost](/docs/pro/dashboard). The **function runtime** is one primitive for every per-row job over an index. Embedding, classification, tagging, and attribute migration are all the same thing: a stateless [UDF](/docs/pro/kubernetes/function-crd) declared as a Kubernetes-native `Function`. The gateway discovers the work, leases it to worker pools, retries, and writes results back, with KEDA scaling each pool to zero between bursts. You write and declare the function, and Layer runs the worker fleet for you. You call the gateway four ways: the [Python client](/docs/pro/api/introduction#install), the [Go client](/docs/pro/api/introduction#install), the [TypeScript client](/docs/pro/api/introduction#install), or the REST API directly — the clients are generated from the same OpenAPI spec, and every endpoint page shows them side by side. Layer also ships an optional GUI [dashboard](/docs/pro/dashboard). The dashboard manages cluster configuration through CRDs; all other state is persisted in object storage (S3). No durable state lives in a Layer process, so the compute tier is stateless and fully elastic. Because indexing is bursty, especially GPU-bound work, our [Terraform](/docs/pro/install#terraform) installs [Karpenter](https://karpenter.sh) as a cluster autoscaler to provision and scale the nodes Layer's compute runs on. The remaining backing services are the document cache, the indexing-state store, and the metrics store. Every component Layer runs alongside is open source: - **[Karpenter](https://karpenter.sh)** — cluster autoscaler that provisions and scales nodes for Layer's bursty, GPU-bound compute (Apache-2.0). - **[Aerospike](https://aerospike.com)** — ephemeral document cache (AGPL-3.0). - **[PostgreSQL](https://www.postgresql.org)** — indexing-state store for the pipeline and embed queue (PostgreSQL License). - **[VictoriaMetrics](https://victoriametrics.com)** — metrics store (Apache-2.0). To get started, see the [install guide](/docs/pro/install). For more technical detail, see [Concepts](/docs/pro/concepts), [Guarantees](/docs/pro/guarantees), and [Tradeoffs](/docs/pro/tradeoffs). # Demos Source: https://hevlayer.com/docs/pro/demos import Edition from "../../components/docs/Edition.astro"; Every demo below is a live app built on Layer that reimplements nothing. Each composes shipped gateway features — [routing](/docs/pro/api/query#query-routing), [hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion), fuzzy matching, [local embedding serving](/docs/pro/api/embed), [pipelines](/docs/pro/api/pipelines), [snapshots](/docs/pro/api/snapshots), and the [function runtime](/docs/pro/kubernetes/function-crd) — over a different corpus, and makes the gateway's behavior legible in the UI. They are also the fastest way to see what the gateway does without standing up a cluster. | Demo | What it shows | Corpus | | --- | --- | --- | | [shelf](https://shelf.hevlayer.com) | The query router, made legible | Books | | [chart](https://chart.hevlayer.com) | Query routing on clinical search, with a number | PMC-Patients case reports | | [hybrid-text](https://hybrid-text.hevlayer.com) | Hybrid text fusion, proven with qrels | BEIR/SciFact abstracts | | [wiki](https://wiki.hevlayer.com) | Auto routing plus CPU-only Lattice embedding, at scale | Simple English Wikipedia | | [lens](https://lens.hevlayer.com) | Text-to-image search with zero GPUs | Wikimedia Commons Quality images | | [shop](https://shop.hevlayer.com) | Everything together — an end-to-end app | Amazon product catalog | These deployed applications demonstrate retrieval behavior. Running their full workloads can require external stores, model artifacts, and data preparation; they are separate from the local Compose quickstart. ## shelf — book search that shows its routing **Live:** [shelf.hevlayer.com](https://shelf.hevlayer.com) · **Source:** [github.com/hev/shelf](https://github.com/hev/shelf) One search box, three routes. Type an author, a title, or a vibe; the gateway's `Auto` rank expression picks keyword (`hybrid_text`), `semantic`, or a `fused` blend from the shape of the query, and shelf renders that decision as a badge with the reason. The routing policy keys on token count, so the canned chips visibly change route as the query gets longer. This is the text-native routing showcase: it makes the [query router](/docs/pro/api/query#query-routing) decision the hero, not a footnote. Built on the [query router](/docs/pro/api/query#query-routing) (`Auto`), [hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion), and fuzzy matching. ## chart — clinical patient-notes search that shows its routing **Live:** [chart.hevlayer.com](https://chart.hevlayer.com) The same routing hero on the corpus with the sharpest bimodal query distribution there is: clinicians search both by exact token (`metformin 500mg`, `CABG`, `aspirn`) and by clinical picture (`elderly woman with progressive dyspnea and bilateral lower-extremity edema`). chart is the first Layer demo with real relevance judgments — PMC-Patients ReCDS qrels — so the routing and hybrid claims are measured, not asserted. Behind the search box, an open-weight Gemma cascade (vLLM, scale-to-zero on the GPU pool) reads each note once and extracts clinical events and facet labels: the [function runtime](/docs/pro/kubernetes/function-crd) showcase. The corpus is published, de-identified case reports (PMC-Patients, CC-BY-NC-SA). It is a search demo — not raw EHR, and not clinical advice. Built on the [query router](/docs/pro/api/query#query-routing), [hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion) with fuzzy matching, [pipelines](/docs/pro/api/pipelines), the [function runtime](/docs/pro/kubernetes/function-crd), and [snapshots](/docs/pro/api/snapshots). ## hybrid-text — hybrid text fusion over SciFact **Live:** [hybrid-text.hevlayer.com](https://hybrid-text.hevlayer.com) · **Source:** [github.com/hev/hybrid-text-fusion-demo](https://github.com/hev/hybrid-text-fusion-demo) The eval-shaped sibling of the routing demos, over ~5,000 scientific abstracts from BEIR/SciFact. One query string fans out into a full-input BM25 leg plus one fuzzy leg per token, fused by reciprocal rank fusion — so results survive typos and morphological variants without losing BM25's signal. It is purely lexical: no embeddings, no GPU, no vector index. SciFact ships qrels, so the UI flags known-relevant abstracts and the demo scores nDCG@10 / recall@10; every search also shows its gateway round-trip time and a fusion inspector (tokens, legs, RRF constant). Built on [hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion) and fuzzy matching. ## wiki — all of Simple English Wikipedia, routed and embedded on CPU **Live:** [wiki.hevlayer.com](https://wiki.hevlayer.com) · **Source:** [github.com/hev/wiki](https://github.com/hev/wiki) The routing hero at corpus scale: one `Auto` query over all 283,997 Simple English Wikipedia articles (1.74M paragraph rows) routes each search to full-text, semantic, or a fused RRF blend, and the UI renders the gateway's `routing` echo beside every result. The semantic leg is the [Lattice](/docs/pro/api/lattice) showcase — the whole corpus embedded through `prefer: lattice`, an ~8 MB int4 lookup-table artifact served in-process on the gateway CPU, with `performance.embedding_ms` and `embedding_tokens` echoed whenever the chosen route embeds. No GPU anywhere in the write or query path. Built on the [query router](/docs/pro/api/query#query-routing), [hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion), and [local embedding serving](/docs/pro/api/lattice) (`prefer: lattice`). ## lens — text-to-image search with zero GPUs **Live:** [lens.hevlayer.com](https://lens.hevlayer.com) · **Source:** [github.com/hev/lens](https://github.com/hev/lens) Cross-modal search over Wikimedia Commons [Quality images](https://commons.wikimedia.org/wiki/Commons:Quality_images): type `sunset over water`, get sunsets. The schema is two lines — a string `image_url` attribute with a [local CLIP](/docs/pro/api/embed#images) embedding profile. The gateway fetches each image and runs CLIP's image tower in-process on CPU at write time, then embeds query text with the same checkpoint's text tower at query time. The app posts writes and queries and renders the echo; it contains no embedding, tokenizer, or image-preprocessing code, and there is no GPU worker or autoscaler pool anywhere in the path. Every result pairs the fixed serving contract (`prefer: local`, gateway CPU) with the live `performance.embedding_ms` echo, and carries its Commons attribution and license. Built on [local CLIP serving](/docs/pro/api/embed#images) (`serving.prefer: local`, `modality: image`) and [full-runtime schema configuration](/docs/pro/kubernetes/index-crd#schema-attribute-embedding). ## shop — semantic shopping, everything together **Live:** [shop.hevlayer.com](https://shop.hevlayer.com) (formerly `hev-shop.com`, which redirects) · **Source:** [github.com/hev/shop](https://github.com/hev/shop) The end-to-end application workload: an indexing pipeline, semantic search, recommendations, facets, and observability in one app. shop embeds product images with CLIP ViT-L/14 and writes one vector per product through Layer [pipelines](/docs/pro/api/pipelines) into turbopuffer; the storefront serves image-native semantic search, [`nearest_to_id`](/docs/pro/api/query#query-by-id) recommendations, facet exploration from [namespace snapshots](/docs/pro/api/snapshots), and Layer freshness signals. KEDA scales workers from pipeline metrics and Karpenter scales nodes next to the workload that creates the demand. Where shelf is the text-native routing showcase, shop is the image-native one — and the demo that exercises the most of Layer at once. Built on [pipelines](/docs/pro/api/pipelines), the [write path](/docs/pro/api/write), [query](/docs/pro/api/query#query-by-id) (`nearest_to_id`), [snapshots](/docs/pro/api/snapshots), [search history](/docs/pro/api/search-history), and [autoscaling](/docs/pro/kubernetes/scaling-crd). # No Guarantees Source: https://hevlayer.com/docs/pro/guarantees import Edition from "../../components/docs/Edition.astro"; import Callout from "../../components/docs/Callout.astro"; import StoreMatrixLink from "../../components/docs/StoreMatrixLink.astro"; Layer can't offer guarantees. We try our best to provide secure, hands-off infrastructure that you are ultimately responsible for. While we can't offer guarantees, we make a set of promises in how we design, secure, and distribute our software that we believe make it easy to use and will stand the test of time. This page covers the specific status of those promises. ## Commitments - Your history is backed up to S3. Search history and namespace snapshots are written to the S3 bucket you specify. The format of this data may change. - Hot data served from cache. Customer document and chunk data is served from Layer's local document cache for price/performance. We try not to stray from this pattern, though some use cases may justify a smaller in-memory document cache. - This documentation is accurate and up to date. When it isn't, that's a bug in the software — report it. - Graceful degradation. We add graceful degradation support whenever possible — the gateway degrades rather than failing hard. The per-scenario behavior and recovery signals live in the [failure-mode runbook](/docs/pro/failure-modes). - Client compatibility. We will (almost) always stay client-compatible with the search systems we front. Where we diverge, it's a feature making an explicit tradeoff we believe is an improvement. - One consistency cut per query. When the gateway expands a query into multiple legs ([hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion), [scatter/gather](/docs/pro/concepts#scattergather)), every leg is filtered at the same stable watermark, injected from a single read. Legs never see different cuts. Layer was developed by a [single person](https://hevmind.com/about) orchestrating agentic coding tools, leveraging open source and building automation. Not a single line of code was hand-written. That said, it was made with ❤️ by a human as much as it is built by AI. # Install Source: https://hevlayer.com/docs/pro/install import Edition from "../../components/docs/Edition.astro"; import Callout from "../../components/docs/Callout.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; ## AWS and Kubernetes An AWS install has two stages. **Terraform** provisions the required AWS resources: IAM, S3, ECR, networking, cost-read roles, and, for the recommended path, a fresh EKS cluster. **Helm** installs the gateway, operator, and document cache into that cluster and wires them to the AWS resources Terraform produced. One command runs both stages: `layer install`. It is the AWS provisioning entrypoint. You can skip Terraform if you already have the AWS resources hev layer needs. At minimum, provide an S3 bucket and gateway IRSA role for snapshots and history. For the full feature set, also provide gateway cost-read IAM, image registry locations, and cluster-level components equivalent to the Terraform outputs. ## layer install Prerequisites: `aws` (with credentials configured), `terraform`, `helm`, and `kubectl` on your PATH, plus your upstream Turbopuffer API key. Clone the `hev/layer` repository — it carries the Terraform configuration and the Helm chart the command drives — and run `layer install` from the checkout: ```sh git clone https://github.com/hev/layer cd layer go build -o layer ./apps/layer-cli export TURBOPUFFER_API_KEY="tpuf_..." ./layer install ``` AWS credentials come from the ambient environment by default; pass `--aws-profile` (or set `AWS_PROFILE`) to select a named credentials profile. Missing required inputs prompt interactively on a TTY. The command prints the resolved plan — profile, region, cluster name, system node shape — and asks for confirmation before provisioning anything. Then it runs both stages in one shot: Terraform provisions the opinionated AWS footprint — VPC, EKS, IAM/IRSA, S3, ECR — and Helm installs the release wired to those outputs, waiting for the gateway rollout before printing next steps. | Flag | Environment | Default | | --- | --- | --- | | `--profile` | `LAYER_INSTALL_PROFILE` | `demo` | | `--aws-profile` | `AWS_PROFILE` | ambient credentials | | `--region` | `AWS_REGION` | `us-east-1` | | `--cluster-name` | `CLUSTER_NAME` | `layer` | | `--namespace` | `NAMESPACE` | `layer` | | `--helm-release` | `HELM_RELEASE` | `layer` | | `--node-type` | `SYSTEM_NODE_INSTANCE_TYPE` | profile default (`m8g.large`) | | `--turbopuffer-api-key` | `TURBOPUFFER_API_KEY` | none (required) | | `--version` | `LAYER_VERSION` | `latest` | | `--license-token` | `LICENSE_TOKEN` | none | | `--dashboard-user` | `DASHBOARD_USER` | `admin` | | `--dashboard-password` | `DASHBOARD_PASSWORD` | generated and printed | | `--source` | `LAYER_SRC` | walk up from the working directory | | `--skip-terraform` | none | off | | `--yes` | none | off | | `--dry-run` | none | off | Non-interactive installs (CI, scripts) pass every value as a flag or environment variable and must add `--yes`; without a terminal the command refuses to provision unconfirmed. `--dry-run` prints the resolved plan and the exact commands it would run, then exits. `--skip-terraform` reuses existing Terraform outputs and reruns only the cluster components and the Helm release; on that path, the saved cluster name and namespace are authoritative. ### Profiles `--profile` selects the install footprint. `demo` is the default. **`demo`** is the lean evaluation footprint. The always-on system node is one arm64 `m8g.large` with an 80 GiB gp3 data volume. The document cache runs on that system pool, backed by a gp3 PVC (80 Gi) instead of NVMe instance store; no dedicated cache node pool is created. Every Pro feature — gateway, operator, dashboard, extractions, snapshots, keys — runs the same as on the larger footprint. Always-on cost is roughly $40–70/mo on current us-east-1 on-demand pricing. **`indexing`** is the design-partner footprint for installs with heavy indexing duty cycles. It adds a dedicated document-cache Karpenter pool on arm64 `i4g.large` NVMe instance-store nodes, so the cache gets local flash instead of a gp3 volume. Pass `--node-type` to override the system node instance type on either profile. The cache is ephemeral on both profiles (`resetOnStart: true`); losing the volume or the node is a non-event. ### install status `layer install status` reports the installed release and workload health: Helm release status, pod readiness, and document-cache node age, type, and utilization — so a forgotten instance-store node shows up instead of billing quietly. ```sh ./layer install status ``` It takes `--aws-profile`, `--region`, `--cluster-name`, `--namespace`, and `--helm-release`, with the same environment variables and defaults as `layer install`. ### install uninstall `layer install uninstall` removes the Helm release and cluster components and destroys the Terraform footprint. It confirms before destroying (pass `--yes` to skip) and is idempotent. With `--skip-terraform` it removes only the in-cluster install and retains the AWS footprint. ```sh ./layer install uninstall ``` The rest of this page is the reference for what the install sets up and the bring-your-own-cluster alternative. ## Install shape An install is one Helm release per environment with one S3 bucket for snapshot and history data. The chart renders a default [`VectorStore`](/docs/pro/kubernetes/vectorstore-crd) from the credential you provide; an install can define additional `VectorStore` resources, each with its own upstream credential and inbound auth policy, and route namespaces between them with `Index.spec.backend.storeRef`. Scoped gateway-only bearer keys are available through the `keys` inbound auth mode described below. ## Terraform The Terraform configuration in `infra/terraform/` provisions the AWS resources that the gateway and operator need. It is opinionated about the resources hev layer needs to behave correctly and conservative about resources around it. Route53 hosted zones and ACM certificates are opt-in; most installs bring existing DNS and TLS. ### What it sets up | Resource | Purpose | | --- | --- | | S3 bucket | Durable storage for namespace snapshots, search history, and clickstream events. | | IAM roles + IRSA policies | Gateway S3 and Cost Explorer access, plus worker/operator AWS access. | | ECR repositories | Registry space for customer-built function and pipeline worker images. Layer-owned gateway, operator, and dashboard images are pulled from Docker Hub. | | EKS + VPC + node pools | Recommended fresh-cluster runtime. | | Route53 + ACM | Optional DNS zones, records, and TLS certificates when `manage_public_dns=true`. | ### Cluster: recommended Installs should use a fresh EKS cluster unless there is a specific reason to bind hev layer to an existing one. The cluster path provisions: - a VPC with the subnets and endpoints hev layer expects - an EKS control plane and one always-on `system` node group, defaulting to an arm64 `m8g.large` with an 80 GiB gp3 data volume - public worker subnets by default, with no NAT Gateway in the fresh cluster path - Karpenter for scale-from-zero `worker-cpu` and `worker-gpu` indexing capacity - the AWS EBS CSI add-on and a `gp3` StorageClass for the demo-profile document-cache PVC - the AWS Load Balancer Controller for ingress - EFS for shared persistent volumes If you already operate an EKS cluster, you can disable the cluster modules and point hev layer at the existing cluster. You are still responsible for the functional prerequisites: an S3 bucket for snapshots/history, gateway IRSA that can read/write that bucket and call AWS Cost Explorer for tag-scoped cost reads, Docker Hub pull access for Layer-owned images, registry access for worker images, Karpenter or equivalent node autoscaling for workers, and the AWS Load Balancer Controller if you use public ingress. Deploy hev layer to a fresh cluster. The baseline is one always-on ARM node for the gateway, dashboard, control loops, and document cache. CPU and GPU indexing workers scale from zero, so embedding and extraction cost follows indexing duty cycle instead of becoming a standing line item. The fresh path also avoids a NAT Gateway: workers run in public subnets, so the large data volumes that flow during indexing skip NAT's per-GB processing charge. Existing clusters typically route worker egress through NAT already, which turns every pipeline run into a metered transfer. ### Cost notes The Terraform is designed to deploy a cost-efficient AWS footprint with autoscaling for on-demand indexing work. At rest, the fixed costs are EKS, one small ARM `system` node, the shared ALB, and small storage lines — roughly $40–70/mo on current us-east-1 on-demand pricing for the demo profile, before variable traffic, object storage, and upstream vector-store usage. The indexing profile adds the dedicated document-cache node while it runs. Indexing bursts scale CPU or GPU worker nodes up through Karpenter and back down when queues drain. If you switch workers to private subnets, enabling NAT adds a standing hourly and egress cost. Heavier search use cases may need more read-side infrastructure: additional gateway replicas, larger always-on nodes, or a dedicated document-cache pool for steady cache pressure. Contact hev layer for help sizing read-heavy deployments. ### Outputs Terraform emits the values the Helm chart needs to install: the S3 bucket name, gateway IRSA role ARN, and cluster metadata. Runtime images are pulled from Docker Hub for the Layer-owned gateway, operator, and dashboard containers. Pass these into the Helm values file described below. The Terraform provider tags managed resources with `Project=hevlayer`; activate that tag as a cost-allocation tag in AWS Billing so the gateway can scope Cost Explorer reads to the Layer stack. ## Helm The Helm chart at `infra/helm/layer/` installs the gateway, operator, and document cache into a cluster that already has the AWS resources from [Terraform](#terraform) or equivalent resources you manage. `layer install` applies the chart with the profile overlay (`values-demo.yaml` or `values-indexing.yaml`) plus a generated values file; a bring-your-own-cluster install runs Helm directly with the same values. ### Local gateway development `docker compose` starts the gateway's local dependencies, not a replacement control plane. The gateway still resolves [`VectorStore`](/docs/pro/kubernetes/vectorstore-crd) and [`Index`](/docs/pro/kubernetes/index-crd) resources from Kubernetes at startup, so a compose-based gateway run needs a current kube context with Layer CRDs installed and the matching `VectorStore`, `Index`, and Secret objects applied. For a local search backend running on the compose network, use a local-only `VectorStore.endpoint.url` that the gateway container can reach; cluster Service DNS names only work inside Kubernetes. ### Required values Most of the chart is opinionated defaults. In a typical install the credential you bring from outside the cluster becomes the default `VectorStore` credential. | Value | Required | Notes | | --- | --- | --- | | `vectorStore.credential.apiKey` | yes | Upstream store credential. With the default `deriveFromStore` auth mode, clients also send this as the gateway bearer key. | | `vectorStore.endpoint.url` | yes | Upstream store API base URL. Defaults to turbopuffer's AWS us-east-1 endpoint. | | `vectorStore.endpoint.region` | yes | Region label for the rendered `VectorStore`. | | `vectorStore.inboundAuth.mode` | no | `deriveFromStore`, `keys`, or `open`. Defaults to `deriveFromStore`. | | `vectorStore.inboundAuth.keys` | for `keys` mode | Gateway-only bearer keys with `read`, `write`, and `admin` scopes. | | `search.enabled` | no | Installs the Layer-operated `search` backend in-cluster and, when `vectorStore.kind=search` and `vectorStore.endpoint.url` is blank, points the default `VectorStore` at that Service. | | `search.image` | for `search.enabled` | Container image for the `search` backend, distributed separately from the Layer repo images. The chart rejects `ghcr.io/hev/*`. | | `gateway.image` | yes | Gateway image URL. Customer installs pull the pro image from Docker Hub, `hevlayer/layer-gateway-pro:`. | | `operator.image` | for `operator.enabled` | Operator image URL. Customer installs pull `hevlayer/layer-operator:` from Docker Hub. | | `dashboard.image` | for `dashboard.enabled` | Dashboard image URL. Customer installs pull `hevlayer/layer-dashboard:` from Docker Hub. | | `license.token` | trial/commercial installs | Signed hev layer license key from the trial or commercial license email. The chart writes it to a Kubernetes Secret and surfaces it to the gateway. | | `license.existingSecret` / `license.secretKey` | optional | Existing Secret name and key containing the license key, for clusters where secret material is managed outside Helm. | | `s3.bucket` | yes | S3 bucket Terraform created for snapshots and history. | | `serviceAccount.roleArn` | yes | IRSA role ARN that grants the gateway access to the S3 bucket and Cost Explorer. | | `dashboard.serviceAccount.name` | yes | Dashboard ServiceAccount name from Terraform output `layer_dashboard_service_account_name`. | | `dashboard.serviceAccount.roleArn` | yes | Dashboard IRSA role ARN from Terraform output `layer_dashboard_role_arn`; this renders the EKS role annotation on the dashboard ServiceAccount at first boot. | | `documentCache.storage.pvc.enabled` | no | Back the document cache with a PVC (`size`, `storageClass`) instead of node-local instance store. The demo profile sets an 80 Gi `gp3` PVC. | | `documentCache.nodeRole` | no | `system` schedules the cache on the always-on system pool (demo profile); `document-cache` targets a dedicated pool (indexing profile). | | `documentCache.karpenter.enabled` | no | Provision a dedicated document-cache Karpenter pool. The indexing profile enables it with `instanceType: i4g.large`. | | `gateway.indexNamespace` | no | Namespace containing `Index` CRs. Blank follows `operator.discovery.indexNamespace`, then the Helm release namespace. | | `gateway.indexConfig.enabled` | no | Enables gateway reads of `Index` CR routing and policy such as `spec.backend.storeRef`, `spec.snapshot.facetFields`, and `spec.scan.threads`. | | `gateway.indexGc.enabled` | no | Enables namespace hard-delete cleanup of operator-discovered `Index` CRs. | | `gateway.consistency.stablePollIntervalMs` | no | Slow polling cadence for namespaces last observed stable. Defaults to `60000`; cold and updating namespaces keep the fast gateway default. | | `gateway.cost.tagKey` / `gateway.cost.tagValue` | no | Cost-allocation tag filter for AWS Cost Explorer. Defaults to `Project=hevlayer`. | | `ingress.host` | optional | Set when you want a public ingress; use your DNS/TLS or enable Terraform-managed Route53/ACM. | Most other Helm inputs are wiring between resources the install process already produced. The store API key is the credential hev layer cannot generate for you. The chart stores it in a Kubernetes Secret, points the default `VectorStore` at that Secret, and the gateway derives its default inbound bearer from the same key. After you [start a trial](/#start-trial), hev layer emails a signed license key. Set it as `license.token` or store it in an existing Secret referenced by `license.existingSecret` and `license.secretKey`. The gateway exposes local license health at [`/v2/license`](/docs/pro/licensing#license-states), with `licensed`, `grace`, and `floor` states. ### Image Coordinates The customer pull path for the Layer-owned runtime images is Docker Hub: ```yaml gateway: image: hevlayer/layer-gateway-pro: operator: enabled: true image: hevlayer/layer-operator: dashboard: enabled: true image: hevlayer/layer-dashboard: ``` These pro images are public to pull, but licensed surfaces are only useful with a valid hevlayer license key installed through `license.token` or `license.existingSecret`. Without a valid key, the gateway, operator, and dashboard project the install to the license floor described in [Licensing](/docs/pro/licensing#license-states). The in-cluster `search` backend image is distributed separately from the Layer repo images. Demo worker images are not part of the first Docker Hub release lane; build customer Function and Pipeline images into the registry your cluster already pulls from. ### Layer-Operated Search Set `search.enabled=true` to run the `search` backend beside the gateway. The chart uses the existing service account/IRSA, stores backend data under `s3:///search` by default, mounts a node-local object cache, adds Prometheus scrape annotations for the bundled vmsingle, and restricts backend ingress to Layer's own components (gateway, operator, and metrics scraper). The in-chart backend takes no credential of its own and is reachable only through that internal connection. For a default `kind: search` VectorStore, set `vectorStore.inboundAuth.mode` to `keys` or `open`; `deriveFromStore` is only valid when the upstream store has its own credential. ### Gateway auth modes The default `deriveFromStore` mode is the single-tenant BYOC path: ```yaml vectorStore: credential: apiKey: tpuf_... inboundAuth: mode: deriveFromStore ``` For an install that needs a gateway-only bearer, use `keys` mode. The chart renders `apiKey` values into the release Secret and references them from the `VectorStore`; omit `apiKey` when pointing at a pre-created Secret. ```yaml vectorStore: credential: apiKey: tpuf_... inboundAuth: mode: keys workerSecretKey: layer-inbound-worker-api-key keys: - name: worker scopes: [read, write, admin] apiKey: layer_worker_... secretRef: key: layer-inbound-worker-api-key ``` In `keys` mode, operator workers, KEDA, and the dashboard use `workerSecretName` / `workerSecretKey` as their gateway bearer. Blank `workerSecretName` uses the release Secret; blank `workerSecretKey` uses `layer-inbound-worker-api-key`. ### Run the install On a bring-your-own cluster, run Helm directly with a profile overlay and your values: ```sh helm upgrade --install layer ./infra/helm/layer \ --namespace layer --create-namespace \ -f ./infra/helm/layer/values-demo.yaml \ -f values.customer.yaml ``` The chart is not published to a public Helm repository — install from the source path or from the chart artifact provided during onboarding. ### What gets installed - `layer-gateway` — Rust gateway for turbopuffer-compatible routes, fetch, scans, snapshots, warm jobs, and pipeline state. - `layer-operator` — reconciler for VectorStore, Index, InfraRules, Pipeline, and Function CRDs documented in [Kubernetes](/docs/pro/kubernetes/operator). - `layer-document-cache` — Aerospike-backed document cache, scale-to-zero by default. On the demo profile it runs on the system pool over a gp3 PVC; on the indexing profile it gets a dedicated instance-store node pool. - Optional Karpenter `NodePool` / `EC2NodeClass` resources for `worker-cpu` and `worker-gpu` indexing capacity when `workerKarpenter.enabled=true`, and the dedicated `document-cache` pool when the indexing profile (or `documentCache.karpenter.enabled=true`) is in effect. - Supporting resources: service accounts, IRSA bindings, ingress, and CRDs. ### Built-in compute pools The operator supplies built-in compute pools when no cluster-scoped `InfraRules/default` object exists. Helm does not create that object. If a workload omits `scaling.pool`, the operator maps `worker.computeClass: cpu` or `gpu` to the stock `cpu` or `gpu` pool. The default compute pools are: | Pool | Use | | --- | --- | | `cpu` | General CPU workers such as extraction, ingestion, and lightweight Functions. | | `cpu-large` | CPU workers that need local ephemeral-storage headroom for per-pod source caches. | | `gpu` | One-NVIDIA-GPU workers for embedding and model inference. | The built-in pools select `layer.hev.dev/node-role=worker-cpu` or `worker-gpu`, matching the chart's `workerKarpenter` NodePools. Override them by applying `InfraRules/default` when you need to tune resource requests, limits, node selectors, tolerations, GPU SKU hints, or per-workload replica ceilings for your cluster. See [InfraRules CRD](/docs/pro/kubernetes/scaling-crd) for the full field shape. # Limits Source: https://hevlayer.com/docs/pro/limits import Edition from "../../components/docs/Edition.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; Layer is limited by certain constraints of the underlying components we ship with. We will lift these as demand increases. - **Single-node document cache.** We enforce this for simplicity and also believe that a single large local drive offers enough storage for almost every dataset. - **~4,090 turbopuffer namespaces.** We use Aerospike sets for logical separation of data, which are limited by the Aerospike Community Edition AGPL license. - **~3 TB cache size.** Another limitation of the Aerospike license. - **10,000 distinct values per scan facet field.** Pre-computed snapshot scans cap each facet field's cardinality. If a field exceeds the cap, it is noted in `fields_skipped[]` rather than `fields[]`, so readers can treat every emitted field as complete. See [snapshots](/docs/pro/api/snapshots). - **1,000,000 distinct values per values scan.** On-demand values scans accumulate their histogram in gateway memory. A job that crosses the cap completes with `truncated: true`: the cap applies after the full pass, keeping the top values by count — each with an exact count — and dropping the low-count tail. See [scans](/docs/pro/api/scans#values-mode). ## No limits These have no enforced ceiling, but practical limits exist and will show up under load — see [failure modes](/docs/pro/failure-modes) for how each surface degrades. - **CRD instances** (`Index`, `Function`, `Pipeline`, `Scaling`) — bounded only by the etcd and operator throughput of your Kubernetes cluster. - **Snapshot history per namespace** — durable in S3; bounded by `spec.snapshot.retention` when set, or by object storage cost under `retention: never`. - **Search history retention** — accumulates indefinitely in S3; no automatic expiry. - **Clickstream event volume** — accumulates indefinitely in S3; no automatic expiry. - **UDF concurrency per function** — KEDA scales replicas to match queue depth, bounded by your cluster's capacity. - **Pipeline queue depth** — pipeline queues, including chunked document queues, store document IDs and chunk ID lists in S3 manifests and keep only segment state and counters in Postgres. - **Document size and attribute count** — bounded by turbopuffer and Aerospike record limits, not by Layer. # Licensing Source: https://hevlayer.com/docs/pro/licensing import Edition from "../../components/docs/Edition.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; hev layer is licensed per environment. Design-partner and trial installs use the same license path as production: sign up, receive a key by email, install the key with Helm, and monitor the gateway's local license state. For tier prices and what each tier includes, see [pricing](/pricing). ## Start a Trial Use the [trial signup](/#start-trial) on the hev layer site. Submit the email address you want associated with the install; hev layer emails back a signed trial key and the current install instructions. The key is the only license material you need for a standard self-hosted install. Treat it like a deployment secret: store it in your secret manager, do not commit it to source control, and avoid pasting it into support tickets or docs. Self-hosted customer installs pull the Layer-owned pro images from Docker Hub: `hevlayer/layer-gateway-pro:`, `hevlayer/layer-operator:`, and `hevlayer/layer-dashboard:`. These images are only useful with a valid license key; without one, licensed gateway routes, operator actions, and dashboard write surfaces project to the license floor. ## Install the Key For Helm installs, pass the emailed key as `license.token`: ```sh helm upgrade --install layer ./infra/helm/layer \ --namespace layer --create-namespace \ --set license.token="$HEVLAYER_LICENSE" \ -f values.customer.yaml ``` If your cluster policy requires pre-created Kubernetes Secrets, create the Secret through your normal secret workflow and point Helm at it with `license.existingSecret` and `license.secretKey`. See the [install guide](/docs/pro/install#required-values) for the full values table. ## License Claims The license key is a signed PASETO `v4.public` value issued by hev layer and verified locally by the gateway, operator, and dashboard. Verification is offline: the cluster does not call a license server to answer license health. The license answers what the deployment is entitled to: `sub`, `tier`, `features`, `limits`, `iat`, and `exp`. API keys still answer who the caller is and what that caller may do. A request must pass both checks. The initial feature strings are: | Feature | Gates | | --- | --- | | `transform-runtime` | Pipeline, Function, UDF, worker dispatch, and scaling surfaces. | | `agents` | Agent management and invocation surfaces. | | `rbac` | Scoped key mint/manage routes and multi-tenant enforcement. | | `warehouses` | Warehouse APIs and data-supply verification. | | `doc-cache` | Managed document cache, blob, and cache-backed warm paths. | | `history` | Search history, clickstream, checkpoints, restore, and activity. | | `cost` | Cost and fin-ops APIs and dashboard panels. | Core gateway routes are not represented as license features. Queries, point reads, writes, scans, namespace metadata, snapshots, and backend routing remain available in every license state. ## License States The gateway evaluates license state locally from its configured key. It does not require a network callback to answer license health. | State | Meaning | |---|---| | `licensed` | The key is valid and the current time is before its expiration. Licensed Layer surfaces are available. | | `grace` | A commercial key has expired, but the install is still inside its grace window. Licensed surfaces continue to work while renewal is handled. Responses on gated routes include a grace signal. Trial keys do not enter this state. | | `floor` | No valid key is configured, a trial key has expired, or a commercial key is past expiration plus grace. Licensed surfaces are refused or degraded to the CE behavior. | Read the local state with: ```sh curl -H "Authorization: Bearer $LAYER_API_KEY" \ https:///v2/license ``` The response includes whether the key is valid, the licensed subject, tier, features, limits, expiration, and the gateway's `licensed` / `grace` / `floor` projection. Operator and dashboard enforcement use the same state model. ## End-to-End Runbook The full-fidelity license acceptance run is scripted: ```sh scripts/license-e2e-real.sh ``` The script uses a per-run plus-addressed inbox, stands up a disposable kind cluster from `infra/helm/layer`, installs the extracted key with `license.token`, checks `GET /v2/license`, and queries PostHog when a read key is available. Each leg is independently gated and the final report says exactly which credential or local tool unlocks the next assertion. It never runs the grace/floor walk against the shared AWS cluster. No-key and trial installs do not get post-expiration grace. For a trial, the trial period itself is the evaluation window, and licensed surfaces drop to the floor when the key expires. Commercial grace is a lapse cushion measured from a real `exp`. Read the current gateway projection with [`GET /v2/license`](/docs/pro/api/license). ## Metrics License health is exported with the gateway metrics and uses the `license_tier` and `license_sub` labels. Surface metrics also include `surface`; Phase 1 emits `surface="gateway"`. | Metric | Type | Meaning | | --- | --- | --- | | `hevlayer_license_valid` | Gauge | `1` when the configured key verifies; `0` for missing or invalid keys. | | `hevlayer_license_expiry_seconds` | Gauge | Seconds until `exp`; negative after expiry for a valid expired key. | | `hevlayer_license_grace_seconds_remaining` | Gauge | Seconds left before a surface drops to the floor; `0` outside grace. | | `hevlayer_license_degraded` | Gauge | `1` once a surface is on the floor. | | `hevlayer_license_grace_requests_total` | Counter | Gateway requests allowed while the license is in grace. | Useful alerts are "license expires in less than 14 days", any grace requests, and `hevlayer_license_degraded == 1`. ## Renewals When a trial or commercial license is close to expiration, request a renewal through your hev layer contact or reply to the license email. Replace the key in Helm or in the referenced Secret and roll the gateway release so it reads the new value. ## Governing Terms | Document | Governs | |---|---| | [`TRADEMARKS.md`](https://github.com/hev/layer/blob/main/TRADEMARKS.md) / [brand policy](/trademarks) | Use of the Layer and hevlayer names, marks, and product identity. | | [Hosted-service Terms of Service](/terms) | The operated Layer service at hevlayer.com, including acceptable use, billing, SLA, liability, and support terms. | | [Privacy Policy](/privacy) | Data handling for the hosted service, site, and product telemetry. | Self-hosting the gateway is governed by the gateway license and trademark policy. Using the hosted Layer service is governed by the hosted-service terms and privacy policy. ## Client SDKs The generated client SDKs stay Apache-2.0. They are pure onramps to the public API surface and are intended to be easy to adopt in any application. # Health and metrics Source: https://hevlayer.com/docs/pro/observability ## Health ```sh curl --fail http://localhost:8080/health ``` The health route requires no bearer token. Use Compose health checks and gateway logs to diagnose startup and database connectivity. ## Metrics `GET /metrics` exposes Prometheus-compatible gateway metrics without auth. The metrics catalog and proxy routes under `/v2/metrics` provide names and query access; proxy queries require a configured metrics service. The local Compose bundle does not include that service. ```sh curl --fail http://localhost:8080/metrics ``` ## Telemetry The standalone gateway sends anonymous startup and aggregate feature-use telemetry. Disable it with `LAYER_TELEMETRY=off` or `DO_NOT_TRACK=1`. The local Compose bundle disables it by default. Telemetry excludes query text, vectors, namespace names, document IDs, bearer tokens, API keys, and document contents. See the generated [telemetry reference](https://github.com/hev/layer/blob/v0.6/docs/telemetry.md). # Quickstart Source: https://hevlayer.com/docs/pro/quickstart import Edition from "../../components/docs/Edition.astro"; import CodeTabs from "../../components/docs/CodeTabs.astro"; import Preview from "../../components/docs/Preview.astro"; ## 1. Sign up for a 30-day trial [Start your free trial](/#start-trial) with your work email. You'll receive a trial license key and install instructions. Layer runs in your AWS account, in front of your existing Turbopuffer store. ## 2. Install in your AWS account Have Go, the AWS CLI, Terraform, Helm, and kubectl installed, with AWS credentials configured. Set your Turbopuffer API key and the trial license key from your email, then run the installer: ```sh git clone https://github.com/hev/layer.git cd layer go build -o layer ./apps/layer-cli export TURBOPUFFER_API_KEY="tpuf_..." export LICENSE_TOKEN="your-trial-license-key" ./layer install ``` Review and confirm the plan. The installer provisions the AWS infrastructure and installs Layer in your cluster. The [install guide](/docs/pro/install#layer-install) covers prerequisites, configuration, and existing infrastructure. ## 3. Switch your client Point your client at your new gateway endpoint and keep your Turbopuffer API key. Your data stays in Turbopuffer; requests now go through Layer. ```sh export LAYER_GATEWAY_URL="https://your-layer-gateway" export LAYER_GATEWAY_API_KEY="$TURBOPUFFER_API_KEY" ``` Layer's [Python, Go, and TypeScript clients](/docs/pro/api/introduction#install) expose the gateway's additional operations: ```python import os from hevlayer import AsyncHevlayer client = AsyncHevlayer( base_url=os.environ["LAYER_GATEWAY_URL"], api_key=os.environ["LAYER_GATEWAY_API_KEY"], ) ``` ```go import ( "os" hevlayer "github.com/hev/layer-go" ) client := hevlayer.NewClient( hevlayer.WithBaseURL(os.Getenv("LAYER_GATEWAY_URL")), hevlayer.WithAPIKey(os.Getenv("LAYER_GATEWAY_API_KEY")), ) ``` ```typescript import { Hevlayer } from "hevlayer"; const client = new Hevlayer({ baseUrl: process.env.LAYER_GATEWAY_URL, apiKey: process.env.LAYER_GATEWAY_API_KEY, }); ``` ```bash curl --fail-with-body "$LAYER_GATEWAY_URL/v2/namespaces" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` Explore the [API docs](/docs/pro/api/introduction) or see Layer in action in the [demos](/demos). # Changelog Source: https://hevlayer.com/docs/pro/roadmap import FeatureGate from "../../components/docs/FeatureGate.astro"; The [published release history](https://github.com/hev/layer/releases) records released versions and their artifacts. Production documentation follows the released tag; development previews follow their version branch. Surfaces marked **in preview** are deliberately absent from this page. They are documented and usable, but they sit outside the release line and carry no compatibility promise, so they are not part of a version's contract. ## Edge `edge` is the opt-in development build. It tracks the `v0.6` branch and is republished as the branch moves; pin a released tag for anything you depend on. ### Running edge ```sh git clone --branch v0.6 https://github.com/hev/layer.git cd layer export GATEWAY_IMAGE=hevlayer/layer-gateway:edge export TURBOPUFFER_API_KEY="tpuf_..." docker compose up -d --wait curl --fail http://localhost:8080/health ``` The [quickstart](/docs/pro/quickstart) covers the rest. ## 0.6 ### Community Edition - 📦 One-bundle Community Edition — a single Compose file and a public image, run with a Turbopuffer key - 🧑‍💻 [`layer` CLI](/docs/pro/cli) on Community Edition — keyless `index get`, `env add`, and inspection ### Gateway and pipelines - 🚦 Higher fan-out for pinned namespaces — 4× the default concurrency - 📄 REST source pagination — `searchAfter` over enumerated snapshots - 🦾 arm64 REST worker - 🗑️ Namespace deletion without S3 ### Fixes - 🔒 Scoped keys confined to their namespaces - 🧮 Document-cache scans agree with counts - 🪣 Standalone gateway runs without an object store ## 0.5 ### Embedding - 🧮 [Gateway-side query embedding](/docs/pro/api/embed) — `embed:` attributes resolved on the wire - 🎛️ [Serving preference](/docs/pro/api/embed) — per-attribute choice of where embedding runs - 🤝 Native Turbopuffer embeddings wired through the gateway - 🪟 Lattice embedding provider — pinned artifact mounted by Helm - 🖼️ Local CLIP provider — multimodal without a GPU worker - 🧰 BYO models — the blended embedding policy removed - 💸 Native embed cost attribution ### Install and CLI - 🧙 `layer install aws` — guided Terraform + Helm install wizard - ♻️ Profile-aware [`layer install`](/docs/pro/cli) lifecycle — the install script deleted - 🗄️ Document cache Helm profiles - 🚀 [Quickstart](/docs/pro/quickstart) from a clone — the bundled Compose flow ### Licensing - 🎟️ [Team tier gates](/docs/pro/licensing) — custom InfraRules and multiple vector stores - 🔏 Authenticated `/v2/license` probe - ⏳ Trial licenses skip post-expiry grace ### Pipelines - 📚 Enumerated REST full snapshots - 🧬 Idempotent sweeps — content hashes keep Function-written attributes ### Stores and gateway - 🗃️ Kubernetes vector stores preferred in pro - 🧊 Turbopuffer base64 vectors accepted - 🎯 Namespace delete routed by vector store - 🔓 Segment lock convoys resolved - 📴 Standalone gateway runs with no object store ## 0.4 ### API hardening - 🧩 Finalize CRDs - 🚆 Wire-compatible pass-through reads and writes - 🏷️ Naming things ### Lifecycle and operability - 🎚️ [Autoscaling compute](/docs/pro/kubernetes/scaling-crd) for pipelines and UDFs - 🗄️ [Document cache endpoint](/docs/pro/api/query#fetch) for multi-stage pipelines - 📸 [Index snapshot history](/docs/pro/api/snapshots) - 🧨 Coordinated delete - ⛵ [Helm and Terraform install](/docs/pro/install) scripts - 🔐 [Scoped API keys](/docs/pro/api/keys) — minted [`ApiKey` resources](/docs/pro/kubernetes/apikey-crd) - 🔑 License key validation - 🧾 Key audit logs — lifecycle events to S3 - 🏭 [Warehouse CRD](/docs/pro/kubernetes/warehouse-crd) — declared Snowflake and Hugging Face sources - 🏗️ Production cluster cutover — lean topology live in prod ### Surfaces - 🪟 [Dashboard MVP](/docs/pro/dashboard) — CRD management and observability - 📚 Documentation site - 🧰 Official Python, Go, and TypeScript clients ### Search - 🎯 [Stable reads](/docs/pro/api/query#stable-reads) during heavy writes - 🕰️ Temporal queries — `as_of` / `between` selector on reads - 🚦 [Ready signal](/docs/pro/api/namespace-metadata) — namespace reports when every row is indexed - 📜 Precomputed facet listings in [snapshots](/docs/pro/api/snapshots) - 🪙 Precomputed facet counts in [snapshots](/docs/pro/api/snapshots) - 🪃 [Scans](/docs/pro/api/scans) — row selection by filter, `fts`, `hybrid_text`, or `ann` - 🆔 Search by id via document-cached vector - 🪢 [Hybrid text fusion](/docs/pro/api/query#hybrid-text-fusion) - 🧭 [Query routing](/docs/pro/api/query#query-routing) - 📰 [Search history](/docs/pro/api/search-history) saved to S3 - 🔥 Trending searches - 🗂️ [Enhanced namespace metadata](/docs/pro/api/namespace-metadata) ## Proposals Unreleased design proposals are tracked separately from published release notes. A proposal does not establish store or edition support; use the selected edition's API reference. # Tradeoffs Source: https://hevlayer.com/docs/pro/tradeoffs import Edition from "../../components/docs/Edition.astro"; import StoreNote from "../../components/docs/StoreNote.astro"; import FeatureGate from "../../components/docs/FeatureGate.astro"; Layer makes a set of design tradeoffs we believe improve functionality of your search system. This page makes those tradeoffs explicit. As this list grows, we will offer configuration where possible to allow users to configure their preference. Layer adds latency to the query path in the following ways. - An additional network hop (not configurable). - A query plan that allows for [stable reads](/docs/pro/api/query#stable-reads) during heavy writes ([index configurable](/docs/pro/kubernetes/index-crd)). - The same query plan also checks [RBAC entitlements](/docs/pro/kubernetes/apikey-crd#entitlements) on every request (not configurable). On a turbopuffer-backed namespace, Layer also increases index storage requirements via. - A secondary indexing for filtering by upsert time (not configurable). - A secondary indexing used for scatter gather sharding (not configurable). # Agentic search Source: https://hevlayer.com/docs/pro/api/agents import CodeTabs from "../../../components/docs/CodeTabs.astro"; import Preview from "../../../components/docs/Preview.astro"; **Agentic search** runs a configured reasoning loop over one or more namespaces and returns the same row shape as every other search endpoint. A model reads the query, fans out diverse phrasings in parallel via layer's [scatter/gather](/docs/pro/concepts#scattergather), ranks the candidates for relevance, and returns a ranking fused from both signals. It is a better-ranked result set, not a generated answer — the response is the [federated query](/docs/pro/api/federated-query#response) shape, so any client that reads `/v2/query` reads this with no changes. The endpoint names a configured [`Agent`](/docs/pro/kubernetes/agent-crd) in the path. The model, the turn budget, the indices, and the output shaping are bound on that resource, so the request body is just a query, an optional query embedding, and a result count. ``` POST /v2/agents/{name}/query ``` ## Request ```python response = await client.query_agent("support-search", { "query": "auth errors after the june upgrade", "top_k": 20, }) ``` ```go response, err := client.QueryAgent(ctx, "support-search", &hevlayer.AgentQueryRequest{ Query: "auth errors after the june upgrade", TopK: 20, }) ``` ```typescript const response = await client.queryAgent("support-search", { query: "auth errors after the june upgrade", top_k: 20, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/agents/support-search/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "auth errors after the june upgrade", "top_k": 20 }' ``` | Field | Purpose | | --- | --- | | `query` | The natural-language query. The agent reformulates it; you do not pre-shape it into a route expression. | | `vector` | Optional. The embedding of `query`, used for the agent's semantic recall leg. See [Bring your own embedding](#bring-your-own-embedding). | | `top_k` | Rows to return after fusion. | The model, fan-out, fusion weighting, and output are bound on the [`Agent`](/docs/pro/kubernetes/agent-crd), which keeps the request trivial and makes the agent the single source of truth for what a call costs and what it can read. `query` and `vector` are the only request inputs, and they are data, not config — there are no per-request overrides of the agent's configured behavior. ### Bring your own embedding The agent fans out for recall over both routes: a lexical leg on your query text and a semantic leg on a query vector. Layer never embeds query text — you supply the vector, the same bring-your-own-embedding contract as [`/v2/query`](/docs/pro/api/query). Pass it as `vector`: ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/agents/support-search/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "auth errors after the june upgrade", "vector": [0.0123, -0.0456, 0.0789], "top_k": 20 }' ``` `vector` is the embedding of `query`. The agent uses this one vector for every planned semantic leg — it does not embed the reformulated phrasings, so the vector carries the query's semantic intent while the text reformulations broaden lexical recall. Embed `query` with the same model your indices were embedded with, and match their dimensionality. Omit `vector` and the agent's semantic legs fall back to the lexical route: recall runs on the reformulations alone, which is the right behavior when an index has no vector column or you have no embedder on the client. ## Response The response is the [federated query](/docs/pro/api/federated-query#response) shape: `rows` each carrying `$namespace`, `$rank`, and a native `$score`/`$dist`, plus a `merge` block and a `namespaces` block. The merge names the dual-score fusion. ```json { "rows": [ { "id": "T-4821", "$namespace": "tickets", "$rank": 1, "$score": 9.7, "subject": "SSO login fails after upgrade" } ], "merge": { "method": "weighted-rrf", "route": "dual-score" }, "namespaces": [ { "namespace": "tickets", "stable_as_of": 1747300000123, "matched": 20 } ] } ``` By default the response is byte-shape-identical to a [federated query](/docs/pro/api/federated-query): a client cannot tell whether a reasoning loop produced it. Set [`output.provenance`](/docs/pro/kubernetes/agent-crd#output) on the agent to surface the scores. ### Provenance and trace With provenance on, the response gains an `agent` echo and each row carries a `$agent` field with both scores: ```json { "rows": [ { "id": "T-4821", "$namespace": "tickets", "$rank": 1, "$score": 9.7, "$agent": { "retrievalScore": 3, "relevanceScore": 0.92, "query": "authentication failure post-upgrade", "queryIndex": 0 } } ], "merge": { "method": "weighted-rrf", "route": "dual-score" }, "namespaces": [ { "namespace": "tickets", "stable_as_of": 1747300000123, "matched": 20 } ], "agent": { "turns": 2, "deadlineHit": false, "recallDepth": 50, "relevanceWeight": 0.6, "queries": [ { "namespaces": ["tickets"], "rankBy": "hybridText", "query": "authentication failure post-upgrade", "filters": { "created_at": { "$gte": "2026-06-01" } } } ] } } ``` | Field | Meaning | | --- | --- | | `$agent.retrievalScore` | The row's rank within the leg that first surfaced it — the per-query position (1-based; lower is better), not the fused-pool rank. With `fanout` > 1 a row can appear in several legs; this records the first leg's rank. The fused recall signal is computed separately (RRF over every leg the row appeared in). | | `$agent.relevanceScore` | The model's graded relevance for the row (the precision signal). | | `$agent.query` | The planned variant that first surfaced the row. | | `$agent.queryIndex` | Zero-based index of that planned variant in `agent.queries`. | | `agent.turns` | Model turns the call spent. | | `agent.deadlineHit` | True when the deadline ended the request early and returned the best ranking so far. | | `agent.queries` | The planned variants: route, reformulated text, and inferred filters. | With [`output.trace`](/docs/pro/kubernetes/agent-crd#output) the `agent` echo also carries the full reasoning trace. The trace is written to the [search-history](/docs/pro/api/search-history) record whether or not it is echoed, so agentic and plain searches share one surface for evaluation. ## Auth Auth follows the same model as the other API endpoints; multi-namespace queries follow [federated query](/docs/pro/api/federated-query#entitlements) auth behavior. A minted key additionally needs an `agent.` entitlement on its [ApiKey](/docs/pro/kubernetes/apikey-crd#entitlements) to invoke the agent. ## Configuration Everything the request omits is bound on the [`Agent`](/docs/pro/kubernetes/agent-crd) resource: the model and its credential, the deadline, the indices, the fan-out and fusion weighting, and the output shaping. Save the Agent manifest as `agent.yaml` and apply it to the gateway's Kubernetes namespace: ```bash kubectl apply -n layer -f agent.yaml kubectl get agent support-search -n layer -o yaml ``` The SDK query methods invoke an existing Agent; configure it through Kubernetes. ## Validation | Condition | Status | | --- | --- | | `{name}` is not a known, `Ready` agent | 404 | | The minted key lacks the `agent.` entitlement | 403 | | A bound index is outside the key's namespace grant | 403 | | `query` is empty | 422 | | `vector` is present and its dimensionality does not match the bound indices' vector schema | 422 | | Deadline hit with `onDeadline: bestEffort` | 200, best ranking so far, `agent.deadlineHit: true` | | Deadline hit with `onDeadline: error` | 504 | | The provider is unreachable on both primary and fallback | 502 | # Blobs Source: https://hevlayer.com/docs/pro/api/blobs import CodeTabs from "../../../components/docs/CodeTabs.astro"; Blobs store opaque bytes in Layer's S3 bucket and serve them through the gateway with Aerospike as a pull-through hot cache. A row never stores the bytes themselves. It stores an ordinary string attribute such as `image_blob: "blob://products/"`. Use blobs for media or other binary payloads that must have a durable home outside the vector engine while still riding the gateway read path. ## Routes | Route | Method | Behavior | | --- | --- | --- | | `PUT /v1/namespaces/{ns}/blobs` | PUT | Store raw bytes by sha256 and return a `blob://` reference. | | `GET /v1/namespaces/{ns}/blobs/{sha256}` | GET | Serve bytes from Aerospike raw cache, falling back to S3 and backfilling cache. | ## Store ```python with open("image.jpg", "rb") as f: stored = await client.put_blob("products", f.read()) print(stored.ref) ``` ```go body, _ := os.ReadFile("image.jpg") stored, err := client.PutBlob(ctx, "products", body, nil) ``` ```typescript import fs from "node:fs/promises"; const bytes = await fs.readFile("image.jpg"); const stored = await client.putBlob("products", bytes); ``` ```bash curl -X PUT "$LAYER_GATEWAY_URL/v1/namespaces/products/blobs" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/octet-stream" \ --data-binary @image.jpg ``` Response: ```json { "ref": "blob://products/9f86d081884c7d659a2feaa0c55ad015...", "sha256": "9f86d081884c7d659a2feaa0c55ad015...", "size": 48213 } ``` The same bytes always return the same reference. The route rejects empty bodies and bodies over the gateway's blob size cap. Write the returned `ref` as a normal row attribute: ```json { "id": "B0123", "vector": [0.1, 0.2], "image_blob": "blob://products/9f86d081884c7d659a2feaa0c55ad015..." } ``` The removed document `blobs` payload shape is still rejected. Binary bytes do not traverse `/v2/namespaces/{ns}` writes. ## Fetch ```python image = await client.get_blob("products", stored.sha256) ``` ```go image, err := client.GetBlob(ctx, "products", stored.Sha256) ``` ```typescript const image = await client.getBlob("products", stored.sha256); ``` ```bash curl "$LAYER_GATEWAY_URL/v1/namespaces/products/blobs/$SHA256" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -o image.jpg ``` Successful responses include immutable cache headers: ```http Cache-Control: public, max-age=31536000, immutable ETag: "" ``` The gateway sniffs common image types (`jpeg`, `png`, `gif`, `webp`) for `Content-Type`; otherwise it returns `application/octet-stream`. ## Warm Policy Blob reads pull through from S3 on a cache miss, then backfill Aerospike best-effort. `PUT ...?warm=true` writes one object through to cache. For bulk warming, declare the row attributes containing blob references in the Index's `spec.blobs.referenceAttributes`, then call `hint_cache_warm` with `blobs=true` and a positive `blob_budget_bytes`: ```yaml spec: blobs: referenceAttributes: [image_blob] ``` ```bash curl "$LAYER_GATEWAY_URL/v1/namespaces/products/hint_cache_warm?turbopuffer=false&documents=false&snapshots=false&blobs=true&blob_budget_bytes=104857600" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` This example warms only blobs, up to 100 MiB of cached bytes. The gateway scans origin rows, follows same-namespace references in the declared attributes (strings or arrays), and deduplicates objects. It stops before caching the first object that would exceed the budget; the response reports `blobs.budget_exhausted`. The budget bounds bytes written to cache, not S3 transfer: concurrent reads may fetch beyond the cutoff. Missing objects and invalid references are counted and skipped. See [Warm cache](/docs/pro/api/warm-cache#blob-warming) for SDK examples and response fields. # Checkpoints Source: https://hevlayer.com/docs/pro/api/checkpoints import CodeTabs from "../../../components/docs/CodeTabs.astro"; import Preview from "../../../components/docs/Preview.astro"; Checkpoints give an application a stable name for a known-good namespace cut. Creating a checkpoint labels the newest durable [snapshot](/docs/pro/api/snapshots) body for the namespace and stores that small label record in S3. It does not run a scan or write rows. Use checkpoints when a downstream app needs to browse, diff, or drop data by a named catalog cut instead of by an ad hoc `catalog_run_id` filter. The checkpoint response includes the snapshot `watermark_ms`, content `sha`, and `row_count` added since the previous checkpoint. ## Routes | Route | Method | Behavior | | --- | --- | --- | | `POST /v2/namespaces/{ns}/checkpoints` | POST | Create or return an immutable checkpoint label. | | `GET /v2/namespaces/{ns}/checkpoints` | GET | List checkpoints newest first. | | `GET /v2/namespaces/{ns}/checkpoints/{label}` | GET | Resolve one checkpoint label. | ## Create ```python checkpoint = await client.create_checkpoint("products", { "label": "catalog-2026-06-15", }) ``` ```go checkpoint, err := client.CreateCheckpoint(ctx, "products", &hevlayer.CreateCheckpointRequest{Label: "catalog-2026-06-15"}) ``` ```typescript const checkpoint = await client.createCheckpoint("products", { label: "catalog-2026-06-15", }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/checkpoints" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{"label": "catalog-2026-06-15"}' ``` Response: ```json { "namespace": "products", "label": "catalog-2026-06-15", "watermark_ms": 1749513600000, "sha": "3f9e8b21...", "row_count": 10000 } ``` Re-posting the same `label` returns the existing checkpoint unchanged, even if newer snapshots have landed. Labels are namespace-local and may contain ASCII letters, numbers, `-`, `_`, `.`, and `:`. The namespace must already have at least one durable snapshot. If no snapshot body exists yet, creation returns `412 precondition_failed`. ## List ```python page = await client.list_checkpoints("products", limit=20) ``` ```go page, err := client.ListCheckpoints(ctx, "products", &hevlayer.ListCheckpointsParams{Limit: 20}) ``` ```typescript const page = await client.listCheckpoints("products", { limit: 20 }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/checkpoints?limit=20" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ```json { "checkpoints": [ { "namespace": "products", "label": "catalog-2026-06-15", "watermark_ms": 1749513600000, "sha": "3f9e8b21...", "row_count": 10000 } ], "next_cursor": null } ``` | Query param | Default | Purpose | | --- | --- | --- | | `limit` | 50 | Maximum entries returned. Capped at 500. | | `before` | none | Opaque cursor from the previous page's `next_cursor`. | ## Resolve ```python checkpoint = await client.get_checkpoint("products", "catalog-2026-06-15") ``` ```go checkpoint, err := client.GetCheckpoint(ctx, "products", "catalog-2026-06-15") ``` ```typescript const checkpoint = await client.getCheckpoint("products", "catalog-2026-06-15"); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/checkpoints/catalog-2026-06-15" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` Resolve returns `404 not_found` when the label does not exist in that namespace. # Data connections Source: https://hevlayer.com/docs/pro/api/data-supply ## VectorStores See [VectorStores](/docs/pro/api/vectorstores) to list and inspect serving connections. ## Warehouses See [Warehouses](/docs/pro/api/warehouses) to list and inspect upstream source connections. # Embed Source: https://hevlayer.com/docs/pro/api/embed import Edition from "../../../components/docs/Edition.astro"; import StoreNote from "../../../components/docs/StoreNote.astro"; import PostgresWarning from "../../../components/docs/PostgresWarning.astro"; import Upstream from "../../../components/docs/Upstream.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; import StoreMatrixLink from "../../../components/docs/StoreMatrixLink.astro"; The `embed` schema block and the `Embed` rank expression are Turbopuffer's, on every backend. Layer takes the same request and response shapes whichever store is behind it, so a client written against Turbopuffer's embedding documentation works unchanged through Layer. This documentation covers only Layer enhancements. Add an `embed` block to a string attribute in your schema and Layer computes that attribute's vector on every write. Put `["Embed", "..."]` in `rank_by` and Layer computes the query vector with the same model. Your application never loads a model or sends a vector of its own. ## Where the vector comes from `embed.serving.prefer` picks the provider that runs the model: | `embed.serving.prefer` | Who computes the vector | | --- | --- | | `local` | A CPU model bundled with Layer, running beside the gateway. No key, no GPU, no account. | | `worker` | A GPU worker in your own cluster, serving an open-weights checkpoint you declared. | | `turbopuffer` | Turbopuffer's hosted embedding service, from its managed model menu. | The provider is independent of the store the vector is written to, so any store that accepts `embed` can use any configured provider. Layer never substitutes one provider for another. A profile that selects a provider the deployment has not configured fails validation at write time, and a provider that fails at request time returns an error instead of falling back to a different model. `native` is accepted as an alias for `turbopuffer`, `autoscaler` for `worker`, and `lattice` for `local` on a [Lattice](/docs/pro/api/lattice) profile. All three providers are available. Layer validates a `turbopuffer` profile and forwards it unchanged to the upstream `POST /v2/namespaces/{ns}` and `POST /v2/namespaces/{ns}/query`, so Turbopuffer computes the vector and it never passes through Layer. `local` and `worker` compute the vector in Layer and write an ordinary ANN column. ## CPU models Layer bundles three CPU embedding models, small enough to run on a laptop under Docker. Their weights are baked into the gateway image, so there is nothing to download or configure before the first write. They use the same schema as the larger GPU and hosted models, with lower retrieval quality. | Model | Dims | Modality | Use it for | | --- | --- | --- | --- | | `sentence-transformers/all-MiniLM-L6-v2` | 384 | text | The default. 22M parameters, symmetric, no prefixes. | | `BAAI/bge-small-en-v1.5` | 384 | text | Better retrieval for 50% more parameters. Try it when MiniLM's results are weak. | | `openai/clip-vit-base-patch32` | 512 | image | Text-to-image search. Both towers run on CPU. | ### Text This write creates the `articles` namespace with an embedded `text` attribute and upserts two rows. Layer embeds each row's `text` with MiniLM before storing it. ```python await client.write_namespace("articles", { "upsert_rows": [ {"id": "planet-1", "title": "Planet", "text": "Jupiter is the biggest planet in the Solar System."}, {"id": "photo-1", "title": "Photosynthesis", "text": "Plants turn sunlight, water, and carbon dioxide into food."}, ], "distance_metric": "cosine_distance", "schema": { "text": { "type": "string", "embed": { "model": "sentence-transformers/all-MiniLM-L6-v2", "dims": 384, "serving": {"prefer": "local"}, }, }, }, }) ``` ```go _, err := client.WriteNamespace(ctx, "articles", hevlayer.TurbopufferWriteRequest{ "upsert_rows": []map[string]any{ {"id": "planet-1", "title": "Planet", "text": "Jupiter is the biggest planet in the Solar System."}, {"id": "photo-1", "title": "Photosynthesis", "text": "Plants turn sunlight, water, and carbon dioxide into food."}, }, "distance_metric": "cosine_distance", "schema": map[string]any{ "text": map[string]any{ "type": "string", "embed": map[string]any{ "model": "sentence-transformers/all-MiniLM-L6-v2", "dims": 384, "serving": map[string]any{"prefer": "local"}, }, }, }, }) ``` ```typescript await client.writeNamespace("articles", { upsert_rows: [ { id: "planet-1", title: "Planet", text: "Jupiter is the biggest planet in the Solar System." }, { id: "photo-1", title: "Photosynthesis", text: "Plants turn sunlight, water, and carbon dioxide into food." }, ], distance_metric: "cosine_distance", schema: { text: { type: "string", embed: { model: "sentence-transformers/all-MiniLM-L6-v2", dims: 384, serving: { prefer: "local" }, }, }, }, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/articles/write" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "upsert_rows": [ {"id": "planet-1", "title": "Planet", "text": "Jupiter is the biggest planet in the Solar System."}, {"id": "photo-1", "title": "Photosynthesis", "text": "Plants turn sunlight, water, and carbon dioxide into food."} ], "distance_metric": "cosine_distance", "schema": { "text": { "type": "string", "embed": { "model": "sentence-transformers/all-MiniLM-L6-v2", "dims": 384, "serving": { "prefer": "local" } } } } }' ``` Query by meaning with `Embed`. Layer reads the model from the `text` schema and embeds the query string with it: ```python response = await client.query_namespace("articles", { "rank_by": ["text", "ANN", ["Embed", "largest planet in the solar system"]], "top_k": 3, "include_attributes": ["title", "text"], }) print(response.rows, response.performance) ``` ```go response, err := client.QueryNamespace(ctx, "articles", &hevlayer.QueryRequest{ RankBy: []any{"text", "ANN", []any{"Embed", "largest planet in the solar system"}}, TopK: 3, IncludeAttributes: []string{"title", "text"}, }) ``` ```typescript const response = await client.queryNamespace("articles", { rank_by: ["text", "ANN", ["Embed", "largest planet in the solar system"]], top_k: 3, include_attributes: ["title", "text"], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/articles/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["text", "ANN", ["Embed", "largest planet in the solar system"]], "top_k": 3, "include_attributes": ["title", "text"] }' ``` ```jsonc { "rows": [ { "id": "planet-1", "$dist": 0.137, "title": "Planet", "text": "Jupiter is the biggest planet in the Solar System." } ], "performance": { "embedding_tokens": 7, "embedding_ms": 9 } } ``` The two text models are embedded differently, and Layer handles both. bge expects an instruction prefix on queries and MiniLM expects none, so Layer adds the prefix only when it embeds a query. bge uses CLS pooling and MiniLM uses mean pooling. Both outputs are L2-normalized, so `cosine_distance` scores are comparable across rows. ### Images With `modality: image` on a CLIP model, Layer embeds each attribute value with the image tower at write time and embeds `Embed` query text with the text tower, against the same vector column. Both towers run on CPU beside the gateway. ```python await client.write_namespace("photos", { "upsert_rows": [ {"id": "commons-131", "title": "Sunset at Porto Covo", "image_url": "https://upload.wikimedia.org/…/640px-Porto_Covo.jpg"}, ], "distance_metric": "cosine_distance", "schema": { "image_url": { "type": "string", "embed": { "model": "openai/clip-vit-base-patch32", "dims": 512, "modality": "image", "serving": {"prefer": "local"}, }, }, }, }) ``` ```go _, err := client.WriteNamespace(ctx, "photos", hevlayer.TurbopufferWriteRequest{ "upsert_rows": []map[string]any{ {"id": "commons-131", "title": "Sunset at Porto Covo", "image_url": "https://upload.wikimedia.org/…/640px-Porto_Covo.jpg"}, }, "distance_metric": "cosine_distance", "schema": map[string]any{ "image_url": map[string]any{ "type": "string", "embed": map[string]any{ "model": "openai/clip-vit-base-patch32", "dims": 512, "modality": "image", "serving": map[string]any{"prefer": "local"}, }, }, }, }) ``` ```typescript await client.writeNamespace("photos", { upsert_rows: [ { id: "commons-131", title: "Sunset at Porto Covo", image_url: "https://upload.wikimedia.org/…/640px-Porto_Covo.jpg" }, ], distance_metric: "cosine_distance", schema: { image_url: { type: "string", embed: { model: "openai/clip-vit-base-patch32", dims: 512, modality: "image", serving: { prefer: "local" }, }, }, }, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/photos/write" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "upsert_rows": [ {"id": "commons-131", "title": "Sunset at Porto Covo", "image_url": "https://upload.wikimedia.org/…/640px-Porto_Covo.jpg"} ], "distance_metric": "cosine_distance", "schema": { "image_url": { "type": "string", "embed": { "model": "openai/clip-vit-base-patch32", "dims": 512, "modality": "image", "serving": { "prefer": "local" } } } } }' ``` Query the image column with text: ```python response = await client.query_namespace("photos", { "rank_by": ["image_url", "ANN", ["Embed", "sunset over water"]], "top_k": 16, "include_attributes": ["title", "image_url"], }) ``` ```go response, err := client.QueryNamespace(ctx, "photos", &hevlayer.QueryRequest{ RankBy: []any{"image_url", "ANN", []any{"Embed", "sunset over water"}}, TopK: 16, IncludeAttributes: []string{"title", "image_url"}, }) ``` ```typescript const response = await client.queryNamespace("photos", { rank_by: ["image_url", "ANN", ["Embed", "sunset over water"]], top_k: 16, include_attributes: ["title", "image_url"], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/photos/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["image_url", "ANN", ["Embed", "sunset over water"]], "top_k": 16, "include_attributes": ["title", "image_url"] }' ``` ```jsonc { "rows": [ { "id": "commons-131", "$dist": 0.412, "title": "Sunset at Porto Covo", "image_url": "https://upload.wikimedia.org/…/640px-Porto_Covo.jpg" } ], "performance": { "embedding_tokens": 5, "embedding_ms": 134 } } ``` Write responses report `embedding_images` instead of `embedding_tokens`. CPU CLIP handles query-time text embeds and write-time image embeds for small and medium corpora. A bulk image backfill needs a GPU. The provider is set per namespace, so a backfill can run on a GPU while queries embed on CPU. Declare the checkpoint for that backfill under [open-weights models on your own GPU](#open-weights-models-on-your-own-gpu). The [lens demo](https://lens.hevlayer.com) runs this setup: Wikimedia Commons Quality images embedded and searched on CPU, with the gateway's `performance` echo shown beside each result. Source at [github.com/hev/lens](https://github.com/hev/lens). ### Image input An image profile accepts an HTTP(S) URL or a base64 image string and fetches at most 20 MiB per URL. A rate-limited image host returns HTTP `429` with error `upstream_error`; a server error from the image host returns HTTP `503` with error `service_unavailable`. Layer preserves the host's `Retry-After` response header for both. Malformed URLs or base64, non-retryable 4xx responses, oversize content, and undecodable images return `422 validation_error`. ### Changing models requires a re-index The two text models both emit 384 dimensions, so switching between them leaves the namespace schema valid. It still requires re-embedding every row. Different models place vectors in unrelated spaces. If documents were embedded with MiniLM and queries are embedded with bge, the distances compare incompatible vectors and the ranking is meaningless, and Layer returns no error. The same applies when moving from a CPU model to a hosted or GPU model. Re-index from your source data so every vector comes from the new model. ### Bringing your own weights You can mount a model directory over the bundled menu to add or override checkpoints. The mount is optional and the bundled models need none. On Kubernetes, the Helm chart provisions a mounted model with the opt-in `gateway.localModels` values. An init container downloads the checkpoint directory from a private artifact prefix, verifies a pinned SHA-256 checksum for each file before the gateway starts, and mounts the directory read-only. A checksum mismatch fails the pod instead of serving unverified weights. For a single static retriever that trades retrieval quality for microsecond embeds and a few megabytes of deployment size, see [Lattice](/docs/pro/api/lattice). ## Open-weights models on your own GPU To use a stronger retrieval model than the CPU menu offers, name any Hugging Face checkpoint in the schema and run it on a GPU worker in your own cluster. Compared with the CPU example, only `model`, `dims`, and `serving.prefer` change: ```python await client.write_namespace("articles", { "upsert_rows": [ {"id": "planet-1", "text": "Jupiter is the biggest planet in the Solar System."}, ], "distance_metric": "cosine_distance", "schema": { "text": { "type": "string", "embed": { "model": "BAAI/bge-m3", "dims": 1024, "serving": {"prefer": "worker"}, }, }, }, }) ``` ```go _, err := client.WriteNamespace(ctx, "articles", hevlayer.TurbopufferWriteRequest{ "upsert_rows": []map[string]any{ {"id": "planet-1", "text": "Jupiter is the biggest planet in the Solar System."}, }, "distance_metric": "cosine_distance", "schema": map[string]any{ "text": map[string]any{ "type": "string", "embed": map[string]any{ "model": "BAAI/bge-m3", "dims": 1024, "serving": map[string]any{"prefer": "worker"}, }, }, }, }) ``` ```typescript await client.writeNamespace("articles", { upsert_rows: [ { id: "planet-1", text: "Jupiter is the biggest planet in the Solar System." }, ], distance_metric: "cosine_distance", schema: { text: { type: "string", embed: { model: "BAAI/bge-m3", dims: 1024, serving: { prefer: "worker" }, }, }, }, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/articles/write" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "upsert_rows": [ {"id": "planet-1", "text": "Jupiter is the biggest planet in the Solar System."} ], "distance_metric": "cosine_distance", "schema": { "text": { "type": "string", "embed": { "model": "BAAI/bge-m3", "dims": 1024, "serving": { "prefer": "worker" } } } } }' ``` Queries are unchanged. Moving a namespace from a CPU model to a GPU checkpoint means editing those fields and [re-indexing](#changing-models-requires-a-re-index). ### Declaring what the cluster serves The cluster decides which checkpoints it serves, so they are declared once in `InfraRules/default`, next to the compute pools that run them: ```yaml apiVersion: hevlayer.com/v1alpha1 kind: InfraRules metadata: name: default spec: embedders: - name: bge-m3 model: BAAI/bge-m3 revision: 5617a9f61b028005a4858fdac845db406aefb181 dims: 1024 scaling: pool: gpu mode: autoscale warmWindowSeconds: 300 replicas: min: 0 max: 2 ``` | Field | Purpose | | --- | --- | | `model` | The Hugging Face repo id a schema may name. A checkpoint absent from this list is refused at write time. | | `revision` | Pins the checkpoint. If omitted, the worker resolves the repo's default branch once and records the revision it got. | | `dims` | The dimension the worker emits. A schema declaring a different `embed.dims` fails validation. | | `scaling` | The same [workload scaling](/docs/pro/kubernetes/scaling-crd#workload-scaling) block Pipelines and Functions use. `pool` names a GPU compute pool and `max` may not exceed that pool's `maxReplicasPerWorkload`. | Embedding workers scale to zero like any other GPU workload. Set `warmWindowSeconds` here for the same reason as on pipelines. A cold start provisions a node, pulls a multi-gigabyte image, and loads the model before it embeds anything, and a warm window lets consecutive batches reuse the same node. Adding a checkpoint is an edit to this object and needs no gateway image rebuild or redeploy. ### Errors | Condition | Response | | --- | --- | | Schema names a checkpoint no `InfraRules` embedder declares | `422 validation_error`, naming the requested model | | Declared checkpoint whose weights will not load | `503 service_unavailable`, with the worker's condition on the `InfraRules` status | | No embedder declared at all, on a `worker` profile | `422 validation_error` | | Worker pool at its replica ceiling | `429`, with `Retry-After` | An undeclared checkpoint is a configuration error you can fix, so Layer returns a `4xx` that names the model. `503` means a declared model is unavailable. ## Query with `Embed` `["Embed", text]` computes a query vector from `text` using the model settings of the attribute being ranked. When `rank_by` names the source attribute, Layer reads the model from its schema: ```python response = await client.query_namespace("clinical-notes", { "rank_by": ["text", "ANN", ["Embed", "chest pain radiating to left arm"]], "top_k": 10, }) print(response.rows) ``` ```go response, err := client.QueryNamespace(ctx, "clinical-notes", &hevlayer.QueryRequest{ RankBy: []any{"text", "ANN", []any{"Embed", "chest pain radiating to left arm"}}, TopK: 10, }) ``` ```typescript const response = await client.queryNamespace("clinical-notes", { rank_by: ["text", "ANN", ["Embed", "chest pain radiating to left arm"]], top_k: 10, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/clinical-notes/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["text", "ANN", ["Embed", "chest pain radiating to left arm"]], "top_k": 10 }' ``` When `rank_by` names the derived vector attribute `embed_`, pass the model explicitly. Omitting it returns `422` with `a model name must be provided`. ```python response = await client.query_namespace("clinical-notes", { "rank_by": ["embed_text", "ANN", ["Embed", "chest pain radiating to left arm", { "model": "acme/clinical-retrieval-v3", }]], "top_k": 10, }) ``` ```go response, err := client.QueryNamespace(ctx, "clinical-notes", &hevlayer.QueryRequest{ RankBy: []any{"embed_text", "ANN", []any{"Embed", "chest pain radiating to left arm", map[string]any{"model": "acme/clinical-retrieval-v3"}}}, TopK: 10, }) ``` ```typescript const response = await client.queryNamespace("clinical-notes", { rank_by: ["embed_text", "ANN", ["Embed", "chest pain radiating to left arm", { model: "acme/clinical-retrieval-v3", }]], top_k: 10, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/clinical-notes/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["embed_text", "ANN", ["Embed", "chest pain radiating to left arm", { "model": "acme/clinical-retrieval-v3" }]], "top_k": 10 }' ``` Query vectors are cached for 60 seconds by default. Set `LAYER_EMBED_CACHE_TTL_MS` to change the TTL. Instruction prefixes are part of the cache key. A missing provider returns `503 service_unavailable`. ### `Embed` with `Auto` An inline `Embed` lets [query routing](/docs/pro/api/query#query-routing) run a semantic or fused query in one request: ```python response = await client.query_namespace("articles", { "rank_by": ["title", "Auto", "how plants turn sunlight into food", { "vector": ["Embed", "how plants turn sunlight into food", {"field": "text"}], }], "top_k": 10, }) ``` ```go response, err := client.QueryNamespace(ctx, "articles", &hevlayer.QueryRequest{ RankBy: []any{"title", "Auto", "how plants turn sunlight into food", map[string]any{ "vector": []any{"Embed", "how plants turn sunlight into food", map[string]any{"field": "text"}}, }}, TopK: 10, }) ``` ```typescript const response = await client.queryNamespace("articles", { rank_by: ["title", "Auto", "how plants turn sunlight into food", { vector: ["Embed", "how plants turn sunlight into food", { field: "text" }], }], top_k: 10, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/articles/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["title", "Auto", "how plants turn sunlight into food", { "vector": ["Embed", "how plants turn sunlight into food", {"field": "text"}] }], "top_k": 10 }' ``` The first tuple field (`title`) is the attribute for the lexical legs. `field` inside `Embed` names the attribute whose schema supplies the embedding profile and vector column (`text` above). Omit `field` when both are the same attribute. Layer chooses the route before it resolves `Embed`, so a short input routed to `hybrid_text` never calls the embedding provider. A semantic or fused response reports the routing decision (`routing.policy: "v1"`, `routing.executed: true`) and merges embedding measurements into `performance`. Without a vector or an inline `Embed`, the router returns `routing.executed: false` and leaves embedding to the caller. ## Model settings The full `embed` block: | Field | Meaning | | --- | --- | | `model` | A provider-namespaced Hugging Face repo id. | | `dims` | The vector dimension. Must match what the model emits. | | `attribute` | Where the vector is stored. Defaults to `embed_`, and may not be the source attribute. | | `serving.prefer` | `local`, `worker`, or `turbopuffer`. See [where the vector comes from](#where-the-vector-comes-from). | | `modality` | `text` (the default) or `image`. `image` requires a CLIP-family model. | | `revision` | Pins a checkpoint revision, including a finetuned one. | | `instructions.document` / `instructions.query` | Prefixes for asymmetric retrieval models. Both affect the query-cache key. | | `chunk` | Splits the attribute into one row per chunk on write. See [chunking long documents](#chunking-long-documents). | The first write that establishes an embedded schema must also set `distance_metric`. `revision`, `instructions`, and `chunk` are Layer extensions. Layer never forwards them upstream, and they require a GPU-served profile, except that a CLIP image profile may use `local`. ## Chunking long documents A single vector for a long document matches queries poorly, so long sources should be split into chunks and each chunk embedded as its own row. Add `embed.chunk` to the schema and Layer splits the attribute on write. The split runs on the gateway's CPU during the write request, and only the chunks go to the GPU worker for embedding. This profile splits `text` into windows of up to 512 tokens that overlap by 64: ```python await client.write_namespace("manuals", { "upsert_rows": [ {"id": "pump-manual", "title": "Pump maintenance", "text": long_text}, ], "distance_metric": "cosine_distance", "schema": { "text": { "type": "string", "embed": { "model": "BAAI/bge-m3", "dims": 1024, "serving": {"prefer": "worker"}, "chunk": { "strategy": "recursive", "unit": "tokens", "tokenizer": "BAAI/bge-m3", "size": 512, "overlap": 64, }, }, }, }, }) ``` ```go _, err := client.WriteNamespace(ctx, "manuals", hevlayer.TurbopufferWriteRequest{ "upsert_rows": []map[string]any{ {"id": "pump-manual", "title": "Pump maintenance", "text": longText}, }, "distance_metric": "cosine_distance", "schema": map[string]any{ "text": map[string]any{ "type": "string", "embed": map[string]any{ "model": "BAAI/bge-m3", "dims": 1024, "serving": map[string]any{"prefer": "worker"}, "chunk": map[string]any{ "strategy": "recursive", "unit": "tokens", "tokenizer": "BAAI/bge-m3", "size": 512, "overlap": 64, }, }, }, }, }) ``` ```typescript await client.writeNamespace("manuals", { upsert_rows: [ { id: "pump-manual", title: "Pump maintenance", text: longText }, ], distance_metric: "cosine_distance", schema: { text: { type: "string", embed: { model: "BAAI/bge-m3", dims: 1024, serving: { prefer: "worker" }, chunk: { strategy: "recursive", unit: "tokens", tokenizer: "BAAI/bge-m3", size: 512, overlap: 64, }, }, }, }, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/manuals/write" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "upsert_rows": [ {"id": "pump-manual", "title": "Pump maintenance", "text": "..."} ], "distance_metric": "cosine_distance", "schema": { "text": { "type": "string", "embed": { "model": "BAAI/bge-m3", "dims": 1024, "serving": { "prefer": "worker" }, "chunk": { "strategy": "recursive", "unit": "tokens", "tokenizer": "BAAI/bge-m3", "size": 512, "overlap": 64 } } } } }' ``` Layer keeps the original row and adds one row per chunk. A chunk row copies the original's attributes, replaces the embedded attribute with the chunk text, and gets the id `{id}#{n}` plus two generated attributes: `_hevlayer_parent_id` (the original id) and `_hevlayer_chunk_index` (`n`). A query returns chunk rows, and `_hevlayer_parent_id` groups them back to their document. A row whose text fits in one chunk is written unchanged. | `embed.chunk` field | Meaning | | --- | --- | | `strategy` | `fixed`, `recursive`, `sentence`, `markdown`, `section`, or `none`. | | `unit` | `characters` (the default) or `tokens`. | | `size` | Maximum chunk length in `unit`s. Required unless `strategy` is `none`. | | `overlap` | Units repeated between adjacent chunks. Must be smaller than `size`. | | `tokenizer` | The Hugging Face tokenizer that counts tokens. Required when `unit: tokens`. | The `section` strategy splits a structured row by field before windowing. Set `sectionSource: jsonFields` and list the source attributes in `fields`, and each field becomes its own section. The chunk id becomes `{id}#{field}#{n}` and the field name is stored in `sectionAttribute` (default `section`). Put the window settings for each section in a nested `split` block. Chunking has these limits: - The profile must use `serving.prefer: worker`. - A namespace can have one chunked embedding attribute. - Chunking cannot be combined with `modality: image`. - Writes must use `upsert_rows` with a string `id` on every row. Columnar `upsert_columns` writes are rejected. Because the split runs inside the write request, a large document makes that write slower and uses gateway CPU that is also serving queries. For bulk ingest, or for sources that need extraction first (PDFs, scans), use a [two-stage pipeline](/docs/pro/api/pipelines). Its CPU worker extracts and chunks outside the gateway and scales separately, and its GPU stage embeds the staged chunks. The pipeline takes the same chunk settings; see [chunking](/docs/pro/kubernetes/pipeline-crd#chunking). ## Performance accounting Write and query responses report embedding work under `performance`: ```jsonc { "rows": [ /* ... */ ], "performance": { "embedding_tokens": 8, "embedding_ms": 42 } } ``` Queries omit `embedding_tokens` on a cache hit. Layer merges provider measurements into the same object and exports the work as `hevlayer_embed_tokens_total` and `hevlayer_embed_compute_seconds_total`, labeled by namespace, store kind, model, and serving mode. # Federated query Source: https://hevlayer.com/docs/pro/api/federated-query import Edition from "../../../components/docs/Edition.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; A **federated query** runs one query across a **set** of namespaces. `POST /v2/query` is namespace-less: the per-namespace [query endpoint](/docs/pro/api/query) names its namespace in the path, while this endpoint takes the set in the body, so the namespace is no longer a path parameter. It has no upstream equivalent — turbopuffer's multi-query is single-namespace, so the fan-out and the merge are a Layer composition over per-namespace reads. One ranking is spread across every namespace in the set and merged into a single ranked list — "search my whole feed / my whole library." For several **independent** rankings instead, query each namespace separately; a federated query always returns one fused list. ## Fan-out and fuse Supply one ranking and a `namespaces` set. The gateway runs the ranking against each namespace and returns one merged `rows` list, each row tagged with the namespace it came from. ```python response = await client.query({ "namespaces": ["moment-pod-changelog", "moment-pod-latent-space", "moment-pod-no-priors"], "rank_by": ["text", "Auto", "evaluating RAG systems"], "top_k": 12, "filters": ["published_at", "Gte", 1740000000], "include_attributes": ["text", "show", "source_url", "start_sec"], }) ``` ```go response, err := client.Query(ctx, &hevlayer.FederatedQueryRequest{ Namespaces: []string{"moment-pod-changelog", "moment-pod-latent-space", "moment-pod-no-priors"}, RankBy: []any{"text", "Auto", "evaluating RAG systems"}, TopK: 12, Filters: []any{"published_at", "Gte", 1740000000}, IncludeAttributes: []string{"text", "show", "source_url", "start_sec"}, }) ``` ```typescript const response = await client.query({ namespaces: ["moment-pod-changelog", "moment-pod-latent-space", "moment-pod-no-priors"], rank_by: ["text", "Auto", "evaluating RAG systems"], top_k: 12, filters: ["published_at", "Gte", 1740000000], include_attributes: ["text", "show", "source_url", "start_sec"], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "namespaces": ["moment-pod-changelog", "moment-pod-latent-space", "moment-pod-no-priors"], "rank_by": ["text", "Auto", "evaluating RAG systems"], "top_k": 12, "filters": ["published_at", "Gte", 1740000000], "include_attributes": ["text", "show", "source_url", "start_sec"] }' ``` `rank_by` accepts the same vocabulary as a single-namespace query, including the Layer [`HybridText`](/docs/pro/api/query#hybrid-text-fusion) and [`Auto`](/docs/pro/api/query#query-routing) expressions. The query text is identical across the fan-out, so `Auto` routes **once** and the chosen route runs against every namespace — a single `routing` block is echoed. `filters` apply to every namespace. Name the explicit set to search, or pass `namespaces: ["*"]` to expand the authenticated key's namespace allowlist at request time. Omitting `namespaces` is equivalent to `["*"]`. ### Response One fused list. Each row carries `$namespace` (its origin) and `$rank` (its position within that namespace's results — the key the merge orders on). A `merge` block names the strategy, and a `namespaces` block reports each namespace's freshness and how many rows it returned to the merge. ```json { "rows": [ { "id": "ep123#7", "$namespace": "moment-pod-latent-space", "$rank": 1, "$score": 11.4, "show": "Latent Space", "text": "..." } ], "merge": { "method": "rank-interleave", "route": "fused" }, "routing": { "route": "fused", "policy": "v1", "tokens": 3, "executed": true }, "hybrid": { "tokens": ["evaluating", "rag", "systems"], "tokens_dropped": 0, "fuzziness": "auto", "rank_constant": 60, "legs": 4, "per_leg_limit": 60 }, "namespaces": [ { "namespace": "moment-pod-latent-space", "stable_as_of": 1747300000123, "matched": 14 }, { "namespace": "moment-pod-changelog", "stable_as_of": 1747299999001, "matched": 9 }, { "namespace": "moment-pod-no-priors", "stable_as_of": 1747300000050, "matched": 0 } ] } ``` | Field | Meaning | | --- | --- | | `$namespace` | The namespace this row came from. | | `$rank` | The row's 1-based rank **within its namespace**. The merge orders on this on a text route; see [Merge](#merge). | | `$score` / `$dist` | The row's native score within its namespace, carried as provenance. Comparable **within** a namespace, not across the fused list — do not threshold on it. On a vector route `$dist` is the merged ordering key and *is* globally comparable. | | `merge` | The merge applied. `method` is `"distance"` on a vector route, `"rank-interleave"` on a text route; `route` is currently always `"fused"` (reserved for future route-specific provenance). | | `namespaces` | Per-namespace echo: each reached namespace's `stable_as_of` watermark and `matched` — the rows it **returned to the merge** (up to [`per_namespace_limit`](#fusion-options)), not its surviving share of the final `top_k`. A namespace that matched nothing reports `matched: 0`. | `routing` and `hybrid` echo exactly as they do for a single-namespace [`Auto`](/docs/pro/api/query#query-routing) / [`HybridText`](/docs/pro/api/query#response) query, since the route runs once for the whole fan-out. ### Fusion options | Option | Default | Meaning | | --- | --- | --- | | `fusion.per_namespace_limit` | `clamp(2 × top_k, 10, 100)` | How many rows each namespace returns to the merge. Shallower than the single-namespace `per_leg_limit`: across a wide fan-out most namespaces contribute nothing to the final `top_k`, so deep per-namespace retrieval is wasted. Integer > 0. | | `fusion.rank_constant` | `60` | Reserved for route-dependent fusion tuning. It is accepted for forward compatibility and is inert in the current gateway. | ## Entitlements The `namespaces` set uses the same store-derived authentication path as individual namespace queries: the upstream key must be able to read each listed namespace. A namespace read failure is reported under [partial failure](#partial-failure) unless `strict` is enabled. For minted scoped keys, explicitly named namespaces must be inside a `vectorstore.` read grant. Naming a namespace outside the grant is a hard `403`, not a partial result. `namespaces: ["*"]` expands by listing upstream namespaces and filtering them through the key's vectorstore namespace globs, so the key is the feed/library set and the client does not enumerate it. ## Filters One `filters` expression is applied to **every** namespace in the set, and each namespace evaluates it independently against its own schema. So a filter only behaves uniformly when the attributes it references are part of a **shared filterable schema** across the set — present in every namespace, with the same type, and declared filterable. This is the filter analog of the [shared embedding space](#vector-merge-requires-a-matching-embedding-space) a vector merge needs: a federated query is only as coherent as the contract its namespaces share. A namespace that cannot evaluate the filter — the attribute is absent, has an incompatible type, or is not filterable there — is reported as `filter_schema_mismatch`, not as `matched: 0`. This is a per-namespace validity failure: the namespace did not participate in the filtered ranking because it could not evaluate the predicate. In default best-effort mode, the namespace is omitted from `rows`, listed in `errors`, and the response carries `x-layer-partial: true`. With `strict: true`, the whole request fails with `422`. This docs contract selects `422` for the strict-mode failure because the namespace set and filter expression are valid only if every required namespace can evaluate the filter. Keep filters to attributes declared filterable in every namespace in the set. Using the same embedding model does not imply a shared filterable schema; scope the set to namespaces that support the filters you send. ## Merge A federated query merges by the quantity the route makes comparable across namespaces: - **Vector route** (`ANN` over a query vector) — distances are comparable across namespaces that share an embedding space, so the gateway merges by `$dist` and the fused order is the exact global nearest-neighbor ranking. `merge.method` is `"distance"`. - **Text route** (`BM25`, `HybridText`, or a routed `fused`/`hybrid_text`) — BM25 and hybrid scores are **not** comparable across corpora (different term statistics; a hybrid `$score` is already a per-namespace fusion). The gateway merges by **rank-interleave**: rows are ordered by their `$rank` within their namespace, ties broken by `id`. `merge.method` is `"rank-interleave"`. No single pod dominates the head of the list; each contributes its best matches in rank order. The fused list exposes `$rank` as the ordering key and carries each row's native `$score` only as provenance. `top_k` truncates the merged list. Each namespace returns [`fusion.per_namespace_limit`](#fusion-options) rows to the merge. ### Vector merge requires a matching embedding space Merging by distance is only meaningful when every namespace in the set embeds into the same geometry: model, output dimension, normalization, and distance metric must match. A standalone namespace without an embedding profile uses the best-effort downgrade below, or fails when `strict: true`. Declare the profile through [`spec.embedding`](/docs/pro/kubernetes/index-crd#embedding) and `spec.backend.distanceMetric` on the namespace's `Index`. The gateway compares those profiles before a vector fan-out uses distance merge: - All reached namespaces have the same profile → `merge.method: "distance"`. - A profile is missing or differs → best-effort responses downgrade to `merge.method: "rank-interleave"` and include `merge.downgraded_reason` (`"missing_embedding_profile"` or `"embedding_profile_mismatch"`). - With `strict: true`, a missing or mismatched profile is a `422`. A text fan-out is rank-interleave regardless, so embedding profiles do not affect it. ## Consistency Each namespace has its own [stable-read](/docs/pro/api/query#stable-reads) watermark; there is no single consistent cut across independent namespaces. The `namespaces` block reports each namespace's `stable_as_of`, and the response header `x-layer-stable-as-of` carries the **minimum** across the reached namespaces — the most conservative answer to "as of when." Layer does not manufacture a global watermark. ## Partial failure Across many namespaces, one may be deleted, time out, error upstream, or fail to evaluate the [filter](#filters). Unlike single-namespace [multi-query](/docs/pro/api/query#batch-query), the fan-out defaults to **best-effort**: it returns the namespaces that succeeded, lists the rest in an `errors` block, and sets `x-layer-partial: true`. A feed search does not blank because one pod is briefly unavailable. ```json { "rows": [ "..." ], "errors": [ { "namespace": "moment-pod-no-priors", "error": "Upstream error: namespace not found" } ] } ``` Availability failures carry a human-readable upstream message in `error`, not a stable machine code — match on `namespace`, not on the `error` string. Filter schema mismatches are the exception: they carry the stable `code: "filter_schema_mismatch"` plus a human-readable `detail` so clients can separate "namespace unavailable" from "namespace cannot evaluate this filter." ```json { "rows": [ { "id": "ep123#7", "$namespace": "moment-pod-latent-space", "$rank": 1 } ], "errors": [ { "namespace": "moment-pod-no-priors", "code": "filter_schema_mismatch", "error": "filter schema mismatch", "detail": "filter attribute published_at is absent, not filterable, or has an incompatible type" } ] } ``` Set `"strict": true` to opt into fail-fast: any namespace error fails the whole request. Reach for it when a missing namespace would make the result misleading rather than merely thinner. ## Pinned namespace concurrency Federated queries run up to `64` pinned and ready namespace legs concurrently, configured with `LAYER_PINNED_FEDERATED_QUERY_NAMESPACE_THREADS` (clamped to `1..512`). Other namespace legs retain `LAYER_FEDERATED_QUERY_NAMESPACE_THREADS` (default `16`). Mixed requests use separate lane limits with an overall ceiling of `512` when a pinned lane is present. Readiness uses the same [metadata observations and expiry as scans](/docs/pro/api/scans#pinning-and-fan-out). HybridText retains its `15`-token expansion limit regardless of pinning. Pinning changes scheduling capacity, not token selection or ranking semantics. ## Limits | Limit | Value | | --- | --- | | Namespaces per request | 512. Over the cap → `422` naming the excess. | | Pagination | Not supported. `cursor` is rejected — a fused cursor across independent namespaces does not form the monotone bands pagination relies on. | ## Validation | Condition | Status | | --- | --- | | A named namespace is outside the minted key's namespace grant | 403 | | A namespace read fails upstream | 200 with `errors`, or 502 with `strict: true` | | A namespace cannot evaluate `filters` (attribute absent, wrong type, or not filterable) | 200 with `errors[].code: "filter_schema_mismatch"` and `x-layer-partial: true`, or 422 with `strict: true` | | `namespaces` is empty | 422 | | `namespaces: ["*"]` mixed with other names | 422 | | `namespaces` set exceeds the cap | 422 | | Vector route missing/mismatched embedding profiles with `strict: true` | 422 | | `cursor` present | 422 | | `rank_by` expression invalid | 422 (same checks as a single-namespace query) | # Lattice Source: https://hevlayer.com/docs/pro/api/lattice import Preview from "../../../components/docs/Preview.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro";

Lattice is in preview. It is documented and usable, but it sits outside the release line: it is not listed in the changelog, its configuration can change without a deprecation cycle, and it carries no compatibility promise. The supported way to embed text on CPU is the [bundled model menu](/docs/pro/api/embed#cpu-models); Lattice is for workloads that have measured that menu and need something smaller.

Lattice is a static retriever — a token lookup table rather than a transformer. It embeds text in microseconds on a CPU and adds a few megabytes to a deployment. It scores materially below a real dense embedder on retrieval, which is the trade it exists to make. It is an explicit serving leg. A namespace that selects Lattice never falls back to another leg, and an unconfigured artifact is a validation error rather than a silent substitution. ## Provisioning Generate a deployment artifact with the upstream [Lattice slicer](https://github.com/ErikKaum/lattice/tree/main/slicer), place its `model.safetensors` and `tokenizer.json` together, and set `LAYER_LATTICE_MODEL_PATH` to the model file before starting the gateway. The supported model id is `erikkaum/lattice-retrieval`; the requested `embed.dims` must match the loaded artifact, and only text modality is supported. ```bash uv run slicer slice \ --dim 512 \ --quant int4_row \ --output-dir /var/lib/hevlayer/lattice export LAYER_LATTICE_MODEL_PATH=/var/lib/hevlayer/lattice/model.safetensors ``` ```jsonc "text": { "type": "string", "embed": { "model": "erikkaum/lattice-retrieval", "dims": 512, "serving": { "prefer": "lattice" } } } ``` `prefer: lattice` selects the Lattice artifact. `prefer: local` also resolves to it when the declared model is `erikkaum/lattice-retrieval`. The recommended operating point is an int4-per-row, 512-dimensional artifact. Int4 quantizes the model's lookup-table weights only. Layer writes the resulting normalized vectors as `[512]f32`; Turbopuffer's int8 minimum for quantized vector storage is a separate choice and is not used by this path. ## End-to-end example Declare the Lattice profile on a string attribute, write rows, and query with `Embed`. The gateway embeds both sides in-process — no external inference provider is involved. Write two rows into a namespace whose `text` attribute carries the profile above: ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/articles/write" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "upsert_rows": [ {"id": "planet-1", "title": "Planet", "text": "Jupiter is the biggest planet in the Solar System."}, {"id": "photo-1", "title": "Photosynthesis", "text": "Plants turn sunlight, water, and carbon dioxide into food."} ], "schema": { "text": { "type": "string", "embed": { "model": "erikkaum/lattice-retrieval", "dims": 512, "serving": { "prefer": "lattice" } } } } }' ``` Query by meaning rather than exact phrase: ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/articles/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["text", "ANN", ["Embed", "largest planet in the solar system"]], "top_k": 3, "include_attributes": ["title", "text"] }' ``` ```jsonc { "rows": [ { "id": "planet-1", "$dist": 0.137, "title": "Planet", "text": "Jupiter is the biggest planet in the Solar System." } ], "performance": { "embedding_tokens": 7, "embedding_ms": 1 // in-process lookup — no network hop to a provider } } ``` A live example of exactly this contract is the [Wikipedia × Lattice demo](https://wiki.hevlayer.com): all 283,997 Simple English Wikipedia articles (1.74M paragraph rows) embedded through Lattice and searched on Turbopuffer, with the `performance` echo displayed beside each result. Source at [github.com/hev/wiki](https://github.com/hev/wiki). ## Limits - Text only. An image modality on a Lattice profile is a validation error. - No [revision pins or instructions](/docs/pro/api/embed#model-settings). Those extensions require a GPU-served profile. - `embed.dims` must equal the sliced artifact's dimension. A mismatch is a validation error at write time, not a silent reshape. - A directory that fails to load stops the gateway at startup rather than serving a namespace that cannot embed. # License Source: https://hevlayer.com/docs/pro/api/license import CodeTabs from "../../../components/docs/CodeTabs.astro"; `GET /v2/license` returns the gateway's local license projection. It is an operator and dashboard oracle: it never phones home, and it derives state from the configured license key plus the gateway's codified grace cushion. ```bash curl "$LAYER_GATEWAY_URL/v2/license" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ## Response A valid key that is still within its licensed or grace window returns `valid: true` and the key claims the gateway is using: ```json { "valid": true, "sub": "acme-corp", "tier": "design-partner", "features": ["transform-runtime", "agents", "rbac", "warehouses", "doc-cache", "history", "cost"], "limits": {"namespaces": 50, "udf_workers": 20}, "exp": "2026-12-14T00:00:00Z", "gateway": { "state": "licensed", "seconds_to_deadline": 1209600, "grace_seconds_remaining": 0 } } ``` When the key is expired but still inside the gateway grace window, `gateway.state` is `grace`, `valid` remains `true`, and `grace_seconds_remaining` counts down to the floor. Missing, invalid, or fully degraded licenses return `valid: false`: ```json { "valid": false, "state": "floor", "reason": "missing", "gateway": { "state": "floor", "seconds_to_deadline": 0, "grace_seconds_remaining": 0 } } ``` Invalid keys use `reason` to report the verifier failure. Missing keys use `reason: "missing"`. ## Fields | Field | Present when | Meaning | | --- | --- | --- | | `valid` | Always | Whether the gateway currently treats the deployment as licensed or in grace. | | `state` | Missing/invalid/floor key | Top-level floor marker for a missing or invalid license. | | `reason` | Missing/invalid key | Human-readable verifier reason, or `missing`. | | `sub` | Valid key | Licensed account or trial subject. | | `tier` | Valid key | License tier label such as `trial` or `design-partner`. | | `features` | Valid key | Feature strings the key enables. Absence denies the gated feature. | | `limits` | Valid key | Numeric entitlement limits. Missing keys are unlimited for that dimension. | | `exp` | Valid key | Key expiration timestamp. | | `gateway.state` | Always | `licensed`, `grace`, or `floor` for the gateway surface. | | `gateway.seconds_to_deadline` | Always | Seconds to `exp` while licensed, seconds to `exp + grace` while in grace, otherwise `0`. | | `gateway.grace_seconds_remaining` | Always | Seconds left in gateway grace, otherwise `0`. | Phase 1 reports the gateway surface. Operator and dashboard states use the same `licensed` / `grace` / `floor` model, but they are not included in this response until their enforcement surfaces ship. ## State Effects | Gateway state | Gated route behavior | CE route behavior | | --- | --- | --- | | `licensed` | Feature-gated routes work if `features` includes the route's feature. | Always works. | | `grace` | Feature-gated routes work and responses include `x-hevlayer-license-grace: true`. | Always works. | | `floor` | Feature-gated routes return `402` with `error: "license_required"`. | Always works. | The CE floor includes query, point read, write, scan, namespace metadata, snapshot, and backend routing routes. ## Client Call ```python state = await client.get_license() print(state.gateway.state) ``` ```go state, err := client.GetLicense(ctx) if err != nil { return err } fmt.Println(state.Gateway.State) ``` ```typescript const state = await client.getLicense(); console.log(state.gateway.state); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/license" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` # API keys Source: https://hevlayer.com/docs/pro/api/keys import CodeTabs from "../../../components/docs/CodeTabs.astro"; Layer mints its own API keys. What a key opens is declared per resource: each entitlement names a [`VectorStore`](/docs/pro/kubernetes/vectorstore-crd), a [`Warehouse`](/docs/pro/kubernetes/warehouse-crd), or Layer itself, and carries the scopes and claims for that target. The [`ApiKey` CRD page](/docs/pro/kubernetes/apikey-crd) covers the resource model; this page is the REST surface. You don't have to mint anything. The default `VectorStore` credential (the store key you already own) is accepted as an admin bearer. Minting starts from it: admin scope is what calls these routes. ## Key model - Tokens look like `hvl_iqGFsDD2PNkyhCqr59jjvKuKL47vqXMz`. The raw token is returned **once**, in the mint response. Layer stores only one-way hashes; a lost token is revoked and re-minted, never recovered. - Every key is an `ApiKey` resource in the cluster — `kubectl get apikeys` is the audit trail, and `kubectl apply` is an equal authoring surface (the operator mints and delivers the token via Secret). - Revoke is the default end-of-life action. It disables the credential while keeping its owner, entitlements, and lifecycle record available for audit. Propagation takes seconds, not milliseconds. - Hard delete is a rare, deliberate cleanup action. A key must be `Revoked` first; deletion then permanently removes its audit record. ## Routes | Route | Method | Auth | Behavior | | --- | --- | --- | --- | | `/v2/keys` | POST | admin | Mint a key. The only response that contains the raw token. | | `/v2/keys` | GET | admin | List keys — metadata, never material. `?includeRevoked` adds revoked and expired keys. | | `/v2/keys/{keyId}` | GET | admin | One key's metadata. | | `/v2/keys/{keyId}/revoke` | POST | admin | Revoke. Idempotent; the record stays. | | `/v2/keys/{keyId}` | DELETE | admin | Hard-delete a `Revoked` key and permanently remove its audit record. | | `/v2/keys/authenticate` | POST | none | Exchange a raw token for identity and entitlements. | Admin here means a key with the `layer` entitlement at `admin` scope, or the bootstrap gateway key. `authenticate` is unauthenticated by construction — the token is the credential. ## Mint ```python key = await client.mint_key({ "name": "cohort-reader", "owner": "acme", "entitlements": { "vectorstore.prod-turbopuffer": { "scopes": ["read"], "namespaces": ["cohort-*"], }, "warehouse.prod-snowflake": { "claims": ["notes:cohort:*:read"], }, }, "expiresAfter": "365d", }) print(key.token) # shown once, never again ``` ```go key, err := client.MintKey(ctx, &hevlayer.MintKeyRequest{ Name: "cohort-reader", Owner: "acme", Entitlements: hevlayer.ApiKeyEntitlements{ "vectorstore.prod-turbopuffer": { Scopes: []string{"read"}, Namespaces: []string{"cohort-*"}, }, "warehouse.prod-snowflake": { Claims: []string{"notes:cohort:*:read"}, }, }, ExpiresAfter: "365d", }) fmt.Println(key.Token) // shown once, never again ``` ```typescript const key = await client.mintKey({ name: "cohort-reader", owner: "acme", entitlements: { "vectorstore.prod-turbopuffer": { scopes: ["read"], namespaces: ["cohort-*"], }, "warehouse.prod-snowflake": { claims: ["notes:cohort:*:read"], }, }, expiresAfter: "365d", }); console.log(key.token); // shown once, never again ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/keys" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "cohort-reader", "owner": "acme", "entitlements": { "vectorstore.prod-turbopuffer": {"scopes": ["read"], "namespaces": ["cohort-*"]}, "warehouse.prod-snowflake": {"claims": ["notes:cohort:*:read"]} }, "expiresAfter": "365d" }' ``` The response is `201 Created`: ```json { "keyId": "0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9", "name": "cohort-reader", "owner": "acme", "entitlements": { "vectorstore.prod-turbopuffer": {"scopes": ["read"], "namespaces": ["cohort-*"]}, "warehouse.prod-snowflake": {"claims": ["notes:cohort:*:read"]} }, "phase": "Active", "createdAt": "2026-06-10T00:00:00Z", "expiresAt": "2027-06-10T00:00:00Z", "token": "hvl_iqGFsDD2PNkyhCqr59jjvKuKL47vqXMz" } ``` | Field | Required | Behavior | | --- | --- | --- | | `name` | yes | Unique per install. Becomes the `ApiKey` resource name. | | `owner` | no | Free-form owner label, echoed in list and authenticate responses. | | `description` | no | Free text, shown in listings. | | `entitlements` | no | Map keyed by target — `vectorstore.`, `warehouse.`, `agent.`, or `layer`. Unknown prefixes are 400s. See the [entitlement model](/docs/pro/kubernetes/apikey-crd#entitlements). | | `expiresAfter` | no | Duration or `never`. Defaults to `365d`; `expiresAt` is computed at mint. | An agent invocation entitlement is `"agent.": {}`. It does not accept scopes or namespace restrictions. Validation failures are 400s with field-level messages; nothing is created on a failed mint. An entitlement whose target does not exist is accepted — it grants nothing and surfaces as an `EntitlementTargetMissing` condition on the resource, so keys and targets can be applied in either order. Mint an admin key the same way — `"entitlements": {"layer": {"scopes": ["admin"]}}`. An admin key can mint further keys; key custody is the only hierarchy. ## List and get ```python keys = await client.list_keys() key = await client.get_key("0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9") ``` ```go keys, err := client.ListKeys(ctx, nil) key, err := client.GetKey(ctx, "0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9") ``` ```typescript const keys = await client.listKeys(); const key = await client.getKey("0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9"); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/keys" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ```json { "keys": [ { "keyId": "0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9", "name": "cohort-reader", "owner": "acme", "entitlements": { "vectorstore.prod-turbopuffer": {"scopes": ["read"], "namespaces": ["cohort-*"]}, "warehouse.prod-snowflake": {"claims": ["notes:cohort:*:read"]} }, "phase": "Active", "createdAt": "2026-06-10T00:00:00Z", "expiresAt": "2027-06-10T00:00:00Z", "lastSeenAt": "2026-06-10T12:00:00Z" } ] } ``` Listings carry metadata only — never tokens or recoverable hashes. `lastSeenAt` advances at most once per five minutes per key. ## Authenticate External systems present a raw token and get back `keyId` — a stable actor id — plus the full entitlements map, then make their own authorization decisions from the claims. This is the verb that makes Layer a key store for applications that keep authorization to themselves: Layer never interprets a claim string. ```python identity = await client.authenticate_key({"token": presented}) claims = identity.entitlements["warehouse.prod-snowflake"].claims ``` ```go identity, err := client.AuthenticateKey(ctx, &hevlayer.AuthenticateKeyRequest{ Token: presented, }) claims := identity.Entitlements["warehouse.prod-snowflake"].Claims ``` ```typescript const identity = await client.authenticateKey({ token: presented }); const claims = identity.entitlements["warehouse.prod-snowflake"].claims; ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/keys/authenticate" \ -H "Content-Type: application/json" \ -d '{"token": "hvl_iqGFsDD2PNkyhCqr59jjvKuKL47vqXMz"}' ``` `200` returns `{keyId, name, owner, entitlements, expiresAt}`. Invalid, revoked, and expired tokens all answer `401` indistinguishably, in constant time on a miss. The route is rate-limited. ## Revoke by default ```python await client.revoke_key("0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9") ``` ```go _, err := client.RevokeKey(ctx, "0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9") ``` ```typescript await client.revokeKey("0a1b2c3d-4e5f-6071-8293-a4b5c6d7e8f9"); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/keys/$KEY_ID/revoke" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` The gateway stops accepting a revoked key within seconds. Rotation is mint-new, deploy, revoke-old — there is no in-place rotation. Revoked keys remain in `?includeRevoked` listings indefinitely: Layer does not automatically garbage-collect them. Set an external retention policy that meets your audit requirements. Hard delete is the explicit exception for records that must be forgotten. It is accepted only after the key is `Revoked`; deleting an `Active`, `Pending`, or `Expired` key returns `409 Conflict`: ```bash curl -X DELETE "$LAYER_GATEWAY_URL/v2/keys/$KEY_ID" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` Deleting removes the `ApiKey` resource and its audit history permanently. For CRD-authored keys, Kubernetes also garbage-collects the owned token Secret. Use deletion only after the applicable retention period has passed or when policy requires the record itself to be removed. ## Using a minted key A minted key works anywhere its entitlements reach. A `vectorstore.` entitlement opens data-plane routes against that store, inside its namespace globs: ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/cohort-7/query" \ -X POST \ -H "Authorization: Bearer hvl_iqGFsDD2PNkyhCqr59jjvKuKL47vqXMz" \ -H "Content-Type: application/json" \ -d '{"rank_by": ["text", "BM25", "acme"], "top_k": 10}' ``` Outside the grant, the gateway answers 403: ```json {"error": "namespace not in key grant", "namespace": "orders"} ``` A request that needs a higher scope answers 403 with the scope named: ```json {"error": "insufficient API key scope", "required_scope": "admin"} ``` A key whose entitlements carry only claims — no scopes — is a pure external-store key: it authenticates, but opens no Layer route. A minted key is gateway-only and cannot authenticate directly to the upstream store. SDKs return connection errors when the gateway is unreachable; see [client failure behavior](/docs/pro/failure-modes#client-failures). ## kubectl The CRD is the other authoring surface — apply an `ApiKey` with no credential and the operator mints the token into a Secret named by `status.secretRef`: ```bash kubectl apply -f key.yaml kubectl get apikeys -n layer kubectl get secret apikey-cohort-reader -n layer -o jsonpath='{.data.token}' | base64 -d ``` Both surfaces round-trip through one schema — `kubectl get apikey -o yaml` and `GET /v2/keys/{keyId}` are two spellings of the same object. The [`ApiKey` CRD page](/docs/pro/kubernetes/apikey-crd) has the full resource model and the Kubernetes RBAC the chart ships for it. ## CLI The same operations from the [CLI](/docs/pro/cli#keys): ```bash layer keys mint cohort-reader --owner acme \ --entitle vectorstore.prod-turbopuffer=read \ --namespaces "cohort-*" \ --claim warehouse.prod-snowflake="notes:cohort:*:read" layer keys ls layer keys revoke cohort-reader # Rare cleanup after the retention period: layer keys rm cohort-reader ``` `layer keys mint` prints the token once, alone on stdout for piping; the metadata table goes to stderr. # Namespace metadata Source: https://hevlayer.com/docs/pro/api/namespace-metadata import Edition from "../../../components/docs/Edition.astro"; import Upstream from "../../../components/docs/Upstream.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; Metadata requests are wire-compatible with the upstream `GET /v2/namespaces/{ns}/metadata` endpoint and forwarded as-is after validation. This documentation covers only Layer enhancements. ## Request ```python metadata = await client.get_namespace_metadata("products") ``` ```go metadata, err := client.GetNamespaceMetadata(ctx, "products") ``` ```typescript const metadata = await client.getNamespaceMetadata("products"); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/metadata" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ```jsonc { // Proxied from turbopuffer verbatim "schema": { }, "approx_row_count": 12500, "approx_logical_bytes": 48800000, "created_at": "2026-03-15T10:30:45Z", "updated_at": "2026-05-12T18:49:00Z", "last_write_at": "2026-05-12T18:48:30Z", "index": { "status": "up-to-date" }, // Layer enhancement "layer": { "stable_as_of": 1715600400000, "is_stable": true, "indexed": true, "index_lag_rows": 0 } } ``` ## The `layer` block | Field | Meaning | | --- | --- | | `stable_as_of` | Epoch-ms watermark from the most recent stable poll. Null on cold start before the watcher has observed a stable namespace. | | `is_stable` | Whether the most recent poll observed `index.status == "up-to-date"`. False on cold start, true once the watcher catches up. | | `indexed` | Whether every row in the namespace carries an indexed vector. True once the snapshot's indexed-vector row count has caught up to the namespace row count; false while rows are still awaiting their first index, as during a bulk load or a [pipeline](/docs/pro/api/pipelines) mid-flight. Null for FTS-only namespaces, which have no vector column to reconcile. | | `index_lag_rows` | Count of rows present in the namespace that do not yet have an indexed vector. Zero when `indexed` is true. Reconciled from the most recent [snapshot](/docs/pro/api/snapshots), so it trails live writes by the snapshot cadence. | A read for a namespace that does not exist returns upstream's 404, matching turbopuffer's own metadata endpoint. `is_stable` is the *current* signal — it drives the per-query filter-skip decision on the query path. `stable_as_of` is the *historical* watermark — the cut a filtered query would apply. After a namespace is observed stable, the watcher refreshes this watermark on the stable-tier cadence (`CONSISTENCY_STABLE_POLL_INTERVAL_MS`, default 60000 ms). Writes re-arm the fast tier, so active namespaces are polled on `CONSISTENCY_POLL_INTERVAL_MS`. `indexed` answers a different question than `is_stable`. `is_stable` reports whether the upstream index has caught up on the rows it has *seen*, which is what read-after-write depends on. `indexed` reports whether every row that *should* be present is present and queryable, which is what a bulk load or a [pipeline](/docs/pro/api/pipelines) needs to know it has finished: rows can be staged and counted before their vectors are indexed, so a namespace can read `is_stable: true` while `indexed: false` with a non-zero `index_lag_rows`. The reconciliation runs against the latest [snapshot](/docs/pro/api/snapshots), so `indexed` advances on the snapshot cadence rather than per write. For snapshot history derived from these freshness signals, see [Snapshots](/docs/pro/api/snapshots). ## List namespaces `GET /v2/namespaces` is a Layer-only augmented listing. It pages the upstream namespace list and enriches each row with stability and cache signals. It is the endpoint the dashboard's inventory view reads. ```python namespaces = await client.list_namespaces(prefix="prod", page_size=100) ``` ```go namespaces, err := client.ListNamespaces(ctx, &hevlayer.ListNamespacesParams{ Prefix: "prod", PageSize: 100, }) ``` ```typescript const namespaces = await client.listNamespaces({ prefix: "prod", pageSize: 100, }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces?prefix=prod&page_size=100" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ```jsonc { "namespaces": [ { "name": "products", "row_count": 12500, "size_bytes": 48800000, "stable_as_of_ms": 1715600400000, "is_stable": true, "index": { "status": "up-to-date" }, "cache_state": {"state": "warm", "warm_inflight": false}, "last_write_ms": 1715600399000, "shadow": false, "labels": {} } ], "next_cursor": "..." } ``` Each row carries freshness signals derived from that row's metadata fetch. `is_stable` is true when `index.status` is `"up-to-date"`, false when it is `"updating"`, and omitted when metadata has no index signal or the fetch failed. `stable_as_of_ms` is set to the metadata observation time for rows reported up to date. `indexed` and `index_lag_rows` live on `GET /v2/namespaces/{namespace}/metadata`, where the gateway can do the snapshot lookup for one namespace without adding object-store reads to the high-fanout list path. `index` is turbopuffer's indexing state, passed through verbatim: | Field | Meaning | | --- | --- | | `index.status` | `"updating"` or `"up-to-date"`. | | `index.unindexed_bytes` | Write-ahead-log bytes not yet indexed. Present only while `updating` (omitted once caught up). Unindexed data is still searched by queries, so a non-zero value means *behind, but serving* — watch it fall to confirm indexing is draining rather than wedged. | Listing is read-only and does not register namespaces with the consistency watcher. Write traffic and snapshot facet configuration register the namespaces that need durable watermarks. | Query param | Purpose | | --- | --- | | `prefix` | Restrict to namespaces whose name starts with this string. | | `cursor` | Pagination cursor from a prior `next_cursor`. | | `page_size` | Page size; the upstream list page is capped at 1000. | A per-row metadata failure degrades to a row with `metadata_error` set rather than dropping the namespace, so the list stays complete even when a single namespace's metadata call fails. Responses are served from a short-TTL cache (`NAMESPACE_LIST_CACHE_TTL_MS`, default `10000`) so dashboard polling does not fan out a metadata call per namespace per refresh. # Pipelines Source: https://hevlayer.com/docs/pro/api/pipelines import CodeTabs from "../../../components/docs/CodeTabs.astro"; The pipeline API keeps the code you need to index data simple and organized. A typical pipeline has two stages: extraction and chunking on CPU, followed by embedding on GPU. This guide walks through a best-practice layout for that pipeline; the concepts expand to N stages. ## Document lifecycle ``` put chunks put vectors (new doc) ──────────► pending ──────────────► indexed ▲ │ re-stage (idempotent) ``` - **pending** — chunks stored, waiting for embedding. - **indexed** — vectors written to the namespace's configured VectorStore. `embedding` is a claim stage: documents sit in it only while leased to a worker, and recover to `pending` when a lease expires. Re-staging a document resets it to `pending` with new chunks, which is how you reprocess after source data changes. ## File tree ``` indexer/ ├── pipelines/ │ ├── extract-chunk.yaml # CPU stage — Pipeline resource │ └── embed.yaml # GPU stage — Pipeline resource ├── extract_chunk.py # read the source, stage chunks ├── embed.py # claim pending docs, write vectors └── app.py # REST API: trigger a run, wait for completion ``` The two YAML files declare the worker images, pools, and scaling — see the [Pipeline CRD](/docs/pro/kubernetes/pipeline-crd) for the fields. Both set `pipelineId: products` so the two workers share one queue. The rest of this page is the worker code — shown in Python and Go; every call is also a plain REST endpoint (see [Write & Stage](/docs/pro/api/write)). ## Extract and chunk The CPU worker reads the source, splits text into chunks, and stages them. Staging chunks stores them durably (S3, cached in the document cache) and marks the document `pending`. The worker hardcodes nothing: the operator injects the pipeline id, the gateway URL, and `spec.sourceRef` as environment variables — see the [worker variables](/docs/pro/kubernetes/pipeline-crd#worker) on the CRD page. The queue URL below comes from the `sourceRef` declared in `pipelines/extract-chunk.yaml`. ```python # extract_chunk.py import asyncio import json import os import boto3 from hevlayer import AsyncHevlayer PIPELINE = os.environ["HEVLAYER_PIPELINE_ID"] SOURCE = json.loads(os.environ["HEVLAYER_SOURCE_REF"]) sqs = boto3.client("sqs") def chunks(text: str, size: int = 800) -> list[str]: return [text[i : i + size] for i in range(0, len(text), size)] async def main() -> None: async with AsyncHevlayer( base_url=os.environ["HEVLAYER_BASE_URL"], api_key=os.environ.get("LAYER_GATEWAY_API_KEY"), ) as layer: while True: batch = sqs.receive_message( QueueUrl=SOURCE["queueUrl"], MaxNumberOfMessages=10, ).get("Messages", []) for m in batch: doc = json.loads(m["Body"]) await layer.put_pipeline_document_chunks(PIPELINE, doc["id"], { "chunks": [ {"id": f"{doc['id']}-{i}", "text": t} for i, t in enumerate(chunks(doc["text"])) ], }) sqs.delete_message(QueueUrl=SOURCE["queueUrl"], ReceiptHandle=m["ReceiptHandle"]) asyncio.run(main()) ``` ```go // extract_chunk.go package main import ( "context" "encoding/json" "fmt" "os" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" hevlayer "github.com/hev/layer-go" ) func chunks(text string, size int) []string { var out []string for i := 0; i < len(text); i += size { out = append(out, text[i:min(i+size, len(text))]) } return out } func main() { ctx := context.Background() pipeline := os.Getenv("HEVLAYER_PIPELINE_ID") var source struct { QueueURL string `json:"queueUrl"` } json.Unmarshal([]byte(os.Getenv("HEVLAYER_SOURCE_REF")), &source) cfg, _ := config.LoadDefaultConfig(ctx) queue := sqs.NewFromConfig(cfg) layer := hevlayer.NewClient( hevlayer.WithBaseURL(os.Getenv("HEVLAYER_BASE_URL")), hevlayer.WithAPIKey(os.Getenv("LAYER_GATEWAY_API_KEY")), ) for { batch, err := queue.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{ QueueUrl: &source.QueueURL, MaxNumberOfMessages: 10, }) if err != nil { continue } for _, m := range batch.Messages { var doc struct { ID string `json:"id"` Text string `json:"text"` } json.Unmarshal([]byte(*m.Body), &doc) var staged []hevlayer.Chunk for i, t := range chunks(doc.Text, 800) { staged = append(staged, hevlayer.Chunk{ID: fmt.Sprintf("%s-%d", doc.ID, i), Text: t}) } layer.PutPipelineDocumentChunks(ctx, pipeline, doc.ID, &hevlayer.PutChunksRequest{Chunks: staged}) queue.DeleteMessage(ctx, &sqs.DeleteMessageInput{ QueueUrl: &source.QueueURL, ReceiptHandle: m.ReceiptHandle, }) } } } ``` ```typescript // extract_chunk.ts import { DeleteMessageCommand, ReceiveMessageCommand, SQSClient, } from "@aws-sdk/client-sqs"; import { Hevlayer } from "hevlayer"; const PIPELINE = process.env.HEVLAYER_PIPELINE_ID!; const SOURCE = JSON.parse(process.env.HEVLAYER_SOURCE_REF!); const sqs = new SQSClient({}); const layer = new Hevlayer({ baseUrl: process.env.HEVLAYER_BASE_URL, apiKey: process.env.LAYER_GATEWAY_API_KEY, }); function chunks(text: string, size = 800): string[] { const out: string[] = []; for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size)); return out; } while (true) { const batch = await sqs.send(new ReceiveMessageCommand({ QueueUrl: SOURCE.queueUrl, MaxNumberOfMessages: 10, })); for (const message of batch.Messages ?? []) { const doc = JSON.parse(message.Body ?? "{}"); await layer.putPipelineDocumentChunks(PIPELINE, doc.id, { chunks: chunks(doc.text).map((text, i) => ({ id: `${doc.id}-${i}`, text })), }); await sqs.send(new DeleteMessageCommand({ QueueUrl: SOURCE.queueUrl, ReceiptHandle: message.ReceiptHandle, })); } } ``` ## Embed The GPU worker claims pending documents, reads their chunks back, and writes vectors. Writing vectors upserts to the namespace's configured VectorStore and marks the document `indexed`. Claims are leased, so a worker that crashes loses nothing. For multivector namespaces on a `kind: search` store, send `vectors: [[...], [...]]` on an entry instead of `vector: [...]`; the gateway forwards the bag and caches the first inner vector for `nearest_to_id` lookup. ```python # embed.py import asyncio import os from hevlayer import AsyncHevlayer from sentence_transformers import SentenceTransformer PIPELINE = os.environ["HEVLAYER_PIPELINE_ID"] model = SentenceTransformer("all-MiniLM-L6-v2") async def main() -> None: async with AsyncHevlayer( base_url=os.environ["HEVLAYER_BASE_URL"], api_key=os.environ.get("LAYER_GATEWAY_API_KEY"), ) as layer: while True: claimed = await layer.claim_documents(PIPELINE, { "stage": "pending", "claim_stage": "embedding", "limit": 16, "worker_id": "embed-0", }) for doc_id in claimed.documents: doc_chunks = await layer.get_pipeline_document_chunks(PIPELINE, doc_id) vectors = model.encode([c.text for c in doc_chunks]) await layer.put_pipeline_document_vectors(PIPELINE, doc_id, { "vectors": [ {"id": c.id, "vector": v.tolist(), "attributes": {"text": c.text}} for c, v in zip(doc_chunks, vectors) ], }) asyncio.run(main()) ``` ```go // embed.go package main import ( "context" "os" hevlayer "github.com/hev/layer-go" ) func main() { ctx := context.Background() pipeline := os.Getenv("HEVLAYER_PIPELINE_ID") layer := hevlayer.NewClient( hevlayer.WithBaseURL(os.Getenv("HEVLAYER_BASE_URL")), hevlayer.WithAPIKey(os.Getenv("LAYER_GATEWAY_API_KEY")), ) for { claimed, err := layer.ClaimDocuments(ctx, pipeline, &hevlayer.ClaimDocumentsRequest{ Stage: "pending", ClaimStage: "embedding", Limit: 16, WorkerID: "embed-0", }) if err != nil { continue } for _, docID := range claimed.Documents { docChunks, err := layer.GetPipelineDocumentChunks(ctx, pipeline, docID) if err != nil { continue } texts := make([]string, len(*docChunks)) for i, c := range *docChunks { texts[i] = c.Text } vectors := embed(texts) // your embedding model or service entries := make([]hevlayer.VectorEntry, len(*docChunks)) for i, c := range *docChunks { entries[i] = hevlayer.VectorEntry{ ID: c.ID, Vector: vectors[i], Attributes: map[string]interface{}{"text": c.Text}, } } layer.PutPipelineDocumentVectors(ctx, pipeline, docID, &hevlayer.PutVectorsRequest{Vectors: entries}) } } } ``` ```typescript // embed.ts import { Hevlayer } from "hevlayer"; const PIPELINE = process.env.HEVLAYER_PIPELINE_ID!; const layer = new Hevlayer({ baseUrl: process.env.HEVLAYER_BASE_URL, apiKey: process.env.LAYER_GATEWAY_API_KEY, }); while (true) { const claimed = await layer.claimDocuments(PIPELINE, { stage: "pending", claim_stage: "embedding", limit: 16, worker_id: "embed-0", }); for (const docId of claimed.documents) { const docChunks = await layer.getPipelineDocumentChunks(PIPELINE, docId); const vectors = await embed(docChunks.map((chunk) => chunk.text)); await layer.putPipelineDocumentVectors(PIPELINE, docId, { vectors: docChunks.map((chunk, i) => ({ id: chunk.id, vector: vectors[i], attributes: { text: chunk.text }, })), }); } } ``` ## Deploy Build the two workers into the images your YAML references and push them to a registry your cluster can pull — Layer does not build images. Then apply the resources: ```sh kubectl apply -f pipelines/ ``` The operator creates one Deployment per resource and the embed pool's KEDA object. Order doesn't matter here: the app creates the gateway pipeline before it enqueues a batch (staging into a pipeline id that doesn't exist returns 404), so workers never see a missing pipeline. Nothing else to wire: the CRD [types themselves](/docs/pro/install#helm) install with the Helm chart. ## Trigger a run The app exposes the pipeline to the rest of your system as one endpoint: `POST /index-runs` sends a batch to the source queue, then waits for the run to complete and returns the snapshot it produced. The pipeline is created on first use — this is where the target namespace is set in code. Layer deduplicates `create_missing` staging by pipeline and document id. Large staging calls publish queue segments incrementally, so downstream workers can claim committed rows and KEDA can observe their depth while the same call is still adding later segments. ```python # app.py import asyncio import json import os import time import boto3 from fastapi import FastAPI from hevlayer import AsyncHevlayer, HevlayerError QUEUE = "https://sqs.us-east-1.amazonaws.com/123456789/product-updates" sqs = boto3.client("sqs") app = FastAPI() layer = AsyncHevlayer( base_url=os.environ["HEVLAYER_BASE_URL"], api_key=os.environ.get("LAYER_GATEWAY_API_KEY"), ) @app.post("/index-runs") async def index_run(documents: list[dict]) -> dict: started_ms = int(time.time() * 1000) try: await layer.create_pipeline({"id": "products", "target_namespace": "products"}) except HevlayerError as e: if e.status_code != 409: # 409: already exists raise for doc in documents: sqs.send_message(QueueUrl=QUEUE, MessageBody=json.dumps(doc)) await drain() sha = await next_snapshot(after_ms=started_ms) return {"documents": len(documents), "snapshot": sha} ``` ```go // app.go var ( queueURL = "https://sqs.us-east-1.amazonaws.com/123456789/product-updates" queue *sqs.Client // sqs.NewFromConfig in main layer = hevlayer.NewClient( hevlayer.WithBaseURL(os.Getenv("HEVLAYER_BASE_URL")), hevlayer.WithAPIKey(os.Getenv("LAYER_GATEWAY_API_KEY")), ) ) func indexRun(w http.ResponseWriter, r *http.Request) { ctx := r.Context() startedMs := time.Now().UnixMilli() var documents []map[string]interface{} json.NewDecoder(r.Body).Decode(&documents) _, err := layer.CreatePipeline(ctx, &hevlayer.CreatePipelineRequest{ ID: "products", TargetNamespace: "products", }) var herr *hevlayer.HevlayerError if err != nil && !(errors.As(err, &herr) && herr.StatusCode == 409) { // 409: already exists http.Error(w, err.Error(), http.StatusBadGateway) return } for _, doc := range documents { body, _ := json.Marshal(doc) mb := string(body) queue.SendMessage(ctx, &sqs.SendMessageInput{QueueUrl: &queueURL, MessageBody: &mb}) } drain(ctx) sha := nextSnapshot(ctx, startedMs) json.NewEncoder(w).Encode(map[string]interface{}{ "documents": len(documents), "snapshot": sha, }) } ``` ```typescript // app.ts import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; import { Hevlayer } from "hevlayer"; const queueUrl = "https://sqs.us-east-1.amazonaws.com/123456789/product-updates"; const queue = new SQSClient({}); const layer = new Hevlayer({ baseUrl: process.env.HEVLAYER_BASE_URL, apiKey: process.env.LAYER_GATEWAY_API_KEY, }); async function indexRun(documents: Record[]) { const startedMs = Date.now(); await layer.ensurePipeline({ id: "products", target_namespace: "products" }); for (const doc of documents) { await queue.send(new SendMessageCommand({ QueueUrl: queueUrl, MessageBody: JSON.stringify(doc), })); } await drain(); return { documents: documents.length, snapshot: await nextSnapshot(startedMs) }; } ``` ## Wait for completion A run is complete in two steps: the queue drains, then the consistency watcher observes the namespace stable and writes a [snapshot](/docs/pro/api/snapshots) past the run's watermark. `pending_count` is the same signal KEDA scales on — when it reaches zero, the embed pool scales back to zero. `status` is `waiting_on_upstream` when a downstream worker has no pending rows to claim while upstream stages are still active. If a worker cannot load a document's durable chunk payload after the configured retry budget, Layer moves that document to `failed` and adds the dead-letter reason to `failed_reasons`, such as `{"chunks_unavailable": 2}`. The snapshot SHA addresses facet listings and counts exact at that watermark; flip your application to it. ```python # app.py async def drain() -> None: while True: status = await layer.get_pipeline_status("products") if status.pending_count == 0: # status.counts: {"pending": 0, "indexed": 8530} return await asyncio.sleep(10) async def next_snapshot(after_ms: int) -> str: while True: history = await layer.list_namespace_history("products", limit=1) if history and history[0].watermark_ms >= after_ms: return history[0].sha await asyncio.sleep(30) ``` ```go // app.go func drain(ctx context.Context) { for { status, err := layer.GetPipelineStatus(ctx, "products") if err == nil && status.PendingCount == 0 { // status.Counts: {"pending": 0, "indexed": 8530} return } time.Sleep(10 * time.Second) } } func nextSnapshot(ctx context.Context, afterMs int64) string { for { history, err := layer.ListNamespaceHistory(ctx, "products", &hevlayer.ListNamespaceHistoryParams{Limit: 1}) if err == nil && len(history) > 0 && history[0].WatermarkMs >= afterMs { return history[0].Sha } time.Sleep(30 * time.Second) } } ``` ```typescript // app.ts const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); async function drain() { while (true) { const status = await layer.getPipelineStatus("products"); if (status.pending_count === 0) return; await sleep(10_000); } } async function nextSnapshot(afterMs: number): Promise { while (true) { const history = await layer.listNamespaceHistory("products", { limit: 1 }); if (history.length > 0 && history[0].watermark_ms >= afterMs) { return history[0].sha; } await sleep(30_000); } } ``` Once vectors are indexed, query and fetch them through the namespace API — see [Query & Fetch](/docs/pro/api/query). ## Failure model - VectorStore write failures are hard: the vectors route returns 502 and the document stays in `embedding` for re-claim. - Aerospike cache failures do not block chunk reads when S3 backing is present; PostgreSQL connectivity failures return 500 and should be retried with backoff. The stop-writes recovery path and the metrics to watch live in the [failure-mode runbook](/docs/pro/failure-modes#pipeline-stop-writes). - Lease expiry is handled server-side. A worker that crashes mid-embedding has its documents recovered on the next claim sweep. # Query & Fetch Source: https://hevlayer.com/docs/pro/api/query import PostgresWarning from "../../../components/docs/PostgresWarning.astro"; import Edition from "../../../components/docs/Edition.astro"; import StoreMatrixLink from "../../../components/docs/StoreMatrixLink.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; import StoreNote from "../../../components/docs/StoreNote.astro"; import Upstream from "../../../components/docs/Upstream.astro"; import FeatureGate from "../../../components/docs/FeatureGate.astro"; Native queries are wire-compatible with the upstream `POST /v2/namespaces/{ns}/query` endpoint and forwarded as-is after validation. This documentation covers only Layer enhancements. This is Layer's query API. Layer reports its own metadata in `x-layer-*` response headers. ## Stable reads Layer tracks a stable watermark for Turbopuffer-backed namespaces. When one is available, `x-layer-stable-as-of` reports that observation. Store capabilities and watcher state determine whether a watermark filter applies; a cold-start gateway can return a query without this header. This is achieved by querying Turbopuffer with `consistency=eventual` and watching each namespace's `index.status`. While the index is updating, Layer injects a hidden `_hevlayer_upserted_at <= watermark` predicate so the read does not include partially indexed rows. Stable or unknown status runs without that predicate; a 429 can trigger one retry with the watermark filter forced on. Responses report `x-layer-stable-as-of` in epoch milliseconds when the watcher has a watermark. The header is omitted on a cold-start gateway that has not yet observed a stable poll. Query responses carry `next_cursor` and, when another page is available, `x-layer-next-cursor`. Cursor behavior depends on the selected store and query mode; unsupported pagination features return `422 UnsupportedByStore`. ## Query by id Pass `nearest_to_id` in place of `vector` to rank by stored document vectors instead of a raw query vector — exactly one of the two is required. `nearest_to_id` takes an **array of document ids**: the gateway resolves each id's vector (document cache first, the namespace's configured VectorStore on miss with a cache backfill) and averages them component-wise into a single centroid, then ranks nearest neighbors to that centroid. Pass one id to rank by a single document; pass several to get "more like these" over a set of seeds. ```python response = await client.query_namespace("products", { "nearest_to_id": ["asin-B08N5WRWNW", "asin-B07PXGQC1Q"], "top_k": 10, "include_attributes": ["title", "category"], }) ``` ```go response, err := client.QueryNamespace(ctx, "products", &hevlayer.QueryRequest{ NearestToID: []string{"asin-B08N5WRWNW", "asin-B07PXGQC1Q"}, TopK: 10, IncludeAttributes: []string{"title", "category"}, }) ``` ```typescript const response = await client.queryNamespace("products", { nearest_to_id: ["asin-B08N5WRWNW", "asin-B07PXGQC1Q"], top_k: 10, include_attributes: ["title", "category"], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "nearest_to_id": ["asin-B08N5WRWNW", "asin-B07PXGQC1Q"], "top_k": 10, "include_attributes": ["title", "category"] }' ``` | Outcome | Status | | --- | --- | | Every id resolved (cache or origin) | 200, ranked results | | Any id has no stored vector anywhere | 404 (names the missing ids) | | `nearest_to_id` empty, or both/neither of `vector` / `nearest_to_id` | 422 | The centroid is an unweighted mean, so seed ids contribute equally regardless of how many you pass. All resolved vectors share the namespace's dimensionality, so no reconciliation is needed across seeds. This fuses the seeds into one ranking; to run several *independent* rankings in a single request, see [batch query](#batch-query). ## Rank expressions Pass `rank_by` with `top_k` when you need an explicit ranking operator instead of the top-level `vector` / `nearest_to_id` shape. Layer handles the portable subset with the same stable-read behavior as vector queries. Native upstream query bodies that omit `top_k` remain pass-through. `rank_by` is mutually exclusive with `vector` and `nearest_to_id`. ## Batch query `nearest_to_id` fuses several seeds into a **single** ranking. To run several **independent** queries in one round trip, each with its own ranking, post a `queries` array. The response is a parallel `results` array — one ranked result set per query, in request order: `{ "results": [{ "rows": ... }] }`. Layer holds every leg on the same stable cut, so a batch reads one consistent view of the index. (The method is `batch_query_namespace`. It is named apart from turbopuffer's own upstream multi-query — a `rerank_by` body, which Layer passes through unchanged, as noted at the end of this section — to keep the two distinct.) ```python batch = await client.batch_query_namespace("products", { "queries": [ {"rank_by": ["vector", "ANN", [0.1, 0.2, 0.3]], "top_k": 10}, {"rank_by": ["title", "BM25", "wireless earbuds"], "top_k": 10}, ], }) # batch.results[0].rows ranked by vector; batch.results[1].rows by text ``` ```go batch, err := client.BatchQueryNamespace(ctx, "products", &hevlayer.BatchQueryRequest{ Queries: []hevlayer.TurbopufferQueryRequest{ {"rank_by": []any{"vector", "ANN", []float64{0.1, 0.2, 0.3}}, "top_k": 10}, {"rank_by": []any{"title", "BM25", "wireless earbuds"}, "top_k": 10}, }, }) ``` ```typescript const batch = await client.batchQueryNamespace("products", { queries: [ { rank_by: ["vector", "ANN", [0.1, 0.2, 0.3]], top_k: 10 }, { rank_by: ["title", "BM25", "wireless earbuds"], top_k: 10 }, ], }); // batch.results[0].rows ranked by vector; batch.results[1].rows by text ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "queries": [ {"rank_by": ["vector", "ANN", [0.1, 0.2, 0.3]], "top_k": 10}, {"rank_by": ["title", "BM25", "wireless earbuds"], "top_k": 10} ] }' ``` All legs in a non-fused batch share one `x-layer-stable-as-of` value. A leg may use native `rank_by`, or the Layer `vector` / `nearest_to_id` single-query shape; `nearest_to_id` is resolved before the leg is sent upstream. Batches must contain 2 to 16 legs. `cursor` is rejected at the top level and per leg because pagination is single-query only. When `rerank_by` is present, Layer treats the request as an upstream fused query and passes the body through unchanged. Reach for a batch query when you genuinely need N rankings — distinct user queries batched into one round trip, or hybrid retrieval fused upstream with RRF. Reach for `nearest_to_id` when many seeds should collapse into one "more like these" ranking. To get typo-tolerant text search without building the fused query yourself, see [hybrid text fusion](#hybrid-text-fusion). Every leg here targets the namespace in the path. To fan one query across a **set** of namespaces — and merge them into a single ranked list — see [federated query](/docs/pro/api/federated-query). ## Hybrid text fusion BM25 misses typos and morphological variants; fuzzy matching alone loses the relevance signal BM25 provides. `HybridText` runs both in one request: the gateway tokenizes your input string, expands it into one BM25 leg plus one fuzzy leg per token, and the effective legs are RRF-fused into one ranking. One expression in, typo-tolerant ranked results out. `HybridText` is a Layer-only `rank_by` spelling on the existing query route — no new endpoint, no client changes beyond the expression. The gateway tokenizes with [`alyze`](https://github.com/turbopuffer/alyze), turbopuffer's own open-source tokenizer and the same code that segmented your text at index time, so query tokens match index terms by construction. The ranked field must be indexed for both full-text and fuzzy matching — declare it `{"type": "string", "full_text_search": true, "fuzzy": true}` in the namespace schema. The BM25 leg uses the full-text index; the per-token fuzzy legs use the fuzzy index. ```python response = await client.query_namespace("support-tickets", { "rank_by": ["content", "HybridText", "conection timout kubernets"], "top_k": 10, "filters": ["tenant", "Eq", "t-42"], "include_attributes": ["content", "title"], }) ``` ```go response, err := client.QueryNamespace(ctx, "support-tickets", &hevlayer.QueryRequest{ RankBy: []any{"content", "HybridText", "conection timout kubernets"}, TopK: 10, Filters: []any{"tenant", "Eq", "t-42"}, IncludeAttributes: []string{"content", "title"}, }) ``` ```typescript const response = await client.queryNamespace("support-tickets", { rank_by: ["content", "HybridText", "conection timout kubernets"], top_k: 10, filters: ["tenant", "Eq", "t-42"], include_attributes: ["content", "title"], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/support-tickets/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["content", "HybridText", "conection timout kubernets"], "top_k": 10, "filters": ["tenant", "Eq", "t-42"], "include_attributes": ["content", "title"] }' ``` An optional fourth tuple element tunes the expansion. Defaults: ```json ["content", "HybridText", "conection timout kubernets", { "fuzziness": "auto", "stopwords": "en", "rank_constant": 60, "per_leg_limit": null }] ``` | Option | Default | Meaning | | --- | --- | --- | | `fuzziness` | `"auto"` | Edit-distance tolerance for the fuzzy legs, keyed to each token's length (turbopuffer requires at least 3 query characters per edit). `"auto"` permits up to distance 2: exact for tokens of 3–5 characters, distance 1 for 6–8, distance 2 for 9 or more. Fixed `0`, `1`, or `2` caps the ladder, so `0` is exact-only. | | `stopwords` | `"en"` | Tokens that do not get a fuzzy leg. `"en"` is the built-in English list, `false` gives every token a fuzzy leg, and an array of strings replaces the built-in list (entries are lowercased). The BM25 leg always ranks the full input and is unaffected. | | `rank_constant` | `60` | turbopuffer's RRF constant, passed through verbatim. Integer > 0. | | `per_leg_limit` | `clamp(5 × top_k, 50, 200)` | How deep each leg retrieves before fusion. Integer > 0. | | `threads` | `8` unless configured per namespace | Maximum concurrent upstream requests when the gateway scatter/gathers the expansion across a [sharded](/docs/pro/concepts#scattergather) namespace — the same fan-out control as [scans](/docs/pro/api/scans). Clamped to active shards. No effect on unsharded namespaces, where the expansion is a single fused upstream call. | Set top-level `include_leg_breakdown: true` to return per-row `$fused.legs` attribution. Each leg entry reports the leg label, that row's 1-based rank within the leg, and the leg's raw score or distance. `rank` and `score` are `null` when the row fell outside that leg's `per_leg_limit` cut. Labels are `bm25`, `fuzzy:`, and `semantic` on routed fused queries. ### Tokenization The input string becomes tokens under a fixed, documented policy: 1. Split on Unicode (UAX #29) word boundaries and lowercase, using `alyze` — the code behind turbopuffer's production `word_v4` tokenizer. Punctuation-only tokens never survive the split. 2. Drop tokens shorter than 2 characters. 3. Dedupe. 4. Remove stop words under the `stopwords` option (English by default). Removed tokens are reported in `stopwords_dropped` and do not count against the cap, so on long queries the cap spends its legs on content tokens. 5. Cap at 15 tokens (15 fuzzy legs + 1 BM25 leg = 16, the upstream subquery limit). Tokens cut by the cap are counted in `tokens_dropped`. Stop words only suppress fuzzy legs: the BM25 leg ranks the full input string. Stemming and language detection are not applied. The input must yield at least one token before stop-word removal. An input made only of stop words is valid: it has no fuzzy legs and ranks on the BM25 leg alone. ### Response Results are the RRF-fused list. A `hybrid` block echoes the effective expansion so defaults are never invisible: ```json { "rows": [ { "id": "ticket-4117", "$score": 0.0639, "content": "...", "title": "Connection timeout on Kubernetes ingress" } ], "hybrid": { "tokens": ["conection", "timout", "kubernets"], "tokens_dropped": 0, "stopwords": "en", "stopwords_dropped": [], "fuzziness": "auto", "rank_constant": 60, "legs": 4, "per_leg_limit": 50 }, "next_cursor": null } ``` | Field | Meaning | | --- | --- | | `$score` | RRF score. Comparable **within** a response, not across requests — do not threshold on it. | | `$fused.legs` | Present only when `include_leg_breakdown: true`. Per-leg attribution in effective leg order; each item has `leg`, `rank`, and `score`. | | `tokens` | Tokens that produced fuzzy legs, post-policy. | | `tokens_dropped` | Tokens removed by the 15-token cap (not by the length or punctuation rules, or as stop words). | | `stopwords` | The effective `stopwords` option: `"en"`, `false`, or the caller's list. | | `stopwords_dropped` | Tokens removed as stop words, in input order. Empty when `stopwords` is `false`. | | `legs` | Total effective subqueries in the fused expansion. Normally the fuzzy legs + 1 BM25 leg (plus 1 ANN leg on routed fused queries). On the `surfaced` fallback there is no BM25 leg, so `legs` equals the token count (one fuzzy leg per token). | | `surfaced` | Present and `true` only when the empty-result fallback fired (see [Surfacing fallback](#surfacing-fallback)). Absent on the normal path. | | `next_cursor` | Top-level field (not inside `hybrid`), always present in the body: the next page token, or `null` on the last page. Mirrors the `x-layer-next-cursor` header. Pass a non-null value back as `cursor`. | The `hybrid` block appears only on `HybridText` responses. On sharded namespaces it also reports the effective `threads` fan-out width. Requests without a `HybridText` expression, including native turbopuffer multi-query + `rerank_by` bodies, keep their upstream-shaped responses byte-for-byte. ### Surfacing fallback Every primary leg ranks by BM25 over the full input, which upstream scores at zero — and drops — when no token matches a stored term exactly. A fully-misspelled query therefore fuses to zero rows. When the primary expansion returns nothing, Layer re-runs one fuzzy leg per token, reorders each leg by field/token edit distance, and fuses those instead, so a typo-heavy query still surfaces near matches. The response then carries `"surfaced": true` in the `hybrid` block, and `legs` reflects the surfacing expansion — one fuzzy leg per token, with no BM25 leg. Working queries never reach this path; the fallback is purely additive and absent (`surfaced` omitted) on the normal path. ### Semantics - **Fusion.** RRF uses the effective leg order: BM25 first, then one fuzzy leg per token, then the semantic ANN leg on routed fused queries. `include_leg_breakdown: true` can require one upstream query per leg on unsharded namespaces so Layer can report per-leg ranks. - **One consistency cut.** Request-level `filters` are replicated to every leg, and the [stable-read](#stable-reads) watermark predicate is injected into every leg from a single read — all legs see the same cut. Responses carry `x-layer-stable-as-of` as usual. - **All-or-nothing.** Any leg failure fails the request; Layer does not return a partial fusion over surviving legs. - **Replay as a unit.** The query logs to [search history](/docs/pro/api/search-history) as one entry carrying the `HybridText` expression, so replaying it reproduces the whole expansion. ### Validation All return `422`: | Condition | Why | | --- | --- | | Input yields zero tokens under the policy before stop-word removal | Nothing to expand. An input made only of stop words is not rejected. | | `HybridText` inside a `queries` array | The expansion is already one batch deep by construction. | | `fuzziness` not in `"auto" \| 0 \| 1 \| 2`; `stopwords` not `"en"`, `false`, or an array of strings; `rank_constant` ≤ 0; `per_leg_limit` ≤ 0; `threads` < 1 | Out of range. | To let the gateway pick between hybrid text and semantic retrieval per query, see [query routing](#query-routing). ## Query routing Real search boxes receive both `"timout"` and `"why do pods lose their connection during deploys"`. The first wants [hybrid text fusion](#hybrid-text-fusion); the second wants semantic retrieval — lexical legs add noise on long conversational input, and ANN underperforms on short identifier-shaped tokens. `Auto` is a Layer-only `rank_by` spelling that makes that call per query, so the branch doesn't live ad hoc in your application code. The route is chosen from the shape of the input alone. Supply an inline `Embed` as the vector source and Layer resolves it only after the policy selects `semantic` or `fused`; a `hybrid_text` route never calls the embedding provider. Without either an inline `Embed` or a numeric vector, a vector-needing route returns the routing decision instead of results so the application can embed and re-issue. Short keyword traffic executes immediately and never pays for an embedding. ```python response = await client.query_namespace("support-tickets", { "rank_by": ["title", "Auto", user_input, { "vector": ["Embed", user_input, {"field": "content"}], }], "top_k": 10, "filters": ["tenant", "Eq", "t-42"], }) ``` ```go response, err := client.QueryNamespace(ctx, "support-tickets", &hevlayer.QueryRequest{ RankBy: []any{"title", "Auto", userInput, map[string]any{ "vector": []any{"Embed", userInput, map[string]any{"field": "content"}}, }}, TopK: 10, Filters: []any{"tenant", "Eq", "t-42"}, }) ``` ```typescript const response = await client.queryNamespace("support-tickets", { rank_by: ["title", "Auto", userInput, { vector: ["Embed", userInput, { field: "content" }], }], top_k: 10, filters: ["tenant", "Eq", "t-42"], }); ``` ```bash # One request: title is lexical; content selects the embedding profile. curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/support-tickets/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rank_by": ["title", "Auto", "why do pods lose their connection during deploys", { "vector": ["Embed", "why do pods lose their connection during deploys", { "field": "content" }] }], "top_k": 10, "filters": ["tenant", "Eq", "t-42"] }' ``` ### Routing policy The v1 policy reads the token count of the input under the same [tokenizer policy](#tokenization) as hybrid text fusion: | Tokens | Route | Runs | | --- | --- | --- | | ≤ 2 | `hybrid_text` | The [hybrid text fusion](#hybrid-text-fusion) expansion. | | ≥ 8 | `semantic` | ANN over the supplied query vector. | | 3 – 7 | `fused` | Both, merged upstream by RRF. | Vector availability never changes which route is chosen — only whether it executes in this request. `hybrid_text` always executes and does not resolve an inline `Embed`; `semantic` and `fused` resolve it after routing, execute with a numeric `vector`, and defer only when neither is present. The policy is versioned (`"policy": "v1"`) in the response. Threshold changes are also visible in [search history](/docs/pro/api/search-history). ### Options The optional fourth tuple element: | Option | Default | Meaning | | --- | --- | --- | | `route` | `"auto"` | Force `"hybrid_text"`, `"semantic"`, or `"fused"` instead of applying the policy. Used on re-issue after a deferral, and for A/B comparison of strategies on the same input. | | `vector` | — | A numeric query vector, or `["Embed", input, {field?, model?}?]`. `field` selects the source or derived attribute whose embedding profile supplies the model and vector target; it defaults to the Auto lexical field. Layer resolves `Embed` only for `semantic` and `fused`. A derived `embed_` field requires `model`. | | `fuzziness` | `"auto"` | Forwarded to the `HybridText` expansion on the `hybrid_text` and `fused` routes: `"auto"`, `0`, `1`, or `2`. `0` forces exact-only matching. No effect on the `semantic` route. | | `stopwords` | `"en"` | Forwarded to the `HybridText` expansion on the `hybrid_text` and `fused` routes: `"en"`, `false`, or an array of strings. Does not change the token count the routing policy reads. | When the chosen route expands hybrid-text legs, the hybrid defaults apply and the [`hybrid` echo block](#response) appears alongside `routing`. Set top-level `include_leg_breakdown: true` to add `$fused.legs` to each fused row; the fused route includes a final `semantic` leg after the BM25 and fuzzy-token legs. ### Response Every `Auto` response carries a `routing` block: ```json { "rows": [{"id": "ticket-4117", "$score": 0.0639, "title": "..."}], "routing": { "route": "hybrid_text", "policy": "v1", "tokens": 1, "executed": true }, "hybrid": {"tokens": ["timout"], "tokens_dropped": 0, "stopwords": "en", "stopwords_dropped": [], "fuzziness": "auto", "rank_constant": 60, "legs": 2, "per_leg_limit": 50} } ``` | Field | Meaning | | --- | --- | | `route` | The strategy chosen (or forced). | | `policy` | Routing policy version that made the decision. `"forced"` when `route` was supplied. | | `tokens` | Token count the policy read, post tokenizer policy. | | `executed` | `false` on a deferral: the route needs a vector the request didn't supply. `rows` is empty; embed and re-issue with the route forced. | Routed queries follow the same semantics as their underlying strategy: one consistency cut across all legs and all-or-nothing leg failure. A single [search history](/docs/pro/api/search-history) entry carries the `Auto` expression and the decision. When an inline `Embed` is resolved, its `embedding_tokens` and `embedding_ms` measurements are merged into the normal top-level `performance` object. ### Validation All return `422`: | Condition | Why | | --- | --- | | Forced `"semantic"` or `"fused"` without `vector` | Forcing asserts you have the vector; only auto-routing defers. | | Input yields zero tokens under the policy | Nothing to route. | | `vector` dimensionality mismatch | Same check as a plain vector query. | | `Auto` inside a `queries` array | Inherited from [hybrid text fusion](#validation). | ## Counting matches To count how many rows match a full-text or vector query, use [scan](/docs/pro/api/scans) count mode with the `fts` or `ann` selector. Ranked counts share the single `/scans` endpoint with filter counts — `fts` is exact, `ann` is a radius scan flagged `approximate`, and both honor the `exhaustive` flag and the count deadline. ## Fetch Fetch is a Layer-only endpoint with no upstream equivalent. The document cache is checked first; on miss or error the gateway falls through to the backing store and backfills the cache best-effort. ### Single fetch ```python doc = await client.fetch_document( "products", "asin-B08N5WRWNW", include_attributes=["title", "category"], ) ``` ```go doc, err := client.FetchDocument(ctx, "products", "asin-B08N5WRWNW", &hevlayer.FetchDocumentParams{ IncludeAttributes: []string{"title", "category"}, }) ``` ```typescript const doc = await client.fetchDocument("products", "asin-B08N5WRWNW", { includeAttributes: ["title", "category"], }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/documents/asin-B08N5WRWNW?include_attributes=title,category" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` | Outcome | Status | Header | | --- | --- | --- | | Cached hit | 200 | `x-layer-cache: hit` | | Cache miss, upstream hit, cache backfilled | 200 | `x-layer-cache: miss` | | Cache unavailable, upstream hit | 200 | `x-layer-cache: miss-on-error` | | Missing from both layers | 404 | — | ### Batch fetch ```python batch = await client.fetch_documents("products", { "ids": ["asin-1", "asin-2", "asin-3"], "include_attributes": ["title"], }) ``` ```go batch, err := client.FetchDocuments(ctx, "products", &hevlayer.FetchDocumentsRequest{ Ids: []string{"asin-1", "asin-2", "asin-3"}, IncludeAttributes: []string{"title"}, }) ``` ```typescript const batch = await client.fetchDocuments("products", { ids: ["asin-1", "asin-2", "asin-3"], include_attributes: ["title"], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/documents" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "ids": ["asin-1", "asin-2", "asin-3"], "include_attributes": ["title"] }' ``` ```json { "documents": [ {"id": "asin-1", "attributes": {"title": "..."}}, {"id": "asin-3", "attributes": {"title": "..."}} ], "missing": ["asin-2"] } ``` Batch fetch returns found documents and missing ids inline instead of a partial 404. `documents` preserves request order; ids the gateway could not find anywhere land in `missing`. Because order is preserved, batch fetch is a convenient way to reassemble a [pipeline](/docs/pro/api/pipelines)'s chunks back into their original document — request the chunk ids in sequence and concatenate the results. ### Behavior matrix | Cache state | Single fetch | Batch fetch | | --- | --- | --- | | Hit | cache | cache | | Miss, upstream present | upstream + backfill | upstream + backfill | | Miss, upstream absent | 404 | inline `missing` | | Cache unavailable | upstream, `miss-on-error` | upstream, `miss-on-error` | # Introduction Source: https://hevlayer.com/docs/pro/api/introduction import Edition from "../../../components/docs/Edition.astro"; import StoreMatrixLink from "../../../components/docs/StoreMatrixLink.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; import StoreNote from "../../../components/docs/StoreNote.astro"; import Upstream from "../../../components/docs/Upstream.astro"; import FeatureGate from "../../../components/docs/FeatureGate.astro"; Native requests are wire-compatible with the upstream Turbopuffer endpoints and forwarded as-is after validation. This documentation covers only Layer enhancements. Layer speaks the upstream store's native wire protocol, adding the fields it needs through `x-layer-*` headers, so pointing a client at the gateway just works — and gains stable reads, the document cache, and Layer's enhanced search features without changing the requests you already send. ## Install There are four ways to call Layer: the Python client, the Go client, the TypeScript client, and the REST API itself. The clients are generated from `apps/layer-gateway/openapi.yaml`, so all four expose the same operations — every endpoint page on this site shows them side by side. Anything the clients can do, plain HTTP can do. ```sh pip install hevlayer # Python 3.11+ go get github.com/hev/layer-go # Go 1.22+ npm install hevlayer # Node 18+ ``` Point a client at the gateway: ```python import os from hevlayer import AsyncHevlayer client = AsyncHevlayer( base_url=os.environ["LAYER_GATEWAY_URL"], api_key=os.environ["LAYER_GATEWAY_API_KEY"], ) ``` ```go import ( "os" hevlayer "github.com/hev/layer-go" ) client := hevlayer.NewClient( hevlayer.WithBaseURL(os.Getenv("LAYER_GATEWAY_URL")), hevlayer.WithAPIKey(os.Getenv("LAYER_GATEWAY_API_KEY")), ) ``` ```typescript import { Hevlayer } from "hevlayer"; const client = new Hevlayer({ baseUrl: process.env.LAYER_GATEWAY_URL, apiKey: process.env.LAYER_GATEWAY_API_KEY, }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` Code examples across these pages assume this `client` — and in Go, a `ctx context.Context`. The cURL tab on each page is the bare REST contract; any HTTP stack works the same way. ## Authentication Every request carries `Authorization: Bearer `. The gateway accepts two kinds of bearer: - **The store key.** The default `VectorStore` credential (the turbopuffer key you already own) is accepted as an admin bearer. This is the drop-in default for a turbopuffer-backed store: point an existing client at the gateway and keep your key. No setup, full access. - **A minted key.** Admin can mint keys scoped to a set of namespaces crossed with `read`/`write` — hand one to a team or a service without exposing the rest of the store. Minted keys are gateway-only and never work against the upstream directly. See [API keys](/docs/pro/api/keys). Routes are classified `read`, `write`, or `admin`; each endpoint page notes anything beyond the obvious (GET/query-shaped routes are `read`, namespace writes are `write`, Pipeline/Function/key management is `admin`). A request past a key's scope or namespace grant answers 403 with the reason named. Connection environment variables: | Variable | Purpose | | --- | --- | | `LAYER_GATEWAY_URL` | Base URL of the gateway. | | `LAYER_GATEWAY_API_KEY` | Bearer token sent on every gateway request. In `deriveFromStore` mode this is the default `VectorStore` credential; in `keys` mode it is one of the configured inbound keys. | Additional language targets are added through the SDK harness rather than maintained by hand. ## Gateway failures The Python, Go, and TypeScript SDKs talk to the Layer gateway. If the gateway is unreachable, the original connection error is returned. SDKs do not retry directly against a backing store, because the server chooses that store from the namespace's `VectorStore` and the client surface stays backend-neutral. ## Enhancements to upstream routes Each of the routes below is wire-compatible with turbopuffer. The body of each section describes only what Layer overlays on top. ### Write — `POST /v2/namespaces/{ns}` - Best-effort Aerospike document-cache mirror before explicit-id upstream writes. - Server-stamped `_hevlayer_upserted_at` on every upsert and patch, which powers the consistency watermark on the query path. - `_hevlayer_*` attributes are reserved — writes to them are rejected. Page: [Write](/docs/pro/api/write). ### Query — `POST /v2/namespaces/{ns}/query` - Stable reads via an injected `_hevlayer_upserted_at <= watermark` predicate while the upstream index is `updating`. - One-shot 429 retry with the watermark filter forced on, for queries that race a write storm. - `x-layer-stable-as-of` returned on stable-read responses so callers can correlate freshness across reads. Page: [Query](/docs/pro/api/query). ### Metadata — `GET /v2/namespaces/{ns}/metadata` - Proxied upstream verbatim, then enriched with a `layer` block containing `stable_as_of` and `is_stable`. Page: [Namespace metadata](/docs/pro/api/namespace-metadata). ### Cache warm hint — `GET /v1/namespaces/{ns}/hint_cache_warm` - With no query parameters: a raw upstream passthrough, response returned verbatim. - With any warm option supplied: forwards the hint upstream and runs Layer-side warm steps — a warm job to backfill the Aerospike document cache from origin, plus a mirror of the latest S3 snapshot body into Aerospike. Each step is independently toggleable per request. Page: [Warm cache](/docs/pro/api/warm-cache). ## Cross-cutting conventions These apply to every endpoint Layer proxies, whether the route is upstream-compatible or Layer-only. - **`_hevlayer_*` reserved.** Document attributes prefixed with `_hevlayer_` are reserved for the proxy layer. Writing to them is a validation error; reading them is fine when explicitly requested. The gateway stamps `_hevlayer_upserted_at` itself on every upsert and patch — a caller-supplied value is ignored and overwritten with the server's epoch-ms watermark. - **Hard vs soft failures.** The backing engine's write and query failures are hard failures and return 5xx. Aerospike document-cache failures are soft and never block the response. - **`x-layer-cache` header.** Fetch responses include `hit`, `miss`, or `miss-on-error` so callers can distinguish a cold cache from an outage. - **Response headers.** Query pagination uses `x-layer-next-cursor`. See [Response headers](/docs/pro/api/response-headers). ## Compatibility posture Layer is a drop-in for existing turbopuffer clients. Routes the upstream does not implement are namespaced under `/v2/` and do not shadow upstream behavior; a request to a route Layer doesn't proxy returns 404 rather than being silently re-routed to an upstream that might handle it differently. # Scan Source: https://hevlayer.com/docs/pro/api/scans import PostgresWarning from "../../../components/docs/PostgresWarning.astro"; import Edition from "../../../components/docs/Edition.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; import FeatureGate from "../../../components/docs/FeatureGate.astro"; A scan is on-demand row selection over a namespace. It picks rows by one of four **selectors** and returns their IDs (`mode: ids`, an asynchronous job), their count (`mode: count`, synchronous), or the distinct values of one attribute field (`mode: values`, an asynchronous job): | Input | Field | Meaning | Notes | | --- | --- | --- | --- | | Filter selector | `filters` | An attribute predicate, or all rows when omitted. | Exact | | Full-text selector | `fts` | A BM25 predicate against a text field. | Exact | | Hybrid-text selector | `hybrid_text` | The BM25 leg, the per-token fuzzy legs, and the per-token surfacing legs — a superset of the `hybrid_text` query route (see [Hybrid text count](#hybrid-text-count)). | Exact | | Radius selector | `ann` | Rows within `radius` of a query vector. | Approximate (ANN recall) | | Fan-out control | `threads` | Maximum concurrent upstream requests for origin scatter/gather. | Origin only; defaults from `Index.spec.scan.threads`, then `32` for pinned and ready namespaces or `8` otherwise. | Origin scatter/gather is enabled only for namespaces whose shard backfill is complete. For adopted namespaces initialized through `POST /v2/namespaces/{ns}/init`, scans stay on the single-namespace origin path while `layer.shard_lag_rows` is greater than `0`; this keeps count, ID, and values scans from missing rows that have not yet been stamped with `_hevlayer_shard`. A request carries **at most one** ranked selector (`fts`, `hybrid_text`, or `ann`). `filters` is always optional and, when present alongside a ranked selector, is ANDed onto the match set as an extra constraint. A request with more than one ranked selector is a `422`. At cutover, `mode: ids` is filter-only (ranked IDs are a defined fast-follow), while `mode: count` and `mode: values` support all four selectors. Use scans for bulk exports, manual inspection, UDF discovery debugging, cache/origin consistency checks, exact or approximate counts, and field value discovery. ## Routes | Route | Method | Behavior | | --- | --- | --- | | `POST /v2/namespaces/{ns}/scans` | POST | Create an ID or values scan job, or return a count. | | `GET /v2/namespaces/{ns}/scans` | GET | List scan jobs for the namespace. | | `GET /v2/namespaces/{ns}/scans/{id}` | GET | Read one scan job. | | `GET /v2/namespaces/{ns}/scans/{id}/results` | GET | Read completed scan IDs or values. | | `DELETE /v2/namespaces/{ns}/scans/{id}` | DELETE | Drop the in-memory scan job. | ## ID Mode ```python job = await client.create_scan("products", { "source": "auto", "mode": "ids", "filters": ["category", "Eq", "Electronics"], "threads": 8, "page_size": 1000, }) ``` ```go job, err := client.CreateScan(ctx, "products", &hevlayer.CreateScanRequest{ Source: "auto", Mode: "ids", Filters: []interface{}{"category", "Eq", "Electronics"}, Threads: 8, PageSize: 1000, }) ``` ```typescript const job = await client.createScan("products", { source: "auto", mode: "ids", filters: ["category", "Eq", "Electronics"], threads: 8, page_size: 1000, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/scans" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "source": "auto", "mode": "ids", "filters": ["category", "Eq", "Electronics"], "threads": 8, "page_size": 1000 }' ``` `mode` defaults to `ids`. Valid ID-mode sources are `auto`, `cache`, and `origin`. Every client also ships a helper that creates the job and polls until it finishes (`status` is `completed` or `failed`): `scan(...)` in Python and TypeScript, `Scan` in Go. To wait on a job you already created, use `wait_for_scan` / `waitForScan` / `WaitForScan`. The create response is `202 Accepted`: ```json { "id": "scan-uuid", "namespace": "products", "source": "auto", "effective_source": "origin", "status": "running", "progress": 0, "documents_scanned": 0, "threads": 8, "created_at": "2026-05-26T10:00:00Z" } ``` Read IDs after `status` is `completed`: ```python results = await client.get_scan_results("products", job.id, limit=1000, offset=0) ``` ```go results, err := client.GetScanResults(ctx, "products", scanID, &hevlayer.GetScanResultsParams{Limit: 1000, Offset: 0}) ``` ```typescript const results = await client.getScanResults("products", job.id, { limit: 1000, offset: 0, }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/scans/scan-uuid/results?limit=1000&offset=0" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ```json { "ids": ["doc-1", "doc-2"], "total": 2 } ``` ## Count Mode ```python count = await client.create_scan("products", { "mode": "count", "source": "auto", "filters": ["category", "Eq", "Electronics"], "threads": 8, "timeout_seconds": 30, }) ``` ```go count, err := client.CreateScan(ctx, "products", &hevlayer.CreateScanRequest{ Mode: "count", Source: "auto", Filters: []interface{}{"category", "Eq", "Electronics"}, Threads: 8, TimeoutSeconds: 30, }) ``` ```typescript const count = await client.createScan("products", { mode: "count", source: "auto", filters: ["category", "Eq", "Electronics"], threads: 8, timeout_seconds: 30, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/scans" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "mode": "count", "source": "auto", "filters": ["category", "Eq", "Electronics"], "threads": 8, "timeout_seconds": 30 }' ``` ```json { "count": 4210, "served_by": "snapshot", "snapshot_sha": "3f9e8b21", "watermark_ms": 1747300000123, "elapsed_ms": 3 } ``` When `watermark_ms` is present, the response also includes `x-layer-stable-as-of` with the same epoch-ms value. Count-mode sources are `auto`, `snapshot`, `cache`, and `origin`. Snapshot reads are eligible only for a single leaf `Eq` or `In` filter on a field present in the latest snapshot `fields[]`. `And`, `Or`, `Not`, range operators, fields absent from the snapshot, and skipped fields fall through under `auto` and fail with `412 precondition_failed` under `source: snapshot`. All scan modes accept the same temporal selectors as query: `as_of` conjoins `_hevlayer_upserted_at <= as_of`; `between: [lo, hi]` conjoins `lo < _hevlayer_upserted_at <= hi`. The temporal predicate is ANDed with `filters` and with any ranked selector (`fts`, `hybrid_text`, or `ann`). Snapshot-served scans cannot evaluate temporal windows from a pre-aggregated body, so `source: auto` falls through to cache/origin when a temporal selector is present and `source: snapshot` fails with `412 precondition_failed`. Live count responses include: ```json { "count": 4210, "served_by": "origin", "bounded": false, "timed_out": false, "shards_saturated": 0, "shards_total": 1, "threads": 1, "elapsed_ms": 42 } ``` ## Values Mode A values scan enumerates the distinct values of one attribute `field` over the rows the selector picks, each with its document count. Use it to discover a field's value set — what product categories exist, what tags appear on rows matching a query — instead of confirming values you already know with counts. `field` is required for `mode: values` (and rejected on other modes with `422`). It must name a scalar string or integer attribute, or an array of strings — each array element counts once per containing document. Vector fields are a `422`. ```python job = await client.create_scan("products", { "mode": "values", "field": "category", "source": "auto", "filters": ["in_stock", "Eq", True], }) ``` ```go job, err := client.CreateScan(ctx, "products", &hevlayer.CreateScanRequest{ Mode: "values", Field: "category", Source: "auto", Filters: []interface{}{"in_stock", "Eq", true}, }) ``` ```typescript const job = await client.createScan("products", { mode: "values", field: "category", source: "auto", filters: ["in_stock", "Eq", true], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/scans" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "mode": "values", "field": "category", "source": "auto", "filters": ["in_stock", "Eq", true] }' ``` Like ID mode, the create response is a `202 Accepted` job, and the `scan(...)` SDK helpers poll it to completion: ```json { "id": "scan-uuid", "namespace": "products", "mode": "values", "field": "category", "source": "auto", "effective_source": "origin", "status": "running", "progress": 0, "documents_scanned": 0, "threads": 8, "created_at": "2026-05-26T10:00:00Z" } ``` Read values from the same results route after `status` is `completed`, with the same `limit`/`offset` pagination as scan IDs: ```json { "values": [ {"v": "electronics", "n": 4210}, {"v": "books", "n": 1240} ], "total": 2, "truncated": false } ``` `v`/`n` is the same vocabulary [snapshot](/docs/pro/api/snapshots) facet histograms use: `v` is the value, `n` its document count. Ordering is deterministic — `n` descending, then `v` ascending. Counts are exact for filter-selector scans; on a ranked scan with a saturated shard the job carries `bounded: true` and each `n` is a `>=` lower bound. ### Precomputed serving An unfiltered values scan (no `filters`, no ranked selector) on a field present in the latest snapshot `fields[]` is answered straight from the snapshot's facet histogram: the job completes during the create call — the `202` body already shows `status: completed` — and carries `effective_source: snapshot` with `snapshot_sha` and `watermark_ms`. Fields in `fields_skipped[]` or absent from the snapshot fall through to cache/origin under `auto` and fail with `412 precondition_failed` under explicit `source: snapshot`, as do scans carrying any selector. ### High cardinality Snapshot facet histograms cap each field at 10,000 distinct values and skip fields beyond it; values scans are the enumeration path for exactly those fields. A values job accumulates its histogram in gateway memory and caps the listing at **1,000,000 distinct values**. A scan that crosses the cap completes rather than failing: - The cap applies after the full pass, so every emitted `n` stays exact. - The listing truncates deterministically to the top 1,000,000 values by count (value-ascending tiebreak); the low-count tail is dropped. - The job and its results carry `truncated: true`, meaning the listing is incomplete. `truncated`, `bounded`, and `approximate` are independent flags: `truncated` is a gateway memory bound on the listing, `bounded` is upstream `top_k` saturation on a ranked scan's counts, and `approximate` is ANN recall fuzz on a radius ball's membership. ## Fan-out width Origin scans fan out one upstream request per active shard. `threads` sets the maximum number of those upstream requests a single scan may have in flight at once. It means concurrent requests, not operating-system threads; the gateway is async. Resolution order: 1. `threads` on the scan request. 2. `spec.scan.threads` on the namespace's `Index` resource. 3. The gateway default: `32` for pinned and ready namespaces, `8` otherwise. The effective value is clamped to the active shard count and the server cap (`512` for pinned and ready namespaces, `32` otherwise), then echoed as `threads` on origin responses and completed scan jobs. Snapshot and cache reads do not fan out, so they ignore this field and omit the echo. ## Full-text count Count rows matching a BM25 query with the `fts` selector. Full-text counts are exact and always run origin scatter/gather, so `source` must be omitted, `auto`, or `origin`. A `filters` array, when present, is ANDed on as an extra constraint. ```python count = await client.create_scan("products", { "mode": "count", "fts": {"field": "title", "query": "wireless headphones"}, "filters": ["category", "Eq", "Electronics"], "exhaustive": True, }) ``` ```go count, err := client.CreateScan(ctx, "products", &hevlayer.CreateScanRequest{ Mode: "count", Fts: hevlayer.FtsScan{Field: "title", Query: "wireless headphones"}, Filters: []interface{}{"category", "Eq", "Electronics"}, Exhaustive: true, }) ``` ```typescript const count = await client.createScan("products", { mode: "count", fts: { field: "title", query: "wireless headphones" }, filters: ["category", "Eq", "Electronics"], exhaustive: true, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/scans" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "mode": "count", "fts": {"field": "title", "query": "wireless headphones"}, "filters": ["category", "Eq", "Electronics"], "exhaustive": true }' ``` ## Hybrid text count Count rows in the keyword/fuzzy neighborhood of a `HybridText` query with the `hybrid_text` selector. The scan tokenizes `query` with the HybridText policy, then evaluates the BM25 leg, one fuzzy leg per token, **and** one surfacing leg per token (the RFC 0057 empty-result fallback's legs), and counts the de-duplicated union of returned row ids. This count is a **superset** of the `hybrid_text` query route's deduped rows: the scan always includes the surfacing legs, whereas the query route only adds them when its primary legs (BM25 + fuzzy) return nothing. On a partial-typo query whose primary legs do match, the scan can therefore count more rows than the route returns. Use this selector for a generous live count next to `hybrid_text` or `auto` results that routed to `hybrid_text`; plain `fts` counts exact BM25 only. ```python count = await client.create_scan("products", { "mode": "count", "hybrid_text": {"field": "title", "query": "wireles headphones"}, "filters": ["category", "Eq", "Electronics"], }) ``` ```go count, err := client.CreateScan(ctx, "products", &hevlayer.CreateScanRequest{ Mode: "count", HybridText: hevlayer.HybridTextScan{Field: "title", Query: "wireles headphones"}, Filters: []interface{}{"category", "Eq", "Electronics"}, }) ``` ```typescript const count = await client.createScan("products", { mode: "count", hybrid_text: { field: "title", query: "wireles headphones" }, filters: ["category", "Eq", "Electronics"], }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/scans" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "mode": "count", "hybrid_text": {"field": "title", "query": "wireles headphones"}, "filters": ["category", "Eq", "Electronics"] }' ``` ## Radius count Count rows within `radius` of a query vector with the `ann` selector — a distance-ball scan. `radius` is required and finite (without an upper bound every row is in the ball); `field` defaults to `vector`. Like `fts`, radius counts always run origin scatter/gather. The count is **approximate**: ANN recall means the index's membership of the ball may differ from the true set, independent of saturation, so the response carries `approximate: true`. The radius bound is applied by the gateway to the `$dist` returned by the ranked query. It is not sent upstream as a filter. ```python count = await client.create_scan("products", { "mode": "count", "ann": {"field": "vector", "vector": [0.12, -0.3, 0.88], "radius": 0.25}, }) ``` ```go count, err := client.CreateScan(ctx, "products", &hevlayer.CreateScanRequest{ Mode: "count", Ann: hevlayer.AnnScan{Field: "vector", Vector: []float64{0.12, -0.3, 0.88}, Radius: 0.25}, }) ``` ```typescript const count = await client.createScan("products", { mode: "count", ann: { field: "vector", vector: [0.12, -0.3, 0.88], radius: 0.25 }, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/scans" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "mode": "count", "ann": {"field": "vector", "vector": [0.12, -0.3, 0.88], "radius": 0.25} }' ``` ```json { "count": 980, "served_by": "origin", "approximate": true, "bounded": false, "timed_out": false, "shards_saturated": 0, "shards_total": 1, "threads": 1, "elapsed_ms": 51 } ``` ### Bounding ranked scans Ranked selectors fan out one turbopuffer query per shard, each capped at `top_k = 10_000`. `threads` bounds fan-out width: how many shard requests can run at once. `exhaustive` and `timeout_seconds` bound depth: what happens when a shard hits that cap and how long recursion can run. - `exhaustive: false` (default) — one scatter/gather. A saturated shard contributes its cap as a lower bound; the response carries `bounded: true` with `shards_saturated > 0`. - `exhaustive: true` — for BM25, recurse on each saturated shard via score-band pagination (`$score < last` with an `id` tiebreak) until every page is short or `timeout_seconds` elapses. ANN radius scans do not push `$dist` filters upstream; the gateway counts returned rows whose `$dist <= radius` and marks the shard exhausted when the first over-radius row appears. If the full page is still inside the radius, the shard remains `bounded`. The same `threads` value applies to the initial round and every exhaustive round over the remaining saturated shards. `bounded` and `approximate` are independent. `bounded` means a shard saturated and the count is a `>=` lower bound for the rows the index returned; `approximate` means the distance ball's membership is itself fuzzy. An `ann` count can be `bounded: false` yet still `approximate: true`. ## Sources | Source | ID mode | Count mode | Values mode | | --- | --- | --- | --- | | `auto` | Cache when fresh enough, otherwise origin | Snapshot first, then cache/origin. | Snapshot when eligible, then cache/origin. | | `snapshot` | Not supported | Latest snapshot only; requires eligible `Eq` or `In`. | Latest snapshot facet listing; requires an unfiltered scan on a field in `fields[]`. | | `cache` | Aerospike document cache only | Aerospike document cache only | Aerospike document cache only. | | `origin` | turbopuffer paginated scan | turbopuffer paginated scan | turbopuffer paginated scan with gateway-side dedupe. | This table covers the filter selector. The `fts`, `hybrid_text`, and `ann` selectors have no snapshot or cache evaluator, so they always run origin scatter/gather: omitted, `auto`, and `origin` all resolve to origin, and `snapshot` or `cache` returns `422`. ## Filters Scans accept the same turbopuffer filter array as [query](/docs/pro/api/query). On origin scans, the filter is pushed to turbopuffer. On cache scans, the gateway evaluates it against cached document attributes. Supported cache operators are `Eq`, `NotEq`, `Gt`, `Gte`, `Lt`, `Lte`, `In`, `NotIn`, `And`, `Or`, and `Not`. If `auto` sees a filter the cache cannot evaluate, it uses origin. Explicit `source: cache` with an unsupported filter fails rather than returning partial results. ## Auto-Mode Policy Auto ties cache freshness to the same consistency watermark used by [stable reads](/docs/pro/api/query#stable-reads). The gateway tracks per-namespace `cache_warmed_through`, the watermark observed at the end of the last successful origin warm. | Cache state | Watermark state | Action | | --- | --- | --- | | Empty | any | Run origin and stamp `cache_warmed_through`. | | Populated, `cache_warmed_through >= watermark` | observed | Serve cache. | | Populated, `cache_warmed_through < watermark` | observed | Serve cache and start a background origin warm. | | Populated, no `cache_warmed_through` yet | observed | Serve cache and start a background origin warm. | | Populated | not yet observed | Serve cache. | When cache is used, `_hevlayer_upserted_at <= cache_warmed_through` is added before the user filter so the scan is a stable warmed view. ## Operational notes - ID and values scan state is in-memory and ephemeral; it resets on gateway restart. - Count scans have a deadline, default 30s and maximum 300s. - Values jobs cap at 1,000,000 distinct values per scan and set `truncated: true` when crossed; the listing keeps the top values by count, each with an exact count. - Origin scan fan-out uses the [pinning-aware defaults and caps](#pinning-and-fan-out) unless the request or `Index.spec.scan.threads` sets a different default. - Snapshot-served count scans are exact at the snapshot `watermark_ms`. ## Pinning and fan-out Origin fan-out defaults to `32` requests for namespaces whose latest upstream metadata reports `pinning.ready_replicas > 0`; its maximum is `512`. Other namespaces default to `8` with a maximum of `32`. Request-level `threads` overrides `Index.spec.scan.threads`; both remain bounded by the applicable maximum and active shard count. The gateway observes readiness through metadata reads and background consistency polling. Missing or zero ready replicas, metadata failures, and observations older than two minutes use the unpinned limits. Cold namespaces use those limits until readiness is observed. These controls do not enable pinning. # Response Headers Source: https://hevlayer.com/docs/pro/api/response-headers import Edition from "../../../components/docs/Edition.astro"; Layer keeps turbopuffer-compatible read bodies in the upstream shape and returns Layer-specific metadata in response headers. | Header | Values | Returned by | | --- | --- | --- | | `x-layer-stable-as-of` | Epoch milliseconds | Query, multi-query, scan counts | | `x-layer-next-cursor` | Opaque cursor token | Single-query pagination | | `x-layer-cache` | `hit`, `miss`, `miss-on-error` | Fetch | | `x-layer-warning` | `vector_attribute_dropped` | Query, fetch | | `x-hevlayer-license-grace` | `true` | Licensed gateway routes allowed while the license is in grace | | `traceparent` | W3C trace context | Query, multi-query | SDKs expose these headers as fields where that is more convenient. For example, `query_namespace` returns upstream `rows` and also sets `stable_as_of` / `next_cursor` on the parsed response object when the headers are present. # Query History Source: https://hevlayer.com/docs/pro/api/search-history import CodeTabs from "../../../components/docs/CodeTabs.astro"; Layer logs every query the gateway serves into a durable JSONL trail in S3, mirrored into Layer's hot cache for fast recent reads. Fetch events that downstream consumers tag back to a query land in a sibling clickstream feed. Together they make a search session reconstructable after the fact — for relevance tuning, A/B comparison, or incident review. Both feeds are Layer-only. ## Routes | Route | Behavior | | --- | --- | | `GET /v2/namespaces/{ns}/search-history` | Per-namespace query log, newest first. | | `GET /v2/namespaces/{ns}/clickstream` | Fetch events correlated to a search, newest first. | The `/v1/` versions of both routes are identical aliases held for client compatibility. ## Search history entry ```json { "entries": [ { "timestamp": "2026-05-22T08:00:00.000Z", "timestamp_nanos": 1747900800000000000, "namespace": "products", "trace_id": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "raw_query": "wireless headphones", "stable_as_of": 1747900700000, "query": {"vector": "[…]", "top_k": 10, "filters": "[…]"}, "top_result_ids": ["asin-B08N5WRWNW", "asin-B07PXGQC1Q"], "tags": ["app:hev-shop", "route:search", "surface:storefront"] } ], "next_cursor": "1747900799000000000" } ``` | Field | Meaning | | --- | --- | | `timestamp` / `timestamp_nanos` | Wall-clock and nanosecond timestamps. `timestamp_nanos` is the pagination cursor. | | `trace_id` | Trace context propagated or generated for the query. Joins to the clickstream feed. | | `raw_query` | Caller-supplied query string from the `x-hevlayer-search-query` header (e.g. the BM25 input). Omitted when the header is absent. | | `stable_as_of` | Epoch-ms namespace watermark used by the served response. Omitted on cold-start gateways before the namespace has a watermark. | | `query` | Structured query summary — vector shape, filters, ranking. | | `top_result_ids` | IDs from the served response, in rank order. | | `tags` | Caller-supplied labels propagated through request headers. Used for ad-hoc segmentation. | [Hybrid text](/docs/pro/api/query#hybrid-text-fusion) queries log as a single entry whose `query` carries the `HybridText` expression, not the expanded legs, so re-issuing the logged query reproduces the whole expansion (tokenization, fuzzy legs, fusion) as a unit. [Routed](/docs/pro/api/query#query-routing) queries additionally carry the routing decision (route, policy version, executed), so per-route engagement can be measured against the clickstream and a logged query can be replayed under a forced route. ### Writing metadata Set `x-hevlayer-search-query` on query requests to capture the human input, and set `x-hevlayer-tags` to a comma-separated list of segmentation tags. The Python client exposes these as the `raw_query` and `tags` keyword arguments; the Go client as the `WithSearchQuery` and `WithSearchTags` request options: ```python query = await client.query_namespace( "products", {"vector": embedding, "top_k": 10, "include_attributes": ["title"]}, raw_query="wireless headphones", tags=["app:hev-shop", "surface:storefront", "route:search", "page:first"], ) history = await client.list_search_history( "products", tags=["app:hev-shop", "route:search", "page:first"], limit=20, ) ``` ```go query, err := client.QueryNamespace(ctx, "products", &hevlayer.QueryRequest{Vector: embedding, TopK: 10, IncludeAttributes: []string{"title"}}, hevlayer.WithSearchQuery("wireless headphones"), hevlayer.WithSearchTags([]string{"app:hev-shop", "surface:storefront", "route:search", "page:first"}), ) history, err := client.ListSearchHistory(ctx, "products", &hevlayer.ListSearchHistoryParams{ Tag: []string{"app:hev-shop", "route:search", "page:first"}, Limit: 20, }) ``` ```typescript const query = await client.queryNamespace( "products", { vector: embedding, top_k: 10, include_attributes: ["title"] }, { searchQuery: "wireless headphones", tags: ["app:hev-shop", "surface:storefront", "route:search", "page:first"], }, ); const history = await client.listSearchHistory("products", { tags: ["app:hev-shop", "route:search", "page:first"], limit: 20, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/query" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -H "x-hevlayer-search-query: wireless headphones" \ -H "x-hevlayer-tags: app:hev-shop,surface:storefront,route:search,page:first" \ -d '{"vector": [0.0012, -0.043], "top_k": 10, "include_attributes": ["title"]}' curl "$LAYER_GATEWAY_URL/v2/namespaces/products/search-history?tag=app:hev-shop,route:search,page:first&limit=20" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` Keep the query text in `raw_query`; use tags for segmentation, not for duplicating the query string. ### Tag contract Layer splits `x-hevlayer-tags` and `?tag=` on commas, trims whitespace, drops empty values, then sorts and dedupes tags before storing or matching them. Commas are separators and cannot be escaped. Limits: | Limit | Value | | --- | --- | | Max tags | 32 unique tags per request or filter | | Max tag length | 128 bytes | | Allowed characters | ASCII letters, digits, `:`, `_`, `-`, `.`, `/`, `=`, `+` | The list filter uses AND semantics: `?tag=a,b` returns only entries that carry both `a` and `b`. ### Query parameters | Param | Purpose | | --- | --- | | `tag` | Comma-separated tag filter. AND semantics — every tag must match. | | `from` / `to` | RFC3339 time bounds. | | `before` | Pagination cursor; return entries strictly older than the given `timestamp_nanos`. | | `limit` | Cap 500, default 50. | ## Clickstream entry ```json { "events": [ { "timestamp": "2026-05-22T08:00:02.143Z", "timestamp_nanos": 1747900802143000000, "trace_id": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "namespace": "products", "doc_id": "asin-B08N5WRWNW", "tags": ["session:abc123"], "source": "fetch", "served_from": "cache" } ], "next_cursor": "1747900802142000000" } ``` `trace_id` joins to the search-history entry that produced the result; `served_from` distinguishes a cache hit from an upstream fetch. `trace_id` is also a supported query parameter so you can pull every event for a single search session: ```python events = await client.list_clickstream( "products", trace_id="f81d4fae-7dec-11d0-a765-00a0c91e6bf6", ) ``` ```go events, err := client.ListClickstream(ctx, "products", &hevlayer.ListClickstreamParams{ TraceID: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", }) ``` ```typescript const events = await client.listClickstream("products", { traceId: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/clickstream?trace_id=f81d4fae-7dec-11d0-a765-00a0c91e6bf6" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ## Storage ```text search-history/{namespace}/{YYYY-MM-DD}/{timestamp_nanos}.jsonl ``` Writes are best-effort and never block the query response. Aerospike holds a recent window for fast reads; S3 is the durable store. A cache outage degrades read latency but not durability — list calls walk the S3 prefix and merge inline. # Snapshot History Source: https://hevlayer.com/docs/pro/api/snapshots import Edition from "../../../components/docs/Edition.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; Snapshots are materialized facet histograms for a namespace. They carry facet listings in `values[].v` and facet counts in `values[].n`, stored durably in S3 and mirrored into Aerospike for the latest body. Use `POST /snapshots` to materialize a field now. Use history and body routes to read the durable chronology written by the consistency watcher. ## Snapshot policy Configure automatic snapshot writes with the `Index.spec.snapshot` shape. Kubernetes operators put the shape on the namespace's `Index` CR: ```yaml apiVersion: hevlayer.com/v1 kind: Index metadata: name: products spec: backend: namespace: products snapshot: interval: 5m retention: 30d facetFields: - category - brand ``` | Field | Default | Behavior | | --- | --- | --- | | `facetFields` | `[]` | Facet fields to histogram. Empty or unset disables the automatic snapshot writer for the namespace, so history and activity stay empty. | | `interval` | `5m` | Minimum spacing between automatic snapshot writes. The writer fires on each upstream-stable advance; `interval` only floors how often a write lands. The gateway fallback is `LAYER_SNAPSHOT_MIN_INTERVAL_MS`. | | `retention` | `never` | `never` keeps all history. A duration such as `30d` prunes S3 bodies older than the window, while always keeping the most recent body. | Snapshots are event-driven, not scheduled: an idle namespace does not get a new snapshot just because `interval` elapsed. The gateway refreshes Index policy periodically, so edits take effect without a pod restart. API-only namespaces can set the same shape on the gateway: ```bash curl -X PUT "$LAYER_GATEWAY_URL/v2/namespaces/products/snapshot-policy" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "facetFields": ["category", "brand"], "interval": "5m", "retention": "30d" }' ``` The API policy is stored gateway-side and takes effect immediately for the automatic writer. `GET /v2/namespaces/{ns}/snapshot-policy` returns the API-managed policy for review and automation. Manual `POST /snapshots` jobs with `source: origin` and the automatic writer use the same shard fan-out path. Origin work is bounded by `spec.scan.threads`; stored and cache snapshot reads do not fan out. ## Routes | Route | Method | Behavior | | --- | --- | --- | | `POST /v2/namespaces/{ns}/snapshots` | POST | Create an on-demand snapshot job for one field. | | `GET /v2/namespaces/{ns}/snapshot-policy` | GET | Read the API-managed snapshot policy. | | `PUT /v2/namespaces/{ns}/snapshot-policy` | PUT | Set `facetFields`, `interval`, and `retention` using the `Index.spec.snapshot` shape. | | `GET /v2/namespaces/{ns}/snapshot-jobs` | GET | List in-memory snapshot jobs. | | `GET /v2/namespaces/{ns}/snapshot-jobs/{id}` | GET | Read one snapshot job. | | `GET /v2/namespaces/{ns}/history` | GET | Newest-first durable snapshot history. | | `GET /v2/namespaces/{ns}/snapshots/{sha}` | GET | Full snapshot body by full SHA or 7-char prefix. | | `GET /v2/activity/snapshots` | GET | Cross-namespace snapshot-write activity stream. | Need a named cut for a downstream app? Use [checkpoints](/docs/pro/api/checkpoints) to label the newest durable snapshot watermark without running a scan. ## Manual snapshot ```python job = await client.create_snapshot("products", { "field": "category", "source": "auto", "filters": ["brand", "Eq", "Acme"], "page_size": 1000, }) ``` ```go job, err := client.CreateSnapshot(ctx, "products", &hevlayer.CreateSnapshotRequest{ Field: "category", Source: "auto", Filters: []interface{}{"brand", "Eq", "Acme"}, PageSize: 1000, }) ``` ```typescript const job = await client.createSnapshot("products", { field: "category", source: "auto", filters: ["brand", "Eq", "Acme"], page_size: 1000, }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/snapshots" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "field": "category", "source": "auto", "filters": ["brand", "Eq", "Acme"], "page_size": 1000 }' ``` Valid sources are `auto`, `stored`, `cache`, and `origin`. | Source | Reads from | Notes | | --- | --- | --- | | `auto` | Stored snapshot when possible, otherwise cache/origin policy | Default. Stored snapshots only support unfiltered configured fields. | | `stored` | Latest S3 snapshot body, with Aerospike mirror as a cache | Fastest path for configured facet fields. | | `cache` | Aerospike document cache | Supports filters the cache can evaluate. | | `origin` | turbopuffer paginated scan | Authoritative. Persists the computed snapshot body to S3. | The response is `202 Accepted`: ```json { "id": "snapshot-job-uuid", "namespace": "products", "field": "category", "source": "auto", "status": "running", "progress": 0, "documents_scanned": 0, "created_at": "2026-05-26T10:00:00Z" } ``` Poll the job: ```python job = await client.get_snapshot_job("products", job.id) ``` ```go job, err := client.GetSnapshotJob(ctx, "products", jobID) ``` ```typescript const job = await client.getSnapshotJob("products", jobId); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/snapshot-jobs/snapshot-job-uuid" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` Completed jobs include `sha` when a body was materialized: ```json { "id": "snapshot-job-uuid", "namespace": "products", "field": "category", "source": "origin", "status": "completed", "documents_scanned": 12844, "sha": "3f9e8b21", "stable_as_of": 1747300000123 } ``` ## History ```python history = await client.list_namespace_history("products", limit=20) ``` ```go history, err := client.ListNamespaceHistory(ctx, "products", &hevlayer.ListNamespaceHistoryParams{Limit: 20}) ``` ```typescript const history = await client.listNamespaceHistory("products", { limit: 20 }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/history?limit=20" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ```json [ {"watermark_ms": 1747300000123, "sha": "3f9e8b21...", "tags": ["pre-migration"]}, {"watermark_ms": 1747299600045, "sha": "a1c5b09f...", "tags": []} ] ``` | Query param | Default | Purpose | | --- | --- | --- | | `limit` | 50 | Maximum entries returned. Capped at 500. | | `before` | none | Return entries older than this SHA. 7-char prefixes are accepted. | The history endpoint lists S3 keys only; it does not read every snapshot body. `tags` is metadata for operator grouping and restore workflows; it is not part of the snapshot content hash. ## Snapshot body ```python body = await client.get_namespace_snapshot("products", "3f9e8b2") ``` ```go body, err := client.GetNamespaceSnapshot(ctx, "products", "3f9e8b2") ``` ```typescript const body = await client.getNamespaceSnapshot("products", "3f9e8b2"); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/snapshots/3f9e8b2" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ```json { "namespace": "products", "watermark_ms": 1747300000123, "sha": "3f9e8b21", "row_count": 12500, "fields": [ { "name": "category", "values": [ {"v": "books", "n": 1240}, {"v": "electronics", "n": 873} ] } ], "fields_skipped": [ { "name": "tags", "reason": "exceeded_cap", "distinct_observed": 247000, "cap": 10000 } ] } ``` `fields[].values[].v` is the facet listing. `fields[].values[].n` is the facet count. `row_count` is the number of rows scanned into the snapshot; for vector namespaces, [namespace metadata](/docs/pro/api/namespace-metadata) compares it with the upstream namespace row count to report `indexed` and `index_lag_rows`. Fields present in `fields[]` are complete. Fields above the 10,000 distinct-value cap are listed in `fields_skipped[]` instead of being partially materialized. A skipped field is still enumerable on demand with a [values scan](/docs/pro/api/scans#values-mode), which carries a 1,000,000-value cap instead. ## Activity ```python activity = await client.list_snapshot_activity(since=1747200000000, limit=50) ``` ```go activity, err := client.ListSnapshotActivity(ctx, &hevlayer.ListSnapshotActivityParams{Since: 1747200000000, Limit: 50}) ``` ```typescript const activity = await client.listSnapshotActivity({ since: 1747200000000, limit: 50, }); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/activity/snapshots?since=1747200000000&limit=50" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` | Query param | Required | Purpose | | --- | --- | --- | | `since` | yes | Epoch-ms lower bound on `ts_ms`. | | `limit` | no | Cap 500, default 50. | | `namespace` | no | Exact namespace filter. | | `cursor` | no | Pagination cursor from `next_cursor`. | Activity is snapshot lifecycle only. Search history and clickstream events have separate feeds. # Warehouses Source: https://hevlayer.com/docs/pro/api/warehouses A `Warehouse` is an upstream source connection. The read-only warehouse API requires a Pro gateway connected to Kubernetes. It includes Secret reference names and keys, never Secret contents. All routes require a key with `read` scope. Create and edit connections through the [Warehouse CRD](/docs/pro/kubernetes/warehouse-crd) or the dashboard's apply forms. ## List Warehouses ```sh curl -H "Authorization: Bearer $LAYER_API_KEY" \ "$LAYER_BASE_URL/v2/warehouses" ``` ```json { "warehouses": [ { "name": "prod-snowflake", "kind": "snowflake", "snowflake": { "account": "acme-xy12345", "user": "SVC_LAYER", "role": "SVC_LAYER_ROLE", "warehouse": "EXTRACT_WH", "keyPairSecretRef": { "name": "snowflake-rsa" }, "pool": { "size": 5, "timeout": "30s" } }, "verifyInterval": "1h", "status": { "phase": "Verified", "verifiedAt": "2026-06-10T00:00:00Z", "consumers": { "pipelines": 2, "apiKeys": 1 }, "conditions": [] } } ] } ``` `GET /v2/warehouses/{name}` returns one object in the same shape. `phase` is `Pending`, `Verified`, or `Failed`; failed warehouses include `status.failureReason`. `status.consumers` counts pipelines and API keys that still reference the warehouse. # VectorStores Source: https://hevlayer.com/docs/pro/api/vectorstores import Edition from "../../../components/docs/Edition.astro"; import StoreNote from "../../../components/docs/StoreNote.astro"; A `VectorStore` is the serving connection used to write and query rows. The gateway exposes read-only routes that include Secret reference names and keys, never Secret contents. All routes require a key with `read` scope. Create and edit connections through the [VectorStore CRD](/docs/pro/kubernetes/vectorstore-crd) or the dashboard's apply forms. ## List VectorStores ```sh curl -H "Authorization: Bearer $LAYER_API_KEY" \ "$LAYER_BASE_URL/v2/vectorstores" ``` ```json { "vectorstores": [ { "name": "prod-turbopuffer", "kind": "turbopuffer", "default": true, "endpoint": { "url": "https://aws-us-east-1.turbopuffer.com", "region": "aws-us-east-1" }, "turbopuffer": { "orgId": "org_123" }, "credential": { "secretRef": { "name": "layer-turbopuffer", "key": "turbopuffer-api-key" } }, "inboundAuth": { "mode": "deriveFromStore" }, "status": { "reachable": true, "observedGeneration": 7, "conditions": [] }, "turbopufferUrl": "https://turbopuffer.com/organizations/org_123" } ] } ``` `GET /v2/vectorstores/{name}` returns one object in the same shape. `turbopufferUrl` is omitted when `spec.turbopuffer.orgId` is not set. # Search Source: https://hevlayer.com/docs/pro/api/search import StoreSwitch from "../../../components/docs/StoreSwitch.astro"; import StoreNote from "../../../components/docs/StoreNote.astro"; import StoreMatrixLink from "../../../components/docs/StoreMatrixLink.astro"; import Preview from "../../../components/docs/Preview.astro"; `POST /v2/namespaces/{namespace}/search` takes a query string and returns ranked, scored rows. Text in, rows out — no vector to compute, no legs to assemble, no fusion math to write. [`/query`](/docs/pro/api/query) is unchanged and stays the turbopuffer-shaped wire. `/search` is Layer-native. ## The pipeline Every request walks the same seven stages. Two of them call a model, and both models are yours to choose — see [Models and keys](#models-and-keys). ``` POST /v2/namespaces/{namespace}/search { "query": "...", "top_k": 10 } │ ▼ ┌───────────────────────────┐ │ 1 embed │ ──▶ [ query model ] └───────────────────────────┘ the schema's embed: attribute │ vector ▼ ┌───────────────────────────────────────────────┐ │ 2 expand legs 16-leg budget │ │ ann · bm25 per attribute · fuzzy per token │ └───────────────────────────────────────────────┘ │ ▼ one stable-read cut, filters replicated to every leg ┌───────────────────────────┐ │ 3 scatter │ shard 1 … shard N └───────────────────────────┘ │ ▼ ┌───────────────────────────┐ │ 4 fuse │ reciprocal rank fusion, dedupe by id └───────────────────────────┘ │ ▼ ┌───────────────────────────┐ │ 5 cut to pool │ the L1 stage └───────────────────────────┘ │ pool candidates ▼ ┌───────────────────────────┐ │ 6 rerank optional │ ──▶ [ reranker ] └───────────────────────────┘ one yes/no relevance question per document │ a calibrated probability per row ▼ ┌───────────────────────────┐ │ 7 prune and cut │ threshold, then top_k └───────────────────────────┘ │ ▼ rows[] with score + routing · plan · hybrid · rerank echo ``` Stages 1–5 are the gateway's own work and always run. Stage 6 is the only one that needs a key, and it is the only one you can switch off — with it off, the pipeline ends at stage 5 and `score` is the fusion rank. The namespace must declare an `embed:` attribute and at least one `full_text_search` attribute. ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/papers/search" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{"query": "does vitamin D improve bone density in older adults", "top_k": 10}' ``` ## Models and keys Two stages call a model, and they are configured independently. **The query model** (stage 1) is a property of the namespace, not of the request: it is whatever the schema's `embed:` attribute names, served through that attribute's [serving preference](/docs/pro/api/embed). `/search` does not choose it and cannot override it. A namespace with several `embed:` attributes takes `embed.attribute` to say which one. **The reranker** (stage 6) is configured on the gateway, not per request: one OpenAI-compatible endpoint, one key, and a default model. With no key configured the stage is off — see [Turning it off](#turning-it-off). The default sends the pool to [Jev](https://openrouter.ai/typesafe), TypeSafe's System One model, through OpenRouter — a decision model that answers a yes/no question with a calibrated probability rather than prose, which is exactly the shape stage 6 wants. Nothing about the stage is specific to it. The gateway owns the reranking: it builds the shortlist, writes the relevance question, batches the documents, reads the probabilities back, and prunes. The endpoint is a transport. So one OpenRouter key reaches every model OpenRouter serves, and the gateway's endpoint can point at anything else that speaks the same wire — a self-hosted endpoint, another aggregator, a provider's own API. ### Choosing a model per request `rerank.model` overrides the gateway's default model for one request. The key and the base URL are not overridable: a request cannot make the gateway spend a credential on an endpoint the operator did not configure. ```json { "query": "...", "rerank": { "model": "typesafe/jev-1.13" } } ``` The response echoes the model that actually answered under `rerank.model`, which is not always the slug you asked for — an alias like `typesafe/jev-latest` resolves to a version. A model that cannot return a usable probability is a runtime failure, not a validation error: the request [degrades](#degrade) and says so. ### Turning it off Three ways, in increasing scope: | Scope | How | Result | | --- | --- | --- | | One request | `"rerank": false` | Stage skipped. `200`, fused order. | | The whole gateway | configure no reranker key | Every request behaves as though it sent `"rerank": false`. | | Never quietly | `"rerank": { "required": true }` | A request that cannot rerank fails loudly instead. | With the stage off, the response is still `200` and still complete: rows in fused order, `rerank.executed: false` with a `reason`, and `score` carrying the fusion rank instead of a probability. A gateway with no key answers every request this way and needs no configuration at all. It is off, not hidden. An unconfigured gateway sets `x-layer-warning: rerank_unconfigured` on every `/search` response, so a caller that expected probabilities finds out on the first response rather than from the scores. A caller that will not accept fused-only results sends `rerank.required: true` and gets `503 rerank_unavailable`. ## Request Only `query` is required. Unknown fields are rejected with `422`. ```json { "query": "does vitamin D improve bone density in older adults", "top_k": 10, "filters": ["year", "Gte", 2015], "include_attributes": ["title", "text", "year"], "pool": 50, "embed": { "attribute": "text" }, "text": { "fuzziness": "auto", "stopwords": "en" }, "rerank": { "model": "typesafe/jev-latest", "threshold": 0.0, "attributes": ["title", "text"], "docs_per_call": 30, "max_chars": 2000, "question": "generic-1", "required": false }, "explain": false } ``` | Field | Default | Meaning | | --- | --- | --- | | `query` | required | The search text. Embedded for the ANN leg, ranked as-is by the BM25 legs, tokenized for the fuzzy legs. | | `top_k` | `10` | Rows returned. `1..100`, and at most `pool`. | | `filters` | none | Filter expression in the [query](/docs/pro/api/query) grammar. A hard filter, replicated to every leg. See [Filtering](#filtering). | | `include_attributes` | `true` | `true`, `false`, or a list of attribute names to return under each row's `attributes`. Reserved `_hevlayer_*` attributes are returned only when named; vector columns are never returned. | | `pool` | `50` | Candidates handed to the reranker after the L1 cut. `50..200`. Also sets per-leg depth: `clamp(5 × pool, 50, 200)`. | | `embed.attribute` | the only one | Which `embed:` attribute embeds `query`. Required when the schema declares several. | | `text.fuzziness` | `"auto"` | `"auto"` or `0..2`, as in [`HybridText`](/docs/pro/api/query#hybrid-text-fusion). | | `text.stopwords` | `"en"` | `"en"`, `false`, or a list. Suppresses fuzzy legs for stop words; BM25 legs are unaffected. | | `rerank` | on when a key is set | `false` disables the stage. Otherwise an object; every key is optional. | | `rerank.model` | the gateway default | Model slug for this request. | | `rerank.threshold` | `0.0` | Drop rows whose probability is below this, before `top_k`. `0.1` is the recommended prune: on BEIR shortlists rows under `0.1` were judged relevant about 0.5% of the time. | | `rerank.attributes` | every full-text attribute | Attributes whose text the reranker reads. An attribute named `title` goes first, then schema order. `_hevlayer_*` names are rejected. | | `rerank.docs_per_call` | `30` | Documents per reranker call, `1..50`. Calls run concurrently. | | `rerank.max_chars` | `2000` | Per-document character budget for reranker text, `1..20000`. | | `rerank.question` | `"generic-1"` | Named question version. `generic-1` is the only one. | | `rerank.required` | `false` | `true` turns an unconfigured or failing reranker into `503` instead of a degrade. | | `explain` | `false` | `true` adds the L1 feature vector to every row. | There is no pagination: a reranked page does not compose with a fused cursor. Ask for a larger `top_k`, up to `pool`. ### Filtering `filters` takes the same expression grammar as [`/query`](/docs/pro/api/query) — no subset, no separate dialect. What matters is *where* it applies. The filter is replicated to every leg and pushed into the store, at stage 2, before anything is fused or reranked: ``` filters: ["tenant", "Eq", "acme"] │ ├──▶ ann leg WHERE tenant = 'acme' ├──▶ bm25:title WHERE tenant = 'acme' ├──▶ bm25:text WHERE tenant = 'acme' └──▶ fuzzy:text:… WHERE tenant = 'acme' └─▶ fuse ─▶ pool ─▶ rerank ``` So it is a hard pre-filter, not a post-filter on the returned rows. Two consequences worth relying on: - **`pool` is spent entirely on matching rows.** A filter that selects 1% of the namespace still hands the reranker a full `pool` of candidates from that 1%, rather than a pool drawn from everything and then cut down to a handful. - **It is a tenancy boundary, not a display preference.** A row excluded by `filters` is never embedded into a leg result, never fused, never sent to the reranker, and so its text never leaves the environment. ```json { "query": "annual report", "filters": ["And", [["tenant", "Eq", "acme"], ["year", "Gte", 2015]]], "top_k": 10 } ``` The filter expression is passed to the store as-is; the gateway does not parse it. A malformed or unsupported expression therefore surfaces as the store's own error rather than a gateway `422 validation_error`. ## Response ```json { "rows": [ { "id": "PMC5461234", "score": 0.93, "attributes": { "title": "...", "text": "...", "year": 2019 } } ], "routing": { "route": "fused", "policy": "v1", "tokens": 10, "executed": true, "advisory": true }, "plan": { "executed": false, "reason": "unconfigured" }, "hybrid": { "tokens": ["vitamin", "improve", "bone", "density", "older", "adults"], "tokens_dropped": 0, "stopwords": "en", "stopwords_dropped": ["does", "in"], "fuzziness": "auto", "rank_constant": 60, "per_leg_limit": 200, "legs": [ { "label": "ann", "kind": "ann", "attribute": "text", "rows": 200 }, { "label": "bm25:text", "kind": "bm25", "attribute": "text", "rows": 143 }, { "label": "bm25:title", "kind": "bm25", "attribute": "title", "rows": 61 }, { "label": "fuzzy:text:vitamin", "kind": "fuzzy", "attribute": "text", "rows": 88 } ], "dropped_legs": 0, "surfaced": false }, "rerank": { "model": "typesafe/jev-1.13", "question": "generic-1", "executed": true, "pool": 50, "calls": 2, "docs_per_call": 30, "threshold": 0.0, "pruned": 0, "input_tokens": 41200, "latency_ms": 231 }, "performance": { "embedding_tokens": 17, "embedding_ms": 4, "legs_ms": 88, "fuse_ms": 1, "l1_ms": 0, "rerank_ms": 231, "total_ms": 340 } } ``` Every response carries the four echo blocks: `routing`, `plan`, `hybrid`, `rerank`. | Field | Meaning | | --- | --- | | `rows[].score` | The reranker's probability in `[0, 1]` when `rerank.executed` is `true`. It is absolute: comparable across rows, legs, shards and requests, so you can threshold on it. When the stage did not execute, `score` is the fusion sum and is only an ordering. The two are never mixed in one response. | | `rows[].attributes` | The attributes `include_attributes` asked for. Text the gateway fetched only for the reranker is stripped. | | `routing` | The [query router](/docs/pro/api/query#query-routing)'s decision for this input. `advisory: true`: `/search` runs every leg regardless, and reports the route for the UI and the history. | | `plan` | The planner stage. Not configured in this release: always `{"executed": false, "reason": "unconfigured"}`. | | `hybrid.legs` | One entry per leg that ran, in fusion order: `label`, `kind` (`ann`, `bm25`, `fuzzy`), the `attribute` it ran over, and the `rows` it returned after the shard merge. | | `hybrid.dropped_legs` | Legs the 16-leg budget, or the store, did not run. | | `hybrid.surfaced` | `true` when every text leg returned nothing and the fuzzy legs were re-run ordered by edit distance, as in the [`HybridText` fallback](/docs/pro/api/query#surfacing-fallback). | | `hybrid.threads` | Shard fan-out width. Present on sharded namespaces only. | | `hybrid.fuzziness_clamped` | Present and `true` only when a store forced the effective `fuzziness` to `0`. | | `rerank.model` | The model that answered, as the endpoint reports it. Absent when the stage did not execute. | | `rerank.executed` | `false` with a `reason` when the stage was off (`disabled`, `unconfigured`), had nothing to score (`empty_pool`), or the call failed (`provider_error`, `timeout`, `rate_limited`). | | `rerank.pool` | Candidates scored. | | `rerank.calls` | Reranker calls made. | | `rerank.pruned` | Rows dropped by `threshold`. | | `rerank.input_tokens` | Input tokens across all calls, as the endpoint reports them. | | `performance` | Milliseconds per stage, plus the embed wire's token count. | The response also carries `traceparent` and, when a stable-read cut applied, [`x-layer-stable-as-of`](/docs/pro/api/response-headers). ### Leg budget A request runs at most 16 legs. The budget is spent in this order: 1. The ANN leg. 2. One BM25 leg per full-text attribute, over the whole `query`, in schema order. 3. Fuzzy legs from the [`HybridText` tokenizer policy](/docs/pro/api/query#tokenization), one per token, round-robin across attributes, until the budget is spent. A namespace with many full-text attributes spends its budget on BM25 breadth rather than fuzzy depth. Whatever did not fit is counted in `hybrid.dropped_legs`. ### Explain With `explain: true` each row gains an `explain` object: the feature vector the L1 stage saw and each term's contribution to the L1 score. ```json { "id": "PMC5461234", "score": 0.93, "attributes": { "title": "..." }, "explain": { "features": { "rrf_sum": 0.0481, "age_seconds": 86400 }, "contributions": { "rrf_sum": 0.0481, "age_seconds": 0.0 }, "l1_score": 0.0481, "legs": [ { "label": "ann", "rank": 3, "score": 0.18 }, { "label": "bm25:text", "rank": 1, "score": 14.2 } ] } } ``` The L1 stage in this release is the identity: it keeps fusion order and cuts to `pool`, so every contribution other than `rrf_sum` is `0`. `age_seconds` is present when the row carries its write stamp; `fetch_count_30d` is present when the gateway keeps a fetch counter for the namespace. An absent feature is absent, not `0`. ## Degrade If the reranker errors, times out, or keeps answering `429`, the response is still `200`: rows in fused order, `score` as the fusion sum, `rerank.executed: false` with a `reason`, and the header `x-layer-warning: rerank_degraded`. Set `rerank.required: true` to get `503 rerank_unavailable` instead. Degrade is the same shape as running with no key at all, which is the point: a client written against the fused response works in both, and the warning header is the only thing it has to read to tell them apart. ## Errors | Status | `error` | When | | --- | --- | --- | | `422` | `embed_attribute_missing` | The schema declares no `embed:` attribute. | | `422` | `embed_attribute_invalid` | `embed.attribute` names an attribute without `embed:`, or the schema declares several and none is named. | | `422` | `full_text_attribute_missing` | The schema has no `full_text_search` attribute. | | `422` | `UnsupportedByStore` | The store cannot serve an ANN or a BM25 leg. See [Stores](#stores). | | `422` | `validation_error` | `top_k > pool`, `pool` out of range, unknown question, unknown field, a query that yields no tokens. | | `503` | `rerank_unavailable` | `rerank.required` is `true` and the stage is unconfigured or the call failed. | ## Stores `/search` executes on turbopuffer, where reranker text is returned by the store and billed as returned bytes. A store that cannot serve an ANN or a BM25 leg answers `422 UnsupportedByStore`. ## Data leaves the environment Candidate text is sent to the reranker endpoint, and `query` is sent to the embedding provider when the `embed:` attribute serves natively on turbopuffer rather than locally. Configuring no reranker key, or sending `rerank: false`, removes the first entirely. Reserved `_hevlayer_*` attributes are never a text leg and never reranker input. A reranker endpoint inside your own network keeps candidate text there. ## History Each request writes one [search history](/docs/pro/api/search-history) entry with `raw_query` taken from the body, so no `x-hevlayer-search-query` header is needed. # Warm cache Source: https://hevlayer.com/docs/pro/api/warm-cache import Edition from "../../../components/docs/Edition.astro"; import Upstream from "../../../components/docs/Upstream.astro"; import Callout from "../../../components/docs/Callout.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; Cache-warm hints are wire-compatible with the upstream `GET /v1/namespaces/{ns}/hint_cache_warm` endpoint and forwarded as-is after validation. This documentation covers only Layer enhancements. Layer exposes two warm endpoints. `hint_cache_warm` is the turbopuffer-compatible hint; `warm` is the Layer-only shortcut that creates a gateway warm job. ## Hint-cache warm With no query parameters, the call is a raw passthrough: the gateway forwards it to turbopuffer unchanged and returns the upstream response verbatim. Existing turbopuffer clients keep their exact wire behavior. ```bash curl "$LAYER_GATEWAY_URL/v1/namespaces/products/hint_cache_warm" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` Supplying any warm option (`turbopuffer`, `documents`, `snapshots`, `blobs`, `blob_budget_bytes`, `page_size`) switches the call into Layer orchestration. Steps then default on for turbopuffer, documents, and snapshots; blobs default off: | Step | What it does | | --- | --- | | `turbopuffer=true` | Forwards the warm hint upstream. | | `documents=true` | Starts an origin warm job to backfill the document cache. | | `snapshots=true` | Mirrors the latest S3 snapshot body into the cache. | | `blobs=true` | Hydrates declared blob references from S3 into Aerospike within `blob_budget_bytes`. | ```python result = await client.hint_cache_warm( "products", turbopuffer=False, documents=False, snapshots=True, ) ``` ```typescript const result = await client.hintCacheWarm("products", { turbopuffer: false, documents: false, snapshots: true, }); ``` ```bash curl "$LAYER_GATEWAY_URL/v1/namespaces/products/hint_cache_warm?turbopuffer=false&documents=false&snapshots=true" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` The generated Go client omits `false` query parameters, so it cannot turn steps off — disable steps over REST (or the Python client) instead. The orchestrated response reports per-step status: ```json { "namespace": "products", "turbopuffer": { "enabled": true, "status": "completed" }, "documents": { "enabled": true, "status": "started", "job": { "id": "warm-job-uuid", "status": "running" } }, "snapshots": { "enabled": true, "status": "completed", "key": "snapshots/products/...", "watermark_ms": 1715600400000, "sha": "..." } } ``` If `documents` is enabled, the response includes a warm job; poll it through `/warm-jobs/{id}`. ### Blob warming Set `blobs=true` and supply a positive `blob_budget_bytes`. The Index must declare `spec.blobs.referenceAttributes` (for example, `[image_blob]`); see [Blobs](/docs/pro/api/blobs#warm-policy). A missing or zero budget, a budget without `blobs=true`, or an empty reference-attribute declaration is a validation error. ```python result = await client.hint_cache_warm( "products", turbopuffer=False, documents=False, snapshots=False, blobs=True, blob_budget_bytes=104857600, ) ``` ```typescript const result = await client.hintCacheWarm("products", { turbopuffer: false, documents: false, snapshots: false, blobs: true, blobBudgetBytes: 104857600, }); ``` ```bash curl "$LAYER_GATEWAY_URL/v1/namespaces/products/hint_cache_warm?turbopuffer=false&documents=false&snapshots=false&blobs=true&blob_budget_bytes=104857600" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` These examples warm only blobs. Go can enable blob warming with `HintCacheWarmParams{Blobs: true, BlobBudgetBytes: 104857600}`, but its omitted `false` values leave the other three steps enabled. Blob warming finishes within the request. It scans origin rows, deduplicates same-namespace references, and stops before caching an object that would exceed the byte budget. Concurrent S3 reads can fetch beyond that cutoff, so the budget limits cache writes rather than network transfer. Missing objects and invalid references are skipped and counted. The response's `blobs` block reports `attributes`, `budget_bytes`, `documents_scanned`, `refs_seen`, `objects`, `bytes`, `missing`, `invalid_refs`, and `budget_exhausted`. Its status is `completed` even when the budget stops the scan; inspect `budget_exhausted` to distinguish that result. Unlike document warming, blob warming does not return a job to poll. ## Layer warm `POST /v2/namespaces/{ns}/warm` creates an asynchronous job that pages through turbopuffer, backfills Aerospike, and refreshes `cache_warmed_through`. Use it when bootstrapping a namespace whose data was written outside the gateway. ```python job = await client.warm_cache("products", page_size=1000) ``` ```go job, err := client.WarmCache(ctx, "products", &hevlayer.WarmCacheParams{ PageSize: 1000, }) ``` ```typescript const job = await client.warmCache("products", { pageSize: 1000 }); ``` ```bash curl -X POST "$LAYER_GATEWAY_URL/v2/namespaces/products/warm?page_size=1000" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` The response is `202 Accepted` with the warm job: ```json { "id": "warm-job-uuid", "namespace": "products", "status": "running", "progress": 0, "documents_scanned": 0, "created_at": "2026-05-26T10:00:00Z" } ``` Poll it through: ```python job = await client.get_warm_job("products", job.id) ``` ```go job, err := client.GetWarmJob(ctx, "products", jobID) ``` ```typescript const job = await client.getWarmJob("products", jobId); ``` ```bash curl "$LAYER_GATEWAY_URL/v2/namespaces/products/warm-jobs/warm-job-uuid" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" ``` ## Cache-cold behavior Warm jobs, cache scans, cache snapshot jobs, and pipeline chunk reads return 503 `cache_cold` when the document cache is unavailable. Fetch and fetch-many fall through to turbopuffer with `x-layer-cache: miss-on-error` instead. The split is deliberate. Fetch is correctness-first: a cache outage must not turn into a missing document. Warm is throughput-first: warming on a cold cache would be wasted work, so the gateway reports the cold state to the caller rather than silently no-op-ing. A bare `hint_cache_warm` passthrough never touches the gateway cache, so it succeeds even while the cache is cold. The orchestrated form returns 503 `cache_cold` when `documents`, `snapshots`, or `blobs` is requested. For how the cache recovers from an outage and the signals to watch, see the [failure-mode runbook](/docs/pro/failure-modes#read). # Write & Stage Source: https://hevlayer.com/docs/pro/api/write import PostgresWarning from "../../../components/docs/PostgresWarning.astro"; import Edition from "../../../components/docs/Edition.astro"; import StoreMatrixLink from "../../../components/docs/StoreMatrixLink.astro"; import StoreNote from "../../../components/docs/StoreNote.astro"; import Upstream from "../../../components/docs/Upstream.astro"; import FeatureGate from "../../../components/docs/FeatureGate.astro"; import CodeTabs from "../../../components/docs/CodeTabs.astro"; Writes are wire-compatible with the upstream `POST /v2/namespaces/{ns}` endpoint and forwarded as-is after validation. This documentation covers only Layer enhancements. Layer stamps every row-producing write with `_hevlayer_upserted_at` for supported stores. The stamp is what holds the [read watermark](/docs/pro/api/query); the full set of reserved attributes Layer manages on a row lives in the [document model](/docs/pro/document-model). ## Status Layer validates the body before forwarding and can fail independently of the backing store, so the write path carries a few statuses a plain proxy wouldn't: - **200 OK** — applied to the store and stamped. - **422 Unprocessable Entity** — Layer rejected the body before forwarding: no recognized native write operation, a reserved `_hevlayer_*` attribute name, a removed custom-write key, or a schema type the configured store cannot represent. The body is a Layer error (`{ "error": "validation_error", … }` or `{ "error": "UnsupportedByStore", … }`), not a store one. - **Upstream passthrough** — any non-2xx the backing store returns is relayed verbatim. - **502 Bad Gateway** — Layer could not reach the backing store (`{ "error": "upstream_error", … }`); the write did not apply. The passthrough case includes a failed conditional write (`upsert_condition`, `patch_condition`, `delete_condition`) — turbopuffer's error body comes back untouched. ## Stage Stage caches a document before it's upserted into your vector store. That O(1) read/write is especially useful for queuing chunks in a [two-stage pipeline](/docs/pro/api/pipelines), where a CPU worker stages chunks and a GPU worker reads them back to write vectors. Staged documents are ephemeral until they're upserted, though — a Layer document cache outage loses anything still staged. ```python await client.put_pipeline_document_chunks("product-images", "asin-B08N5WRWNW", { "chunks": [ {"id": "asin-B08N5WRWNW-0", "text": "Wireless noise-cancelling headphones"}, {"id": "asin-B08N5WRWNW-1", "text": "40-hour battery life", "metadata": {"page": 2}}, ], }) ``` ```go client.PutPipelineDocumentChunks(ctx, "product-images", "asin-B08N5WRWNW", &hevlayer.PutChunksRequest{ Chunks: []hevlayer.Chunk{ {ID: "asin-B08N5WRWNW-0", Text: "Wireless noise-cancelling headphones"}, {ID: "asin-B08N5WRWNW-1", Text: "40-hour battery life", Metadata: map[string]interface{}{"page": 2}}, }, }) ``` ```typescript await client.putPipelineDocumentChunks("product-images", "asin-B08N5WRWNW", { chunks: [ { id: "asin-B08N5WRWNW-0", text: "Wireless noise-cancelling headphones" }, { id: "asin-B08N5WRWNW-1", text: "40-hour battery life", metadata: { page: 2 } }, ], }); ``` ```bash curl -X PUT "$LAYER_GATEWAY_URL/v2/pipelines/product-images/documents/asin-B08N5WRWNW" \ -H "Authorization: Bearer $LAYER_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "chunks": [ {"id": "asin-B08N5WRWNW-0", "text": "Wireless noise-cancelling headphones"}, {"id": "asin-B08N5WRWNW-1", "text": "40-hour battery life", "metadata": {"page": 2}} ] }' ``` Staging stores chunks in the Aerospike document cache and marks the document `pending`. Re-staging the same document ID replaces the chunks and resets state to `pending`. The full pipeline API is documented under [Pipelines](/docs/pro/api/pipelines). # Agent CRD Source: https://hevlayer.com/docs/pro/kubernetes/agent-crd import FeatureGate from "../../../components/docs/FeatureGate.astro"; import Callout from "../../../components/docs/Callout.astro"; import Preview from "../../../components/docs/Preview.astro"; An `Agent` is a saved agentic-search configuration as a resource. It binds an inference model, a turn budget, and a set of [indices](/docs/pro/kubernetes/index-crd) to a name, so a caller searches with [`POST /v2/agents/{name}/query`](/docs/pro/api/agents) and sends only a query string. Everything that decides what a call costs and what it can read lives on the resource, not in the request. An agent adds no retrieval primitive. Its only tool is the [federated query](/docs/pro/api/federated-query); it sits one level above the [`Auto`](/docs/pro/api/query#query-routing) router, using a model to reformulate the query, fan out for recall, and score the candidates for relevance. What it returns is the same row shape as every other search endpoint — a better-ranked result set, not a generated answer. Like the other CRDs here, an Agent has two authoring surfaces that round-trip through one schema: `kubectl get agent -o yaml` and `client.agent("support-search").apply()` are two spellings of the same object. ```yaml apiVersion: hevlayer.com/v1alpha1 kind: Agent metadata: name: support-search namespace: layer spec: model: provider: openrouter name: anthropic/claude-haiku-4-5 fallback: anthropic/claude-sonnet-4-6 # optional; used on primary timeout/error apiKeySecretRef: name: openrouter key: credential budget: deadlineMs: 60000 onDeadline: bestEffort indices: [docs, tickets] retrieval: fanout: 8 recallDepth: 50 rankBy: auto relevanceWeight: 0.6 output: provenance: false trace: false status: phase: Ready conditions: - type: SecretResolved status: "True" - type: ModelReachable status: "True" - type: IndicesResolved status: "True" ``` ## Model | Field | Purpose | | --- | --- | | `provider` | Inference backend. `openrouter`. | | `name` | Model id passed to the provider, e.g. `anthropic/claude-haiku-4-5`. | | `fallback` | Optional model used when the primary times out or errors. | | `apiKeySecretRef` | Secret holding the provider credential (`name`, `key`). The token is never inline on the resource — the same rule the [ApiKey](/docs/pro/kubernetes/apikey-crd) and [VectorStore](/docs/pro/kubernetes/vectorstore-crd) CRDs follow. | The gateway's in-memory agent spec also accepts a raw inline `model.apiKey` token. This exists only as a local dev-seed escape hatch for running an agent without provisioning a Secret. It is deliberately absent from the `Agent` CRD — the operator rejects anything but `apiKeySecretRef`, and RFC 0074 bans a raw token on the resource. Do not use it in any deployed configuration. ## Budget | Field | Purpose | | --- | --- | | `deadlineMs` | Wall-clock deadline for the whole request. | | `onDeadline` | `bestEffort` (default) returns the best ranking the agent has when the deadline hits; `error` fails the request instead. | ## Indices `indices` is the set of namespaces the agent searches, passed to the [federated query](/docs/pro/api/federated-query) as its `namespaces`. The operator checks that the list is present and every entry is a non-empty string, surfaced as the `IndicesResolved` condition; it does not currently confirm each entry names a namespace that exists. The agent reads each listed namespace under the caller's credential, so a caller only reaches the namespaces its own key grants. ## Retrieval All retrieval behavior is expressed against the [federated query](/docs/pro/api/federated-query) — nothing new reaches the upstream. | Field | Default | Purpose | | --- | --- | --- | | `fanout` | `8` | Query reformulations the agent issues, run in parallel via layer's [scatter/gather](/docs/pro/concepts#scattergather) and merged for recall. Higher fan-out trades latency for recall. | | `recallDepth` | `50` | Candidates gathered for ranking before `top_k`, at least `top_k`. Bounds how much the model reads. | | `rankBy` | `auto` | Default route per leg: `auto`, `hybridText`, or `semantic`. A `semantic` leg needs a query vector, which the caller supplies on the request (`vector`) — layer never embeds query text; see [Agentic search](/docs/pro/api/agents#bring-your-own-embedding). Without a supplied vector, semantic legs fall back to the lexical route. | | `relevanceWeight` | `0.6` | Weight of the relevance score against the recall score in the final ranking. | ## Output | Field | Purpose | | --- | --- | | `provenance` | When true, each row carries a `$agent` field with its `retrievalScore` and `relevanceScore`, and the response gains a top-level `agent` echo. | | `trace` | When true, the `agent` echo also carries the full reasoning trace. | Default off, the response is byte-for-byte the [federated query](/docs/pro/api/federated-query#response) shape: a client cannot tell a reasoning loop produced it. See [Agentic search](/docs/pro/api/agents) for the request and response contract. ## Auth Auth follows the same model as the other API endpoints; multi-namespace queries follow [federated query](/docs/pro/api/federated-query#entitlements) auth behavior. Who may invoke an agent is an `agent.` entitlement on the [ApiKey](/docs/pro/kubernetes/apikey-crd#entitlements). ## Status `status` carries health and validation only; latency, turn counts, and spend go to metrics and history, never into etcd. | Condition | Meaning | | --- | --- | | `SecretResolved` | `model.apiKeySecretRef` exists and is readable. | | `ModelReachable` | the provider answered with the bound credential. | | `IndicesResolved` | `spec.indices` is non-empty and every entry is a non-empty string. (It does not yet verify each entry is a known namespace.) | | Phase | Meaning | | --- | --- | | `Ready` | Resolvable and callable. | | `Degraded` | Reachable but a condition is failing — calls may fall back or error. | | `Invalid` | A required field or reference does not resolve; calls are refused. | `kubectl get agent` print columns: `MODEL`, `INDICES`, `PHASE`. Edits are picked up shortly after they apply: the gateway resolves agents — spec, provider credential, and per-index schema — into memory and refreshes on a periodic tick, so a `kubectl apply` lands within the refresh interval rather than instantly. ## Naming Agent names are cluster-unique at the gateway because callers address agents by name only. If two namespaces define the same Agent name, the gateway sorts by agent name and namespace, keeps the lexicographically later namespace, and logs a warning naming both namespaces. Keep Agent names unique across the cluster. ## Observability Deadline-hit rate, provider latency, and token usage per agent export as `hevlayer_*` metrics. Token counts come back on the inference response, so they cost no extra call; dollar cost is derived from them downstream rather than fetched in the request path. The reasoning trace is written to the [search-history](/docs/pro/api/search-history) record alongside the query it belongs to, so agentic and plain searches share one history surface for evaluation. # ApiKey CRD Source: https://hevlayer.com/docs/pro/kubernetes/apikey-crd An `ApiKey` is a minted credential as a resource. Layer owns the credential lifecycle — mint, verify, revoke, expire — and what the key opens is declared per resource: each entitlement names a [`VectorStore`](/docs/pro/kubernetes/vectorstore-crd), a [`Warehouse`](/docs/pro/kubernetes/warehouse-crd), an [`Agent`](/docs/pro/kubernetes/agent-crd), or Layer itself, and carries the scopes and claims for that target. Claims are opaque to Layer — an external system can use Layer as its key store and keep authorization decisions to itself. Keys have two authoring surfaces that round-trip through one schema: `kubectl get apikey -o yaml` and `GET /v2/keys/{keyId}` are two spellings of the same object. ```yaml apiVersion: hevlayer.com/v1alpha1 kind: ApiKey metadata: name: cohort-reader namespace: layer spec: owner: acme description: cohort read access entitlements: vectorstore.prod-turbopuffer: scopes: [read] namespaces: ["cohort-*"] warehouse.prod-snowflake: claims: - "notes:cohort:*:read" expiresAfter: 365d status: keyId: 0a1b2c3d-… phase: Active lookupHash: sha256:… createdAt: "2026-06-10T00:00:00Z" expiresAt: "2027-06-10T00:00:00Z" secretRef: name: apikey-cohort-reader ``` ## Spec | Field | Purpose | | --- | --- | | `owner` | Optional free-form owner label, echoed in list and authenticate responses. | | `description` | Optional free-form description. | | `entitlements` | Map keyed by target resource. Each entry carries `scopes`, `namespaces`, and `claims` for that target. | | `expiresAfter` | Duration or `never`. Defaults to `365d`; `status.expiresAt` is computed at mint. | ## Entitlements | Key | Target | | --- | --- | | `vectorstore.` | Data-plane access through the named store. `scopes` (`read`, `write`) gate routes whose `Index` resolves to that store; `namespaces` globs constrain which upstream namespaces. | | `warehouse.` | A list of opaque `claims` strings bound to the source system. Layer stores and echoes them; the application routes on them. No client route reaches a source — clients touch indexes, not warehouses — so the entitlement grants nothing in Layer and inerts when the warehouse is deleted. | | `agent.` | Invocation of the named [`Agent`](/docs/pro/kubernetes/agent-crd): the right to call `POST /v2/agents//query`. Data access is separate — the agent's reads run under the caller's own `vectorstore` grants — so this governs *who may invoke*, not *what it reads*. Inerts when the agent is deleted. | | `layer` | The control plane itself. `scopes: [admin]` covers key management and Pipeline/Function create/delete/control routes, and satisfies `read` and `write` everywhere. | Scope meanings match [inbound auth](/docs/pro/kubernetes/vectorstore-crd#inbound-auth): `read` covers query, fetch, scans, and metrics; `write` covers namespace writes and worker routes. `claims` is a list of opaque strings, allowed on any entitlement and the only field on a warehouse entitlement. Layer stores them, returns them from list, get, and authenticate, and never interprets them — an existing permission grammar (`service:resource_type:resource_id:action` strings, a legacy entitlement vocabulary) drops in verbatim, and the consuming application maps them to its own authorization. An entitlement whose target does not exist grants nothing and surfaces as a status condition (`EntitlementTargetMissing`) — not an admission error, so keys and their targets can be applied in either order. Check the condition after applying: a typo in a target name looks the same as a missing target. A key whose entitlements carry only claims — no scopes — is a pure external-store key: it authenticates, but opens no Layer route. ## Minting **REST.** `POST /v2/keys` generates the token, creates the `ApiKey` resource, and returns the token in the response — once. The raw token is never persisted; Layer stores only one-way hashes on the resource. ```http POST /v2/keys # 201 { keyId, …, token } — token returned once GET /v2/keys # metadata only; ?includeRevoked GET /v2/keys/{keyId} POST /v2/keys/{keyId}/revoke # idempotent DELETE /v2/keys/{keyId} # hard delete; Revoked keys only POST /v2/keys/authenticate # body { token } → 200 { keyId, entitlements, … } | 401 ``` Key-management routes require a key with the `layer` entitlement at `admin` scope. `POST /v2/keys/authenticate` is unauthenticated by construction — the token is the credential. **CRD.** Apply an `ApiKey` with no credential. The operator mints the token, writes it to a Secret named in `status.secretRef` (key `token`), and moves `phase` from `Pending` to `Active`. The Secret is the token delivery; it is owned by the `ApiKey` and garbage-collected with it. Rotate by minting a replacement, deploying it, and revoking the old key. ## Verification External systems present the raw token to `POST /v2/keys/authenticate` and get back `keyId` (a stable actor id) plus the full `entitlements` map, then make their own authorization decisions from the claims. The gateway also accepts any `Active` key's token as a bearer on its own routes, enforcing the entitlement for the store or control-plane surface the route resolves to. Verification is one indexed lookup plus one hash check against a watch-fed in-memory map — the hot path never reads the control plane per request. `status.lastSeenAt` advances at most once per five minutes per key. | Phase | Meaning | | --- | --- | | `Pending` | CRD-authored key awaiting mint. | | `Active` | Verifiable; token works. | | `Revoked` | `POST /v2/keys/{keyId}/revoke` was called; token refused. | | `Expired` | `status.expiresAt` passed; token refused. | Revoke is the default lifecycle end-state. Revoked `ApiKey` resources are retained indefinitely for audit and are not automatically garbage-collected. Operators should set a retention policy appropriate to their obligations. Hard delete is rare and deliberate: `DELETE /v2/keys/{keyId}` accepts only a `Revoked` key and permanently removes the resource, its lifecycle record, and any owned token Secret. Other phases return `409 Conflict`; revoke first, then delete only after the retention period has passed or policy requires the record itself to be forgotten. Deleting a `VectorStore` or `Warehouse` inerts every entitlement that names it: the keys stay `Active` for their other entitlements, and the deletion is finalizer-guarded on the target's side while keys still reference it. ## Backup and migration Use a full namespace Velero backup, or an equivalent etcd snapshot, for portable `ApiKey` migration. Do not export and apply YAML: the verifier lives in `status`, and apply paths do not preserve that subresource. 1. Back up these Layer namespace objects: - `ApiKey` resources with `status`: `status.keyId`, `phase`, `lookupHash`, and `tokenHash` are the credential record; the raw token is not recoverable. - The chart's `*-keys` Secret: it holds `LAYER_KEY_PEPPER`, which must match every restored verifier. - Token-delivery Secrets referenced by CRD-authored keys through `status.secretRef`. 2. Restore `ApiKey` status explicitly. Velero restores specs by default and drops `status` unless the restore uses `--status-include-resources apikeys.hevlayer.com`, or the `Restore` sets `spec.restoreStatus.includedResources: ["apikeys.hevlayer.com"]`. 3. Restore the namespace, including the pepper Secret, before running Helm on the target release. If Helm touches an empty namespace first, it can generate a new random pepper, making restored argon2id verifiers unusable. 4. If source and target Velero servers share object storage, wait until the target server lists the completed source backup before creating the restore; otherwise its local `Backup` object may not have synced. 5. Refresh source Velero discovery before backup. Install Layer CRDs before Velero discovers resources, or restart the source Velero deployment after CRD installation and wait for readiness; stale discovery can produce a `Completed` backup that omits `ApiKey`. 6. Quiesce the Layer operator before backup and keep it quiesced through initial restore. Velero restores `ApiKey` spec and `status` separately; an operator that starts in that window can mark a transient spec-only key `MintBlocked` or `Pending`. 7. Inspect the completed backup from inside the Velero server's cluster. Its item list must include `apikeys.hevlayer.com`, expected `ApiKey` objects, the chart's `*-keys` pepper Secret, and token-delivery Secrets referenced by `status.secretRef`. 8. Restart gateway/operator discovery after restore so the watch-fed key map rebuilds from restored `ApiKey` status and Secrets before traffic depends on the migrated tokens. 9. Treat `MintBlocked` as a failed restore, not a key rotation. The operator refuses to mint a replacement when `status.keyId` is empty but the deterministic delivery Secret exists; it writes a `MintBlocked` condition and warning Event instead. A new CRD-authored `ApiKey` with no delivery Secret still mints normally. Validate the key store before accepting traffic: ```sh SOURCE_CONTEXT=layer-a \ TARGET_CONTEXT=layer-b \ LAYER_NAMESPACE=layer \ SOURCE_BASE_URL=https://source.example.com \ TARGET_BASE_URL=https://target.example.com \ SOURCE_ADMIN_KEY=hvl_... \ scripts/apikey-velero-migration.sh ``` The script mints REST and CRD-authored keys, backs up the namespace, waits for the target Velero server to sync the completed backup, restores with `--status-include-resources apikeys.hevlayer.com`, and asserts: - original active tokens still authenticate - revoked and expired tokens remain refused - the completed backup contains expected `ApiKey` resources and Secrets - the source operator was quiesced and the expired control key reached `Expired` before backup - the restored pepper Secret matches the source - restored key status fields are present, so spec-only, incomplete, racing, or misordered restores fail loudly Local reproduction currently needs the temporary test-license setup from the `/v2/keys` test `kid` keygen work in PR #199. Velero backups are credential-bearing: they contain one-way verifiers, the pepper, and any remaining CRD-authored delivery Secrets. Store and encrypt them like other credential material. ## Kubernetes RBAC CRD authoring makes kubectl a minting surface, so the chart ships roles to delegate key administration without cluster-admin: | ClusterRole | Grants | | --- | --- | | `hevlayer-key-admin` | Full verbs on `apikeys`, plus `get` on delivered token Secrets. Can mint, revoke, and collect tokens. | | `hevlayer-key-viewer` | `get`/`list`/`watch` on `apikeys`. No Secret access — status hashes are one-way, so viewing is audit, not credential access. | Neither role aggregates into the built-in `view`/`edit`/`admin` ClusterRoles: namespace viewer never silently means key viewer. Bindings are the cluster operator's explicit act; set `rbac.keyRoleBindings` in Helm values to render them for the single-team case. ## Bootstrapping `LAYER_GATEWAY_API_KEY` is the bootstrap credential: it mints the first admin key — ```yaml spec: entitlements: layer: scopes: [admin] ``` — after which routine minting uses minted admin keys. Cluster operators can equally bootstrap by applying an `ApiKey` resource, since CRD authoring needs only kubectl access. # Function CRD Source: https://hevlayer.com/docs/pro/kubernetes/function-crd import CodeTabs from "../../../components/docs/CodeTabs.astro"; import FeatureGate from "../../../components/docs/FeatureGate.astro"; The `Function` CRD is a User Defined Function (UDF) that runs over rows that already exist in an [Index](/docs/pro/kubernetes/index-crd). It is the right shape for classifiers, enrichment, backfills, fan-out from an existing row, and deterministic re-upserts. UDFs are best defined in YAML and invoked by the [layer CLI](/docs/pro/cli#run-a-function). The operator creates worker resources; the gateway owns discovery, queueing, retries, leases, and completion markers. Workers own their data writes. Use a [Pipeline](/docs/pro/kubernetes/pipeline-crd) when external data becomes rows in Layer. Use a Function when compute starts from rows that are already in Layer. ```yaml apiVersion: hevlayer.com/v1alpha1 kind: Function metadata: name: tag-products namespace: layer spec: targetNamespaces: - products inputs: - id - title version: v1 filter: - category - Eq - outdoor worker: image: .dkr.ecr.us-east-1.amazonaws.com/hev-tag-products:latest dispatch: pull computeClass: cpu batchSize: 32 timeoutSeconds: 30 schedule: discoveryIntervalSeconds: 300 leaseSeconds: 120 maxInFlightBatches: 8 maxConcurrentScans: 1 retry: maxAttempts: 8 initialBackoffSeconds: 5 maxBackoffSeconds: 300 triggers: - discovery scaling: pool: cpu mode: autoscale replicas: min: 0 max: 6 ``` ## Selection Use `targetNamespaces` for explicit namespaces. Use `indexSelector` when labels on `Index` resources should choose the namespaces. `filter` preserves arbitrary JSON, including array-form turbopuffer filters. The operator stores the shape as-is; the gateway evaluates it during discovery after AND-ing it with the generated completion-marker predicate. Do not include a version-marker predicate in `filter`; the gateway creates that from `spec.version`. ## Worker | Field | Purpose | | --- | --- | | `image` | Worker image. | | `dispatch` | `pull` for SDK claim/poll workers, `push` for HTTP `/run` workers. | | `computeClass` | `cpu` or `gpu`. Defaults to `cpu`; when `scaling.pool` is omitted, the operator maps this to the stock `cpu` or `gpu` pool. | | `port` | Push-dispatch service port. | | `batchSize` | Rows per batch. | | `timeoutSeconds` | Worker call timeout. | | `podSpec` | Optional pod-level merge patch. | To apply the CR, register the gateway UDF, trigger discovery, and watch the queue with one command, use [`layer run -f`](/docs/pro/cli#run-a-function). The worker pod receives `HEVLAYER_UDF_ID`, `HEVLAYER_BASE_URL`, `HEVLAYER_UDF_BATCH_SIZE`, `HEVLAYER_UDF_TIMEOUT_SECONDS`, `HEVLAYER_UDF_LEASE_SECONDS`, and `LAYER_GATEWAY_API_KEY`. The gateway bearer is sourced from the default `VectorStore` credential in `deriveFromStore` mode, or from the configured inbound worker key in `keys` mode. ## Simple classifier The Python client turns a normal function into the claim/process/complete loop. `output="tags"` is client-side metadata: the CRD does not declare an output attribute. `run_udf_worker` sends the returned value as a completion `attributes.tags` patch, and the gateway stamps the reserved completion marker in the same patch. The Go client drives the same worker protocol directly, as does the TypeScript client — claim a batch, process rows, report completions and failures. ```python import asyncio from hevlayer.udf import PermanentError, TransientError, run_udf_worker, udf @udf(inputs=["id", "title", "description"], output="tags", kind="tags") def tag_product(*, id: str, title: str | None, description: str | None) -> list[str]: if not title: raise PermanentError(f"{id}: missing title") try: text = f"{title} {description or ''}".lower() except TypeError as exc: raise TransientError(str(exc)) from exc tags: list[str] = [] if "wireless" in text: tags.append("wireless") if "waterproof" in text: tags.append("waterproof") return tags or ["uncategorized"] if __name__ == "__main__": asyncio.run(run_udf_worker(tag_product, udf_id="product-tags")) ``` ```go package main import ( "context" "os" "strings" hevlayer "github.com/hev/layer-go" ) func tags(title, description string) []string { text := strings.ToLower(title + " " + description) var out []string if strings.Contains(text, "wireless") { out = append(out, "wireless") } if strings.Contains(text, "waterproof") { out = append(out, "waterproof") } if len(out) == 0 { out = []string{"uncategorized"} } return out } func main() { ctx := context.Background() udfID := os.Getenv("HEVLAYER_UDF_ID") layer := hevlayer.NewClient( hevlayer.WithBaseURL(os.Getenv("HEVLAYER_BASE_URL")), hevlayer.WithAPIKey(os.Getenv("LAYER_GATEWAY_API_KEY")), ) for { claimed, err := layer.ClaimUdfItems(ctx, udfID, &hevlayer.UdfClaimRequest{ WorkerID: "tag-products-0", Limit: 32, }) if err != nil { continue } var done []hevlayer.UdfCompleteItem var failed []hevlayer.UdfFailItem for _, item := range claimed.Items { title, _ := item.Input["title"].(string) description, _ := item.Input["description"].(string) if title == "" { failed = append(failed, hevlayer.UdfFailItem{ Namespace: item.Namespace, ID: item.ID, Kind: "permanent", Message: "missing title", }) continue } done = append(done, hevlayer.UdfCompleteItem{ Namespace: item.Namespace, ID: item.ID, Attributes: map[string]interface{}{"tags": tags(title, description)}, }) } if len(done) > 0 { layer.CompleteUdfItems(ctx, udfID, &hevlayer.UdfCompleteRequest{ WorkerID: "tag-products-0", Items: done, }) } if len(failed) > 0 { layer.FailUdfItems(ctx, udfID, &hevlayer.UdfFailRequest{ WorkerID: "tag-products-0", Items: failed, }) } } } ``` ```typescript import { Hevlayer } from "hevlayer"; function tags(title: string, description: string): string[] { const text = `${title} ${description}`.toLowerCase(); const out: string[] = []; if (text.includes("wireless")) out.push("wireless"); if (text.includes("waterproof")) out.push("waterproof"); return out.length ? out : ["uncategorized"]; } const udfId = process.env.HEVLAYER_UDF_ID!; const layer = new Hevlayer({ baseUrl: process.env.HEVLAYER_BASE_URL, apiKey: process.env.LAYER_GATEWAY_API_KEY, }); while (true) { const claimed = await layer.claimUdfItems(udfId, { worker_id: "tag-products-0", limit: 32, }); const done = []; const failed = []; for (const item of claimed.items) { const title = typeof item.input.title === "string" ? item.input.title : ""; const description = typeof item.input.description === "string" ? item.input.description : ""; if (!title) { failed.push({ namespace: item.namespace, id: item.id, kind: "permanent", message: "missing title", }); continue; } done.push({ namespace: item.namespace, id: item.id, attributes: { tags: tags(title, description) }, }); } if (done.length > 0) { await layer.completeUdfItems(udfId, { worker_id: "tag-products-0", items: done }); } if (failed.length > 0) { await layer.failUdfItems(udfId, { worker_id: "tag-products-0", items: failed }); } } ``` In Python, function parameters are keyword-only and named to match `inputs`; raise `TransientError` for retryable work and `PermanentError` for unrecoverable input. In Go and TypeScript, report the same split through `FailUdfItems` / `failUdfItems` with `kind: "transient"` or `kind: "permanent"`. ## GPU classifier More complicated classifiers (e.g. a vision-language classifier) may require a model to run on a GPU. ```yaml apiVersion: hevlayer.com/v1alpha1 kind: Function metadata: name: product-color namespace: layer spec: targetNamespaces: - amazon-products inputs: - id - image_url version: v1 worker: image: .dkr.ecr.us-east-1.amazonaws.com/hev-shop-udf-product-color:latest dispatch: pull computeClass: gpu batchSize: 8 timeoutSeconds: 120 schedule: leaseSeconds: 300 maxInFlightBatches: 2 triggers: - discovery scaling: pool: gpu mode: autoscale replicas: min: 0 max: 2 ``` `worker.computeClass: gpu` defaults omitted `scaling.pool` to the [built-in `gpu` pool](/docs/pro/kubernetes/scaling-crd). The stock pool selects `layer.hev.dev/node-role=worker-gpu`, requests one NVIDIA GPU, and carries the worker and NVIDIA tolerations: ```yaml computePools: - name: gpu kind: gpu maxReplicasPerWorkload: 4 nodeSelector: layer.hev.dev/node-role: worker-gpu layer.hev.dev/compute: gpu tolerations: - key: layer.hev.dev/node-role operator: Equal value: worker-gpu effect: NoSchedule - key: nvidia.com/gpu operator: Exists effect: NoSchedule resources: requests: { memory: 4Gi, nvidia.com/gpu: "1" } limits: { memory: 10Gi, nvidia.com/gpu: "1" } ``` The worker loads the model once at startup and classifies per row. CLIP zero-shot classification labels each product image with its dominant color: ```python import asyncio import io import httpx import torch from PIL import Image from transformers import pipeline from hevlayer.udf import PermanentError, TransientError, run_udf_worker, udf COLORS = ["black", "white", "gray", "red", "blue", "green", "brown", "multicolor"] classifier = pipeline( "zero-shot-image-classification", model="openai/clip-vit-large-patch14", device="cuda" if torch.cuda.is_available() else "cpu", ) @udf(inputs=["id", "image_url"], output="color", kind="classification") def classify_color(*, id: str, image_url: str | None) -> str: if not image_url: raise PermanentError(f"{id}: missing image_url") try: resp = httpx.get(image_url, timeout=10.0, follow_redirects=True) resp.raise_for_status() image = Image.open(io.BytesIO(resp.content)).convert("RGB") except httpx.HTTPError as exc: raise TransientError(f"{id}: image fetch failed: {exc}") from exc except OSError as exc: raise PermanentError(f"{id}: undecodable image: {exc}") from exc scores = classifier(image, candidate_labels=COLORS) return scores[0]["label"] if __name__ == "__main__": asyncio.run(run_udf_worker(classify_color, udf_id="product-color")) ``` The worker image needs `torch`, `transformers`, `pillow`, and `httpx` alongside the `hevlayer` Python client. Bake the model weights into the image so autoscaled pods do not re-download them on every cold start. Sizing for inference: keep `worker.batchSize` low and `worker.timeoutSeconds` high enough for one batch of forward passes, and make `schedule.leaseSeconds` outlast a full batch so claims do not reissue mid-inference. `replicas.min: 1` keeps a warm worker when model cold-start dominates; `min: 0` scales to zero between sweeps. ## Scaling `spec.scaling` is the same scaling config [Pipelines use](/docs/pro/kubernetes/pipeline-crd#scaling): a pool from the built-in set or `InfraRules/default`, a mode, and replica bounds. For Functions, `mode: autoscale` emits a KEDA `ScaledObject` triggered by `layer_udf_queue_depth`. Replica maxima above the pool's `maxReplicasPerWorkload` are rejected in status. For GPU Functions on a scale-to-zero pool, set `spec.scaling.warmWindowSeconds` to hold the worker — and its node — warm for a cooldown after the queue drains, so adjacent batches skip the cold start (fresh node, image pull, model load) before the pool returns to zero. See [Workload scaling](/docs/pro/kubernetes/scaling-crd#warm-window). ## Writeback Workers own data writes. The common single-attribute case uses the Python client's sugar: `@udf(output="tags")` makes `run_udf_worker` send returned values as `attributes.tags` in the completion call — in Go (or over REST) the same thing is `attributes` on each completion item. The gateway applies those attributes and the reserved completion marker in one `patch_columns` write. Completion attributes must not use the reserved `_hevlayer_*` prefix. Embedding Functions can include `vector` on each completion item. The Python helper emits `vector` for `@udf(kind="embedding")` return values. The gateway fetches the existing row, merges returned attributes and reserved markers, then re-upserts the full row with the replacement vector. Python workers that need more control can declare the `tpuf` parameter, write through the client, and return `None`; completion then stamps only the marker. Use deterministic IDs when a Function creates rows so at-least-once retries remain idempotent. Deleting a Function garbage-collects operator-managed Kubernetes resources. It does not delete already-written attributes. ## Lifecycle ```sh kubectl get function product-tags kubectl describe function product-tags layer udf get product-tags kubectl patch function product-tags --type=merge -p '{"spec":{"paused":true}}' kubectl patch function product-tags --type=merge -p '{"spec":{"paused":false}}' curl -X POST -H "authorization: Bearer $LAYER_GATEWAY_API_KEY" \ $LAYER_GATEWAY_URL/v2/udfs/product-tags/reset-failed kubectl delete function product-tags ``` Registration in the gateway's UDF registry happens at reconciliation, not at first discovery run — a Function created with `spec.paused: true` (or paused later) is registered immediately with `paused: true`, so it is observable from creation onward: When the Function spec changes, reconciliation upserts the registered UDF definition in place. Pending, processing, failed, and indexed queue state remain attached to the same UDF id. ``` GET /v2/udfs → 200 {"udfs": [{"id": "product-tags", "paused": true, ...}]} GET /v2/udfs/product-tags/status → 200 {"udf_id": "product-tags", "paused": true, ...} ``` A `404` from `/v2/udfs/{id}/status` means the Function was never registered — a real failure, not an intentional pause. `paused` on the `Udf` and `UdfStatus` resources is the single source of truth for "is this installed and paused" versus "does this exist at all." ## Version markers `spec.version` is the re-run safety rail and defaults to `v1`. On completion, the gateway stamps `_hevlayer_udf__v` with that version, normalizing hyphens in the Function name to underscores. For `metadata.name: product-color`, the marker is `_hevlayer_udf_product_color_v`. Discovery automatically looks for rows whose marker is missing, differs from `spec.version`, or has an expired `_hevlayer_udf__stale_after` marker. Bump `spec.version` when a model, taxonomy, or prompt changes. ## Tuning knobs | Knob | What it bounds | | --- | --- | | `worker.batchSize` | Rows per worker batch. | | `worker.timeoutSeconds` | Worker call timeout. | | `schedule.leaseSeconds` | How long a claim is held before reissue. | | `schedule.discoveryIntervalSeconds` | Time between discovery scan jobs. | | `schedule.maxInFlightBatches` | Concurrent worker batches per UDF. | | `schedule.maxConcurrentScans` | Concurrent namespace discovery jobs. | | `retry.maxAttempts` | Tries before a row lands in `failed`. | # Index CRD Source: https://hevlayer.com/docs/pro/kubernetes/index-crd import FeatureGate from "../../../components/docs/FeatureGate.astro"; An `Index` represents one namespace exposed through the gateway. It declares which upstream namespace to use, snapshot policy, cache posture, and consistency mode. The backend connection itself lives in a [VectorStore](/docs/pro/kubernetes/vectorstore-crd). ```yaml apiVersion: hevlayer.com/v1 kind: Index metadata: name: products namespace: layer spec: backend: storeRef: turbopuffer-default namespace: products distanceMetric: cosine_distance embedding: model: voyage-3-large@v1 outputDim: 1024 normalization: l2 metadata: labels: app: shop tags: - catalog snapshot: interval: 5m retention: never facetFields: - category - brand search: fullText: true scan: threads: 8 cache: ttl: 24h capGiB: 64 mode: standard consistency: strong ``` ## Backend | Field | Purpose | | --- | --- | | `backend.storeRef` | Optional `VectorStore` name in the same namespace. The gateway routes requests for this upstream namespace to that store. Defaults to the namespace's default store. | | `backend.namespace` | Optional upstream namespace override. Defaults to the Index name. | | `backend.distanceMetric` | Vector metric, default `cosine_distance`. | For `kind: search` stores, the operator accepts only the metrics the backend serves directly today: L2-style metrics for single-vector namespaces and `cosine_distance` for multivector namespaces. Unsupported values put the Index in `Ready=False` with reason `MetricMismatch`. ## Embedding `spec.embedding` declares the embedding identity of this namespace's vectors. It is optional for a single-namespace query, where distances are only ever compared within the namespace. It is **required** to include a namespace in a [federated vector query](/docs/pro/api/federated-query#vector-merge-requires-a-matching-embedding-space): the gateway merges those by distance, which is only meaningful when every namespace in the set shares one embedding space. | Field | Purpose | | --- | --- | | `embedding.model` | Model identity and version, e.g. `voyage-3-large@v1`. Treated as an opaque token compared for equality across a namespace set. | | `embedding.outputDim` | Vector dimensionality. Part of the identity because a model truncated to a smaller dimension (Matryoshka) is not comparable to its full-width output. Cross-checked against the namespace schema. | | `embedding.normalization` | Vector normalization, e.g. `l2` or `none`. | Together with `backend.distanceMetric`, these form the embedding profile the gateway compares across a fan-out. Two namespaces are distance-comparable only when all four match; otherwise a fused vector query over them falls back to rank-interleave (or is rejected under `strict`). `spec.embedding` declares an already-computed embedding's identity for comparison purposes; it does not compute anything. To have the gateway compute vectors for you, declare `embed:` on a schema attribute instead — see below. ## Schema-attribute embedding A schema attribute can declare `embed:` so its source value is embedded on write. This is Turbopuffer's native-embeddings wire (`embed` on a schema attribute, private beta at [turbopuffer.com/docs/embedding](https://turbopuffer.com/docs/embedding)). With native serving on a Turbopuffer store, Layer validates and transparently forwards the wire to Turbopuffer's managed embedding service. Autoscaler serving uses that same service through the gateway, then writes only concrete derived vectors to the active store. ```jsonc // simple form — tpuf-compatible "schema": { "text": { "type": "string", "embed": "voyage/voyage-4-lite" } } // extended form "schema": { "text": { "type": "string", "embed": { "model": "Snowflake/snowflake-arctic-embed-m-v1.5", "revision": "refs/pr/5", "dims": 768, "attribute": "text_vector", "instructions": { "document": "Represent this passage for retrieval: ", "query": "Represent this query for retrieving passages: " }, "chunk": { "strategy": "recursive", "unit": "characters", "size": 1200, "overlap": 120 }, "serving": { "prefer": "autoscaler" } } } } ``` | Field | tpuf-compatible | Purpose | | --- | --- | --- | | `embed` (string) | ✅ | Simple form. A provider-namespaced model id such as `voyage/voyage-4-lite`. | | `embed.model` | ✅ | Extended form's provider-namespaced model id. | | `embed.dims` | ✅ | Output dimensionality via Matryoshka truncation. | | `embed.attribute` | ✅ | Override the derived vector attribute name. Omitting it derives `embed_`. | | `embed.serving.prefer` | Layer extension | `native`, `autoscaler`, or `local` (`lattice` is an alias for local Lattice serving). Defaults to `native`. Layer consumes this field before forwarding the native wire. | | `embed.revision` | Layer extension | Pin a Hugging Face model revision. It participates in profile identity and cache keys. | | `embed.instructions` | Layer extension | Optional `document` and `query` prefixes for asymmetric embedding models. | | `embed.modality` | Layer extension | `text` (default) or `image`. Image values are URLs or base64 strings for a CLIP-family checkpoint; query-time `Embed` still uses its text tower. | | `embed.chunk` | Layer extension | Split or fan out the source before embedding. See [Chunking](#chunking). | Layer extensions require `prefer: autoscaler`, with one exception: a CLIP-family `modality: image` profile may use `prefer: local` without the revision, instruction, or chunking extensions (see [local CLIP](/docs/pro/api/embed#images)). Native and local serving otherwise reject extensions with `422`. A missing production embedding provider returns `503 service_unavailable`. The first row write that establishes an embedded schema must include `distance_metric`. Omitting it returns `422`. The default derived vector column is **`embed_`** — for example, `embed_title` for source attribute `title`. The source attribute is stored alongside the vector. Model ids must be provider-namespaced. Native mode uses Turbopuffer's stock model menu. Autoscaler mode accepts any Hugging Face repo id the configured provider can serve, including finetuned and mixed-case checkpoints. Provider load or model-support failures are returned as upstream embedding errors. ### Chunking For scalar text, `embed.chunk` reuses the Pipeline chunk shape: `strategy` is `none`, `fixed`, `recursive`, `sentence`, or `markdown`; `unit` is `characters` or `tokens`; and `size`, `overlap`, and `tokenizer` control the window. A split document remains as its original row, while each embedded chunk is written as `{id}#{i}` with `_hevlayer_parent_id` and `_hevlayer_chunk_index`. Structured fields use a two-level section composition: ```jsonc "schema": { "text": { "type": "string", "embed": { "model": "BAAI/bge-m3", "chunk": { "strategy": "section", "sectionSource": "jsonFields", "fields": ["boxed_warning", "drug_interactions"], "sectionAttribute": "section", "split": { "strategy": "recursive", "unit": "characters", "size": 1200, "overlap": 120 } }, "serving": { "prefer": "autoscaler" } }} } ``` Each configured non-empty string field on the document row fans out into the embedded attribute first; optional `split` then windows that section. Rows use ids `{id}#{section}#{i}`, retain the document attributes, and add the configured section attribute plus the standard parent/index attributes. Chunked writes require string document ids and `upsert_rows`; columnar writes return `422`. ### Serving mode Per model, `embed.serving.prefer` chooses how vectors are computed. | `prefer` | Behavior | | --- | --- | | `native` (default) | On Turbopuffer, forward the compatible wire to its managed service. | | `autoscaler` | Resolve through the configured inference provider and send only concrete vectors to the active store. Use this for BYO checkpoints and Layer extensions. | | `local` | Resolve in the gateway process with its configured Lattice or CLIP artifact and send only concrete vectors to the active store. | | `lattice` | Alias for `local` with the `erikkaum/lattice-retrieval` model. | Layer does not switch modes after a provider failure. For Lattice, generate a deployment artifact with the upstream slicer, mount `model.safetensors` beside its `tokenizer.json`, and set `LAYER_LATTICE_MODEL_PATH` to the model file. The requested dimensions must match the artifact. The recommended int4-row, 512-dimensional artifact quantizes model weights; Layer stores its normalized output vectors as f32. For a CLIP-family model, set `LAYER_LOCAL_CLIP_MODEL_PATH` to the checkpoint directory — provisioning and the image-input contract are covered in [local CLIP](/docs/pro/api/embed#images). Layer durably records gateway-served attribute profiles in S3, so later writes do not need to repeat `schema`. Query vectors use a short in-memory TTL cache. When changing an embedded source attribute, upsert the full row; patching that attribute returns `422` because Layer cannot safely recompute a vector from a partial row. ## Snapshot policy | Field | Default | Purpose | | --- | --- | --- | | `snapshot.facetFields` | `[]` | Fields the gateway materializes into durable facet snapshots. Empty disables the automatic writer. | | `snapshot.interval` | `5m` | Minimum spacing between automatic snapshot writes after upstream-stable advances. | | `snapshot.retention` | `never` | `never` keeps all snapshot bodies; a duration such as `30d` prunes older bodies while keeping the latest. | ## Search backend policy `spec.search` applies when the Index targets a `kind: search` VectorStore. The operator uses it to drive the backend's explicit index lifecycle. | Field | Default | Purpose | | --- | --- | --- | | `search.fullText` | `false` | Build the backend's BM25 index for the namespace's `text` column. Enable this for lexical, FTS, or hybrid-text namespaces. | ## Scan policy `scan.threads` sets the per-namespace default for origin scan fan-out: the maximum concurrent upstream requests one scan may issue during scatter/gather. It defaults to `32` for pinned and ready namespaces and `8` otherwise. The gateway clamps it to `512` for pinned and ready namespaces and `32` otherwise, and to the active shard count. Request-level `threads` overrides this default for one scan. ## Cache policy Aerospike remains an ephemeral cache; durable snapshot history stays in S3. Cache warming uses the same scan fan-out policy as other origin scans. ## Status The operator reports observed generation, metadata sync state, and conditions. `status.snapshot.lastRun` and `lastSuccess` are reserved for the gateway history bridge. # InfraRules CRD Source: https://hevlayer.com/docs/pro/kubernetes/scaling-crd import Callout from "../../../components/docs/Callout.astro"; import FeatureGate from "../../../components/docs/FeatureGate.astro"; Pipelines and Functions run on Layer's built-in `cpu`, `cpu-large`, and `gpu` pools when no `InfraRules/default` object exists. The built-in pools include the stock resource envelopes, placement rules, and per-workload replica ceilings shown below, so a fresh install needs no infrastructure policy object. `InfraRules` is the cluster-scoped policy object for Layer-managed runtime infrastructure. Apply the singleton `InfraRules/default` when you need to replace the built-in pools or declare document-cache policy. Pipelines and Functions do not reference a separate autoscaling resource. They set `spec.scaling` inline and choose a pool from the built-in pool set or `InfraRules/default.spec.computePools` when the custom object exists. ## InfraRules ```yaml apiVersion: hevlayer.com/v1alpha1 kind: InfraRules metadata: name: default spec: computePools: - name: cpu kind: cpu nodeSelector: layer.hev.dev/node-role: worker-cpu layer.hev.dev/compute: cpu tolerations: - key: layer.hev.dev/node-role operator: Equal value: worker-cpu effect: NoSchedule resources: requests: cpu: "1" memory: 2Gi limits: cpu: "2" memory: 4Gi maxReplicasPerWorkload: 32 - name: cpu-large kind: cpu nodeSelector: layer.hev.dev/node-role: worker-cpu layer.hev.dev/compute: cpu tolerations: - key: layer.hev.dev/node-role operator: Equal value: worker-cpu effect: NoSchedule resources: requests: cpu: "1" memory: 2Gi ephemeral-storage: 35Gi limits: cpu: "4" memory: 4Gi ephemeral-storage: 40Gi maxReplicasPerWorkload: 8 - name: gpu kind: gpu nodeSelector: layer.hev.dev/node-role: worker-gpu layer.hev.dev/compute: gpu tolerations: - key: layer.hev.dev/node-role operator: Equal value: worker-gpu effect: NoSchedule - key: nvidia.com/gpu operator: Exists effect: NoSchedule resources: requests: cpu: 250m memory: 4Gi nvidia.com/gpu: "1" limits: cpu: "2" memory: 10Gi nvidia.com/gpu: "1" maxReplicasPerWorkload: 4 documentCache: capGiB: 256 replicationFactor: 1 scaling: mode: autoscale nodes: min: 0 max: 1 ``` The operator validates that the object is named `default`. ## Compute pools Layer defines three built-in pools: | Pool | Use | | --- | --- | | `cpu` | General CPU workers. | | `cpu-large` | CPU workers that need local ephemeral-storage headroom. | | `gpu` | One-NVIDIA-GPU workers for embedding and inference. | The default pools select the Karpenter-backed worker nodes with `layer.hev.dev/node-role=worker-cpu` or `worker-gpu`. The default `gpu` pool also requests `nvidia.com/gpu: "1"` and includes the standard NVIDIA toleration. Apply `InfraRules/default` with different `nodeSelector`, `gpuType`, or resource envelopes when your cluster uses different worker pool names or specific SKUs. | Field | Purpose | | --- | --- | | `name` | Referenced by `spec.scaling.pool` on Pipeline and Function resources. | | `kind` | Pool class label such as `cpu` or `gpu`. | | `gpuType` | Optional descriptive GPU type for GPU pools. | | `nodeSelector` | Applied to worker pods that choose the pool. | | `tolerations` | Applied to worker pods that choose the pool. | | `resources` | Container resources applied to worker pods. | | `maxReplicasPerWorkload` | Hard ceiling for one Pipeline or Function. | If a workload names an unknown pool or asks for more replicas than the pool ceiling, the operator leaves the workload unready and records a condition on its status. ## Workload scaling ```yaml scaling: pool: gpu mode: autoscale warmWindowSeconds: 300 replicas: min: 0 max: 4 ``` | Mode | Behavior | | --- | --- | | `autoscale` | Emit a KEDA `ScaledObject` and let queue depth scale the Deployment between `min` and `max`. | | `fixed` | Set Deployment replicas to `replicas.min`; no KEDA object is emitted. | | `disabled` | Scale the Deployment to 0; no KEDA object is emitted. | | Field | Purpose | | --- | --- | | `pool` | Names a built-in pool, or a pool in `InfraRules/default.spec.computePools` when custom rules exist. When omitted, the operator maps `worker.computeClass` to the stock `cpu` or `gpu` pool. | | `mode` | `autoscale`, `fixed`, or `disabled` (see the table above). | | `replicas` | `min`/`max` bounds for the Deployment. `max` may not exceed the pool's `maxReplicasPerWorkload`. | | `warmWindowSeconds` | Cooldown that holds a workload warm after its last scaling trigger drains, before `autoscale` returns it to `replicas.min`. See below. | Paused workloads also scale to 0. To keep a cold-start-heavy worker warm, set `mode: autoscale` and `replicas.min: 1`. ### Warm window `warmWindowSeconds` maps to the KEDA `ScaledObject` `cooldownPeriod`: the operator waits this long after the last trigger fires before scaling the Deployment back to `replicas.min`. It defaults to `60` when unset. A non-zero value also annotates the worker pods with `karpenter.sh/do-not-disrupt`, so Karpenter retains the *node* — not just the replica — for the window rather than consolidating it away. This is aimed at scale-to-zero GPU pools, where each wake otherwise pays a full cold start (fresh nodeclaim, multi-GB image pull, model load). A warm window lets adjacent batches reuse one warm node, then lets the pool return to genuine scale-to-zero once the window elapses. It must be `>= 0` and requires `mode: autoscale`; the operator leaves the workload unready and records a condition otherwise. ## Document cache rules `documentCache` captures the operator-owned document cache settings: capacity, replication factor, and node count. Helm still renders the document-cache KEDA object directly; `InfraRules` is the declared policy shape the operator reports and validates against. # VectorStore CRD Source: https://hevlayer.com/docs/pro/kubernetes/vectorstore-crd import StoreMatrixLink from "../../../components/docs/StoreMatrixLink.astro"; import FeatureGate from "../../../components/docs/FeatureGate.astro"; import Callout from "../../../components/docs/Callout.astro"; A `VectorStore` is the gateway's upstream connection. It names the store kind, endpoint, credential Secret, and the inbound auth policy the gateway applies to client requests. An install may define more than one `VectorStore`; each `Index.spec.backend.storeRef` selects which store serves that upstream namespace. ```yaml apiVersion: hevlayer.com/v1alpha1 kind: VectorStore metadata: name: turbopuffer-default namespace: layer spec: kind: turbopuffer default: true endpoint: url: https://aws-us-east-1.turbopuffer.com region: aws-us-east-1 turbopuffer: orgId: org_123 credential: secretRef: name: layer key: turbopuffer-api-key inboundAuth: mode: deriveFromStore ``` ## Connection Apply the `VectorStore` resource to the gateway's Kubernetes namespace. The operator reads upstream credentials from the referenced Secret in that namespace. | Field | Purpose | | --- | --- | | `kind` | The backend engine: `turbopuffer`. | | `default` | Selects the store for namespaces without an explicit store reference. | | `endpoint.url` | Upstream API base URL. | | `endpoint.region` | Operator-visible region label. | | `turbopuffer.orgId` | Optional organization ID for dashboard links. | | `credential.secretRef` | Kubernetes Secret containing the upstream credential. |
Standalone gateway configuration For the standalone gateway, see the [OSS configuration guide](https://github.com/hev/layer/blob/v0.6/docs/setup.md).
## Routing The gateway builds one upstream client per `VectorStore` in the namespace. Requests whose namespace has an `Index` with `spec.backend.storeRef` use that store; other namespaces use the default store. Two `Index` objects cannot resolve to the same upstream namespace. ## Inbound auth `spec.inboundAuth.mode` controls the bearer token the gateway accepts. | Mode | Behavior | | --- | --- | | `deriveFromStore` | Accept the default store's upstream credential as the inbound bearer. | | `keys` | Accept independent key Secrets with `read`, `write`, and `admin` scopes. | | `open` | No inbound authentication; use only for explicitly open environments. | For independent inbound keys: ```yaml spec: inboundAuth: mode: keys keys: - name: shop-rw scopes: [read, write] secretRef: name: layer key: layer-inbound-shop-rw-api-key ``` Kubernetes resolves each Secret in the resource's namespace. Operator-managed workers and KEDA use the same Secret through `LAYER_GATEWAY_API_KEY`. In every mode the gateway also accepts a minted [`ApiKey`](/docs/pro/kubernetes/apikey-crd) token whose `vectorstore.` entitlement names this store, enforcing its scopes and namespace globs. ## Status The operator sets `status.reachable` and a `Ready` condition after validating the Secret references and probing `GET /v1/namespaces` on the store endpoint. # Operator Overview Source: https://hevlayer.com/docs/pro/kubernetes/operator `layer-operator` manages declarative state for your hev layer deployment. It serves a few crucial functions — monitoring for changes to your indexes and managing scaling. It does this through a set of abstractions known as [custom resource definitions (CRDs)](/docs/pro/concepts#glossary). The gateway handles the read and write path; the operator handles everything that wants to be expressed as desired state in the cluster: which vector store the gateway fronts, which indexes exist, how worker pools scale, and which stateless functions run against which indexes. ## CRDs The operator reconciles five resource kinds, each documented on its own page: - [VectorStore CRD](/docs/pro/kubernetes/vectorstore-crd) — the upstream store endpoint, credential reference, and gateway inbound auth policy. - [Index CRD](/docs/pro/kubernetes/index-crd) — one resource per turbopuffer namespace the gateway should manage. - [InfraRules CRD](/docs/pro/kubernetes/scaling-crd) — cluster-wide compute pools, document cache rules, and shared scaling policy. - [Pipeline CRD](/docs/pro/kubernetes/pipeline-crd) — staged work that changes row count. - [Function CRD](/docs/pro/kubernetes/function-crd) — stateless user-defined functions that read and write attributes on an index. ## Relationship to the gateway The gateway and the operator are decoupled. The operator reconciles declarative state; the gateway serves the read and write path. Neither sits in the other's hot path, so the gateway keeps serving even if the operator is restarted or lagging. The link between them is one-directional and read-only. For some features the gateway reads CRD status, such as which indexes exist and which worker pools are ready, to inform what it serves. It never writes to the CRDs; declarative state is authored by you and reconciled by the operator, and the gateway is only ever a reader of it. ## Scheduling and node pools The operator applies the compute pool chosen by each Pipeline and Function. A pool can set container resources, `nodeSelector`, and `tolerations`, so operators can pin CPU, storage-heavy CPU, and GPU work to the right node capacity. The operator supplies built-in `cpu`, `cpu-large`, and `gpu` pools when no `InfraRules/default` exists. The stock pools select the chart-rendered Karpenter worker pools: `layer.hev.dev/node-role=worker-cpu` for CPU and `layer.hev.dev/node-role=worker-gpu` for GPU. The GPU pool also requests `nvidia.com/gpu: "1"` and carries the standard NVIDIA toleration. Custom placement is configured once on `InfraRules/default`, not per workload — see [InfraRules](/docs/pro/kubernetes/scaling-crd) for the compute-pool fields and how Pipelines and Functions choose a pool. # Warehouse CRD Source: https://hevlayer.com/docs/pro/kubernetes/warehouse-crd A `Warehouse` declares an upstream source system — the system of record pipelines extract rows from, plus the verified reachability and credential shape needed to reach it. Data in Layer is derived from a warehouse and reconstructible from it. The serving side is the [`VectorStore`](/docs/pro/kubernetes/vectorstore-crd); the two sit on opposite sides of the gateway. ## Supported Warehouses | Kind | Status | Source | | --- | --- | --- | | `snowflake` | Shipped | Snowflake databases and tables, key-pair credential | | `huggingface` | Shipped | Hugging Face Hub datasets, public or token-gated | | `rest` | Shipped | Any paginated JSON HTTP API | | `databricks` | Reserved | Schema-reserved; rejected by the operator until implemented | | `iceberg` | Reserved | Schema-reserved; rejected by the operator until implemented | Snowflake warehouses hold a key-pair credential. Hugging Face dataset warehouses can be public and credentialless, or can point at a read-token Secret for gated/private datasets. REST warehouses declare a JSON HTTP API — a base URL, optional auth, and a pagination rule — so any paginated JSON API is a source without a bespoke kind. ```yaml apiVersion: hevlayer.com/v1alpha1 kind: Warehouse metadata: name: prod-snowflake namespace: layer spec: kind: snowflake snowflake: account: acme-xy12345 user: SVC_LAYER role: SVC_LAYER_ROLE warehouse: EXTRACT_WH keyPairSecretRef: name: snowflake-rsa pool: size: 5 timeout: 30s verifyInterval: 1h ``` ```yaml apiVersion: hevlayer.com/v1alpha1 kind: Warehouse metadata: name: huggingface-hub namespace: hev-shop spec: kind: huggingface huggingface: endpoint: https://huggingface.co # tokenSecretRef is optional for public datasets. # tokenSecretRef: # name: hf-read # key: token verifyInterval: 1h ``` ```yaml apiVersion: hevlayer.com/v1alpha1 kind: Warehouse metadata: name: openfda namespace: layer spec: kind: rest rest: baseUrl: https://api.fda.gov userAgent: hevlayer/rest-source (+https://hevlayer.com/contact) # auth is optional — omit for open APIs. # auth: # in: query # query | header # name: api_key # the param/header carrying the credential # secretRef: # name: openfda-key # key: token rateLimit: requestsPerSecond: 4 verify: path: /drug/label.json # a cheap GET the operator probes query: limit: "1" verifyInterval: 24h ``` ## Connection `spec.kind` selects the source system. `snowflake`, `huggingface`, and `rest` select a source; `databricks` and `iceberg` are reserved by the schema but rejected by the operator until implemented. Exactly one kind block must be present and match `spec.kind`. `verifyInterval` (default `1h`) sets the probe cadence for any kind. A warehouse is identity and credential — not a catalog. What to read — a Snowflake database and table, a Hugging Face dataset and split — belongs to the [pipeline source](#pipeline-source); one credential reaches many. ### Snowflake | Field | Purpose | | --- | --- | | `kind` | `snowflake`, `huggingface`, or `rest`. `databricks` and `iceberg` are reserved by the schema but rejected by the operator until implemented. | | `snowflake.account` | Snowflake account identifier. | | `snowflake.user` | Service user the key pair authenticates. | | `snowflake.role` | Optional role assumed on connect. | | `snowflake.warehouse` | Snowflake compute warehouse extraction queries run on. | | `snowflake.keyPairSecretRef` | Secret in the same namespace holding `private-key.pem` and optional `passphrase`. The credential is never stored in the CRD. | | `snowflake.pool` | Connection pool tuning: `size`, `timeout`. | | `huggingface.endpoint` | Hub endpoint. Defaults to `https://huggingface.co`; override for Enterprise Hub or a mirror. | | `huggingface.tokenSecretRef` | Optional Secret in the same namespace holding `token` for gated/private datasets. Omit for public datasets. | | `verifyInterval` | Probe cadence. Defaults to `1h`. | A warehouse is source identity and credential — not a catalog. Which database, schema, table, dataset repo, config, or split to read belongs to the [pipeline source](#pipeline-source); one credential can reach many tables or repos. ### REST / HTTP JSON API A `rest` warehouse declares a JSON HTTP API. The credential is optional — many public APIs need none, or take a key that only raises a rate limit (omit `auth` for the anonymous case, the same `Verified`-with-no-Secret shape as a public Hugging Face dataset). | Field | Purpose | | --- | --- | | `rest.baseUrl` | Required. API origin. A source's `request.path` resolves against it. | | `rest.userAgent` | User-Agent sent by the stock REST source worker. Defaults to `hevlayer/rest-source (+https://hevlayer.com/contact)`; set a project-specific contact URL for public crawls. | | `rest.auth` | Optional. `in` (`query` or `header`), `name` (the param or header carrying the credential), and `secretRef` (Secret holding `token`). Omit for open APIs. | | `rest.rateLimit` | Optional. `requestsPerSecond` is a client-side request cap, to stay under the API's fair-access ceiling. Omit to leave pacing to the source worker's defaults. | | `rest.verify` | Required. The reachability probe: a `path` and optional `query` the operator `GET`s to verify the API — and the credential, when `auth` is set. | `rest` holds access only; which endpoint, query, pagination, and field mapping to read belongs to the [pipeline source](#rest) — one warehouse serves many endpoints on the same API. ## Verification The operator probes the warehouse on apply, whenever the referenced Secret's content changes, and every `verifyInterval`. For `snowflake`, the probe opens a key-pair session, runs `SELECT 1` on the declared compute warehouse, and closes. For `huggingface`, the probe calls the Hub dataset API with the optional token. If pipelines reference the warehouse, the operator resolves each declared `repo@revision` and records the resolved commit SHA in `status.sourceRevisions`. With no consumers yet, it verifies that the Hub dataset API is reachable. For `rest`, the probe issues a single `GET` of `rest.verify.path` (with the optional `query`, and `auth` applied when set). Any `2xx` is `Verified`, confirming both reachability and — when a credential is configured — that it is accepted. | Phase | Meaning | | --- | --- | | `Pending` | Not yet probed. | | `Verified` | Last probe succeeded; `status.verifiedAt` is the probe time. | | `Failed` | Last probe failed; `status.failureReason` says why. | `Failed` is a loud signal, not an outage: in-flight pipeline runs keep their connections, new runs refuse to start, and the condition surfaces in `kubectl get warehouse` and the dashboard. Pipelines start only against a `Verified` warehouse. ## Rotation Swap the referenced Secret's content. The operator re-verifies and `status.verifiedAt` advances; consumers resolve credentials through the warehouse at connection-build time, so new connections pick up the new key with no redeploy. Pointing `keyPairSecretRef` or `tokenSecretRef` at a different Secret name is a spec edit with the same flow. For `huggingface`, swapping the token Secret's content re-verifies the same way. Adding or removing `tokenSecretRef` — moving a warehouse between anonymous and authenticated access — is a spec edit the operator re-verifies. ## Pipeline source A pipeline extracting from a warehouse names it in `spec.sourceRef`. The source block owns the *what* — for Snowflake a database, query, and cursor; for Hugging Face a dataset, split, and field mapping — and the warehouse owns the *where* and *who*. The operator requires `warehouseRef` to name a `Verified` warehouse of the matching kind in the same namespace, and carries the source block verbatim to the worker as `HEVLAYER_SOURCE_REF`, as for [any other source](/docs/pro/kubernetes/pipeline-crd#source). ### Snowflake ```yaml spec: sourceRef: kind: snowflake warehouseRef: prod-snowflake database: ANALYTICS query: >- SELECT ID, TITLE, BODY, REFRESH_ID FROM PUBLIC.NOTES WHERE REFRESH_ID > :cursor cursor: column: REFRESH_ID ``` The operator mounts the warehouse's key-pair Secret into the worker pod at `/var/run/hevlayer/warehouse/` and injects `HEVLAYER_WAREHOUSE` — connection JSON resolved from the warehouse spec (account, user, role, compute warehouse, pool), no credential material. The worker builds its own connection from the two. ### Hugging Face ```yaml spec: target: namespace: squad sourceRef: kind: huggingface warehouseRef: hf-public dataset: rajpurkar/squad # Hub repo id config: plain_text # dataset config; omit for the default split: train # train | validation | test | … revision: ~ # omit → the operator resolves and records the parquet-ref commit mapping: id: id # column → document id text: context # column to index or embed attributes: [title, question] # columns to carry as attributes ``` | `mapping` field | Purpose | | --- | --- | | `text` | Required. The column indexed, and embedded by a following stage. | | `id` | Optional. Column used as the document id. Omitted, the worker synthesizes `{config}/{split}#{offset}` — stable within a revision; name a natural key for anything long-lived. | | `attributes` | Optional. Columns carried as attributes. Omit or `[]` for every remaining scalar column; binary feature columns (image, audio) are skipped. | `spec.worker.image` defaults to the stock Hugging Face source image from the mesh-account ECR registry, so no custom image is needed; set it to override. The operator mounts the warehouse's token Secret (when present) into the worker and injects `HEVLAYER_WAREHOUSE` with the endpoint only, no token. The worker streams rows from the dataset's Parquet conversion at the pinned `revision`; the row offset is the cursor. Omitting `revision` pins to the dataset's current parquet-ref commit, which the operator resolves and records, so a long run never drifts onto a newer version mid-flight and re-enumeration is exact. Reading a newer version is a deliberate `revision` edit. A dataset's `text` column is often a whole document that must be split into chunks before it is embedded. Add a `chunk` block to the source to declare how — it is a pipeline-source feature, not specific to Hugging Face. See [Chunking](/docs/pro/kubernetes/pipeline-crd#chunking) on the Pipeline CRD page. ```yaml spec: sourceRef: kind: huggingface warehouseRef: huggingface-hub repo: McAuley-Lab/Amazon-Reviews-2023 config: raw_meta_Electronics split: train revision: main cursor: field: parent_asin ``` When `sourceRef.kind` is `huggingface`, the operator requires `warehouseRef` to name a `Verified` Hugging Face warehouse in the same namespace and requires `repo` on the source block. It injects `HEVLAYER_WAREHOUSE` with the Hub endpoint and, when `tokenSecretRef` is set, mounts the Secret at `/var/run/hevlayer/warehouse/token` and adds `tokenPath` to the connection JSON. `HEVLAYER_SOURCE_REF` remains the verbatim source block and owns the dataset repo, config, split, revision, and cursor. ### REST ```yaml spec: target: namespace: drug-labels sourceRef: kind: rest warehouseRef: openfda request: path: /drug/label.json query: # static query params search: 'openfda.product_type:"HUMAN PRESCRIPTION DRUG"' pagination: kind: offset pageSizeParam: limit # required for offset offsetParam: skip # required for offset pageSize: 1000 # required for offset; must be > 0 response: items: $.results # JSONPath to the record array on each page cursor: field: effective_time # incremental + re-enumeration key (JSONPath per item) mapping: id: openfda.spl_set_id # JSONPath into each item text: ~ # omit when a chunk strategy supplies the section text attributes: [openfda.generic_name, openfda.brand_name, dea_schedule] ``` | Source field | Purpose | | --- | --- | | `request.path` / `request.query` | The endpoint (resolved against `baseUrl`) and any static query params — the *what*. | | `pagination` | How to walk pages. `offset` requires `pageSizeParam`, `offsetParam`, and a positive `pageSize`. `searchAfter` requires `cursorParam`, `cursorPath`, and a positive `pageSize`; `pageSizeParam` is optional. `hasMorePath` optionally stops enumeration when it resolves to `false`. | | `response.items` | JSONPath to the record array on each page. | | `cursor.field` | JSONPath into each item, used as the incremental refresh key and the re-enumeration cursor. | | `mapping` | JSONPath expressions for `id`, `text`, and `attributes` — the same mapping shape as Hugging Face, over JSON instead of Parquet columns. | For one origin with an editorial set of paths, add `request.forEach`. The v1 value source is a ConfigMap in the Pipeline's namespace. `select` runs against the JSON stored at `ref.key`; each selected string is bound to `as`, substituted in `request.path` and `request.query`, and remains available while mapping rows. ```yaml spec: sourceRef: kind: rest warehouseRef: greenhouse request: forEach: values: from: configMap ref: { name: roles-companies, key: companies.json } select: "$[?@.ats == 'greenhouse'].token" as: token path: /v1/boards/{{token}}/jobs query: { content: "true" } pagination: kind: offset pageSizeParam: per_page offsetParam: page pageSize: 500 response: { items: $.jobs } cursor: { field: updated_at } snapshot: mode: full scope: forEachValue absentRow: set: { open: false, closed_at: "{{runStartedAt}}" } mapping: id: "{{token}}:{{id}}" text: "{{title}}\n{{content}}" attributes: title: title company: "{{token}}" ats: "{{warehouseRef}}" department: departments[*].name posted_at: first_published open: true ``` `mapping.attributes` accepts the existing list form or a name-to-expression object. Object values may be JSONPath expressions, template strings, or non-string JSON literals. `{{token}}` is the active `forEach` value; `{{warehouseRef}}` and `{{runStartedAt}}` are worker-provided values. For an ordered incremental projection, omit `request.forEach` and the full-snapshot block. This Travels with Charlie source follows `{data, next_cursor, has_more}` pages and sends the stored cursor back as `since`: ```yaml spec: target: namespace: family-messages sourceRef: kind: rest warehouseRef: travels-with-charlie request: path: /api/layer/messages pagination: kind: searchAfter cursorParam: since cursorPath: $.next_cursor hasMorePath: $.has_more pageSizeParam: limit pageSize: 100 response: items: $.data cursor: field: $.received_at mapping: id: $.id text: $.text attributes: [received_at, sender, subject] ``` The first run starts without `since` and follows echoed cursors until `next_cursor` is absent or null, or `has_more` is false. After successful row writes, the last cursor becomes the stream's S3-backed high-water mark. The next refresh resumes from it, so previously committed rows are not emitted again. A non-advancing cursor while `has_more` remains true fails the stream; the existing 10,000-page guard also remains in force. `snapshot.mode: full` means each selected value is a complete diff partition. After a partition has been read through its final page, rows from its prior S3 manifest that are absent now receive `absentRow.set`; the new manifest commits only after every row write succeeds. A transport error, non-2xx response, or an empty first page leaves that partition's manifest and rows intact. This failure rule is deliberate: an unavailable or renamed endpoint is not evidence that all of its rows disappeared. `spec.worker.image` defaults to the stock REST source image from the mesh-account ECR registry, which pages any JSON API by these rules — there is no per-API worker. The operator injects `HEVLAYER_WAREHOUSE` with the `baseUrl` (and mounts the `auth` Secret when set); `HEVLAYER_SOURCE_REF` is the verbatim source block. A `text` field that is a whole document is split by a [`chunk`](/docs/pro/kubernetes/pipeline-crd#chunking) block, as for any source; the `section` strategy with `sectionSource: jsonFields` makes each top-level JSON field its own section. ## Keys An [`ApiKey`](/docs/pro/kubernetes/apikey-crd) binds to a warehouse with a `warehouse.` entitlement carrying a list of opaque claims strings. Layer stores and echoes the strings; the application routes on them. No client route reaches a source system — clients touch indexes, not warehouses — so the entitlement grants nothing in Layer, and it inerts when the warehouse is deleted. ## Deletion Deleting a warehouse fences everything drawing from it. A finalizer blocks deletion while `status.consumers` is non-zero — pipelines extracting from it or keys entitled to it — annotate with `hevlayer.com/force-delete: "true"` to override. ## Status ```yaml status: phase: Verified verifiedAt: "2026-06-10T00:00:00Z" failureReason: null sourceRevisions: McAuley-Lab/Amazon-Reviews-2023@main: 2b6d039ed471f2ba5fd2acb718bf33b0a7e5598e consumers: pipelines: 2 apiKeys: 1 ``` The operator emits Kubernetes Events on phase transitions and counts observed references in `status.consumers`. # Pipeline CRD Source: https://hevlayer.com/docs/pro/kubernetes/pipeline-crd The `Pipeline` CRD declares the scaling characteristics you want for ingesting data. Ingestion typically runs in stages: a CPU stage for chunking and extraction, followed by a GPU stage for embedding. You can declare the spec in YAML, from code through the [pipeline API](/docs/pro/api/pipelines), or a combination of both — it is recommended you declare your pipeline scaling characteristics in YAML while setting your namespace via the client. `spec.sourceRef` lets you declare your pipeline's upstream details as well — the operator hands it to the worker as an environment variable, so the worker reads its source from config instead of hardcoding it. ```yaml apiVersion: hevlayer.com/v1alpha1 kind: Pipeline metadata: name: product-images namespace: layer spec: target: namespace: products sourceRef: kind: sqs queueUrl: https://sqs.us-east-1.amazonaws.com/123456789/product-images schedule: cron: "0 2 * * *" leaseSeconds: 600 worker: image: .dkr.ecr.us-east-1.amazonaws.com/hev-product-image-worker:latest computeClass: cpu batchSize: 64 timeoutSeconds: 60 scaling: pool: cpu mode: autoscale replicas: min: 0 max: 8 ``` ## Target `spec.target.namespace` is the turbopuffer namespace the pipeline writes. The gateway pipeline API owns document state, chunks, and vector writes for that target namespace. ## Pipeline id `spec.pipelineId` names the gateway pipeline (the queue) the worker stages into and scales on. It defaults to the resource name. Set it when multiple worker resources share one queue: the extract and embed stages of a [two-stage pipeline](/docs/pro/api/pipelines) both set `pipelineId: products`. ## Source `spec.sourceRef` declares the external source that feeds the worker. Its `kind` selects how the operator treats it. For **open kinds** — SQS, Kafka, S3 events, a partner API, a one-off migration — `sourceRef` is arbitrary JSON injected into the worker pod verbatim as `HEVLAYER_SOURCE_REF`; the worker image owns source-specific behavior. See [Extract and chunk](/docs/pro/api/pipelines#extract-and-chunk) for a worker reading it. ### Typed sources For **warehouse-backed kinds** — `snowflake`, `huggingface`, and `rest` — `kind` selects a typed shape the operator validates. The source names a [`Warehouse`](/docs/pro/kubernetes/warehouse-crd) with `warehouseRef`; the operator resolves it (it must be `Verified`), mounts its credential Secret, and injects connection details as `HEVLAYER_WAREHOUSE` with no credential material. `spec.worker.image` is then optional: omit it and the operator defaults to the stock worker for that kind from the mesh-account ECR registry (for example, `.dkr.ecr.us-east-1.amazonaws.com/hev-huggingface-source` or `.dkr.ecr.us-east-1.amazonaws.com/hev-rest-source`), so a typed source needs no custom image. Set `worker.image` to override with your own. The per-kind source fields are on the [Warehouse CRD](/docs/pro/kubernetes/warehouse-crd#pipeline-source) page. A REST source can enumerate an incremental JSON projection without a `request.forEach` block. Use `pagination.kind: searchAfter`, name the query parameter that receives the prior cursor, and point `cursorPath` at the next cursor echoed by each response. The stock worker stores the last cursor in S3 after its row writes succeed and resumes there on the next scheduled refresh. See the [REST search-after example](/docs/pro/kubernetes/warehouse-crd#rest). ### Chunking A source's text column is often a whole document that must be split before it is embedded. An optional `chunk` block declares how, with no code for the common strategies. It applies to any source whose worker honors it — the stock workers do. ```yaml spec: sourceRef: kind: huggingface warehouseRef: hf-public dataset: wikimedia/wikipedia config: 20231101.en split: train mapping: text: text attributes: [title, url] chunk: strategy: recursive # none | fixed | recursive | sentence | markdown unit: tokens # tokens | characters size: 512 overlap: 64 tokenizer: cl100k_base # when unit: tokens ``` | `chunk` field | Purpose | | --- | --- | | `strategy` | `none` (default — one document per row), `fixed`, `recursive` (a paragraph→line→sentence→word ladder kept under `size`), `sentence`, or `markdown` (split on headings). | | `unit` | `tokens` or `characters` — what `size` and `overlap` count in. | | `size` | Target maximum chunk length. | | `overlap` | Units repeated between adjacent chunks for context. | | `tokenizer` | Token model when `unit: tokens`. Pinned so chunk boundaries stay reproducible. | Each row maps to one document; `text` splits into chunks. The chunk is the unit indexed and embedded — a row with id `{documentId}#{i}` carrying the document's attributes plus reserved `_hevlayer_parent_id` and `_hevlayer_chunk_index`. For splits the stock strategies can't express, set `spec.worker.image` to your own chunker. ## Schedule `spec.schedule` is optional. When it is set, the operator wakes the Pipeline worker on a KEDA cron window instead of scaling it on pending pipeline queue depth: ```yaml schedule: cron: "0 2 * * *" # 5-field UTC cron; minute must be a single integer leaseSeconds: 600 # sizes the cron window ``` The worker still owns source semantics: what to pull on wake, how to advance cursors, and how to stage rows. The schedule only controls when the worker runs. Scheduled Pipelines must use `scaling.replicas.min: 0`; the cron window is the wake trigger. ## Worker | Field | Purpose | | --- | --- | | `image` | Worker image. Optional for [typed sources](#typed-sources), where it defaults to the stock worker for the source kind; required otherwise. | | `computeClass` | `cpu` or `gpu`. Defaults to `cpu`; when `scaling.pool` is omitted, the operator maps this to the stock `cpu` or `gpu` pool. | | `batchSize` | Work items per batch. | | `timeoutSeconds` | Worker call timeout. | | `podSpec` | Optional pod-level merge patch. | The operator creates one Deployment per Pipeline and injects: | Variable | Value | | --- | --- | | `HEVLAYER_PIPELINE_ID` | `spec.pipelineId`, defaulting to the resource name. | | `HEVLAYER_TARGET_NAMESPACE` | `spec.target.namespace`. | | `HEVLAYER_BASE_URL` | The gateway base URL. | | `HEVLAYER_SOURCE_REF` | `spec.sourceRef` as JSON, when set. | | `HEVLAYER_FOR_EACH_VALUES_PATH` | Read-only file projected from `request.forEach.values.ref` when a typed REST source uses `from: configMap`; absent for a single REST enumeration stream. | | `HEVLAYER_SNAPSHOT_BUCKET` | The chart's S3 bucket, injected for REST full-snapshot manifests. Region and optional S3-compatible endpoint are provided as `HEVLAYER_SNAPSHOT_REGION` and `HEVLAYER_SNAPSHOT_ENDPOINT`. | | `HEVLAYER_PIPELINE_SCHEDULE` | `1` when `spec.schedule` is set. | | `HEVLAYER_WAREHOUSE` | Resolved `Warehouse` connection JSON (no credential material), for [typed sources](#typed-sources). The credential Secret is mounted separately. | | `LAYER_GATEWAY_API_KEY` | Gateway bearer token. In `deriveFromStore` mode this is the default `VectorStore` credential; in `keys` mode it is the configured inbound worker key. | ## Scaling ```yaml scaling: pool: cpu mode: autoscale replicas: min: 0 max: 8 ``` `spec.scaling.pool`, when set, must name a pool in the [built-in set or `InfraRules/default`](/docs/pro/kubernetes/scaling-crd). When omitted, the operator uses `worker.computeClass` to choose the stock `cpu` or `gpu` pool. Layer provides the well-known `cpu`, `cpu-large`, and `gpu` pools without requiring an `InfraRules` object. `mode: autoscale` creates a KEDA `ScaledObject` backed by pipeline queue depth, or by the cron window when `spec.schedule` is set. `mode: fixed` pins the Deployment to `replicas.min`; `mode: disabled` scales it to zero. `spec.scaling.warmWindowSeconds` sets a cooldown (and node retention) that holds the worker warm after its queue drains — see [Workload scaling](/docs/pro/kubernetes/scaling-crd#warm-window). `spec.paused: true` also scales the worker to zero. ## Status Use the [pipeline status API](/docs/pro/api/pipelines#wait-for-completion) for status: queue counts, stage progress, and worker state. The resource itself reports only managed object references and readiness conditions.