Applies to v1.3.18

ESRA — The Retrieval Pipeline

What happens between an AI client calling esra_{name}-retrieval and the results coming back.

authenticate → authorize → audit          (platform Runtime)
      ↓
resolve effective scope
      ↓
select sources
      ↓
plan searches (per source, concurrently)
      ↓
validate plans          ← nothing unvalidated can reach a provider
      ↓
execute (bounded parallel, parameterized, read-only)
      ↓
normalize → aggregate & deduplicate → rerank → top-K
      ↓
respond

Everything upstream of "resolve effective scope" is the platform's ordinary tool-invocation path. ESRA branches in only after governance authorization and the invocation audit record — so tenant resolution, policy evaluation, audit, metrics and correlation are the same as for every other tool.


1. Resolve effective scope

Deterministic, before any model call. Intersects source policy, capability binding, exposure subset and runtime authorization; applies health; computes the effective limits and response modes. Audited as esra.sources.resolve with all four levels.

An empty effective set fails the invocation with ESRA_NO_SOURCES_AVAILABLE.

2. Select sources

Mandatory and policy-forced sources are included unconditionally and are not sent to the model at all. The service LLM only ever chooses among the Optional ones — which keeps the prompt small and bounds the blast radius of a bad selection.

The model receives business metadata only: description, usage and exclusion guidance, domain tags, languages, example prompts, freshness. Never a schema, a relation name, a field, a host or a credential.

Its output is validated against the candidate set. A source id it was not given is dropped and audited as LLM_UNKNOWN_SOURCE_REJECTED — the model cannot widen its own reach.

Fallback: mandatory and policy-forced sources only, with ESRA_SELECTION_FALLBACK.

On a decision model, each optional source becomes one yes/no question — its name, description and use/avoid guidance — answered with a probability. Sources at or above the capability's selection threshold are kept, most likely first; if none reaches it, the most likely one is. A source the model declines to judge is not selected; the fallback applies only when it judges none. See Decision models at selection and reranking.

Selection results are not cached: every invocation selects afresh.

3. Plan searches

One planning call per selected source, concurrently, so one source's failure never affects another's plan and one source's terminology never reaches another's context.

The planner sees the caller's prompt, the source's business description, and for each mapping its business name, description and the {fieldName, isSearchable, isFilterable, allowedOperators} of each field — plus the field's type when it is not text (type=date, type=number), and for a filterable field its allowed values (values=["INVOICE","RECEIPT"], every one) and its description (about:). It plans against a business schema, never a database schema: the field names are the source's logical field names, the same on every entity whatever column holds them, and a field an entity supplies as a constant is never offered as searchable. Provider capabilities are stated explicitly, so it is never asked to guess what the engine supports.

It emits between one and the effective maximum of queries per source: the lowest of the capability's Max queries per source, the exposure's override and the source's Max queries on its Ceilings tab (each 1 to 20, default 10). Each query has a strategy (phrase, keyword, synonym, acronym, entity, recent), concepts, phrases, excluded terms, and structured filters.

Each strategy is a retrieval path the planner chooses on purpose:

Strategy When the planner uses it
keyword The precise path: the request's most distinctive subject and the attribute that qualifies it
synonym The same question in the vocabulary records actually use
acronym An abbreviation and its expansion, searched together
entity One named person, organization, product, place or identifier on its own. Questions whose answer spans several records get one such query per entity
phrase A title, name, quotation or code that appears verbatim (engines with phrase search)
recent The request asks for the latest or current records. The matches come newest first, by the entity's business timestamp. Offered only on entities that have one

A strategy never changes which records match, and only recent changes their order. A good plan mixes a precise query, an intermediate one and a broad one.

What a query means

Every engine gives a planned query the same meaning:

  • Concepts are AND-ed, and each concept is a list of alternatives, any one of which is enough. [car, automobile] AND [insurance, policy] finds records about car or automobile insurance, or a car or automobile policy.
  • A term matches when all of its words appear, in any order, in their inflected forms where the engine stems. "contract terminated" finds "the contracts were terminated". A multi-word term is not an exact phrase.
  • A phrase must appear word for word.
  • An excluded term removes every record that matches it.

Nothing is optional: every concept and every phrase must match. A broad query is one concept with many alternatives. A query may AND at most 4 concepts and give a concept at most 12 alternatives. MongoDB takes one concept, because $text cannot AND groups of words.

Engine differences that remain:

  • MySQL/MariaDB and Oracle do not stem.
  • MySQL/MariaDB excludes a multi-word term only when its words are adjacent.
  • MongoDB's $text mode treats the words as ranking only once a query has a phrase.
  • SQL Server and Oracle do not index noise words such as "the" or "of", so ESRA leaves those words out of a multi-word term.

