Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

28.8 KB
Raw Blame
import { Buffer } from 'node:buffer';

import { trace } from '@lobechat/observability-otel/api';
import { z } from 'zod';

import type {
  ElasticsearchFtsSearchClient,
  ElasticsearchFtsSearchInput,
  ElasticsearchFtsSearchResponse,
} from '@/database/repositories/ftsSearch';
import { resolveElasticsearchTransport } from '@/database/repositories/ftsSearch/elasticsearch/url';
import type { FtsSearchDocumentEntity } from '@/database/repositories/ftsSearchDocument';
import {
  findFtsSearchIndexSchemaMismatch,
  FTS_SEARCH_DOCUMENT_ENTITIES,
  getFtsSearchIndexAlias,
  parseFtsSearchPhysicalIndexName,
  sha256Json,
} from '@/database/repositories/ftsSearchDocument';
import type { FtsSearchTargetMappingProperties } from '@/database/repositories/ftsSearchDocument/projectionCompatibility';
import { getFtsSearchProjectionCompatibility } from '@/database/repositories/ftsSearchDocument/projectionCompatibility';

import type {
  ElasticsearchFtsSearchErrorCode,
  ElasticsearchFtsSearchRequestResult,
  ElasticsearchFtsSearchTraceContext,
  FtsSearchUsage,
} from './observability';
import { recordElasticsearchFtsSearchRequest } from './observability';

const MAX_ERROR_RESPONSE_BYTES = 16_384;

const searchResponseSchema = z.object({
  hits: z.object({
    hits: z.array(
      z.object({
        _id: z.string(),
        _score: z.number().nullable(),
        sort: z.array(z.unknown()).optional(),
      }),
    ),
    total: z.union([z.number(), z.object({ value: z.number() })]).optional(),
  }),
  took: z.number().nonnegative().optional(),
});

const bulkItemErrorSchema = z.object({ type: z.string().optional() }).passthrough();
const bulkResponseSchema = z.object({
  errors: z.boolean().optional(),
  items: z.array(
    z.object({
      index: z.object({ error: bulkItemErrorSchema.optional(), status: z.number() }),
    }),
  ),
});

const aliasResponseSchema = z.record(
  z.string(),
  z.object({
    aliases: z.record(
      z.string(),
      z.object({ is_write_index: z.boolean().optional() }).passthrough(),
    ),
  }),
);

const syncMappingResponseSchema = z.record(
  z.string(),
  z.object({
    mappings: z.object({
      _meta: z
        .object({
          reindex_run_id: z.string().uuid(),
          schema_version: z.number().int().positive(),
        })
        .passthrough()
        .optional(),
      properties: z
        .record(z.string(), z.object({ type: z.string().optional() }).passthrough())
        .default({}),
    }),
  }),
);

const syncTombstoneMappingSchema = z.object({ type: z.literal('boolean') });

const indexIdentityResponseSchema = z.record(
  z.string(),
  z.object({
    mappings: z
      .object({
        _meta: z
          .object({
            reindex_run_id: z.string().uuid(),
            schema_fingerprint: z.string().optional(),
            schema_version: z.number().int().positive(),
          })
          .passthrough(),
        properties: z.record(z.string(), z.unknown()).default({}),
      })
      .passthrough(),
    settings: z.object({
      index: z
        .object({
          analysis: z.record(z.string(), z.unknown()),
          // Serverless omits internal settings; sync still validates the stamped generation below.
          // https://www.elastic.co/docs/reference/elasticsearch/index-settings/serverless
          uuid: z.string().trim().min(1).optional(),
        })
        .passthrough(),
    }),
  }),
);

export interface ElasticsearchFtsSearchBulkItem {
  index: { error?: { type?: string }; status: number };
}

export interface ElasticsearchFtsSearchBulkResponse {
  errors?: boolean;
  items: ElasticsearchFtsSearchBulkItem[];
}