Fallback: the mapping's default template — one phrase query over the prompt plus one keyword query over its content words — with ESRA_PLANNING_FALLBACK.

4. Validate

Deterministic and non-bypassable. The validator asserts that the mapping belongs to a selected source; every projected field is returnable and not restricted; every filter field is filterable with a permitted operator, and every filter value parses as the field's type (FILTER_VALUE_INVALID otherwise); every limit is within policy, the concept limits included; the provider supports the strategy; no concept is empty and the query asks for something beyond exclusions; and no term, phrase or filter value contains a statement separator or comment sequence.

Two checks are about the entity rather than the query:

  • The record filter must resolve. The fields its conditions compare are resolved on each entity to that entity's column or constant. An entity on which one cannot be resolved is withheld — never searched without its conditions — and the trace says RECORD_FILTER_UNRESOLVED, naming the entity. Conditions no record of the entity can satisfy (a constant they refute, a claim value that is no value of its field's type) skip it the same way as a refuted constant below.
  • Constants are decided once on Elasticsearch and MongoDB. These engines cannot carry a typed constant in their query, so a filter (or a record filter condition) over a field an entity supplies as a constant is decided by the validator, under SQL's rules: one that holds for every row is dropped; one that is false or compares a null excludes the entity, which is not queried and is recorded on the trace as skipped (STATIC_FILTER_EXCLUDES_ENTITY) — not as a degradation, and with no warning to the caller. The four relational engines carry the constant as a typed parameter instead and let the database decide; the two paths give the same answer.

Validation cannot be bypassed. A provider executes only a query the validator itself produced: nothing reaches a database without having passed through validation first.

Rejected queries are dropped and audited with a reason code; the invocation continues with what survived, warning ESRA_PLAN_REJECTED.

Caller filters are checked first. A caller's filters are applied to every planned query, so a filter no source permits would be rejected on every one of them. They are therefore checked before source selection, against the same field-and-operator list the tool schema advertises: a filter naming a field no in-scope source lets callers filter on, or an operator that field does not permit, fails the invocation with ESRA_FILTER_NOT_PERMITTED and a message naming what is accepted — before any model is called. A filter value that is not a value of its field's type — a date that is not yyyy-MM-dd, a number that is not a number — fails the invocation the same way, with ESRA_FILTER_VALUE_INVALID and a message saying what the field takes. So does an eq, ne or in value outside a field's allowed values, when every in-scope source lists them; the message lists the values.