export interface ElasticsearchFtsSearchHttpClientOptions {
  /** Explicit opt-in for plaintext HTTP / no API key on a private container network. */
  allowInsecureHttp?: boolean;
  /** Required unless `allowInsecureHttp` is enabled; never sent over plaintext HTTP. */
  apiKey?: string;
  /** Alias namespace; required to map aliases back to entities when validating index generations. */
  indexNamespace?: string;
  requestTimeoutMs?: number;
  url: string;
  usage?: FtsSearchUsage;
}

export interface ElasticsearchFtsSearchSyncIndexIdentity {
  /** Null when the deployment does not expose its internal index UUID. */
  indexUuid: string | null;
  mappingSha256: string;
  physicalIndex: string;
  reindexRunId: string;
  /** `null` for indexes created before fingerprints were stamped into `_meta`. */
  schemaFingerprint: string | null;
  schemaVersion: number;
  settingsSha256: string;
}

export interface ElasticsearchFtsSearchSyncProjectionIncompatibility {
  entity: FtsSearchDocumentEntity;
  index: string;
  message: string;
}

export interface ElasticsearchFtsSearchSyncIndexFieldsResult {
  fieldsByIndex: Record<string, string[]>;
  incompatibilities: ElasticsearchFtsSearchSyncProjectionIncompatibility[];
}

export class ElasticsearchFtsSearchRequestError extends Error {
  readonly errorCode: ElasticsearchFtsSearchErrorCode;
  readonly status?: number;

  constructor(
    message: string,
    status?: number,
    cause?: unknown,
    errorCode: ElasticsearchFtsSearchErrorCode = 'unknown_http_error',
  ) {
    super(message, { cause });
    this.name = 'ElasticsearchFtsSearchRequestError';
    this.errorCode = errorCode;
    this.status = status;
  }
}

const classifyRequestError = (error: unknown): ElasticsearchFtsSearchRequestResult =>
  error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')
    ? 'timeout'
    : 'other_error';

const readContentLength = (response: Response): number | undefined => {
  const header = response.headers.get('content-length');
  if (!header) return;
  const value = Number(header);
  return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
};

const readBoundedResponseText = async (response: Response): Promise<string> => {
  if (!response.body) return '';

  const reader = response.body.getReader();
  const chunks: Buffer[] = [];
  let completed = false;
  let totalBytes = 0;

  try {
    while (totalBytes < MAX_ERROR_RESPONSE_BYTES) {
      const result = await reader.read();
      if (result.done) {
        completed = true;
        break;
      }

      const remainingBytes = MAX_ERROR_RESPONSE_BYTES - totalBytes;
      const chunk = Buffer.from(result.value.subarray(0, remainingBytes));
      chunks.push(chunk);
      totalBytes += chunk.byteLength;
    }
  } finally {
    if (!completed) {
      try {
        await reader.cancel();
      } catch {
        // The classification fallback still uses the HTTP status when the stream cannot cancel.
      }
    }
  }

  return Buffer.concat(chunks, totalBytes).toString('utf8');
};

/** Extracts only bounded Elasticsearch error type identifiers, never free-form reasons. */
const readElasticsearchErrorTypes = (responseText: string): Set<string> => {
  const errorTypes = new Set<string>();

  for (const match of responseText.matchAll(/"type"\s*:\s*"(\w+)"/gi)) {
    if (match[1]) errorTypes.add(match[1].toLowerCase());
  }

  return errorTypes;
};

const classifyHttpError = (
  status: number,
  responseText: string,
): ElasticsearchFtsSearchErrorCode => {
  const errorTypes = readElasticsearchErrorTypes(responseText);
  if (errorTypes.has('too_many_clauses') || errorTypes.has('too_many_nested_clauses')) {
    return 'too_many_clauses';
  }
  if (status === 401) return 'authentication';
  if (status === 403) return 'authorization';
  if (status === 404 || errorTypes.has('index_not_found_exception')) return 'index_not_found';
  if (status === 413) return 'request_too_large';
  if (status === 429) return 'rate_limited';
  if (status >= 500) return 'server_error';
  if (status === 400) return 'invalid_query';

  return 'unknown_http_error';
};

const getTraceDetails = (): {
  span: ReturnType<typeof trace.getActiveSpan>;
  traceContext: ElasticsearchFtsSearchTraceContext;
  traceId: string;
} => {
  const span = trace.getActiveSpan();
  if (!span) return { span, traceContext: 'missing', traceId: 'none' };

  return {
    span,
    traceContext: span.isRecording() ? 'recording' : 'non_recording',
    traceId: span.spanContext().traceId || 'none',
  };
};

/** HTTP transport that never logs credentials, request text, or Elasticsearch payloads. */
export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchClient {
  private readonly authorizationHeader: string | undefined;
  private readonly indexNamespace: string | undefined;
  private readonly requestTimeoutMs: number;
  private readonly url: URL;
  private readonly usage: FtsSearchUsage;

  constructor({
    allowInsecureHttp,
    apiKey,
    indexNamespace,
    requestTimeoutMs = 10_000,
    url,
    usage = 'unattributed',
  }: ElasticsearchFtsSearchHttpClientOptions) {
    const transport = resolveElasticsearchTransport({ allowInsecureHttp, apiKey, url });
    this.authorizationHeader = transport.authorizationHeader;
    this.indexNamespace = indexNamespace;
    this.requestTimeoutMs = requestTimeoutMs;
    this.url = transport.url;
    this.usage = usage;
  }

  /** Adds the Authorization header only for authenticated endpoints. */
  private headers(extra: Record<string, string> = {}): Record<string, string> {
    return this.authorizationHeader
      ? { Authorization: this.authorizationHeader, ...extra }
      : { ...extra };
  }

  /**
   * Fails closed unless every incremental destination is a writable alias with tombstone support
   * whose live index implements the schema generation declared by the deployed code.
   */
  async assertFtsSearchSyncAliases(aliases: string[]): Promise<void> {
    await this.getFtsSearchSyncIndexIdentities(aliases);
  }

  /** Maps each alias back to its entity so live `_meta` can be compared with the declared mapping. */
  private resolveAliasEntities(aliases: string[]): Map<string, FtsSearchDocumentEntity> {
    if (!this.indexNamespace) {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch full-text search index namespace is required to validate index generations',
      );
    }
    const namespace = this.indexNamespace;
    const entityByAlias = new Map(
      FTS_SEARCH_DOCUMENT_ENTITIES.map(
        (entity) => [getFtsSearchIndexAlias(namespace, entity), entity] as const,
      ),
    );
    const resolved = new Map<string, FtsSearchDocumentEntity>();
    for (const alias of aliases) {
      const entity = entityByAlias.get(alias);
      if (!entity) {
        throw new ElasticsearchFtsSearchRequestError(
          `Elasticsearch full-text search alias does not belong to the configured index namespace: ${alias}`,
        );
      }
      resolved.set(alias, entity);
    }
    return resolved;
  }

  /** Fetches `GET /_alias/...` or `GET /<indices>/_alias` and validates the shared response shape. */
  private async fetchAliasTable(path: string): Promise<z.infer<typeof aliasResponseSchema>> {
    const aliasResponse = await fetch(new URL(path, this.url), {
      headers: this.headers(),
      method: 'GET',
      signal: AbortSignal.timeout(this.requestTimeoutMs),
    });
    if (!aliasResponse.ok) {
      throw new ElasticsearchFtsSearchRequestError(
        `Elasticsearch full-text search sync alias check failed (${aliasResponse.status})`,
        aliasResponse.status,
      );
    }

    let aliasJson: unknown;
    try {
      aliasJson = await aliasResponse.json();
    } catch {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch full-text search sync alias response is not valid JSON',
        aliasResponse.status,
      );
    }
    const aliasPayload = aliasResponseSchema.safeParse(aliasJson);
    if (!aliasPayload.success) {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch full-text search sync alias response has an invalid shape',
        aliasResponse.status,
      );
    }
    return aliasPayload.data;
  }

  /** Picks the unique writable physical index behind `alias`, failing closed on ambiguity. */
  private selectWriteTarget(
    aliasTable: z.infer<typeof aliasResponseSchema>,
    alias: string,
  ): string {
    const targets = Object.entries(aliasTable).filter(([, value]) =>
      Object.hasOwn(value.aliases, alias),
    );
    const explicitWriteTargets = targets.filter(
      ([, value]) => value.aliases[alias].is_write_index === true,
    );
    const writeTarget =
      explicitWriteTargets.length === 1
        ? explicitWriteTargets[0]
        : targets.length === 1 && targets[0][1].aliases[alias].is_write_index !== false
          ? targets[0]
          : undefined;
    if (!writeTarget) {
      throw new ElasticsearchFtsSearchRequestError(
        `Elasticsearch full-text search sync destination is not a writable alias: ${alias}`,
      );
    }
    return writeTarget[0];
  }

  private async getFtsSearchSyncWriteTargetMap(aliases: string[]) {
    const aliasPath = aliases.map(encodeURIComponent).join(',');
    const aliasTable = await this.fetchAliasTable(`/_alias/${aliasPath}`);

    const writeTargets = new Map<string, string>();
    for (const alias of aliases) writeTargets.set(alias, this.selectWriteTarget(aliasTable, alias));
    return writeTargets;
  }

  /**
   * Lists every live physical generation of each alias so incremental sync can write to all of
   * them. Generations follow `<alias>-v<n>` or `<alias>-v<n>-r<run-id>`; the alias's writable index
   * is always included even if it was named differently by an operator. Only open indexes count: a
   * generation being retired is closed first, which drops it from this list before it is deleted.
   *
   * Resolved on every drain rather than cached so a generation created by a running rebuild starts
   * receiving writes on the next batch, and a retired one stops without a restart.
   */
  async getFtsSearchSyncGenerationTargets(aliases: string[]): Promise<Record<string, string[]>> {
    if (aliases.length === 0) return {};

    const patternPath = aliases.map((alias) => encodeURIComponent(`${alias}-v*`)).join(',');
    // Wildcard patterns only expand to physical indexes, so the alias table still has to be fetched
    // by alias name to learn which generation currently serves reads and writes.
    const [aliasTable, generationTable] = await Promise.all([
      this.fetchAliasTable(`/_alias/${aliases.map(encodeURIComponent).join(',')}`),
      this.fetchAliasTable(`/${patternPath}/_alias?expand_wildcards=open&allow_no_indices=true`),
    ]);

    const targets: Record<string, string[]> = {};
    for (const alias of [...aliases].sort()) {
      const writeIndex = this.selectWriteTarget(aliasTable, alias);
      const generations = new Set(
        Object.keys(generationTable).filter(
          (index) => parseFtsSearchPhysicalIndexName(alias, index) !== undefined,
        ),
      );
      generations.add(writeIndex);
      targets[alias] = [...generations].sort();
    }
    return targets;
  }

  /**
   * Validates and returns mapped top-level fields for each physical index. Generations differ in
   * their field sets, and every generation is `dynamic: strict`, so a document must be pruned to
   * the target's fields before it is written there.
   */
  async getFtsSearchSyncIndexFields(
    entitiesByIndex: Record<string, FtsSearchDocumentEntity>,
  ): Promise<ElasticsearchFtsSearchSyncIndexFieldsResult> {
    const indexes = Object.keys(entitiesByIndex).sort();
    if (indexes.length === 0) return { fieldsByIndex: {}, incompatibilities: [] };

    const response = await fetch(
      new URL(
        `/${indexes.map(encodeURIComponent).join(',')}/_mapping?filter_path=*.mappings._meta,*.mappings.properties`,
        this.url,
      ),
      {
        headers: this.headers(),
        method: 'GET',
        signal: AbortSignal.timeout(this.requestTimeoutMs),
      },
    );
    if (!response.ok) {
      throw new ElasticsearchFtsSearchRequestError(
        `Elasticsearch full-text search sync field lookup failed (${response.status})`,
        response.status,
      );
    }
    const payload = syncMappingResponseSchema.safeParse(await response.json());
    if (!payload.success) {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch full-text search sync field lookup response has an invalid shape',
        response.status,
        payload.error,
      );
    }

    const fieldsByIndex: Record<string, string[]> = {};
    const incompatibilities: ElasticsearchFtsSearchSyncProjectionIncompatibility[] = [];
    for (const index of indexes) {
      const properties = payload.data[index]?.mappings.properties;
      if (!properties) {
        throw new ElasticsearchFtsSearchRequestError(
          `Elasticsearch full-text search sync field lookup is missing index ${index}`,
        );
      }
      const entity = entitiesByIndex[index];
      if (this.indexNamespace) {
        const identity = parseFtsSearchPhysicalIndexName(
          getFtsSearchIndexAlias(this.indexNamespace, entity),
          index,
        );
        if (identity?.reindexRunId) {
          const meta = payload.data[index]?.mappings._meta;
          if (
            meta?.reindex_run_id !== identity.reindexRunId ||
            meta.schema_version < identity.builtSchemaVersion
          ) {
            throw new ElasticsearchFtsSearchRequestError(
              `Elasticsearch full-text search rebuild generation ${index} has incompatible reindex metadata`,
            );
          }
        }
      }
      const compatibility = getFtsSearchProjectionCompatibility(
        entity,
        properties satisfies FtsSearchTargetMappingProperties,
      );
      if (!compatibility.compatible) {
        const details = [
          ...compatibility.missingFields.map(
            (field) =>
              `target field ${field} (${properties[field].type ?? 'unknown type'}) is missing from the current mapping`,
          ),
          ...compatibility.incompatibleFields.map(
            ({ currentType, field, targetType }) =>
              `target field ${field} uses ${targetType ?? 'an unknown type'} but the current mapping uses ${currentType}`,
          ),
        ].join('; ');
        incompatibilities.push({
          entity,
          index,
          message: `Elasticsearch full-text search index ${index} is incompatible with the current ${entity} projection: ${details}. Retain compatible source fields in FTS_SEARCH_RETAINED_SOURCE_PROPERTIES and the document builder, or retire the index before syncing ${entity}.`,
        });
      }
      fieldsByIndex[index] = Object.keys(properties).sort();
    }
    return { fieldsByIndex, incompatibilities };
  }

  /**
   * Returns stable runtime identities after validating aliases, soft deletes, and reindex metadata.
   * Each alias is checked against its own entity's declared generation; entities may come from
   * different reindex runs because generations are rebuilt and promoted per entity.
   */
  async getFtsSearchSyncIndexIdentities(
    aliases: string[],
  ): Promise<Record<string, ElasticsearchFtsSearchSyncIndexIdentity>> {
    if (aliases.length === 0) return {};

    const aliasEntities = this.resolveAliasEntities(aliases);
    const writeTargets = await this.getFtsSearchSyncWriteTargetMap(aliases);
    const physicalPath = [...new Set(writeTargets.values())]
      .sort()
      .map(encodeURIComponent)
      .join(',');
    const identityResponse = await fetch(
      new URL(
        `/${physicalPath}?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid`,
        this.url,
      ),
      {
        headers: this.headers(),
        method: 'GET',
        signal: AbortSignal.timeout(this.requestTimeoutMs),
      },
    );
    if (!identityResponse.ok) {
      throw new ElasticsearchFtsSearchRequestError(
        `Elasticsearch full-text search sync index identity check failed (${identityResponse.status})`,
        identityResponse.status,
      );
    }

    let payload: unknown;
    try {
      payload = await identityResponse.json();
    } catch {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch full-text search sync index identity response is not valid JSON',
        identityResponse.status,
      );
    }
    const parsed = indexIdentityResponseSchema.safeParse(payload);
    if (!parsed.success) {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch full-text search sync index identity response has an invalid shape',
        identityResponse.status,
      );
    }

    const identities = new Map<string, ElasticsearchFtsSearchSyncIndexIdentity>();
    for (const [alias, physicalIndex] of writeTargets) {
      const index = parsed.data[physicalIndex];
      if (!index) {
        throw new ElasticsearchFtsSearchRequestError(
          `Elasticsearch full-text search sync index identity is missing for alias: ${alias}`,
        );
      }

      if (
        !syncTombstoneMappingSchema.safeParse(index.mappings.properties.fts_search_sync_deleted)
          .success
      ) {
        throw new ElasticsearchFtsSearchRequestError(
          `Elasticsearch full-text search sync alias lacks a boolean fts_search_sync_deleted mapping: ${alias}`,
        );
      }

      const mismatch = findFtsSearchIndexSchemaMismatch(
        aliasEntities.get(alias)!,
        index.mappings._meta,
      );
      /**
       * An alias still serving an older generation is the normal state while the declared
       * generation is being built and promoted; sync keeps writing, pruned to each generation's
       * fields. A newer generation than the code declares means the deployment was rolled back
       * without moving the alias, which this code cannot serve safely.
       */
      if (mismatch?.kind === 'version' && mismatch.actual > mismatch.expected) {
        throw new ElasticsearchFtsSearchRequestError(
          `Elasticsearch full-text search alias ${alias} implements schema version ${mismatch.actual} but the deployed code declares v${mismatch.expected}; promote the v${mismatch.expected} generation or deploy matching code`,
        );
      }
      if (mismatch?.kind === 'fingerprint') {
        throw new ElasticsearchFtsSearchRequestError(
          `Elasticsearch full-text search alias ${alias} was built from a different v${index.mappings._meta.schema_version} mapping than the deployed code declares; rebuild the index generation`,
        );
      }

      identities.set(alias, {
        indexUuid: index.settings.index.uuid ?? null,
        mappingSha256: sha256Json(index.mappings),
        physicalIndex,
        reindexRunId: index.mappings._meta.reindex_run_id,
        schemaFingerprint: index.mappings._meta.schema_fingerprint ?? null,
        schemaVersion: index.mappings._meta.schema_version,
        settingsSha256: sha256Json(index.settings.index.analysis),
      });
    }

    return Object.fromEntries(
      [...identities].sort(([leftAlias], [rightAlias]) =>
        leftAlias < rightAlias ? -1 : leftAlias > rightAlias ? 1 : 0,
      ),
    );
  }

  /**
   * Actions name physical generation indexes (see `getFtsSearchSyncGenerationTargets`), so
   * `require_alias` cannot be used. The migration CLI closes retired generations and installs an
   * exact-name template with `allow_auto_create: false` before purging them, so late physical writes
   * cannot recreate deleted indexes. Preserve those templates while delayed requests may exist.
   */
  async bulk(body: string): Promise<ElasticsearchFtsSearchBulkResponse> {
    const endpoint = new URL('/_bulk', this.url);
    const response = await fetch(endpoint, {
      body,
      headers: this.headers({ 'Content-Type': 'application/x-ndjson' }),
      method: 'POST',
      signal: AbortSignal.timeout(this.requestTimeoutMs),
    });

    if (!response.ok) {
      throw new ElasticsearchFtsSearchRequestError(
        `Elasticsearch bulk request failed (${response.status})`,
        response.status,
      );
    }

    let payload: unknown;
    try {
      payload = await response.json();
    } catch (error) {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch bulk response is not valid JSON',
        response.status,
        error,
      );
    }

    const parsed = bulkResponseSchema.safeParse(payload);
    if (!parsed.success) {
      throw new ElasticsearchFtsSearchRequestError(
        'Elasticsearch bulk response has an invalid shape',
        response.status,
        parsed.error,
      );
    }

    return parsed.data;
  }

  async search(input: ElasticsearchFtsSearchInput): Promise<ElasticsearchFtsSearchResponse> {
    const endpoint = new URL(`/${encodeURIComponent(input.index)}/_search`, this.url);
    const body = JSON.stringify(input.body);
    const requestBytes = Buffer.byteLength(body);
    const startedAt = Date.now();
    let contentLength: number | undefined;
    let decodedBytes: number | undefined;
    let recorded = false;
    const { span, traceContext, traceId } = getTraceDetails();
    span?.setAttributes({
      'fts.search.elasticsearch.executed_query_characters': input.executedQueryChars,
      'fts.search.elasticsearch.original_query_characters': input.originalQueryChars,
      'fts.search.elasticsearch.query_field_count': input.queryFieldCount,
      'fts.search.elasticsearch.query_truncated': input.truncated,
      'fts.search.elasticsearch.trace_context': traceContext,
      'fts.search.elasticsearch.usage': this.usage,
    });
    const record = (
      result: ElasticsearchFtsSearchRequestResult,
      hits?: number,
      serverTookMs?: number,
      errorCode: ElasticsearchFtsSearchErrorCode = 'none',
    ) => {
      recorded = true;
      recordElasticsearchFtsSearchRequest({
        contentLength,
        decodedBytes,
        durationMs: Date.now() - startedAt,
        entity: input.entity,
        errorCode,
        executedQueryChars: input.executedQueryChars,
        hits,
        originalQueryChars: input.originalQueryChars,
        pagination: input.pagination,
        queryFieldCount: input.queryFieldCount,
        requestBytes,
        result,
        serverTookMs,
        traceContext,
        truncated: input.truncated,
        usage: this.usage,
      });
    };
    const logFailure = (errorCode: ElasticsearchFtsSearchErrorCode, status?: number) => {
      span?.setAttributes({
        'fts.search.elasticsearch.error_code': errorCode,
        ...(status === undefined ? {} : { 'fts.search.elasticsearch.http_status_code': status }),
      });
      console.error('[fts-search] Elasticsearch request failed', {
        entity: input.entity,
        errorCode,
        executedQueryChars: input.executedQueryChars,
        originalQueryChars: input.originalQueryChars,
        queryFieldCount: input.queryFieldCount,
        requestBytes,
        status: status ?? 0,
        traceContext,
        traceId,
        truncated: input.truncated,
        usage: this.usage,
      });
    };

    try {
      const response = await fetch(endpoint, {
        body,
        headers: this.headers({ 'Content-Type': 'application/json' }),
        method: 'POST',
        signal: AbortSignal.timeout(this.requestTimeoutMs),
      });
      contentLength = readContentLength(response);

      if (!response.ok) {
        let responseText = '';
        try {
          responseText = await readBoundedResponseText(response);
        } catch {
          // HTTP status still provides a safe, bounded classification fallback.
        }
        const errorCode = classifyHttpError(response.status, responseText);
        record('http_error', undefined, undefined, errorCode);
        logFailure(errorCode, response.status);
        throw new ElasticsearchFtsSearchRequestError(
          `Elasticsearch search request failed (${response.status}, ${errorCode})`,
          response.status,
          undefined,
          errorCode,
        );
      }

      let payload: unknown;
      try {
        const responseText = await response.text();
        decodedBytes = Buffer.byteLength(responseText);
        payload = JSON.parse(responseText);
      } catch (error) {
        const result = error instanceof SyntaxError ? 'parse_error' : classifyRequestError(error);
        const errorCode = result === 'timeout' ? 'timeout' : 'response_parse_error';
        record(result, undefined, undefined, errorCode);
        logFailure(errorCode, response.status);
        throw new ElasticsearchFtsSearchRequestError(
          'Elasticsearch search response is not valid JSON',
          response.status,
          error,
          errorCode,
        );
      }

      const parsed = searchResponseSchema.safeParse(payload);
      if (!parsed.success) {
        record('parse_error', undefined, undefined, 'response_parse_error');
        logFailure('response_parse_error', response.status);
        throw new ElasticsearchFtsSearchRequestError(
          'Elasticsearch search response has an invalid shape',
          response.status,
          parsed.error,
          'response_parse_error',
        );
      }

      record('success', parsed.data.hits.hits.length, parsed.data.took);
      return parsed.data;
    } catch (error) {
      if (!recorded) {
        const result = classifyRequestError(error);
        const errorCode = result === 'timeout' ? 'timeout' : 'transport_error';
        record(result, undefined, undefined, errorCode);
        logFailure(errorCode);
      }
      throw error;
    }
  }
}