Filters reach only the sources that hold their fields. An exposure over several sources lists every field any of them lets callers filter on, so a caller may filter on a field only some of them hold. Filters combine with AND, and a source — or one entity of a source — that does not hold every filtered field, filterable and with the filter's operator, cannot tell whether a row matches. Right after the check above, before source selection, such entities and sources are left out of the invocation: they are not offered to the selector, cost no planning call, and do not make the response degraded, because leaving them out is the answer the caller asked for. A mandatory source is left out the same way. The trace's source-selection stage names the sources left out (filterExcludedSources) and counts the entities (filterExcludedEntities). When every filtered field is held by some source but no single entity holds them all, nothing could match: the invocation fails with ESRA_FILTER_NOT_PERMITTED, naming the fields. A source also has a limit on filters per query (Max filters per query on the source's limits): a source that holds every field but accepts fewer filters than the caller sent is left out the same way, never searched with only some of them. When no source is left, the invocation fails with ESRA_FILTER_NOT_PERMITTED and says how many filters the sources accept.

Allowed values keep a filter's meaning. A matching value is sent in the field's declared spelling, whatever its letter case. When one source lists a field's values and another does not, a caller's value the listing source does not hold cannot match there: that source's query is skipped — shown on the trace as FILTER_VALUE_NOT_ALLOWED, skipped rather than degraded — and the other source is searched; a ne on such a value holds for every row and is dropped. A value the planning model invents is different: it was a guess, so it is dropped from the query, which still runs, and the plan stage counts it as filter_value_not_allowed (the value itself is recorded only with payload capture on).

Filters compare as their field's type. A field is text, identifier, number, date, dateTime or boolean; the tool schema says which (invoice_date (date; gt)). invoice_date gt 2025-01-01 compares dates and amount gt 99 compares numbers on every engine — as text, "100" would sort before "99". Text fields compare as text.

5. Execute

Concurrent, bounded at four levels (per invocation, per source, per provider, per runtime instance). Each command runs through a resilience pipeline — timeout, transient-only retry, circuit breaker, concurrency limiting — applied per source.

Every command:

  • runs in a read-only transaction with a server-side statement timeout and a restricted search path;
  • carries every prompt-derived and claim-derived value as a parameter, never as command text;
  • resolves relation and field identifiers from configuration by id, quoted by the provider's identifier quoter;
  • applies its row cap server-side, not by reading and discarding — fetching one row past it, so a result that exactly fills the cap is not mistaken for one that was cut (ESRA_SOURCE_PARTIAL);
  • orders by score descending and record key ascending, so results are stable across executions.

A query built entirely out of injection-style content produces command text identical to the equivalent benign query: untrusted content only ever ends up as data, never as part of the command itself.

Errors are classified into a closed set of sixteen codes before leaving the provider — TIMEOUT, CONNECTION_REFUSED, AUTH_FAILED, RELATION_NOT_FOUND, PERMISSION_DENIED, COLUMN_NOT_INDEXED, TEXT_INDEX_UNAVAILABLE, SYNTAX_ERROR, RESOURCE_EXHAUSTED, CANCELLED, SNAPSHOT_ISOLATION_UNAVAILABLE, HOST_NOT_ALLOWED, SECRET_UNRESOLVED, CONNECTION_TEMPLATE_INVALID, UNKNOWN, CIRCUIT_OPEN. Only CONNECTION_REFUSED, RESOURCE_EXHAUSTED and TIMEOUT are retryable; CIRCUIT_OPEN is not, since the breaker has already made the retry decision for that source. Raw driver text goes to the log and nowhere else.

6. Normalize and aggregate

Per query, over that query's own result set:

normalized = (native − min) / (max − min)          (1.0 when max == min)
weighted   = normalized × priorityWeight × freshnessWeight

Cross-query duplicates keep the highest weighted value and merge provenance. Being found by more than one query is weak positive evidence: +0.02 per extra match, capped at +0.1.

Native provider scores are preserved verbatim in provenance and never compared across sources.

For an entity whose rows are parts of longer documents (a document grouping column is set), the parts of one document that matched merge into one result: the best-matching part leads, and provenance's matchedParts says how many parts matched. See Data sources — Documents stored as parts.

7. Rerank

The model sees the caller's prompt and, per candidate, an opaque resultId, the source name, the title, and truncated fragments. Never record keys, restricted fields, or provider scores — those would anchor it to lexical ranking and defeat the purpose.

The fragments are cut around the words that matched, on every engine, so the model scores the passage that made the record a candidate rather than the start of a column that may not contain the match at all (Fragments). They are the same fragments the caller receives.

The model reads up to 600 characters per candidate, and every fragment gets a share of them: a result with three fragments shows the model all three match locations, each shortened, rather than the first one alone. Answer generation reads the same way, up to 1,200 characters per result.

Candidates are selected round-robin across sources so one prolific source cannot crowd out a small source's strong matches.

Final ordering is computed by ESRA, not taken from the model's array order:

final = 0.9 × semantic + 0.1 × weighted        (weights configurable per capability)

A candidate the model omitted keeps a null semantic score and ranks below all scored candidates — an omission is evidence of an incomplete response, not of irrelevance.

Fallback: normalized-score ordering, with ESRA_RERANK_FALLBACK.

On a decision model, every candidate is rated on a fixed four-step scale and its semantic score is the expected rating, 0 to 1; the formula above applies unchanged. Candidates are sent one per request or several per request, as the capability chooses. When the stage's time runs out part-way, the ratings already returned are used, the unrated candidates follow below them, and the response carries ESRA_RERANK_PARTIAL. A candidate the model declines to rate stays unrated; the fallback applies only when nothing was rated.

8. Respond

Top-K selection is deterministic. Field allowlist, then masking, then size cap, then error sanitization.

Status is complete or degraded; degraded always carries at least one warning explaining why.


Document Fetch

Retrieval returns bounded fragments by design. An agent that has found the right document often needs more of it — so each exposure may publish a second tool, esra_{name}-fetch, that returns a larger portion of one already-surfaced document.

Each result then carries a documentRef: an encrypted, expiring token. Encrypted rather than merely signed, because a record key is itself source-internal data that must not leak through an opaque-looking string.

The token identifies; it never authorizes. On every fetch the full chain re-runs: exposure still published, access policy still admits this caller, source still in scope, field allowlist and masking reapplied, record filter re-evaluated against the current caller's claims. A token minted for one caller and replayed by another yields ESRA_DOCUMENT_NOT_FOUND — not a permission error, which would confirm the record exists.

Fetch is off by default, per exposure. It converts a governed retrieval capability into a document-download API, so it is an explicit decision per audience, bounded by a per-caller hourly character quota, and every call is a first-class audit record.