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.

✨ feat(fts-search): safe per-entity Elasticsearch mapping migrations (#19186)

YuTengjing13ada65ad968
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index e4fedbfd6c2..fae7dbe3b13 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -1,6 +1,6 @@
---
name: full-text-search
-description: 'Use for product search: FtsSearchRepo, pg_search/Elasticsearch, projections, Outbox sync, reindexing and performance. Excludes agent web search.'
+description: 'Use for product search: FtsSearchRepo, pg_search/Elasticsearch, mapping migrations, projections, Outbox sync, reindexing and performance. Excludes agent web search.'
---
# Product Full-Text Search
@@ -63,8 +63,11 @@ applicable item:
5. Capture functions/triggers or fanout queries in `captureInfrastructure.ts`.
6. Reindex checkpoints, Outbox draining, metrics, and self-host documentation.
-Schema fields, mappings, builders, and fixed fixtures must agree exactly. A field that is not in the
-document schema must not appear in the mapping or query field list.
+Schema fields, mappings, builders, and fixed fixtures must agree. Current mapping fields plus
+explicit `FTS_SEARCH_RETAINED_SOURCE_PROPERTIES` must equal the current Zod fields, without overlap.
+Retained source properties keep older open indexes writable during field removals; keep the builder
+producing them until those indexes are closed. They must not appear in current query metadata.
+A field outside the document schema must not appear in a mapping or query field list.
Elasticsearch `multi_match` query length is bounded by a shared leaf-clause budget divided by the
selected query-field count. Adding a field reduces that entity's safe query length, and changing a
@@ -89,11 +92,14 @@ field-count regression tests.
fail, or release work reclaimed by another worker.
- Permanent failures and exhausted retries become durable dead letters. A drain that creates or
observes dead work must fail instead of continuing to publish a successful cutover signal.
-- Full backfill does not replace continuous sync and does not switch product traffic. Keep the
- application on PostgreSQL until aliases are ready and the Outbox is empty and stable, then switch
- explicitly.
+- Full backfill does not replace continuous sync. For the initial PostgreSQL-to-Elasticsearch
+ cutover, keep the application on PostgreSQL until aliases are ready and the Outbox is empty and
+ stable, then switch explicitly. Later mapping upgrades keep searches on the existing Elasticsearch
+ alias until promotion.
-The supported operator entrypoints are:
+The supported operator entrypoints below run from the OSS repository root. A wrapping repository
+may expose different package scripts; check its `package.json` before invoking these or the mapping
+migration commands linked below.
```bash
bun run db:install-fts-search-capture
@@ -104,6 +110,63 @@ bun run scripts/pgSearchCleanup/index.ts --status
bun run scripts/pgSearchCleanup/index.ts --apply --yes
```
+## Mapping Generations
+
+Docker startup runs `fts-search-elasticsearch-reindex.cjs --startup --yes` after PostgreSQL
+migrations when the selected provider is Elasticsearch. It blocks serving until index migration
+and catch-up succeed. Persist the same checkpoint volume across application and migration
+containers; failed namespace locks still require explicit recovery. Continuous sync remains a
+separate worker. Hosted and manual workflows keep their explicit migration commands.
+
+For mapping changes, generation operations, repeat/resume behavior, or deployment integration, read
+[Mapping migration workflow](references/mapping-migrations.md). It routes to the public command guide
+and adds recovery, automation, and local Docker rehearsal rules.
+
+Elasticsearch cannot change an existing field's type or index-time analyzer in place. The code
+declares the target and Elasticsearch records the live state, per entity:
+
+- `FTS_SEARCH_INDEX_DEFINITIONS[entity].schemaVersion` is the declared generation; the fingerprint is
+ `sha256` of the mapping plus the shared analysis. Add complete changed-entity definitions in a new
+ `ftsSearchDocument/migration/NNNN-meaningful-name/` batch, register it and update current pointers
+ in `migration/index.ts`. Append expected fingerprints in `__tests__/schemaSnapshots.json`; preserve
+ published batches and baselines. `mappings.test.ts` and `migration/index.test.ts` check current
+ parity, history, version bumps and fingerprint changes. See `migration/README.md` for ownership.
+ Shared analysis changes alter
+ every entity fingerprint and classify as breaking for every entity; bump all affected versions
+ and rebuild rather than using in-place upgrades.
+- Every physical index `<alias>-v<n>` carries `_meta.{reindex_run_id, schema_version,
+schema_fingerprint}`; the alias marks the live generation. Indexes created before fingerprints
+ existed may omit the fingerprint, but still need a valid run ID and schema version for sync
+ readiness. `_meta.schema_version` wins over the `-v<n>` suffix because an in-place upgrade advances
+ `_meta` without renaming the index.
+- The sync runtime accepts an alias that still serves an older generation (upgrade in progress) and
+ refuses one that serves a newer generation or a different fingerprint of the declared version. It
+ writes every change to all open `<alias>-v*` indexes plus the alias write index, pruning each
+ document to the fields that index maps (every generation is `dynamic: strict`), so a new
+ generation can be backfilled beside the live one; a bulk work item is acknowledged only when
+ every existing generation accepted it (2xx or 409 conflict).
+- One reindex checkpoint per `(namespace, schemaVersion)` covers the entities on that generation.
+ `--apply` groups the requested entities by declared version, treats existing aliases as an
+ upgrade (no `--fresh-run`), leaves existing aliases in place, and emits `promotion_pending`. A
+ completed first install creates aliases. Promoting a newer generation requires a completed
+ checkpoint, a fingerprint match when targeting the declared version, and an idle target-entity Outbox. Rollback
+ to an older stamped generation can use its metadata without a retained checkpoint;
+ `--retire` requires `in_sync` and only closes old generations; explicit `--purge` installs
+ exact-index templates forbidding auto-creation before deleting eligible closed generations.
+ `--in-place` requires
+ `mappingChange: additive`, widens the live index with `PUT _mapping`, pins the checkpoint to that
+ index, and backfills with `external_gte` so concurrent sync writes win.
+- Checkpoints are local files, not Drizzle migration history. Preserve `ES_REINDEX_STATE_DIR` across
+ invocations. Completed runs skip backfill; incomplete runs resume from saved cursors. Mutating CLI
+ commands share a non-expiring Elasticsearch namespace lock, independent of checkpoint location.
+ A failed command retains its lock when its outcome may be uncertain. Before `--release-lock=<owner> --yes`, stop the previous process and resolve pending requests; never assume age proves it stopped.
+ The lock does not serialize old binaries or external operator actions.
+- Reconciliation is exact only on a first install; once an alias serves an entity, concurrent sync
+ writes make a higher Elasticsearch count legitimate and only a shortfall fails.
+- `scripts/elasticsearchReindex/runtime/generationService.ts` owns classification (`missing`,
+ `unmanaged`, `in_sync`, `drift`, `upgrade_available`, `rollback_required`), promotion, and
+ retirement; keep them free of Cloud-specific policy.
+
Read `docs/self-hosting/advanced/elasticsearch-migration.mdx` or its Chinese counterpart before
changing the operational sequence. When database rollout or index cost affects the design, also
use the `db-migrations` skill and measure the relevant operation on the actual Dev database before
diff --git a/.agents/skills/full-text-search/references/mapping-migrations.md b/.agents/skills/full-text-search/references/mapping-migrations.md
new file mode 100644
index 00000000000..62c715a5752
--- /dev/null
+++ b/.agents/skills/full-text-search/references/mapping-migrations.md
@@ -0,0 +1,136 @@
+# Mapping migration workflow
+
+Use this reference when changing Elasticsearch field definitions or operating index generations.
+For initial provider cutover and complete environment setup, use
+`docs/self-hosting/advanced/elasticsearch-migration.mdx` from the OSS repository root.
+
+## Choose the operation
+
+- Add a new numbered batch under `ftsSearchDocument/migration/` with complete definitions for the
+ changed entities and bumped `schemaVersion` values; keep the current Zod schema and projection
+ consistent. Register the batch and update current pointers in `migration/index.ts`, then append
+ expected fingerprints in `__tests__/schemaSnapshots.json`. Preserve old batches and baselines;
+ the PR history guard rejects changes to batch directories and JSON entries present in the base.
+ The mapping and history tests reject missing registrations, stale pointers and version bumps
+ without physical changes. Shared analysis changes require
+ version bumps and rebuilds for every entity, even if only one uses the analyzer being changed.
+- Docker startup with `FTS_SEARCH_PROVIDER=elasticsearch` runs `--startup --yes` after PostgreSQL
+ migrations and before serving requests. It checks the declared versions, backfills required
+ generations, drains pending changes, and promotes them. An unchanged completed generation is
+ not scanned again. Other entrypoints retain explicit operator control.
+- Rebuild into a new generation for field type/analyzer changes, removals, or when rollback matters.
+ Only entities whose declared version changes need a new generation.
+- Before removing or renaming a field, retain its Zod definition, builder output and old property
+ in `FTS_SEARCH_RETAINED_SOURCE_PROPERTIES` until every index needing it is closed. New index writes
+ omit retained source-only fields. Sync, apply and promotion reject incompatible open targets;
+ a type or semantic conversion is not supplied automatically.
+- Incompatible same-name JSON type changes are not supported by the online migration path. Use a
+ new field name and retain the old source key through the rollback window. If incompatible code
+ has already created dead letters, fix the mapping/projection first, then requeue only reviewed
+ document ID/revision pairs in PostgreSQL. There is no Outbox requeue CLI flag; `--skip-failure` only
+ resolves backfill checkpoint failures. The standalone sync CLI stops while any dead letters remain.
+- Use `--in-place` only when status reports `upgrade_available` and `mappingChange: additive`.
+ Currently this means new top-level fields; adding a multi-field to an existing field is classified
+ as breaking. In-place still scans historical documents to populate the new fields. It preserves
+ the physical name and offers no old-generation alias rollback.
+
+## Operator prerequisites and recovery
+
+For explicit operator control, use `bun run fts-search:reindex -- --apply --entity=<entity> --yes`, then
+`--promote --entity=<entity> --yes` after catch-up. Optional operations are `--retire`, `--purge`,
+`--apply --in-place`, and rollback with `--promote --version=<previous-version>`; each requires the
+target entity and confirmation. See `scripts/elasticsearchReindex/commandOptions.ts` for supported
+combinations and `runtime/generationService.ts` for the operation gates.
+
+- Configure the intended `DATABASE_URL`, `ES_INDEX_NAMESPACE`, `ES_URL`, and endpoint authentication
+ (`ES_API_KEY` for authenticated endpoints; the explicit insecure-HTTP opt-in for an appropriate
+ local target). Preserve a durable `ES_REINDEX_STATE_DIR` through every step. In containers, mount
+ persistent storage; stop the previous worker before copying the whole directory to another worker.
+- Without `ES_URL`, `--status` reports `generations: null`: that is missing ES inspection, not proof
+ that no upgrade is needed. Inspect `drift`, `unmanaged`, or `rollback_required` rather than forcing
+ an upgrade through them. Live metadata still needs a valid run ID and schema version for sync
+ readiness; only the legacy fingerprint may be absent.
+- Build beside the old live alias with incremental sync running, then promote after backfill
+ completion and an idle target-entity Outbox (`pending`, `retrying`, `inFlight`, `dead` all zero). A completed
+ backfill does not move an existing alias. Verify actual searches and catch-up before retirement.
+- Rollback is an optional recovery branch: select a retained, open older generation first, then
+ redeploy matching older code. Older sync code rejects a live generation newer than it declares.
+ Unlike forward promotion, rollback may accept an older stamped generation without its checkpoint.
+- Retire only while the declared generation is serving and rollback is no longer needed. `--retire`
+ only closes eligible old indexes. Explicit `--purge` installs and verifies an exact-index template
+ with `allow_auto_create: false` before deletion, requiring `manage_index_templates`. Keep these
+ protection templates; conflicts fail closed. An empty Outbox is not a fence against paused workers.
+- Mutating commands acquire a non-expiring lock in `<namespace>-fts-search-control`. Status reads
+ `migrationLock` without acquiring one. Failed/interrupted commands may retain the lock; stop the
+ old process and resolve uncertain requests before `--release-lock=<owner> --yes`. Never use timeout
+ takeover. The lock and tombstones cannot protect against older CLI binaries or external mutations.
+- In-place widens the live mapping before backfill and pins the physical index in its checkpoint.
+ Resume uses ordinary `--apply` with the same directory; no promote/retire step is needed for this
+ operation. Metadata can already say `in_sync` while backfill is incomplete, so also inspect run and
+ entity progress. It does not preserve a pre-upgrade index for alias rollback; recovery may require
+ rebuilding from older code.
+
+## Repeat, resume, and concurrency
+
+The completed-run behavior below assumes the generation still covers the same entities. Adding an
+entity to an existing generation reopens its checkpoint for that entity's backfill.
+
+| Situation | Actual behavior and operator action |
+| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Same namespace/version, completed checkpoint | Backfill returns without scanning or bulk-writing again. Preparation/status work can still run. |
+| Same checkpoint, incomplete run | Reuses run ID, skips completed entities, and continues after saved cursors. An uncheckpointed batch may be replayed. |
+| Missing checkpoint, existing indexes | A new run can be rejected by `_meta.reindex_run_id`; restore the matching checkpoint. This is not a safe way to restart or adopt an existing index. |
+| New empty target | Only this initial installation uses `--apply --fresh-run --yes`. Do not use it to resume or override a conflict. |
+| Two workers, same checkpoint directory | The Elasticsearch namespace lock rejects the second migration owner. |
+| Two workers, different directories, same target | The same namespace lock still rejects the second owner, including different source databases targeting that ES namespace. |
+
+Repeating `--promote` for a valid already-live target returns `already_live`, without a new Outbox
+idle gate. Repeating `--retire` never advances to deletion; use `--purge` explicitly. If in-place
+mapping restamping succeeded before its checkpoint was created, repeat `--apply --in-place` after
+resolving any residual lock; exact mapping and identity checks allow that intermediate state.
+
+## Large datasets and deployment automation
+
+Both rebuild and in-place backfill scale with the documents scanned, projected, transferred, and
+indexed. Measure a representative payload and real resource limits; a fast small synthetic dataset
+does not establish production duration. Use bounded `--batch-size`, `--bulk-max-bytes`, and concurrency
+options in `scripts/elasticsearchReindex/options.ts`. `--max-batches-per-entity` bounds a rehearsal or pause; exit
+code zero alone does not mean the backfill is complete.
+
+For Docker self-hosting, startup migration is a blocking maintenance step, not an image-build step.
+The application and manual migration tool must share the same durable `ES_REINDEX_STATE_DIR`.
+The official Compose file mounts the existing reindex volume on both. Do not silently adopt indexes
+after checkpoint loss or steal a retained lock: restore progress and use explicit owner recovery
+after confirming the old process and uncertain requests have stopped. Keep the separate continuous
+sync worker running on the same application version after startup.
+
+For large hosted deployments, keep the existing explicit migration workflow and isolated preview
+targets. Retain completion/fingerprint/Outbox gates before promotion; starting a migration does not
+mean the migration or traffic switch is complete. No durable task orchestration is supplied here.
+
+## Local Docker rehearsal
+
+Run the relevant existing reindex, mapping, and sync tests for behavioral changes. For operational
+claims about generation migration, exercise the real CLI and sync runtime against isolated Docker
+PostgreSQL and Elasticsearch with the required ICU plugin. Scope the rehearsal to the changed
+behavior; do not require all cases for an unrelated edit. Use synthetic data and record the source
+revision, any future-version fixture override, process identities, checkpoint directory, commands,
+and raw results. Cover the applicable cases:
+
+- A multi-batch dataset: stop after a bounded batch, start a new process with the same checkpoint,
+ and verify the same run ID, advancing cursor, and final active-document count.
+- A completed repeat with source data static and sync inactive: compare per-session bulk events and
+ ES indexing counters. Test a missing checkpoint separately; do not call its error a no-op.
+- A per-entity upgrade with source insert/update/delete while backfilling: verify both generations,
+ per-generation field pruning, and the unchanged live alias before promotion. Prove pending work
+ blocks promotion, then drain and verify only the selected alias switches.
+- Rollback while the previous generation remains available; close, fresh target-resolution cycle,
+ and delete after returning to the declared generation.
+- Additive in-place upgrade: same physical index, populated new field, cross-process resume, and no
+ bulk writes on completed repeat. Check run progress as well as metadata.
+- For deployment/concurrency changes, run same-directory and different-directory workers and report
+ duplicate work or identity rejection separately from data correctness.
+
+Keep deleted-document tombstones separate from active search counts. Do not infer crash-window
+recovery, uninterrupted search under load, or hosted build persistence from a normal bounded pause.
+Report measured payload size and timings without extrapolating a production completion time.
diff --git a/.github/scripts/check-fts-mapping-history.mjs b/.github/scripts/check-fts-mapping-history.mjs
new file mode 100644
index 00000000000..63d4302e9b3
--- /dev/null
+++ b/.github/scripts/check-fts-mapping-history.mjs
@@ -0,0 +1,215 @@
+import { execFile } from 'node:child_process';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { isDeepStrictEqual, promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+
+const MIGRATION_ROOT = 'packages/database/src/repositories/ftsSearchDocument/migration';
+const SNAPSHOTS_PATH =
+ 'packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.json';
+const MIGRATION_ID_PATTERN = /^(\d{4})-.+/;
+
+export class FtsMappingHistoryError extends Error {
+ constructor(violations) {
+ super(
+ `FTS mapping history is not append-only:\n${violations.map((item) => `- ${item}`).join('\n')}`,
+ );
+ this.name = 'FtsMappingHistoryError';
+ this.violations = violations;
+ }
+}
+
+const git = async (repoRoot, args) => {
+ const { stdout } = await execFileAsync('git', args, {
+ cwd: repoRoot,
+ encoding: 'utf8',
+ });
+ return stdout.trim();
+};
+
+const gitObjectExists = async (repoRoot, object) => {
+ try {
+ await git(repoRoot, ['cat-file', '-e', object]);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const assertCommitExists = async (repoRoot, revision) => {
+ if (!(await gitObjectExists(repoRoot, `${revision}^{commit}`))) {
+ throw new Error(`Git revision ${revision} is not available as a commit`);
+ }
+};
+
+const listMigrationDirectories = async (repoRoot, revision) => {
+ if (!(await gitObjectExists(repoRoot, `${revision}:${MIGRATION_ROOT}`))) return [];
+
+ const output = await git(repoRoot, [
+ 'ls-tree',
+ '-d',
+ '--name-only',
+ `${revision}:${MIGRATION_ROOT}`,
+ ]);
+
+ return output.split('\n').filter(Boolean).sort();
+};
+
+const readSnapshots = async (repoRoot, revision) => {
+ if (!(await gitObjectExists(repoRoot, `${revision}:${SNAPSHOTS_PATH}`))) {
+ return { exists: false, value: {} };
+ }
+
+ const source = await git(repoRoot, ['show', `${revision}:${SNAPSHOTS_PATH}`]);
+ let value;
+ try {
+ value = JSON.parse(source);
+ } catch (error) {
+ throw new Error(`${SNAPSHOTS_PATH} is not valid JSON at ${revision}: ${error.message}`, {
+ cause: error,
+ });
+ }
+
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error(`${SNAPSHOTS_PATH} must contain a JSON object at ${revision}`);
+ }
+
+ return { exists: true, value };
+};
+
+const ordinalOf = (migrationId) => Number.parseInt(MIGRATION_ID_PATTERN.exec(migrationId)[1], 10);
+
+const findDuplicateOrdinals = (migrationIds) => {
+ const idsByOrdinal = new Map();
+ for (const migrationId of migrationIds) {
+ const ordinal = ordinalOf(migrationId);
+ idsByOrdinal.set(ordinal, [...(idsByOrdinal.get(ordinal) ?? []), migrationId]);
+ }
+
+ return [...idsByOrdinal.values()].filter((ids) => ids.length > 1);
+};
+
+export const checkFtsMappingHistory = async ({ baseRevision, headRevision = 'HEAD', repoRoot }) => {
+ await Promise.all([
+ assertCommitExists(repoRoot, baseRevision),
+ assertCommitExists(repoRoot, headRevision),
+ ]);
+
+ const [baseDirectories, headDirectories, baseSnapshotState, headSnapshotState] =
+ await Promise.all([
+ listMigrationDirectories(repoRoot, baseRevision),
+ listMigrationDirectories(repoRoot, headRevision),
+ readSnapshots(repoRoot, baseRevision),
+ readSnapshots(repoRoot, headRevision),
+ ]);
+
+ const violations = [];
+ const baseSnapshots = baseSnapshotState.value;
+ const headSnapshots = headSnapshotState.value;
+ const baseMigrationIds = baseDirectories.filter((entry) => MIGRATION_ID_PATTERN.test(entry));
+ const headMigrationIds = headDirectories.filter((entry) => MIGRATION_ID_PATTERN.test(entry));
+ const baseDirectorySet = new Set(baseDirectories);
+
+ for (const directory of headDirectories) {
+ if (!baseDirectorySet.has(directory) && !MIGRATION_ID_PATTERN.test(directory)) {
+ violations.push(
+ `new migration directory ${directory} must start with a unique four-digit ordinal`,
+ );
+ }
+ }
+
+ const headMigrationIdSet = new Set(headMigrationIds);
+ const baseMigrationIdSet = new Set(baseMigrationIds);
+
+ for (const migrationId of baseMigrationIds) {
+ if (!headMigrationIdSet.has(migrationId)) {
+ violations.push(`published migration directory ${migrationId} was deleted or renamed`);
+ continue;
+ }
+
+ const changes = await git(repoRoot, [
+ 'diff',
+ '--name-status',
+ baseRevision,
+ headRevision,
+ '--',
+ `${MIGRATION_ROOT}/${migrationId}`,
+ ]);
+ if (changes) {
+ violations.push(
+ `published migration directory ${migrationId} changed:\n ${changes.replaceAll('\n', '\n ')}`,
+ );
+ }
+ }
+
+ const newMigrationIds = headMigrationIds.filter((id) => !baseMigrationIdSet.has(id));
+ const maximumBaseOrdinal = Math.max(-1, ...baseMigrationIds.map(ordinalOf));
+
+ for (const migrationId of newMigrationIds) {
+ if (ordinalOf(migrationId) <= maximumBaseOrdinal) {
+ violations.push(
+ `new migration ${migrationId} must use an ordinal greater than ${String(maximumBaseOrdinal).padStart(4, '0')}`,
+ );
+ }
+ }
+
+ for (const duplicateIds of findDuplicateOrdinals(headMigrationIds)) {
+ violations.push(`migration ordinal is duplicated by ${duplicateIds.join(', ')}`);
+ }
+
+ for (const [migrationId, snapshot] of Object.entries(baseSnapshots)) {
+ if (!Object.hasOwn(headSnapshots, migrationId)) {
+ violations.push(`published snapshot batch ${migrationId} was deleted or renamed`);
+ } else if (!isDeepStrictEqual(headSnapshots[migrationId], snapshot)) {
+ violations.push(`published snapshot batch ${migrationId} changed`);
+ }
+ }
+
+ const baseSnapshotIds = new Set(Object.keys(baseSnapshots));
+ const newSnapshotIds = Object.keys(headSnapshots).filter((id) => !baseSnapshotIds.has(id));
+ const newMigrationIdSet = new Set(newMigrationIds);
+ const newSnapshotIdSet = new Set(newSnapshotIds);
+
+ for (const migrationId of newMigrationIds) {
+ if (!newSnapshotIdSet.has(migrationId)) {
+ violations.push(`new migration ${migrationId} has no new snapshot batch`);
+ }
+ }
+ for (const snapshotId of newSnapshotIds) {
+ const bootstrapsFrozenMigration =
+ !baseSnapshotState.exists && baseMigrationIdSet.has(snapshotId);
+ if (!newMigrationIdSet.has(snapshotId) && !bootstrapsFrozenMigration) {
+ violations.push(`new snapshot batch ${snapshotId} has no new migration directory`);
+ }
+ }
+
+ if (violations.length > 0) throw new FtsMappingHistoryError(violations);
+
+ return { newMigrationIds, newSnapshotIds };
+};
+
+const isDirectRun =
+ process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
+
+if (isDirectRun) {
+ const [baseRevision, headRevision = 'HEAD'] = process.argv.slice(2);
+ if (!baseRevision) {
+ console.error('Usage: node check-fts-mapping-history.mjs <base-revision> [head-revision]');
+ process.exitCode = 2;
+ } else {
+ try {
+ const result = await checkFtsMappingHistory({
+ baseRevision,
+ headRevision,
+ repoRoot: process.cwd(),
+ });
+ console.log(
+ `FTS mapping history is append-only (${result.newMigrationIds.length} new migration batch(es)).`,
+ );
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : error);
+ process.exitCode = 1;
+ }
+ }
+}
diff --git a/.github/scripts/check-fts-mapping-history.test.mjs b/.github/scripts/check-fts-mapping-history.test.mjs
new file mode 100644
index 00000000000..0f7a2e743b9
--- /dev/null
+++ b/.github/scripts/check-fts-mapping-history.test.mjs
@@ -0,0 +1,199 @@
+import assert from 'node:assert/strict';
+import { execFile } from 'node:child_process';
+import { mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { test } from 'node:test';
+import { promisify } from 'node:util';
+
+import { checkFtsMappingHistory } from './check-fts-mapping-history.mjs';
+
+const execFileAsync = promisify(execFile);
+const migrationRoot = 'packages/database/src/repositories/ftsSearchDocument/migration';
+const snapshotsPath =
+ 'packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.json';
+
+const git = async (repoRoot, args) => {
+ const { stdout } = await execFileAsync('git', args, { cwd: repoRoot, encoding: 'utf8' });
+ return stdout.trim();
+};
+
+const writeRepoFile = async (repoRoot, relativePath, contents) => {
+ const filePath = path.join(repoRoot, relativePath);
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, contents);
+};
+
+const writeSnapshots = async (repoRoot, snapshots) =>
+ writeRepoFile(repoRoot, snapshotsPath, `${JSON.stringify(snapshots, null, 2)}\n`);
+
+const commit = async (repoRoot, message) => {
+ await git(repoRoot, ['add', '--all']);
+ await git(repoRoot, ['commit', '-q', '-m', message]);
+ return git(repoRoot, ['rev-parse', 'HEAD']);
+};
+
+const addMigration = async (repoRoot, migrationId, marker = migrationId) => {
+ await writeRepoFile(
+ repoRoot,
+ `${migrationRoot}/${migrationId}/mapping.ts`,
+ `export const marker = '${marker}';\n`,
+ );
+ await writeRepoFile(
+ repoRoot,
+ `${migrationRoot}/${migrationId}/fields.ts`,
+ `export const field = '${marker}';\n`,
+ );
+};
+
+const createRepository = async (t, { withInitialMigration = true, withSnapshots = true } = {}) => {
+ const repoRoot = await mkdtemp(path.join(os.tmpdir(), 'fts-mapping-history-'));
+ t.after(() => rm(repoRoot, { force: true, recursive: true }));
+
+ await git(repoRoot, ['init', '-q']);
+ await git(repoRoot, ['config', 'user.email', '[email protected]']);
+ await git(repoRoot, ['config', 'user.name', 'Test']);
+
+ if (withInitialMigration) {
+ await addMigration(repoRoot, '0000-initial');
+ if (withSnapshots) {
+ await writeSnapshots(repoRoot, {
+ '0000-initial': { messages: { fingerprint: 'initial', schemaVersion: 1 } },
+ });
+ }
+ } else {
+ await writeRepoFile(repoRoot, 'README.md', 'bootstrap\n');
+ }
+
+ const baseRevision = await commit(repoRoot, 'base');
+ return { baseRevision, repoRoot };
+};
+
+test('allows the first migration catalog to bootstrap when the base has none', async (t) => {
+ const { baseRevision, repoRoot } = await createRepository(t, { withInitialMigration: false });
+ await addMigration(repoRoot, '0000-initial');
+ await writeSnapshots(repoRoot, {
+ '0000-initial': { messages: { fingerprint: 'initial', schemaVersion: 1 } },
+ });
+ await commit(repoRoot, 'bootstrap catalog');
+
+ const result = await checkFtsMappingHistory({ baseRevision, repoRoot });
+
+ assert.deepEqual(result, {
+ newMigrationIds: ['0000-initial'],
+ newSnapshotIds: ['0000-initial'],
+ });
+});
+
+test('allows JSON snapshots to bootstrap for frozen migrations when the base file is absent', async (t) => {
+ const { baseRevision, repoRoot } = await createRepository(t, { withSnapshots: false });
+ await writeSnapshots(repoRoot, {
+ '0000-initial': { messages: { fingerprint: 'initial', schemaVersion: 1 } },
+ });
+ await commit(repoRoot, 'bootstrap snapshots');
+
+ const result = await checkFtsMappingHistory({ baseRevision, repoRoot });
+
+ assert.deepEqual(result, {
+ newMigrationIds: [],
+ newSnapshotIds: ['0000-initial'],
+ });
+});
+
+test('does not bootstrap frozen migrations when the base already has a snapshot file', async (t) => {
+ const { repoRoot } = await createRepository(t, { withSnapshots: false });
+ await writeSnapshots(repoRoot, {});
+ const emptySnapshotRevision = await commit(repoRoot, 'publish empty snapshots');
+ await writeSnapshots(repoRoot, {
+ '0000-initial': { messages: { fingerprint: 'initial', schemaVersion: 1 } },
+ });
+ await commit(repoRoot, 'backfill published snapshots');
+
+ await assert.rejects(
+ checkFtsMappingHistory({ baseRevision: emptySnapshotRevision, repoRoot }),
+ /new snapshot batch 0000-initial has no new migration directory/,
+ );
+});
+
+test('allows higher migration ordinals with matching snapshot batches', async (t) => {
+ const { baseRevision, repoRoot } = await createRepository(t);
+ await addMigration(repoRoot, '0001-add-language');
+ await writeSnapshots(repoRoot, {
+ '0000-initial': { messages: { fingerprint: 'initial', schemaVersion: 1 } },
+ '0001-add-language': { messages: { fingerprint: 'language', schemaVersion: 2 } },
+ });
+ await commit(repoRoot, 'append migration');
+
+ const result = await checkFtsMappingHistory({ baseRevision, repoRoot });
+
+ assert.deepEqual(result.newMigrationIds, ['0001-add-language']);
+});
+
+test('rejects changes and additions inside a published migration directory', async (t) => {
+ const { baseRevision, repoRoot } = await createRepository(t);
+ await writeRepoFile(
+ repoRoot,
+ `${migrationRoot}/0000-initial/mapping.ts`,
+ "export const marker = 'changed';\n",
+ );
+ await writeRepoFile(repoRoot, `${migrationRoot}/0000-initial/analysis.ts`, 'export {};\n');
+ await commit(repoRoot, 'change published migration');
+
+ await assert.rejects(
+ checkFtsMappingHistory({ baseRevision, repoRoot }),
+ /published migration directory 0000-initial changed/,
+ );
+});
+
+test('rejects deleting or renaming a published migration directory', async (t) => {
+ const { baseRevision, repoRoot } = await createRepository(t);
+ await rename(
+ path.join(repoRoot, migrationRoot, '0000-initial'),
+ path.join(repoRoot, migrationRoot, '0001-renamed'),
+ );
+ await writeSnapshots(repoRoot, {
+ '0001-renamed': { messages: { fingerprint: 'initial', schemaVersion: 1 } },
+ });
+ await commit(repoRoot, 'rename published migration');
+
+ await assert.rejects(
+ checkFtsMappingHistory({ baseRevision, repoRoot }),
+ /published migration directory 0000-initial was deleted or renamed/,
+ );
+});
+
+test('rejects modifying a published snapshot batch, including adding an entity', async (t) => {
+ const { baseRevision, repoRoot } = await createRepository(t);
+ await writeSnapshots(repoRoot, {
+ '0000-initial': {
+ messages: { fingerprint: 'changed', schemaVersion: 1 },
+ topics: { fingerprint: 'added', schemaVersion: 1 },
+ },
+ });
+ await commit(repoRoot, 'change published snapshots');
+
+ await assert.rejects(
+ checkFtsMappingHistory({ baseRevision, repoRoot }),
+ /published snapshot batch 0000-initial changed/,
+ );
+});
+
+test('rejects reused ordinals and snapshots without matching migration directories', async (t) => {
+ const { baseRevision, repoRoot } = await createRepository(t);
+ await addMigration(repoRoot, '0000-second');
+ await addMigration(repoRoot, 'missing-ordinal');
+ await writeSnapshots(repoRoot, {
+ '0000-initial': { messages: { fingerprint: 'initial', schemaVersion: 1 } },
+ '0000-second': { messages: { fingerprint: 'second', schemaVersion: 2 } },
+ '0001-orphan': { topics: { fingerprint: 'orphan', schemaVersion: 1 } },
+ });
+ await commit(repoRoot, 'reuse ordinal');
+
+ await assert.rejects(checkFtsMappingHistory({ baseRevision, repoRoot }), (error) => {
+ assert.match(error.message, /new migration 0000-second must use an ordinal greater than 0000/);
+ assert.match(error.message, /new migration directory missing-ordinal must start/);
+ assert.match(error.message, /migration ordinal is duplicated/);
+ assert.match(error.message, /new snapshot batch 0001-orphan has no new migration directory/);
+ return true;
+ });
+});
diff --git a/.github/workflows/fts-search-mapping-history.yml b/.github/workflows/fts-search-mapping-history.yml
new file mode 100644
index 00000000000..c3f17ad870a
--- /dev/null
+++ b/.github/workflows/fts-search-mapping-history.yml
@@ -0,0 +1,31 @@
+name: FTS Search Mapping History
+
+on:
+ pull_request:
+ types: [opened, synchronize, reopened, edited]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: fts-search-mapping-history-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+jobs:
+ verify:
+ name: Verify Append-Only History
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout pull request merge
+ uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+ persist-credentials: false
+
+ - name: Test history guard
+ run: node --test .github/scripts/check-fts-mapping-history.test.mjs
+
+ - name: Verify history against pull request base
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ run: node .github/scripts/check-fts-mapping-history.mjs "$BASE_SHA" HEAD
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.test.ts b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
index 96a764aca3a..e8f352d09f8 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.test.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
@@ -1,6 +1,12 @@
// @vitest-environment node
import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ FTS_SEARCH_INDEX_DEFINITIONS,
+ getFtsSearchIndexSchemaFingerprint,
+ getFtsSearchIndexSchemaVersion,
+} from '@/database/repositories/ftsSearchDocument';
+
import { ElasticsearchFtsSearchHttpClient } from './elasticsearch';
const mocks = vi.hoisted(() => ({
@@ -17,6 +23,33 @@ afterEach(() => {
vi.clearAllMocks();
});
+/** Identity response body for a physical index that implements the declared generation of `entity`. */
+const identityIndex = (
+ entity: 'agents' | 'topics',
+ uuid: string,
+ meta: Partial<Record<'reindex_run_id' | 'schema_fingerprint' | 'schema_version', unknown>> = {},
+) => ({
+ mappings: {
+ _meta: {
+ reindex_run_id: '00000000-0000-4000-8000-000000000001',
+ schema_fingerprint: getFtsSearchIndexSchemaFingerprint(entity),
+ schema_version: getFtsSearchIndexSchemaVersion(entity),
+ ...meta,
+ },
+ dynamic: 'strict',
+ properties: {
+ id: { type: 'keyword' },
+ fts_search_sync_deleted: { type: 'boolean' },
+ },
+ },
+ settings: {
+ index: {
+ analysis: { analyzer: { lobehub_icu: { type: 'custom' } } },
+ uuid,
+ },
+ },
+});
+
describe('ElasticsearchFtsSearchHttpClient', () => {
it('rejects remote HTTP endpoints before exposing the API key', () => {
expect(
@@ -85,7 +118,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
expect(Object.keys(init.headers)).not.toContain('Authorization');
});
- it('returns no write targets without making requests when no aliases are provided', async () => {
+ it('returns no identities without making requests when no aliases are provided', async () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const client = new ElasticsearchFtsSearchHttpClient({
@@ -93,7 +126,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
url: 'https://search.example.com',
});
- await expect(client.getFtsSearchSyncWriteTargets([])).resolves.toEqual({});
+ await expect(client.getFtsSearchSyncIndexIdentities([])).resolves.toEqual({});
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -325,7 +358,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
);
});
- it('sends bulk payloads to the alias-only endpoint', async () => {
+ it('sends bulk payloads addressed to physical generation indexes', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ errors: false, items: [{ index: { status: 201 } }] }), {
headers: { 'Content-Type': 'application/json' },
@@ -345,7 +378,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
items: [{ index: { status: 201 } }],
});
expect(fetchMock).toHaveBeenCalledWith(
- new URL('https://search.example.com/_bulk?require_alias=true'),
+ new URL('https://search.example.com/_bulk'),
expect.objectContaining({
body,
headers: {
@@ -357,29 +390,22 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
);
});
- it('verifies writable aliases and their soft-delete mappings before synchronization', async () => {
+ it('lists every live generation behind each alias, including the writable index', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
Response.json({
- 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
- 'lobehub-topics-v2': {
- aliases: { 'lobehub-topics': { is_write_index: true } },
- },
+ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': { is_write_index: true } } },
+ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': { is_write_index: false } } },
+ 'custom-topics': { aliases: { 'lobehub-topics': {} } },
}),
)
.mockResolvedValueOnce(
Response.json({
- 'lobehub-agents-v2': {
- mappings: {
- properties: { fts_search_sync_deleted: { type: 'boolean' } },
- },
- },
- 'lobehub-topics-v2': {
- mappings: {
- properties: { fts_search_sync_deleted: { type: 'boolean' } },
- },
- },
+ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': { is_write_index: false } } },
+ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': { is_write_index: true } } },
+ 'lobehub-agents-v3': { aliases: {} },
+ 'lobehub-agents-v3-backup': { aliases: {} },
}),
);
vi.stubGlobal('fetch', fetchMock);
@@ -389,106 +415,129 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
});
await expect(
- client.assertFtsSearchSyncAliases(['lobehub-agents', 'lobehub-topics']),
- ).resolves.toBeUndefined();
+ client.getFtsSearchSyncGenerationTargets(['lobehub-topics', 'lobehub-agents']),
+ ).resolves.toEqual({
+ 'lobehub-agents': ['lobehub-agents-v1', 'lobehub-agents-v2', 'lobehub-agents-v3'],
+ 'lobehub-topics': ['custom-topics'],
+ });
expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
- 'https://search.example.com/_alias/lobehub-agents,lobehub-topics',
- 'https://search.example.com/lobehub-agents-v2,lobehub-topics-v2?filter_path=*.mappings.properties.fts_search_sync_deleted',
+ 'https://search.example.com/_alias/lobehub-topics,lobehub-agents',
+ 'https://search.example.com/lobehub-topics-v*,lobehub-agents-v*/_alias?expand_wildcards=open&allow_no_indices=true',
]);
});
- it('returns writable physical indices in stable alias order', async () => {
+ it('refuses generation targets for an alias without a unique writable index', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce(
Response.json({
+ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
- 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } },
}),
)
- .mockResolvedValueOnce(
- Response.json({
- 'lobehub-agents-v2': {
- mappings: {
- properties: { fts_search_sync_deleted: { type: 'boolean' } },
- },
- },
- 'lobehub-topics-v2': {
- mappings: {
- properties: { fts_search_sync_deleted: { type: 'boolean' } },
- },
- },
- }),
- ),
+ .mockResolvedValueOnce(Response.json({})),
);
const client = new ElasticsearchFtsSearchHttpClient({
apiKey: 'test-api-key',
url: 'https://search.example.com',
});
- const writeTargets = await client.getFtsSearchSyncWriteTargets([
- 'lobehub-topics',
- 'lobehub-agents',
- ]);
+ await expect(client.getFtsSearchSyncGenerationTargets(['lobehub-agents'])).rejects.toThrow(
+ 'is not a writable alias: lobehub-agents',
+ );
+ });
- expect(writeTargets).toEqual({
- 'lobehub-agents': 'lobehub-agents-v2',
- 'lobehub-topics': 'lobehub-topics-v2',
+ it('verifies sync readiness from one alias lookup and its complete index identity', async () => {
+ const aliasResponse = () =>
+ Response.json({
+ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
+ 'lobehub-topics-v1': {
+ aliases: { 'lobehub-topics': { is_write_index: true } },
+ },
+ });
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(aliasResponse())
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v1': identityIndex('agents', 'agents-index-uuid'),
+ 'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid'),
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
});
- expect(Object.keys(writeTargets)).toEqual(['lobehub-agents', 'lobehub-topics']);
+
+ await expect(
+ client.assertFtsSearchSyncAliases(['lobehub-agents', 'lobehub-topics']),
+ ).resolves.toBeUndefined();
+ expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
+ 'https://search.example.com/_alias/lobehub-agents,lobehub-topics',
+ 'https://search.example.com/lobehub-agents-v1,lobehub-topics-v1?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid',
+ ]);
});
- it('returns stable runtime identities for indices from one reindex run', async () => {
- const reindexRunId = '00000000-0000-4000-8000-000000000001';
+ it.each(['missing', 'keyword'])(
+ 'rejects sync readiness with a %s tombstone mapping',
+ async (type) => {
+ const identity = identityIndex('agents', 'agents-index-uuid');
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v1': {
+ ...identity,
+ mappings: {
+ ...identity.mappings,
+ properties: type === 'missing' ? {} : { fts_search_sync_deleted: { type } },
+ },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.assertFtsSearchSyncAliases(['lobehub-agents'])).rejects.toThrow(
+ 'Elasticsearch full-text search sync alias lacks a boolean fts_search_sync_deleted mapping: lobehub-agents',
+ );
+ },
+ );
+
+ it('returns stable runtime identities for indices that implement the declared generations', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
Response.json({
- 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
- 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } },
+ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
+ 'lobehub-topics-v1': { aliases: { 'lobehub-topics': {} } },
}),
)
.mockResolvedValueOnce(
Response.json({
- 'lobehub-agents-v2': {
- mappings: {
- _meta: { reindex_run_id: reindexRunId, schema_version: 2 },
- dynamic: 'strict',
- properties: {
- id: { type: 'keyword' },
- fts_search_sync_deleted: { type: 'boolean' },
- },
- },
- settings: {
- index: {
- analysis: { analyzer: { lobehub_icu: { type: 'custom' } } },
- uuid: 'agents-index-uuid',
- },
- },
- },
- 'lobehub-topics-v2': {
- mappings: {
- _meta: { reindex_run_id: reindexRunId, schema_version: 2 },
- dynamic: 'strict',
- properties: {
- id: { type: 'keyword' },
- fts_search_sync_deleted: { type: 'boolean' },
- },
- },
- settings: {
- index: {
- analysis: { analyzer: { lobehub_icu: { type: 'custom' } } },
- uuid: 'topics-index-uuid',
- },
- },
- },
+ 'lobehub-agents-v1': identityIndex('agents', 'agents-index-uuid', {
+ reindex_run_id: '00000000-0000-4000-8000-000000000001',
+ }),
+ 'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid', {
+ reindex_run_id: '00000000-0000-4000-8000-000000000002',
+ }),
}),
);
vi.stubGlobal('fetch', fetchMock);
const client = new ElasticsearchFtsSearchHttpClient({
apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
url: 'https://search.example.com',
});
@@ -497,48 +546,75 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
'lobehub-agents',
]);
+ // Entities are rebuilt and promoted independently, so different reindex runs are expected.
expect(identities).toEqual({
'lobehub-agents': {
indexUuid: 'agents-index-uuid',
mappingSha256: expect.stringMatching(/^[\da-f]{64}$/),
- physicalIndex: 'lobehub-agents-v2',
- reindexRunId,
- schemaVersion: 2,
+ physicalIndex: 'lobehub-agents-v1',
+ reindexRunId: '00000000-0000-4000-8000-000000000001',
+ schemaFingerprint: getFtsSearchIndexSchemaFingerprint('agents'),
+ schemaVersion: getFtsSearchIndexSchemaVersion('agents'),
settingsSha256: expect.stringMatching(/^[\da-f]{64}$/),
},
'lobehub-topics': {
indexUuid: 'topics-index-uuid',
mappingSha256: expect.stringMatching(/^[\da-f]{64}$/),
- physicalIndex: 'lobehub-topics-v2',
- reindexRunId,
- schemaVersion: 2,
+ physicalIndex: 'lobehub-topics-v1',
+ reindexRunId: '00000000-0000-4000-8000-000000000002',
+ schemaFingerprint: getFtsSearchIndexSchemaFingerprint('topics'),
+ schemaVersion: getFtsSearchIndexSchemaVersion('topics'),
settingsSha256: expect.stringMatching(/^[\da-f]{64}$/),
},
});
expect(Object.keys(identities)).toEqual(['lobehub-agents', 'lobehub-topics']);
- expect(identities['lobehub-agents'].mappingSha256).toBe(
- identities['lobehub-topics'].mappingSha256,
- );
expect(identities['lobehub-agents'].settingsSha256).toBe(
identities['lobehub-topics'].settingsSha256,
);
expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
'https://search.example.com/_alias/lobehub-topics,lobehub-agents',
- 'https://search.example.com/lobehub-agents-v2,lobehub-topics-v2?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid',
+ 'https://search.example.com/lobehub-agents-v1,lobehub-topics-v1?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid',
]);
});
+ it('accepts a legacy index without a schema fingerprint on version alone', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v1': identityIndex('agents', 'agents-index-uuid', {
+ schema_fingerprint: undefined,
+ }),
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-agents'])).resolves.toEqual({
+ 'lobehub-agents': expect.objectContaining({ schemaFingerprint: null }),
+ });
+ });
+
it('rejects a runtime identity response with missing reindex metadata', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce(
- Response.json({ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } } }),
+ Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
)
.mockResolvedValueOnce(
Response.json({
- 'lobehub-agents-v2': {
+ 'lobehub-agents-v1': {
mappings: {
properties: { fts_search_sync_deleted: { type: 'boolean' } },
sensitive_payload: 'must-not-leak',
@@ -550,6 +626,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
);
const client = new ElasticsearchFtsSearchHttpClient({
apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
url: 'https://search.example.com',
});
@@ -560,54 +637,214 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
await expect(request).rejects.not.toThrow(/test-api-key|must-not-leak/);
});
- it('rejects aliases that point to indices from different reindex runs', async () => {
+ it('accepts an alias that still serves an older generation while the upgrade is in progress', async () => {
+ const liveVersion = getFtsSearchIndexSchemaVersion('topics');
+ const definition = FTS_SEARCH_INDEX_DEFINITIONS.topics as unknown as { schemaVersion: number };
+ // Every entity declares v1 today; pretend the deployed code moved topics one generation ahead.
+ definition.schemaVersion = liveVersion + 1;
+ try {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({ 'lobehub-topics-v1': { aliases: { 'lobehub-topics': {} } } }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid', {
+ schema_fingerprint: 'older-generation',
+ schema_version: liveVersion,
+ }),
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.getFtsSearchSyncIndexIdentities(['lobehub-topics']),
+ ).resolves.toMatchObject({ 'lobehub-topics': { schemaVersion: liveVersion } });
+ } finally {
+ definition.schemaVersion = liveVersion;
+ }
+ });
+
+ it('rejects an alias whose live index implements a newer schema version than the code', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce(
- Response.json({
- 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
- 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } },
- }),
+ Response.json({ 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } } }),
)
.mockResolvedValueOnce(
Response.json({
- 'lobehub-agents-v2': {
- mappings: {
- _meta: {
- reindex_run_id: '00000000-0000-4000-8000-000000000001',
- schema_version: 2,
- },
- properties: { fts_search_sync_deleted: { type: 'boolean' } },
- },
- settings: { index: { analysis: {}, uuid: 'agents-index-uuid' } },
+ 'lobehub-topics-v2': identityIndex('topics', 'topics-index-uuid', {
+ schema_version: getFtsSearchIndexSchemaVersion('topics') + 1,
+ }),
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-topics'])).rejects.toThrow(
+ `Elasticsearch full-text search alias lobehub-topics implements schema version ${getFtsSearchIndexSchemaVersion('topics') + 1} but the deployed code declares v${getFtsSearchIndexSchemaVersion('topics')}`,
+ );
+ });
+
+ it('lists the mapped fields of every generation index', async () => {
+ const fetchMock = vi.fn().mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-topics-v1': {
+ mappings: { properties: { id: { type: 'keyword' }, title: { type: 'text' } } },
+ },
+ 'lobehub-topics-v2': {
+ mappings: {
+ properties: {
+ id: { type: 'keyword' },
+ content: { type: 'text' },
+ title: { type: 'text' },
},
- 'lobehub-topics-v2': {
- mappings: {
- _meta: {
- reindex_run_id: '00000000-0000-4000-8000-000000000002',
- schema_version: 2,
- },
- properties: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.getFtsSearchSyncIndexFields({
+ 'lobehub-topics-v1': 'topics',
+ 'lobehub-topics-v2': 'topics',
+ }),
+ ).resolves.toEqual({
+ fieldsByIndex: {
+ 'lobehub-topics-v1': ['id', 'title'],
+ 'lobehub-topics-v2': ['content', 'id', 'title'],
+ },
+ incompatibilities: [],
+ });
+ expect(fetchMock.mock.calls[0][0].toString()).toBe(
+ 'https://search.example.com/lobehub-topics-v1,lobehub-topics-v2/_mapping?filter_path=*.mappings.properties',
+ );
+ });
+
+ it('rejects a field lookup that omits a requested generation index', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-topics-v1': { mappings: { properties: { id: { type: 'keyword' } } } },
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.getFtsSearchSyncIndexFields({
+ 'lobehub-topics-v1': 'topics',
+ 'lobehub-topics-v2': 'topics',
+ }),
+ ).rejects.toThrow('field lookup is missing index lobehub-topics-v2');
+ });
+
+ it('reports a generation that requires a field missing from the current projection', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v1': {
+ mappings: {
+ properties: {
+ id: { type: 'keyword' },
+ legacy_title: { type: 'text' },
},
- settings: { index: { analysis: {}, uuid: 'topics-index-uuid' } },
},
+ },
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.getFtsSearchSyncIndexFields({ 'lobehub-agents-v1': 'agents' }),
+ ).resolves.toEqual({
+ fieldsByIndex: {
+ 'lobehub-agents-v1': ['id', 'legacy_title'],
+ },
+ incompatibilities: [
+ {
+ entity: 'agents',
+ index: 'lobehub-agents-v1',
+ message:
+ 'Elasticsearch full-text search index lobehub-agents-v1 is incompatible with the current agents projection: target field legacy_title (text) is missing from the current mapping. Retain compatible source fields in FTS_SEARCH_RETAINED_SOURCE_PROPERTIES and the document builder, or retire the index before syncing agents.',
+ },
+ ],
+ });
+ });
+
+ it('rejects an alias whose live index was built from a drifted mapping of the same version', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({ 'lobehub-topics-v1': { aliases: { 'lobehub-topics': {} } } }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid', {
+ schema_fingerprint: 'f'.repeat(64),
+ }),
}),
),
);
const client = new ElasticsearchFtsSearchHttpClient({
apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
url: 'https://search.example.com',
});
- await expect(
- client.getFtsSearchSyncIndexIdentities(['lobehub-agents', 'lobehub-topics']),
- ).rejects.toThrow(
- 'Elasticsearch full-text search sync aliases do not share one reindex run identity',
+ await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-topics'])).rejects.toThrow(
+ 'Elasticsearch full-text search alias lobehub-topics was built from a different v1 mapping than the deployed code declares',
);
});
+ it('rejects identity validation without an index namespace or with a foreign alias', async () => {
+ vi.stubGlobal('fetch', vi.fn());
+
+ await expect(
+ new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ }).getFtsSearchSyncIndexIdentities(['lobehub-topics']),
+ ).rejects.toThrow('index namespace is required');
+ await expect(
+ new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
+ }).getFtsSearchSyncIndexIdentities(['other-topics']),
+ ).rejects.toThrow('alias does not belong to the configured index namespace: other-topics');
+ });
+
it('selects the unique explicit write index for a multi-target alias', async () => {
vi.stubGlobal(
'fetch',
@@ -625,22 +862,21 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
)
.mockResolvedValueOnce(
Response.json({
- 'lobehub-agents-v2': {
- mappings: {
- properties: { fts_search_sync_deleted: { type: 'boolean' } },
- },
- },
+ 'lobehub-agents-v2': identityIndex('agents', 'agents-index-uuid'),
}),
),
);
const client = new ElasticsearchFtsSearchHttpClient({
apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
url: 'https://search.example.com',
});
- await expect(client.getFtsSearchSyncWriteTargets(['lobehub-agents'])).resolves.toEqual({
- 'lobehub-agents': 'lobehub-agents-v2',
- });
+ await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-agents'])).resolves.toMatchObject(
+ {
+ 'lobehub-agents': { physicalIndex: 'lobehub-agents-v2' },
+ },
+ );
});
it('rejects a multi-target alias without an explicit write index', async () => {
@@ -653,32 +889,13 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
vi.stubGlobal('fetch', fetchMock);
const client = new ElasticsearchFtsSearchHttpClient({
apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
url: 'https://search.example.com',
});
- await expect(client.getFtsSearchSyncWriteTargets(['lobehub-agents'])).rejects.toThrow(
+ await expect(client.assertFtsSearchSyncAliases(['lobehub-agents'])).rejects.toThrow(
'Elasticsearch full-text search sync destination is not a writable alias: lobehub-agents',
);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
-
- it('rejects an alias whose write index lacks the soft-delete mapping', async () => {
- vi.stubGlobal(
- 'fetch',
- vi
- .fn()
- .mockResolvedValueOnce(
- Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
- )
- .mockResolvedValueOnce(Response.json({ 'lobehub-agents-v1': { mappings: {} } })),
- );
- const client = new ElasticsearchFtsSearchHttpClient({
- apiKey: 'test-api-key',
- url: 'https://search.example.com',
- });
-
- await expect(client.getFtsSearchSyncWriteTargets(['lobehub-agents'])).rejects.toThrow(
- 'Elasticsearch full-text search sync alias lacks a boolean fts_search_sync_deleted mapping: lobehub-agents',
- );
- });
});
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.ts b/apps/server/src/services/ftsSearch/elasticsearch.ts
index 8476cd1a7e0..26c2848aad6 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.ts
@@ -1,5 +1,4 @@
import { Buffer } from 'node:buffer';
-import { createHash } from 'node:crypto';
import { trace } from '@lobechat/observability-otel/api';
import { z } from 'zod';
@@ -10,6 +9,15 @@ import type {
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,
+ sha256Json,
+} from '@/database/repositories/ftsSearchDocument';
+import type { FtsSearchTargetMappingProperties } from '@/database/repositories/ftsSearchDocument/projectionCompatibility';
+import { getFtsSearchProjectionCompatibility } from '@/database/repositories/ftsSearchDocument/projectionCompatibility';
import type {
ElasticsearchFtsSearchErrorCode,
@@ -35,15 +43,18 @@ const searchResponseSchema = z.object({
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: z.unknown().optional(), status: z.number() }),
+ index: z.object({ error: bulkItemErrorSchema.optional(), status: z.number() }),
}),
),
});
+const escapeRegExp = (value: string) => value.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`);
+
const aliasResponseSchema = z.record(
z.string(),
z.object({
@@ -58,11 +69,15 @@ const syncMappingResponseSchema = z.record(
z.string(),
z.object({
mappings: z.object({
- properties: z.record(z.string(), z.object({ type: z.string() }).passthrough()).default({}),
+ 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({
@@ -71,14 +86,11 @@ const indexIdentityResponseSchema = z.record(
_meta: z
.object({
reindex_run_id: z.string().uuid(),
+ schema_fingerprint: z.string().optional(),
schema_version: z.number().int().positive(),
})
.passthrough(),
- properties: z
- .object({
- fts_search_sync_deleted: z.object({ type: z.literal('boolean') }).passthrough(),
- })
- .passthrough(),
+ properties: z.record(z.string(), z.unknown()).default({}),
})
.passthrough(),
settings: z.object({
@@ -92,22 +104,13 @@ const indexIdentityResponseSchema = z.record(
}),
);
-const stableStringify = (value: unknown): string => {
- if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
-
- return `{${Object.entries(value)
- .sort(([leftKey], [rightKey]) => (leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0))
- .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`)
- .join(',')}}`;
-};
-
-const sha256Json = (value: unknown) =>
- createHash('sha256').update(stableStringify(value)).digest('hex');
+export interface ElasticsearchFtsSearchBulkItem {
+ index: { error?: { type?: string }; status: number };
+}
export interface ElasticsearchFtsSearchBulkResponse {
errors?: boolean;
- items: Array<{ index: { error?: unknown; status: number } }>;
+ items: ElasticsearchFtsSearchBulkItem[];
}
export interface ElasticsearchFtsSearchHttpClientOptions {
@@ -115,6 +118,8 @@ export interface ElasticsearchFtsSearchHttpClientOptions {
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;
@@ -125,10 +130,23 @@ export interface ElasticsearchFtsSearchSyncIndexIdentity {
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;
@@ -240,6 +258,7 @@ const getTraceDetails = (): {
/** 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;
@@ -247,12 +266,14 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
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;
@@ -265,14 +286,43 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
: { ...extra };
}
- /** Fails closed unless every incremental destination is a writable alias with tombstone support. */
+ /**
+ * 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.getFtsSearchSyncWriteTargets(aliases);
+ await this.getFtsSearchSyncIndexIdentities(aliases);
}
- private async getFtsSearchSyncWriteTargetMap(aliases: string[]) {
- const aliasPath = aliases.map(encodeURIComponent).join(',');
- const aliasResponse = await fetch(new URL(`/_alias/${aliasPath}`, this.url), {
+ /** 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),
@@ -300,42 +350,90 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
aliasResponse.status,
);
}
+ return aliasPayload.data;
+ }
- const writeTargets = new Map<string, string>();
- for (const alias of aliases) {
- const targets = Object.entries(aliasPayload.data).filter(([, value]) =>
- Object.hasOwn(value.aliases, alias),
- );
- const explicitWriteTargets = targets.filter(
- ([, value]) => value.aliases[alias].is_write_index === true,
+ /** 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}`,
);
- 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}`,
- );
- }
- writeTargets.set(alias, writeTarget[0]);
}
+ 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;
}
- /** Returns each alias's unique writable physical index after validating tombstone support. */
- async getFtsSearchSyncWriteTargets(aliases: string[]): Promise<Record<string, string>> {
+ /**
+ * Lists every live physical generation of each alias so incremental sync can write to all of
+ * them. Generations follow `<alias>-v<n>`; 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 writeTargets = await this.getFtsSearchSyncWriteTargetMap(aliases);
+ 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 generationPattern = new RegExp(`^${escapeRegExp(alias)}-v\\d+$`);
+ const generations = new Set(
+ Object.keys(generationTable).filter((index) => generationPattern.test(index)),
+ );
+ generations.add(writeIndex);
+ targets[alias] = [...generations].sort();
+ }
+ return targets;
+ }
- const physicalPath = [...new Set(writeTargets.values())].map(encodeURIComponent).join(',');
- const mappingResponse = await fetch(
+ /**
+ * 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(
- `/${physicalPath}?filter_path=*.mappings.properties.fts_search_sync_deleted`,
+ `/${indexes.map(encodeURIComponent).join(',')}/_mapping?filter_path=*.mappings.properties`,
this.url,
),
{
@@ -344,45 +442,68 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
signal: AbortSignal.timeout(this.requestTimeoutMs),
},
);
- if (!mappingResponse.ok) {
+ if (!response.ok) {
throw new ElasticsearchFtsSearchRequestError(
- `Elasticsearch full-text search sync mapping check failed (${mappingResponse.status})`,
- mappingResponse.status,
+ `Elasticsearch full-text search sync field lookup failed (${response.status})`,
+ response.status,
);
}
-
- const mappingPayload = syncMappingResponseSchema.safeParse(await mappingResponse.json());
- if (!mappingPayload.success) {
+ const payload = syncMappingResponseSchema.safeParse(await response.json());
+ if (!payload.success) {
throw new ElasticsearchFtsSearchRequestError(
- 'Elasticsearch full-text search sync mapping response has an invalid shape',
- mappingResponse.status,
- mappingPayload.error,
+ 'Elasticsearch full-text search sync field lookup response has an invalid shape',
+ response.status,
+ payload.error,
);
}
- for (const [alias, physicalIndex] of writeTargets) {
- const mapping =
- mappingPayload.data[physicalIndex]?.mappings.properties.fts_search_sync_deleted;
- if (mapping?.type !== 'boolean') {
+ 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 alias lacks a boolean fts_search_sync_deleted mapping: ${alias}`,
+ `Elasticsearch full-text search sync field lookup is missing index ${index}`,
);
}
+ const entity = entitiesByIndex[index];
+ 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 Object.fromEntries(
- [...writeTargets].sort(([leftAlias], [rightAlias]) =>
- leftAlias < rightAlias ? -1 : leftAlias > rightAlias ? 1 : 0,
- ),
- );
+ return { fieldsByIndex, incompatibilities };
}
- /** Returns stable runtime identities after validating aliases, soft deletes, and reindex metadata. */
+ /**
+ * 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()
@@ -432,27 +553,47 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
);
}
+ 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,
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),
});
}
- const runIdentities = new Set(
- [...identities.values()].map(({ reindexRunId, schemaVersion }) =>
- JSON.stringify([reindexRunId, schemaVersion]),
- ),
- );
- if (runIdentities.size !== 1) {
- throw new ElasticsearchFtsSearchRequestError(
- 'Elasticsearch full-text search sync aliases do not share one reindex run identity',
- );
- }
-
return Object.fromEntries(
[...identities].sort(([leftAlias], [rightAlias]) =>
leftAlias < rightAlias ? -1 : leftAlias > rightAlias ? 1 : 0,
@@ -460,8 +601,14 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
);
}
+ /**
+ * 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?require_alias=true', this.url);
+ const endpoint = new URL('/_bulk', this.url);
const response = await fetch(endpoint, {
body,
headers: this.headers({ 'Content-Type': 'application/x-ndjson' }),
diff --git a/apps/server/src/services/ftsSearchSync/service.test.ts b/apps/server/src/services/ftsSearchSync/service.test.ts
index 644f73eb33b..eff25379dd6 100644
--- a/apps/server/src/services/ftsSearchSync/service.test.ts
+++ b/apps/server/src/services/ftsSearchSync/service.test.ts
@@ -1,14 +1,24 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { FTS_SEARCH_INDEX_DEFINITIONS } from '@/database/repositories/ftsSearchDocument';
import type {
FtsSearchSyncFailure,
FtsSearchSyncWork,
} from '@/database/repositories/ftsSearchSyncOutbox';
+import type { ElasticsearchFtsSearchSyncIndexFieldsResult } from '../ftsSearch/elasticsearch';
import { ElasticsearchFtsSearchRequestError } from '../ftsSearch/elasticsearch';
import { FtsSearchSyncService } from './service';
+const ALL_DECLARED_FIELDS = [
+ ...new Set(
+ Object.values(FTS_SEARCH_INDEX_DEFINITIONS).flatMap(({ mappings }) =>
+ Object.keys(mappings.properties),
+ ),
+ ),
+];
+
const work = (documentId: string, revision: number = 1): FtsSearchSyncWork => ({
documentId,
entity: 'agents',
@@ -39,11 +49,35 @@ const createHarness = (
),
releaseMany: vi.fn(async (_items: FtsSearchSyncWork[]) => undefined),
};
- const client = { bulk: vi.fn() };
+ const client = {
+ bulk: vi.fn(),
+ getFtsSearchSyncGenerationTargets: vi.fn(async (aliases: string[]) =>
+ Object.fromEntries(aliases.map((alias) => [alias, [`${alias}-v1`]])),
+ ),
+ /** Every generation maps every declared field unless a test narrows one. */
+ getFtsSearchSyncIndexFields: vi.fn(
+ async (
+ entitiesByIndex: Record<string, string>,
+ ): Promise<ElasticsearchFtsSearchSyncIndexFieldsResult> => ({
+ fieldsByIndex: Object.fromEntries(
+ Object.keys(entitiesByIndex).map((index) => [index, ALL_DECLARED_FIELDS]),
+ ),
+ incompatibilities: [],
+ }),
+ ),
+ };
return { builder, client, outbox };
};
+/** Bulk action metadata lines of the first bulk request, in order. */
+const bulkActions = (client: { bulk: { mock: { calls: unknown[][] } } }, call = 0) =>
+ (client.bulk.mock.calls[call][0] as string)
+ .trim()
+ .split('\n')
+ .filter((_, index) => index % 2 === 0)
+ .map((line) => JSON.parse(line).index as { _id: string; _index: string; version: number });
+
describe('FtsSearchSyncService', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -147,6 +181,411 @@ describe('FtsSearchSyncService', () => {
]);
});
+ it('prunes each document to the fields its generation maps', async () => {
+ const works = [work('a', 3)];
+ const harness = createHarness(
+ works,
+ new Map([['a', { id: 'a', summary: 'added in v2', title: 'title' }]]),
+ );
+ harness.client.getFtsSearchSyncGenerationTargets.mockResolvedValue({
+ 'lobehub-test-agents': ['lobehub-test-agents-v1', 'lobehub-test-agents-v2'],
+ });
+ harness.client.getFtsSearchSyncIndexFields.mockResolvedValue({
+ fieldsByIndex: {
+ 'lobehub-test-agents-v1': ['id', 'title'],
+ 'lobehub-test-agents-v2': ['id', 'summary', 'title'],
+ },
+ incompatibilities: [],
+ });
+ harness.client.bulk.mockResolvedValue({
+ errors: false,
+ items: [201, 201].map((status) => ({ index: { status } })),
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ await service.drainOnce();
+
+ expect(harness.client.getFtsSearchSyncIndexFields).toHaveBeenCalledWith({
+ 'lobehub-test-agents-v1': 'agents',
+ 'lobehub-test-agents-v2': 'agents',
+ });
+ const sources = (harness.client.bulk.mock.calls[0][0] as string)
+ .trim()
+ .split('\n')
+ .filter((_, index) => index % 2 === 1)
+ .map((line) => JSON.parse(line));
+ expect(sources).toEqual([
+ { id: 'a', title: 'title' },
+ { id: 'a', summary: 'added in v2', title: 'title' },
+ ]);
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith(works);
+ });
+
+ it('retries the whole batch durably when generation fields cannot be resolved', async () => {
+ const works = [work('a', 3)];
+ const harness = createHarness(works, new Map([['a', { id: 'a', title: 'title' }]]));
+ harness.client.getFtsSearchSyncIndexFields.mockRejectedValueOnce(
+ new ElasticsearchFtsSearchRequestError('field lookup failed', 503),
+ );
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).not.toHaveBeenCalled();
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.not.objectContaining({ permanent: true }),
+ ]);
+ expect(result).toMatchObject({ acknowledged: 0, dead: 0, failed: 1 });
+ });
+
+ it('dead-letters only the incompatible entity and continues syncing compatible entities', async () => {
+ const works: FtsSearchSyncWork[] = [
+ work('agent', 3),
+ { documentId: 'topic', entity: 'topics', leaseToken: '4', revision: 4 },
+ ];
+ const harness = createHarness(
+ works,
+ new Map([
+ ['agent', { id: 'agent', title: 'agent' }],
+ ['topic', { id: 'topic', title: 'topic' }],
+ ]),
+ );
+ harness.client.getFtsSearchSyncIndexFields.mockResolvedValueOnce({
+ fieldsByIndex: {
+ 'lobehub-test-agents-v1': ['id', 'legacy_title', 'title'],
+ 'lobehub-test-topics-v1': ['id', 'title'],
+ },
+ incompatibilities: [
+ {
+ entity: 'agents',
+ index: 'lobehub-test-agents-v1',
+ message:
+ 'Elasticsearch full-text search index lobehub-test-agents-v1 is incompatible with the current agents projection. Retain compatible source fields or retire the index before syncing agents.',
+ },
+ ],
+ });
+ harness.client.bulk.mockResolvedValue({ errors: false, items: [{ index: { status: 201 } }] });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({
+ documentId: 'agent',
+ entity: 'agents',
+ error: expect.objectContaining({
+ message: expect.stringContaining('Retain compatible source fields or retire the index'),
+ }),
+ permanent: true,
+ }),
+ ]);
+ expect(bulkActions(harness.client)).toEqual([
+ {
+ _id: 'topic',
+ _index: 'lobehub-test-topics-v1',
+ version: 4,
+ version_type: 'external',
+ },
+ ]);
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith([works[1]]);
+ expect(result).toMatchObject({ acknowledged: 1, bulkItems: 1, dead: 1, failed: 1 });
+ });
+
+ it('writes every change to each live generation and settles it only when all of them hold it', async () => {
+ const works = [work('a', 3), work('b', 4)];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'title' }])),
+ );
+ harness.client.getFtsSearchSyncGenerationTargets.mockResolvedValue({
+ 'lobehub-test-agents': ['lobehub-test-agents-v1', 'lobehub-test-agents-v2'],
+ });
+ const errorType = `es_rejected_${'x'.repeat(200)}`;
+ harness.client.bulk.mockResolvedValue({
+ errors: true,
+ items: [
+ { index: { status: 201 } },
+ { index: { status: 409 } },
+ { index: { status: 201 } },
+ {
+ index: {
+ error: { reason: 'private source text', type: errorType },
+ status: 429,
+ },
+ },
+ ],
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.getFtsSearchSyncGenerationTargets).toHaveBeenCalledWith([
+ 'lobehub-test-agents',
+ ]);
+ expect(bulkActions(harness.client)).toEqual([
+ { _id: 'a', _index: 'lobehub-test-agents-v1', version: 3, version_type: 'external' },
+ { _id: 'a', _index: 'lobehub-test-agents-v2', version: 3, version_type: 'external' },
+ { _id: 'b', _index: 'lobehub-test-agents-v1', version: 4, version_type: 'external' },
+ { _id: 'b', _index: 'lobehub-test-agents-v2', version: 4, version_type: 'external' },
+ ]);
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith([works[0]]);
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({ documentId: 'b', permanent: false }),
+ ]);
+ const failure = harness.outbox.markFailures.mock.calls[0][0][0];
+ expect(String(failure.error)).toBe(
+ `Error: Elasticsearch bulk item failed (429, type=${errorType.slice(0, 128)})`,
+ );
+ expect(String(failure.error)).not.toContain('private source text');
+ expect(result).toMatchObject({ acknowledged: 1, bulkItems: 4, failed: 1 });
+ expect(result.bulkRequestSamples[0].entities).toEqual({
+ agents: { bytes: expect.any(Number), items: 4, result: 'mixed' },
+ });
+ });
+
+ it('ignores a generation retired mid-drain once another generation accepted the write', async () => {
+ const works = [work('kept'), work('lost')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'title' }])),
+ );
+ harness.client.getFtsSearchSyncGenerationTargets.mockResolvedValue({
+ 'lobehub-test-agents': ['lobehub-test-agents-v1', 'lobehub-test-agents-v2'],
+ });
+ const notFound = {
+ error: { reason: 'private source text', type: 'index_not_found_exception' },
+ status: 404,
+ };
+ harness.client.bulk.mockResolvedValue({
+ errors: true,
+ items: [
+ { index: notFound },
+ { index: { status: 201 } },
+ { index: notFound },
+ { index: notFound },
+ ],
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith([works[0]]);
+ // Every generation vanished: the change must stay durable instead of being silently dropped.
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({ documentId: 'lost', permanent: true }),
+ ]);
+ const failure = harness.outbox.markFailures.mock.calls[0][0][0];
+ expect(String(failure.error)).toBe(
+ 'Error: Elasticsearch bulk item failed (404, type=index_not_found_exception)',
+ );
+ expect(String(failure.error)).not.toContain('private source text');
+ expect(result).toMatchObject({ acknowledged: 1, dead: 1, failed: 1 });
+ });
+
+ it('durably retries every claimed change when generation targets cannot be resolved', async () => {
+ const works = [work('a'), work('b')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'title' }])),
+ );
+ harness.client.getFtsSearchSyncGenerationTargets.mockRejectedValueOnce(
+ new ElasticsearchFtsSearchRequestError('alias check failed', 503),
+ );
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).not.toHaveBeenCalled();
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.not.objectContaining({ permanent: true }),
+ expect.not.objectContaining({ permanent: true }),
+ ]);
+ expect(result).toMatchObject({ dead: 0, failed: 2, released: 0 });
+ });
+
+ it('splits bulk requests by the expanded multi-generation payload size', async () => {
+ const works = [work('a'), work('b')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'x' }])),
+ );
+ harness.client.getFtsSearchSyncGenerationTargets.mockResolvedValue({
+ 'lobehub-test-agents': ['lobehub-test-agents-v1', 'lobehub-test-agents-v2'],
+ });
+ harness.client.bulk.mockResolvedValue({
+ errors: false,
+ items: [{ index: { status: 201 } }, { index: { status: 201 } }],
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 300 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).toHaveBeenCalledTimes(2);
+ expect(
+ harness.client.bulk.mock.calls.flatMap((_, call) => bulkActions(harness.client, call)),
+ ).toHaveLength(4);
+ expect(result).toMatchObject({ acknowledged: 2, bulkItems: 4, bulkRequests: 2 });
+ });
+
+ it('finishes one legal multi-generation document beyond the request budget before acknowledging', async () => {
+ const item = work('a', 3);
+ const following = work('following');
+ const harness = createHarness(
+ [item, following],
+ new Map([
+ ['a', { id: 'a', title: 'x'.repeat(100) }],
+ ['following', { id: 'following', title: 'later' }],
+ ]),
+ );
+ harness.client.getFtsSearchSyncGenerationTargets.mockResolvedValue({
+ 'lobehub-test-agents': [
+ 'lobehub-test-agents-v1',
+ 'lobehub-test-agents-v2',
+ 'lobehub-test-agents-v3',
+ ],
+ });
+ harness.client.bulk.mockImplementation(async (body: string) => {
+ expect(harness.outbox.acknowledgeMany).not.toHaveBeenCalled();
+ return {
+ errors: false,
+ items: Array.from({ length: body.trim().split('\n').length / 2 }, () => ({
+ index: { status: 201 },
+ })),
+ };
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 300, maxBulkRequests: 1 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).toHaveBeenCalledTimes(3);
+ expect(
+ harness.client.bulk.mock.calls.map(([body]) => Buffer.byteLength(body as string)),
+ ).toEqual([expect.any(Number), expect.any(Number), expect.any(Number)]);
+ expect(
+ harness.client.bulk.mock.calls.every(([body]) => Buffer.byteLength(body as string) <= 300),
+ ).toBe(true);
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledTimes(1);
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith([item]);
+ expect(harness.outbox.markFailures).not.toHaveBeenCalled();
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([following]);
+ expect(result).toMatchObject({
+ acknowledged: 1,
+ bulkItems: 3,
+ bulkRequests: 3,
+ dead: 0,
+ released: 1,
+ });
+ });
+
+ it('does not acknowledge when a later request fails one generation', async () => {
+ const item = work('a', 3);
+ const following = work('following');
+ const harness = createHarness(
+ [item, following],
+ new Map([
+ ['a', { id: 'a', title: 'x'.repeat(100) }],
+ ['following', { id: 'following', title: 'later' }],
+ ]),
+ );
+ harness.client.getFtsSearchSyncGenerationTargets.mockResolvedValue({
+ 'lobehub-test-agents': [
+ 'lobehub-test-agents-v1',
+ 'lobehub-test-agents-v2',
+ 'lobehub-test-agents-v3',
+ ],
+ });
+ harness.client.bulk
+ .mockResolvedValueOnce({ errors: false, items: [{ index: { status: 201 } }] })
+ .mockResolvedValueOnce({ errors: true, items: [{ index: { status: 429 } }] });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 300, maxBulkRequests: 1 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).toHaveBeenCalledTimes(2);
+ expect(harness.outbox.acknowledgeMany).not.toHaveBeenCalled();
+ expect(harness.outbox.markFailures).toHaveBeenCalledTimes(1);
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({ documentId: 'a' }),
+ ]);
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([following]);
+ expect(result).toMatchObject({ acknowledged: 0, failed: 1, released: 1 });
+ });
+
+ it('acknowledges across requests when a retired generation is followed by a successful one', async () => {
+ const item = work('a', 3);
+ const harness = createHarness([item], new Map([['a', { id: 'a', title: 'x'.repeat(100) }]]));
+ harness.client.getFtsSearchSyncGenerationTargets.mockResolvedValue({
+ 'lobehub-test-agents': ['lobehub-test-agents-v1', 'lobehub-test-agents-v2'],
+ });
+ harness.client.bulk
+ .mockResolvedValueOnce({
+ errors: true,
+ items: [{ index: { error: { type: 'index_not_found_exception' }, status: 404 } }],
+ })
+ .mockResolvedValueOnce({ errors: false, items: [{ index: { status: 201 } }] });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 300, maxBulkRequests: 1 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith([item]);
+ expect(harness.outbox.markFailures).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ acknowledged: 1, bulkRequests: 2, dead: 0, failed: 0 });
+ });
+
it('writes a soft tombstone when the PostgreSQL row no longer exists', async () => {
const harness = createHarness([work('deleted-agent', 7)], new Map());
harness.client.bulk.mockResolvedValue({
@@ -276,13 +715,10 @@ describe('FtsSearchSyncService', () => {
const result = await service.drainOnce();
- const body = harness.client.bulk.mock.calls[0][0] as string;
- const documentIds = body
- .trim()
- .split('\n')
- .filter((_, index) => index % 2 === 0)
- .map((line) => JSON.parse(line).index._id);
- expect(documentIds).toEqual(['urgent-message', 'ordinary-agent']);
+ expect(bulkActions(harness.client)).toEqual([
+ expect.objectContaining({ _id: 'urgent-message', _index: 'lobehub-test-messages-v1' }),
+ expect.objectContaining({ _id: 'ordinary-agent', _index: 'lobehub-test-agents-v1' }),
+ ]);
expect(result.bulkRequestSamples[0].entities).toEqual({
agents: { bytes: expect.any(Number), items: 1, result: 'success' },
messages: { bytes: expect.any(Number), items: 1, result: 'success' },
diff --git a/apps/server/src/services/ftsSearchSync/service.ts b/apps/server/src/services/ftsSearchSync/service.ts
index 307288fa60c..3dd36899012 100644
--- a/apps/server/src/services/ftsSearchSync/service.ts
+++ b/apps/server/src/services/ftsSearchSync/service.ts
@@ -11,7 +11,11 @@ import type {
FtsSearchSyncWork,
} from '@/database/repositories/ftsSearchSyncOutbox';
-import type { ElasticsearchFtsSearchBulkResponse } from '../ftsSearch/elasticsearch';
+import type {
+ ElasticsearchFtsSearchBulkItem,
+ ElasticsearchFtsSearchBulkResponse,
+ ElasticsearchFtsSearchSyncIndexFieldsResult,
+} from '../ftsSearch/elasticsearch';
export const FTS_SEARCH_SYNC_BULK_MAX_BYTES = 50 * 1024 * 1024;
export const FTS_SEARCH_SYNC_CLAIM_LIMIT = 100;
@@ -20,17 +24,27 @@ export const FTS_SEARCH_SYNC_PROJECTION_BATCH_SIZE = FTS_SEARCH_SYNC_CLAIM_LIMIT
interface FtsSearchSyncElasticsearchClient {
bulk: (body: string) => Promise<ElasticsearchFtsSearchBulkResponse>;
+ /** Live physical generations per alias; every change is written to all of them. */
+ getFtsSearchSyncGenerationTargets: (aliases: string[]) => Promise<Record<string, string[]>>;
+ /** Validated top-level fields per physical index, used to prune documents per generation. */
+ getFtsSearchSyncIndexFields: (
+ entitiesByIndex: Record<string, FtsSearchSyncWork['entity']>,
+ ) => Promise<ElasticsearchFtsSearchSyncIndexFieldsResult>;
}
+/** One bulk action for one live generation of an Outbox change. */
interface FtsSearchSyncOperation {
body: string;
bytes: number;
+ /** Number of Elasticsearch bulk items in this action. */
+ items: number;
work: FtsSearchSyncWork;
}
interface FtsSearchSyncServiceOptions {
bulkMaxBytes: number;
claimLimit: number;
+ /** Soft drain budget checked between works; a started multi-generation work is always finished. */
maxBulkRequests: number;
projectionBatchSize: number;
}
@@ -80,23 +94,61 @@ const chunks = <Item>(items: Item[], size: number): Item[][] => {
return result;
};
-const buildOperation = (
+const buildOperations = (
work: FtsSearchSyncWork,
- indexNamespace: string,
+ targets: string[],
source: Record<string, unknown>,
-): FtsSearchSyncOperation => {
- const metadata = {
- index: {
- _id: work.documentId,
- _index: getFtsSearchIndexAlias(indexNamespace, work.entity),
- version: work.revision,
- version_type: 'external',
- },
- };
- const body = `${JSON.stringify(metadata)}\n${JSON.stringify(source)}\n`;
- return { body, bytes: Buffer.byteLength(body), work };
+ fieldsByIndex: ReadonlyMap<string, ReadonlySet<string>>,
+): FtsSearchSyncOperation[] => {
+ /**
+ * The same revision goes to every generation with `version_type: external`, so a generation that
+ * a concurrent rebuild already filled with a newer revision answers 409 and is settled as done.
+ * Each generation only receives the fields it maps: the document is projected by the deployed
+ * code, which may already declare fields an older generation lacks, and every generation is
+ * `dynamic: strict`.
+ */
+ return targets.map((target) => {
+ const fields = fieldsByIndex.get(target);
+ const projected = fields
+ ? Object.fromEntries(Object.entries(source).filter(([field]) => fields.has(field)))
+ : source;
+ const metadata = {
+ index: {
+ _id: work.documentId,
+ _index: target,
+ version: work.revision,
+ version_type: 'external',
+ },
+ };
+ const body = `${JSON.stringify(metadata)}\n${JSON.stringify(projected)}\n`;
+ return { body, bytes: Buffer.byteLength(body), items: 1, work };
+ });
};
+const isAcceptedBulkItem = ({ index: item }: ElasticsearchFtsSearchBulkItem) =>
+ (item.status >= 200 && item.status < 300) || item.status === 409;
+
+/** A generation retired between target resolution and the write; the next drain re-resolves. */
+const isRetiredGenerationBulkItem = ({ index: item }: ElasticsearchFtsSearchBulkItem) =>
+ item.error?.type === 'index_not_found_exception' || item.error?.type === 'index_closed_exception';
+
+interface ElasticsearchBulkFailureSummary {
+ status: number;
+ type: string;
+}
+
+/** Retains only the bounded Elasticsearch error type; reasons may contain document source data. */
+const summarizeElasticsearchBulkFailure = ({
+ error,
+ status,
+}: ElasticsearchFtsSearchBulkItem['index']): ElasticsearchBulkFailureSummary => ({
+ status,
+ type: error?.type?.slice(0, 128) ?? 'unknown',
+});
+
+const describeElasticsearchBulkFailure = ({ status, type }: ElasticsearchBulkFailureSummary) =>
+ new Error(`Elasticsearch bulk item failed (${status}, type=${type})`);
+
const summarizeBulkEntities = (
operations: FtsSearchSyncOperation[],
result: FtsSearchSyncBulkRequestResult,
@@ -104,14 +156,15 @@ const summarizeBulkEntities = (
): FtsSearchSyncBulkRequestSample['entities'] => {
const summaries = new Map<
FtsSearchSyncWork['entity'],
- { bytes: number; failed: number; items: number }
+ { actions: number; bytes: number; failed: number; items: number }
>();
for (const operation of operations) {
const entity = operation.work.entity;
- const current = summaries.get(entity) ?? { bytes: 0, failed: 0, items: 0 };
+ const current = summaries.get(entity) ?? { actions: 0, bytes: 0, failed: 0, items: 0 };
current.bytes += operation.bytes;
- current.items += 1;
+ current.items += operation.items;
+ current.actions += 1;
if (failedWorkKeys?.has(workKey(operation.work))) current.failed += 1;
summaries.set(entity, current);
}
@@ -123,7 +176,7 @@ const summarizeBulkEntities = (
? result
: summary.failed === 0
? 'success'
- : summary.failed === summary.items
+ : summary.failed === summary.actions
? 'item_error'
: 'mixed';
entitySamples[entity] = {
@@ -200,6 +253,10 @@ export class FtsSearchSyncService {
};
let bulk: FtsSearchSyncOperation[] = [];
let bulkBytes = 0;
+ const workProgress = new Map<
+ string,
+ { accepted: number; remaining: number; retiredFailures: ElasticsearchBulkFailureSummary[] }
+ >();
const forget = (settledWorks: FtsSearchSyncWork[]) => {
for (const work of settledWorks) unsettled.delete(workKey(work));
@@ -209,6 +266,7 @@ export class FtsSearchSyncService {
result.dead += await this.outbox.markFailures(failures);
result.failed += failures.length;
forget(failures);
+ for (const failure of failures) workProgress.delete(workKey(failure));
};
const flush = async () => {
@@ -216,10 +274,11 @@ export class FtsSearchSyncService {
const operations = bulk;
const requestBody = operations.map((operation) => operation.body).join('');
const requestBytes = bulkBytes;
+ const requestItems = operations.reduce((total, operation) => total + operation.items, 0);
bulk = [];
bulkBytes = 0;
result.bulkBytes += requestBytes;
- result.bulkItems += operations.length;
+ result.bulkItems += requestItems;
result.bulkRequests += 1;
let response: ElasticsearchFtsSearchBulkResponse;
@@ -231,68 +290,124 @@ export class FtsSearchSyncService {
bytes: requestBytes,
durationMs: Date.now() - startedAt,
entities: summarizeBulkEntities(operations, 'request_error'),
- items: operations.length,
+ items: requestItems,
result: 'request_error',
});
/** Request-level failures can be deployment or proxy faults; retry every item durably. */
- await fail(operations.map(({ work }) => ({ ...work, error })));
+ await fail(
+ [...new Map(operations.map(({ work }) => [workKey(work), work])).values()].map(
+ (work) => ({ ...work, error }),
+ ),
+ );
return;
}
- if (response.items.length !== operations.length) {
+ if (response.items.length !== requestItems) {
result.bulkRequestSamples.push({
bytes: requestBytes,
durationMs: Date.now() - startedAt,
entities: summarizeBulkEntities(operations, 'response_error'),
- items: operations.length,
+ items: requestItems,
result: 'response_error',
});
await fail(
- operations.map(({ work }) => ({
- ...work,
- error: new Error(
- `Elasticsearch bulk returned ${response.items.length} items for ${operations.length} operations`,
- ),
- })),
+ [...new Map(operations.map(({ work }) => [workKey(work), work])).values()].map(
+ (work) => ({
+ ...work,
+ error: new Error(
+ `Elasticsearch bulk returned ${response.items.length} items for ${requestItems} operations`,
+ ),
+ }),
+ ),
);
return;
}
const acknowledged: FtsSearchSyncWork[] = [];
const failures: FtsSearchSyncFailure[] = [];
- for (const [index, operation] of operations.entries()) {
- const item = response.items[index].index;
- if ((item.status >= 200 && item.status < 300) || item.status === 409) {
- /**
- * A version conflict is safe to settle because two database fences preserve source order:
- * fresh reindexes reserve their base revision before capture activation, and same-document
- * Outbox upserts allocate a revision only after locking the unique Outbox row. Settlement
- * is also revision-and-lease fenced, so a concurrent refresh remains queued.
- */
- acknowledged.push(operation.work);
- } else {
+ const itemsByWork = new Map<
+ string,
+ { items: ElasticsearchFtsSearchBulkItem[]; work: FtsSearchSyncWork }
+ >();
+ let offset = 0;
+ for (const operation of operations) {
+ const items = response.items.slice(offset, offset + operation.items);
+ offset += operation.items;
+ const key = workKey(operation.work);
+ const current = itemsByWork.get(key) ?? { items: [], work: operation.work };
+ current.items.push(...items);
+ itemsByWork.set(key, current);
+ }
+
+ for (const [key, { items, work }] of itemsByWork) {
+ /**
+ * A version conflict is safe to settle because two database fences preserve source order:
+ * fresh reindexes reserve their base revision before capture activation, and same-document
+ * Outbox upserts allocate a revision only after locking the unique Outbox row. Settlement
+ * is also revision-and-lease fenced, so a concurrent refresh remains queued.
+ */
+ const accepted = items.filter(isAcceptedBulkItem).length;
+ const rejected = items.filter(
+ (item) => !isAcceptedBulkItem(item) && !isRetiredGenerationBulkItem(item),
+ );
+ if (rejected.length > 0) {
+ const failedItem = rejected[0].index;
failures.push({
- ...operation.work,
- error: new Error(`Elasticsearch bulk item failed (${item.status})`),
- permanent: isPermanentElasticsearchStatus(item.status),
+ ...work,
+ error: describeElasticsearchBulkFailure(summarizeElasticsearchBulkFailure(failedItem)),
+ permanent: isPermanentElasticsearchStatus(failedItem.status),
});
+ continue;
}
+
+ const progress = workProgress.get(key)!;
+ progress.accepted += accepted;
+ progress.remaining -= items.length;
+ progress.retiredFailures.push(
+ ...items
+ .filter(isRetiredGenerationBulkItem)
+ .map(({ index }) => summarizeElasticsearchBulkFailure(index)),
+ );
+ if (progress.remaining > 0) continue;
+
+ /**
+ * A change is done once every generation that still exists holds it. Retired generations
+ * are ignored only when another generation accepted the write; if none did, the alias
+ * itself is gone and the change must not be lost.
+ */
+ if (progress.accepted > 0) {
+ acknowledged.push(work);
+ workProgress.delete(key);
+ continue;
+ }
+ const failedItem = progress.retiredFailures[0];
+ failures.push({
+ ...work,
+ error: describeElasticsearchBulkFailure(failedItem),
+ permanent: isPermanentElasticsearchStatus(failedItem.status),
+ });
}
const bulkResult =
- failures.length === 0 ? 'success' : acknowledged.length === 0 ? 'item_error' : 'mixed';
+ failures.length === 0
+ ? 'success'
+ : failures.length === itemsByWork.size
+ ? 'item_error'
+ : 'mixed';
result.bulkRequestSamples.push({
bytes: requestBytes,
durationMs: Date.now() - startedAt,
entities: summarizeBulkEntities(operations, bulkResult, new Set(failures.map(workKey))),
- items: operations.length,
+ items: requestItems,
result: bulkResult,
});
- const deleted = await this.outbox.acknowledgeMany(acknowledged);
- result.acknowledged += deleted.length;
- forget(acknowledged);
- await fail(failures);
+ if (acknowledged.length > 0) {
+ const deleted = await this.outbox.acknowledgeMany(acknowledged);
+ result.acknowledged += deleted.length;
+ forget(acknowledged);
+ }
+ if (failures.length > 0) await fail(failures);
};
let hasPrimaryError = false;
@@ -340,47 +455,147 @@ export class FtsSearchSyncService {
}
}
+ /**
+ * Resolve the live generations of every entity in this batch once per drain. Resolution
+ * failures are retried durably like a failed bulk request: the alias table is an
+ * Elasticsearch read that can fail for the same transient reasons.
+ */
+ const targetsByEntity = new Map<FtsSearchSyncWork['entity'], string[]>();
+ const fieldsByIndex = new Map<string, ReadonlySet<string>>();
+ const pendingEntities = [
+ ...new Set(works.filter((work) => unsettled.has(workKey(work))).map((work) => work.entity)),
+ ];
+ if (!stoppedForDeadLetter && pendingEntities.length > 0) {
+ const aliasEntities = new Map(
+ pendingEntities.map(
+ (entity) => [getFtsSearchIndexAlias(this.indexNamespace, entity), entity] as const,
+ ),
+ );
+ try {
+ const targets = await this.client.getFtsSearchSyncGenerationTargets([
+ ...aliasEntities.keys(),
+ ]);
+ for (const [alias, entity] of aliasEntities) {
+ const entityTargets = targets[alias];
+ if (!entityTargets || entityTargets.length === 0) {
+ throw new Error(`Elasticsearch returned no generation targets for alias ${alias}`);
+ }
+ targetsByEntity.set(entity, entityTargets);
+ }
+ const entitiesByIndex: Record<string, FtsSearchSyncWork['entity']> = {};
+ for (const [entity, indexes] of targetsByEntity) {
+ for (const index of indexes) entitiesByIndex[index] = entity;
+ }
+ const indexes = Object.keys(entitiesByIndex).sort();
+ const { fieldsByIndex: resolvedFieldsByIndex, incompatibilities } =
+ await this.client.getFtsSearchSyncIndexFields(entitiesByIndex);
+ const incompatibilityMessagesByEntity = new Map<FtsSearchSyncWork['entity'], string[]>();
+ for (const incompatibility of incompatibilities) {
+ const messages = incompatibilityMessagesByEntity.get(incompatibility.entity) ?? [];
+ messages.push(incompatibility.message);
+ incompatibilityMessagesByEntity.set(incompatibility.entity, messages);
+ }
+ if (incompatibilityMessagesByEntity.size > 0) {
+ await fail(
+ works
+ .filter(
+ (work) =>
+ unsettled.has(workKey(work)) &&
+ incompatibilityMessagesByEntity.has(work.entity),
+ )
+ .map((work) => ({
+ ...work,
+ error: new Error(incompatibilityMessagesByEntity.get(work.entity)!.join(' ')),
+ permanent: true,
+ })),
+ );
+ }
+ for (const index of indexes) {
+ if (!resolvedFieldsByIndex[index]) {
+ throw new Error(`Elasticsearch returned no mapped fields for index ${index}`);
+ }
+ fieldsByIndex.set(index, new Set(resolvedFieldsByIndex[index]));
+ }
+ } catch (error) {
+ await fail(
+ works
+ .filter((work) => unsettled.has(workKey(work)))
+ .map((work) => ({ ...work, error })),
+ );
+ if (result.dead > 0) stoppedForDeadLetter = true;
+ }
+ }
+
let exhaustedBulkBudget = false;
- operations: for (const work of works) {
+ workLoop: for (const work of works) {
if (stoppedForDeadLetter) break;
if (!unsettled.has(workKey(work))) continue;
+ if (result.bulkRequests >= this.options.maxBulkRequests) {
+ /** Flush the tail of the previous started work, then stop before beginning another. */
+ await flush();
+ if (result.dead > 0) stoppedForDeadLetter = true;
+ exhaustedBulkBudget = true;
+ break workLoop;
+ }
/** Soft tombstones prevent delayed external-version writes from resurrecting deletions. */
const source =
projectedSources.get(sourceKey(work.entity, work.documentId)) ??
({ id: work.documentId, fts_search_sync_deleted: true } as Record<string, unknown>);
- const operation = buildOperation(work, this.indexNamespace, source);
+ const operations = buildOperations(
+ work,
+ targetsByEntity.get(work.entity)!,
+ source,
+ fieldsByIndex,
+ );
- if (operation.bytes > this.options.bulkMaxBytes) {
+ const oversizedOperation = operations.find(
+ (operation) => operation.bytes > this.options.bulkMaxBytes,
+ );
+ if (oversizedOperation) {
await fail([
{
...work,
error: new Error(
- `Full-text search document is ${operation.bytes} bytes and exceeds the ${this.options.bulkMaxBytes}-byte bulk limit`,
+ `Full-text search document generation is ${oversizedOperation.bytes} bytes and exceeds the ${this.options.bulkMaxBytes}-byte bulk limit`,
),
permanent: true,
},
]);
if (result.dead > 0) {
stoppedForDeadLetter = true;
- break operations;
+ break workLoop;
}
continue;
}
- if (bulk.length > 0 && bulkBytes + operation.bytes > this.options.bulkMaxBytes) {
- await flush();
- if (result.dead > 0) {
- stoppedForDeadLetter = true;
- break operations;
- }
- if (result.bulkRequests >= this.options.maxBulkRequests) {
- exhaustedBulkBudget = true;
- break operations;
+ const progress = {
+ accepted: 0,
+ remaining: operations.length,
+ retiredFailures: [],
+ };
+ workProgress.set(workKey(work), progress);
+ for (const operation of operations) {
+ if (bulk.length > 0 && bulkBytes + operation.bytes > this.options.bulkMaxBytes) {
+ const deadBeforeFlush = result.dead;
+ await flush();
+ if (result.dead > deadBeforeFlush) {
+ stoppedForDeadLetter = true;
+ break workLoop;
+ }
+ if (!unsettled.has(workKey(work))) break;
+ /** Finish an already-started work even when it spans more requests than the budget. */
+ if (
+ result.bulkRequests >= this.options.maxBulkRequests &&
+ progress.remaining === operations.length
+ ) {
+ exhaustedBulkBudget = true;
+ break workLoop;
+ }
}
- }
- bulk.push(operation);
- bulkBytes += operation.bytes;
+ bulk.push(operation);
+ bulkBytes += operation.bytes;
+ }
}
if (!exhaustedBulkBudget && !stoppedForDeadLetter && bulk.length > 0) await flush();
diff --git a/docker-compose/deploy/docker-compose.yml b/docker-compose/deploy/docker-compose.yml
index 8559c33df00..43dc25bd0a1 100644
--- a/docker-compose/deploy/docker-compose.yml
+++ b/docker-compose/deploy/docker-compose.yml
@@ -18,6 +18,7 @@ services:
- 'KEY_VAULTS_SECRET=${KEY_VAULTS_SECRET}'
- 'AUTH_SECRET=${AUTH_SECRET}'
- 'DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@postgresql:5432/${LOBE_DB_NAME}'
+ - 'ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex'
- 'INTERNAL_APP_URL=http://localhost:3210'
- 'S3_ENDPOINT=${S3_ENDPOINT}'
- 'S3_BUCKET=${RUSTFS_LOBE_BUCKET}'
@@ -33,6 +34,8 @@ services:
- 'REDIS_TLS=0'
env_file:
- .env
+ volumes:
+ - 'fts-search-reindex-state:/app/.elasticsearch-reindex'
restart: always
networks:
- lobe-network
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.mdx b/docs/self-hosting/advanced/elasticsearch-migration.mdx
index acd793f5337..aba529f3d7b 100644
--- a/docs/self-hosting/advanced/elasticsearch-migration.mdx
+++ b/docs/self-hosting/advanced/elasticsearch-migration.mdx
@@ -1,6 +1,6 @@
---
-title: Migrate from pg_search to Elasticsearch (3.x)
-description: Safely move an existing LobeHub deployment from PostgreSQL pg_search to Elasticsearch.
+title: Migrate from pg_search to Elasticsearch
+description: Migrate search for a LobeHub deployment using Docker and Neon.
tags:
- Elasticsearch
- Search
@@ -10,382 +10,126 @@ tags:
# Migrate from pg\_search to Elasticsearch
-This guide moves an existing LobeHub deployment from PostgreSQL `pg_search` to Elasticsearch while
-the application remains available. The 3.x migration tool copies LobeHub's 14 searchable entity
-types into a new Elasticsearch project. It atomically records cursors, counters, and item-level
-failures in a local checkpoint file, so running the same command with the same state directory
-resumes the existing attempt.
-
-This workflow is for a database that has already applied the historical `pg_search` migrations and
-currently serves search with `FTS_SEARCH_PROVIDER=pg_search`. For backend selection and the ongoing
-Elasticsearch data flow, read [Full-Text Search](/docs/self-hosting/advanced/full-text-search).
-
-<Callout type="warning">
- Neon stopped offering `pg_search` to new projects on March 19, 2026. Neon has notified affected
- existing customers that the extension will be removed on September 21, 2026; queries, indexes,
- and applications that still depend on it will stop working after removal. Complete this
- migration before that deadline. Setting `FTS_SEARCH_PROVIDER=elasticsearch` on a fresh database
- does not skip LobeHub's historical `pg_search` migrations: `bun run db:migrate` still attempts to
- create the extension and BM25 indexes, and fails when the database service does not provide them.
- See Neon's
- [pg\_search notice](https://neon.com/docs/extensions/pg_search) and
- [extension catalog](https://neon.com/docs/extensions/pg-extensions) for the current service state.
-</Callout>
-
-<Callout type="warning">
- The reindex command does not switch product search requests to Elasticsearch. Keep the application on PostgreSQL search while you backfill and validate the new indexes. The regular database migration creates the PostgreSQL Outbox schema and the schema-managed Memory fanout GIN index; it does not install search-capture functions or triggers. Capture starts only after you explicitly run `bun run db:install-fts-search-capture` or start `bun run fts-search:reindex -- --apply`, even if the incremental consumer is still paused.
-</Callout>
-
-## Environment variables
-
-| Variable | Required | Purpose |
-| ------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `DATABASE_URL` | Yes | PostgreSQL source database and incremental-change Outbox. Reindex checkpoints are not stored in the database. |
-| `ES_URL` | Apply | Endpoint of the new, empty Elasticsearch target that receives the 3.x search indexes. HTTPS, or plaintext HTTP only for loopback or with `ES_ALLOW_INSECURE_HTTP=true`. |
-| `ES_API_KEY` | Apply | Elasticsearch API key used to create indexes, write bulk documents, refresh/count indexes, and create aliases. Do not use a read-only key. Required unless `ES_ALLOW_INSECURE_HTTP=true`. |
-| `ES_ALLOW_INSECURE_HTTP` | Compose | `true` only for an Elasticsearch node with security disabled that is reachable exclusively inside a private container network, such as the optional Docker Compose service. |
-| `ES_INDEX_NAMESPACE` | Yes | Stable deployment-owned prefix, for example `lobehub`. It produces aliases such as `lobehub-messages`. Keep it unchanged across reruns. |
-| `FTS_SEARCH_SYNC_ENABLED` | Sync | Set to `true` only after the full backfill is ready and before running the incremental consumer. |
-| `FTS_SEARCH_PROVIDER` | Cutover | Set to `elasticsearch` after backfill, catch-up, and validation finish to switch user search traffic. |
-
-`ES_URL` and `ES_API_KEY` are not needed for the read-only `--status` command.
-Operators that keep multiple Elasticsearch targets in one environment can select an explicit pair
-with `--elasticsearch-url-env=<KEY>` and `--elasticsearch-api-key-env=<KEY>`. Both flags are
-required together. `--expected-elasticsearch-host-prefix=<PREFIX>` can additionally refuse a
-mistargeted endpoint before any backfill mutation. The command prints and logs the selected
-hostname and variable names, never credential values.
-
-Remote Elasticsearch targets must use HTTPS. Plain HTTP is accepted only for loopback addresses
-such as `localhost` during local development, so an API key cannot be sent unencrypted to a remote
-host. The single explicit exception is `ES_ALLOW_INSECURE_HTTP=true`, which permits plaintext HTTP
-to a private container hostname without an API key; even then the runtime, reindex, and sync
-clients all refuse to send an API key over plaintext HTTP.
-
-## Before you start
-
-1. Create a new empty Elasticsearch project in the intended production region. LobeHub's search
- analyzers require the official
- [`analysis-icu`](https://www.elastic.co/docs/reference/elasticsearch/plugins/analysis-icu)
- plugin. Elastic Cloud Serverless includes core analysis plugins; on Elastic Cloud Hosted, enable
- the provided plugin for the deployment; on self-managed Elasticsearch, install it on every node
- and restart every node before the first `--apply`. Docker Compose deployments can instead enable
- the optional `elasticsearch` service of the official Compose file, whose image is built with the
- plugin included; see
- [Run Elasticsearch with Docker Compose](/docs/self-hosting/advanced/full-text-search#run-elasticsearch-with-docker-compose).
-
-2. Create and verify a PostgreSQL recovery point before enabling Elasticsearch capture, then
- rehearse the migration against an isolated database copy and an isolated empty Elasticsearch
- target. The rehearsal should exercise at least one batch for every non-empty entity, a resume
- using the same checkpoint, incremental catch-up, and the application smoke tests you will use at
- cutover.
-
- On Neon, create a child branch for the rehearsal and use a manual snapshot or the root branch's
- point-in-time restore window for production recovery. A child branch is an isolated test copy;
- it is not itself a point-in-time restore point. See Neon's
- [branching](https://neon.com/docs/introduction/branching) and
- [backup and restore](https://neon.com/docs/guides/backup-restore) documentation.
-
-3. Apply the database migrations for the same LobeHub release:
-
- ```bash
- bun run db:migrate
- ```
-
- This creates the Outbox sequence, table, ordinary Outbox indexes, and the schema-managed Memory
- fanout GIN index. It does not create the PostgreSQL change-capture functions or triggers. A
- PostgreSQL-only deployment can stop here: it still maintains the schema-managed GIN index, but
- does not pay the trigger or Outbox capture-write overhead.
-
-4. Install the optional PostgreSQL change capture before the first backfill:
-
- ```bash
- bun run db:install-fts-search-capture
- ```
-
- The installer first strictly validates the schema-managed GIN index (it does not create it), then
- atomically installs and verifies the capture functions and 16 triggers in one transaction. It is
- safe to rerun when the complete expected infrastructure already exists; partial, disabled, or
- unexpected definitions fail closed instead of being silently repaired. Once it succeeds, source
- changes are recorded in the Outbox immediately. The `bun run fts-search:reindex -- --apply` command
- also runs this installer automatically; using the explicit command first is useful when you want
- capture active while preparing the Elasticsearch target. If you do not intend to enable
- Elasticsearch, do not run it.
-
-5. Keep the application's search backend on PostgreSQL and keep incremental Elasticsearch draining disabled.
-
-The first production mapping is version `v1`. The tool creates physical indexes such as `lobehub-messages-v1`. After all 14 indexes finish and their counts match the durable checkpoints, it creates stable aliases such as `lobehub-messages`. An alias is only a stable Elasticsearch name; creating it does not change which search backend serves users.
-
-If a stable alias already points to another physical index, the command fails instead of moving it.
-Online schema-version upgrades require a separately coordinated dual-write migration and are not
-supported by this initial migration tool.
-
-## Run from source
-
-The package command bundles the worker and executes it on Node.js. Use this documented command
-instead of invoking the TypeScript entrypoint directly so runtime preparation and temporary-file
-cleanup remain consistent.
-
-Inspect the current state without writing to Elasticsearch:
+If you deploy LobeHub with Docker, use Neon for your database, and currently rely on `pg_search`, follow this guide to move search to Elasticsearch. Complete the migration before Neon disables `pg_search` for your instance.
-```bash
-bun run fts-search:reindex -- --status
-```
+If your database continues to support `pg_search`, you can keep using it without migrating. This migration only changes the search service. Your chat history and other source data stay in the existing database.
-Choose a durable local state directory and start a new backfill into an empty Elasticsearch target:
+## 1. Prepare the configuration
-```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
- bun run fts-search:reindex -- --apply --fresh-run --yes
-```
+Back up your Neon database, then set up Elasticsearch using the [full-text search guide](/docs/self-hosting/advanced/full-text-search).
-Only the first invocation uses `--fresh-run`. Resume the same run with the same state directory:
+On your server, prepare an `.env` file for the migration with the following settings. Do not commit this file to your repository.
-```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
-```
+| Variable | Setting |
+| ------------------------- | ---------------------------------------------------------------------------------------------- |
+| `DATABASE_URL` | Your existing Neon database's direct connection URL, without `-pooler` in the hostname |
+| `DATABASE_DRIVER` | Set to `node` to use the direct connection above |
+| `ES_REINDEX_STATE_DIR` | Set to `/app/.elasticsearch-reindex` and mount the progress volume as shown below |
+| `KEY_VAULTS_SECRET` | Reuse the value from your existing LobeHub application; do not generate a new one |
+| `ES_URL` | Elasticsearch URL, reachable from the Docker containers |
+| `ES_API_KEY` | An API key with permission to create indexes and read and write data |
+| `ES_INDEX_NAMESPACE` | An index prefix, such as `lobehub`; use the same value for the application and migration tools |
+| `FTS_SEARCH_PROVIDER` | Keep set to `pg_search` for now |
+| `FTS_SEARCH_SYNC_ENABLED` | Keep set to `false` for now |
+
+Use HTTPS and an API key for an external Elasticsearch service. The bundled Elasticsearch node on the official Compose private network uses `ES_ALLOW_INSECURE_HTTP=true` and does not require an API key. When using that node, add `--network <elasticsearch-network-name>` to each `docker run` command below. Inside a container, `localhost` does not refer to the host machine.
-`--apply` verifies every physical Elasticsearch index and its ICU analysis settings before reading
-source rows. It also validates the schema-managed Memory fanout GIN index (it never creates this
-index) and idempotently installs the optional PostgreSQL capture infrastructure (unless it was
-installed already). The read-only `--status` command never installs or changes this infrastructure.
-Before reading source rows, `--apply`
-briefly fences writes to all trigger source tables so transactions holding older Outbox revisions
-finish before the snapshot.
-If the three-second lock timeout expires, let the long transaction finish and rerun the command.
-Keep the incremental consumer paused during the initial backfill if
-needed; PostgreSQL continues to append changes to the Outbox, and the consumer can drain them
-after the full snapshot is ready. The required `--yes` acknowledges the mutating operation; it is
-not an interactive prompt.
-
-The run ID is also stored in each physical index's mapping metadata. A different local checkpoint
-cannot silently continue writing the same physical indexes. Never run copies of one checkpoint
-concurrently from multiple machines.
-
-The checkpoint file contains only migration control state and sanitized failure metadata. It never
-stores database or Elasticsearch credentials. Keep the entire state directory until validation and
-incremental catch-up finish; moving to another machine requires copying that directory.
-
-For a bounded rehearsal that exercises every entity without completing the full database, run one
-batch per non-empty entity with bounded concurrency:
+These commands use the official image and connect to the database specified in this configuration, independently of Compose's bundled PostgreSQL service. Run them in the same terminal, replacing the image tag with the version you are deploying:
```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
- bun run fts-search:reindex -- --apply --yes \
- --expected-elasticsearch-host-prefix=search-dev- \
- --entity-concurrency=4 --bulk-concurrency=2 \
- --batch-size=5000 --entity-batch-size=documents:1000 --bulk-max-bytes=10485760 \
- --max-batches-per-entity=1
+export LOBE_MIGRATION_IMAGE='lobehub/lobehub:<deployment-version-tag>'
+docker pull "$LOBE_MIGRATION_IMAGE"
+docker volume create lobehub-search-state
```
-This command creates all 14 entity indexes and writes source rows into each non-empty one. If at
-least one entity has more than the configured batch limit, the run remains in `backfilling` without
-creating aliases. A small deployment whose 14 entities all fit within the limit can complete and
-create aliases in this rehearsal, so always use an isolated empty Elasticsearch target. Re-run the
-same command to exercise resume behavior, or remove `--max-batches-per-entity` to intentionally
-continue until every entity completes.
-
-`--entity-concurrency` controls independent PostgreSQL entity scans. `--bulk-concurrency` controls
-parallel byte-bounded Elasticsearch requests inside each entity batch. Start conservatively and
-increase them only while PostgreSQL and Elasticsearch remain healthy. `--batch-size` limits rows
-per keyset page. `--bulk-max-bytes` limits each encoded `_bulk` request; an individual document
-larger than this limit is stored as an explicit failure. Repeat
-`--entity-batch-size=<entity>:<rows>` to use a smaller PostgreSQL page only for source types with
-materially wider rows, without slowing narrower entities.
-
-Large installations can repeat
-`--entity-range-concurrency=<documents|messages>:<workers>` to scan either high-volume entity in
-parallel ID ranges. Range mode requires the database collation to be bytewise (`C`, `C.UTF-8`, or
-`C.utf8`); the command checks this before writing. Completed ranges advance the durable cursor in
-ID order, so an interrupted run may safely replay a later range that Elasticsearch already
-received. Start with a small worker count and increase it only after measuring sustained database
-and Elasticsearch behavior. Range concurrency cannot be combined with
-`--max-batches-per-entity`.
-
-Repeat `--entity=<entity>` to limit one invocation to selected entities, for example while tuning
-`documents` and `messages`. A selected invocation never creates aliases early and leaves the run in
-`backfilling` while any unselected entity is incomplete. Resume once without `--entity` after all
-selected work finishes so the command can perform the complete 14-entity reconciliation and create
-the stable aliases.
-
-Transient request failures are retried with exponential backoff before the batch cursor advances.
-The defaults are four retries, a 500 ms base delay, and a 30-second request timeout. Override them
-with `--max-request-retries`, `--retry-base-delay-ms`, and `--request-timeout-ms` when required.
-
-Every apply or resume session appends sanitized operational events to
-`<state-dir>/runs/<run-id>/events.jsonl` and atomically replaces
-`<state-dir>/runs/<run-id>/summary.json`. The log records entity and bulk timings, byte and document
-counts, retries, cursors, failures, and final state. It never records database or Elasticsearch
-URLs, credentials, or document source text. Keep these private files with the checkpoint when
-moving or archiving a run.
-
-The backfill command exports OpenTelemetry only when `ENABLE_TELEMETRY` is set. In that case, pass
-`--telemetry-environment=<development|preview|production>` and configure either
-`OTEL_EXPORTER_OTLP_ENDPOINT` or both signal-specific metrics and traces endpoints. Otherwise leave
-telemetry disabled and use the local event and summary files. Always set the same explicit
-`ES_INDEX_NAMESPACE` for the migration command, incremental consumer, and application runtime;
-the command has no development fallback for a missing namespace.
-
-## Run from the Docker image
-
-The official image includes `/app/fts-search-elasticsearch-reindex.cjs`:
+Pause use of the application and run that version's database migrations. Continue only after they succeed:
```bash
-mkdir -m 700 -p .elasticsearch-reindex
-docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
- -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
- -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
- lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --status
-docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
- -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
- -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
- lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --apply --fresh-run --yes
+docker run --rm --env-file .env \
+ "$LOBE_MIGRATION_IMAGE" /app/docker.cjs
```
-The bind mount is required for resume after a `--rm` container exits. Running with the host user's
-ID lets the process write the bind-mounted directory without changing its ownership.
-
-## Run from Docker Compose
+## 2. Import existing data
-The official `docker-compose/deploy/docker-compose.yml` already defines the same command as the
-`fts-search-reindex` service, wired to the Compose PostgreSQL, the optional in-network
-`elasticsearch` service, and a named `fts-search-reindex-state` volume for the checkpoint:
+Create the search indexes and import your existing data:
```bash
-docker compose run --rm fts-search-reindex --status
-docker compose run --rm fts-search-reindex --apply --fresh-run --yes
+docker run --rm --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \
+ -v lobehub-search-state:/app/.elasticsearch-reindex \
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs \
+ --apply --fresh-run --yes
```
-Extra arguments are passed through, so the rehearsal, `--entity`, `--skip-failure`, and resume
-commands above work unchanged. The service uses the `ES_URL`, `ES_ALLOW_INSECURE_HTTP`, and
-`ES_INDEX_NAMESPACE` values from `.env`; with an external Elastic Cloud target, set `ES_URL` and
-`ES_API_KEY` there instead, leave `ES_ALLOW_INSECURE_HTTP` unset, and keep the `elasticsearch`
-profile out of `COMPOSE_PROFILES`; the service depends only on PostgreSQL, so the bundled node is
-neither built nor started. The complete Compose sequence,
-including enabling the node and the sync worker, is in
-[Run Elasticsearch with Docker Compose](/docs/self-hosting/advanced/full-text-search#run-elasticsearch-with-docker-compose).
-
-## Start incremental synchronization
+Migration progress is saved in the `lobehub-search-state` volume. Keep this volume. Use `--fresh-run` only for the initial import; omit it when resuming after an interruption.
-After the reindex status is `ready_for_incremental_sync`, set
-`FTS_SEARCH_SYNC_ENABLED=true` and run the bounded consumer:
+Check the migration status:
```bash
-bun run fts-search:sync -- --max-steps=8 --yes
+docker run --rm --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \
+ -v lobehub-search-state:/app/.elasticsearch-reindex \
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs --status
```
-One invocation processes at most eight drain steps and then exits. `hasMore: true` in the final JSON
-means the bound was reached safely; run it again. Schedule the same command with cron, a container
-job, or another process supervisor so it continues to run while Elasticsearch search is enabled.
-Omitting `--max-steps` processes one step; accepted values are from 1 through 100.
+Continue when the status is `ready_for_incremental_sync` and there are no failed records.
-For a long-running worker instead of an external scheduler, add `--interval-seconds=<1-3600>`: the
-command repeats the same bounded drain, continues immediately while `hasMore` is true, sleeps for
-the interval otherwise, and stops cleanly on `SIGINT` / `SIGTERM` after finishing the drain step in
-progress (not the whole bound), so a supervisor's stop timeout only needs to cover one step. A run that leaves failed or
-dead-letter work still exits non-zero, so the supervisor's restart policy and logs surface it. The
-Compose `fts-search-sync` service (profile `elasticsearch-sync`) uses this mode.
-The consumer validates the PostgreSQL capture definitions and every Elasticsearch write alias before
-claiming work. Missing or stale capture infrastructure, an invalid alias, retryable write failure, or
-dead-letter work produces a non-zero exit code. It never installs triggers and never deletes failed
-work automatically.
+## 3. Start continuous sync
-The official image includes `/app/fts-search-elasticsearch-sync.cjs` for the same bounded operation:
+Start the sync container so that new, updated, and deleted data are reflected in search results:
```bash
-docker run --rm --env-file .env \
+docker run -d --name lobe-fts-search-sync --restart unless-stopped \
+ --env-file .env \
-e FTS_SEARCH_SYNC_ENABLED=true \
-e MIGRATION_DB=1 \
- lobehub/lobehub:latest /app/fts-search-elasticsearch-sync.cjs --max-steps=8 --yes
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-sync.cjs \
+ --max-steps=8 --interval-seconds=15 --yes
```
-Keep scheduling the consumer and run `bun run fts-search:reindex -- --status` until `pending`, `ready`,
-`retrying`, `inFlight`, `dead`, and `revisionLag` are all zero. Recheck that state immediately before
-switching queries. Then set `FTS_SEARCH_PROVIDER=elasticsearch` and redeploy the application. Keep
-`FTS_SEARCH_PROVIDER=pg_search` until catch-up is complete. Elasticsearch failures remain visible to
-callers; the search path does not silently fall back to PostgreSQL or `ilike`.
-
-After deployment, keep the old BM25 indexes and `pg_search` extension during an agreed observation
-window. Confirm that successful backend operations are attributed to `elasticsearch`, no new
-`pg_search` operations appear, the Outbox repeatedly returns to zero lag with no dead work, and the
-product search surfaces your deployment uses pass smoke tests. While the old database objects still
-exist, rollback is limited to restoring `FTS_SEARCH_PROVIDER=pg_search` and redeploying; the Outbox
-consumer may continue running while you diagnose Elasticsearch. If you stop that consumer after
-capture has been installed, source changes continue accumulating in the Outbox until it resumes.
-
-## Resume and verify
-
-- After a process crash or temporary Elasticsearch failure, re-run the `--apply --yes` command with the same state directory but without `--fresh-run`. Completed entities are skipped and the next batch starts after the local cursor. This is safe while the optional capture infrastructure remains installed, because changes made during the pause are retained in the Outbox.
-- Request-level failures do not advance the cursor. If one concurrent bulk succeeds and another fails, the entire database batch is replayed safely on resume. Item-level failures are recorded in the local checkpoint and replayed before an entity can complete.
-- The tool refuses to create aliases while any entity or item-level failure is incomplete.
-- The final status is `ready_for_incremental_sync`. At this point the full snapshot, aliases, and the Outbox high-water boundary exist, but user queries must still remain on PostgreSQL.
-
-The high-water revision is an observation point for catch-up monitoring, not a committed database
-snapshot. An incremental consumer must process every queued row and must never discard rows only
-because their revision is at or below that value.
-
-Run `--status` and confirm all 14 entities show `completed`, every `failedCount` is `0`, and the
-Outbox `dead` count is `0` before starting the incremental consumer documented above. A paused
-incremental consumer may leave queued Outbox work; that is expected
-while backfill is running and does not mean source-change capture is paused. The status output
-lists unresolved document IDs, retryability, and attempt counts without persisting or printing
-Elasticsearch error reasons that may contain source text.
-
-After correcting a rejected source document or mapping, run `--apply --yes` again to retry it. If an
-operator deliberately accepts that one document with a non-retryable failure will be absent from
-the initial Elasticsearch snapshot, resolve the blocker explicitly and then resume:
+Check the logs for errors:
```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
- bun run fts-search:reindex -- --skip-failure=agents:document-id --yes
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
+docker logs --tail 50 lobe-fts-search-sync
```
-Only non-retryable failures can be skipped, and skipping does not count the document as indexed. Use
-it only after reviewing the source record and accepting that it will not be searchable until a
-later source change or incremental repair writes it.
+Run the status command from the previous step again. Wait until the queue's `pending`, `ready`, `retrying`, `inFlight`, `dead`, and `revisionLag` values are all `0` before switching search.
-To pause incremental Elasticsearch writes during backfill, pause the deployment's incremental
-consumer using its normal worker setting. This does not stop the installed PostgreSQL capture
-triggers: source changes continue to accumulate in the Outbox and can be drained when the consumer
-is enabled. Do not disable or remove the triggers, or truncate the Outbox, while a reindex is in
-progress.
+Keep this container running after the switch. Otherwise, subsequent data changes will not appear in search results.
-<Callout type="info">
- The full-reindex command does not run the recurring incremental consumer and does not claim that
- the application is ready to switch search backends by itself. Keep `fts-search:sync` scheduled for as
- long as Elasticsearch serves search traffic.
-</Callout>
+## 4. Switch search
-## Remove pg\_search before the Neon deadline
+Mount the same progress volume on your LobeHub application container with `-v lobehub-search-state:/app/.elasticsearch-reindex` and set `ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex`. In the application's deployment configuration, set the same Elasticsearch connection details and index prefix, and change `FTS_SEARCH_PROVIDER` to `elasticsearch`. Recreate the application container using the same image version. Editing only the migration's `.env` file does not update the running application.
-After Elasticsearch has served search reliably through your observation window and a current
-PostgreSQL recovery point is available, inspect the remaining LobeHub-managed objects:
+Search for an existing chat message, then create a new message and confirm that it becomes searchable. Once both checks succeed and the sync container has no errors, resume normal use.
-```bash
-bun run scripts/pgSearchCleanup/index.ts --status
-```
-
-Then remove them without copying SQL from this guide:
+If you encounter problems after switching, you can change the application's `FTS_SEARCH_PROVIDER` back to `pg_search` and recreate the application container, provided Neon still supports the extension and you have not removed the old search indexes.
-```bash
-bun run scripts/pgSearchCleanup/index.ts --apply --yes
-```
+## 5. Remove the old search indexes
-Use a direct `DATABASE_URL`, not a transaction-pool endpoint. The command refuses to apply before
-`FTS_SEARCH_PROVIDER=elasticsearch`, refuses unrecognized BM25 indexes, removes the known indexes
-concurrently, and then removes the extension without `CASCADE`. It is safe to rerun after an
-interrupted cleanup. It does not remove the Elasticsearch Outbox, capture triggers, or incremental
-consumer.
-
-The official image includes `/app/fts-search-pg-search-cleanup.cjs`:
+Once Elasticsearch search and continuous sync are working, also change `FTS_SEARCH_PROVIDER` to `elasticsearch` in the migration's `.env` file. Inspect and remove the old search indexes and extension:
```bash
docker run --rm --env-file .env \
- lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --status
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --status
docker run --rm --env-file .env \
- lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --apply --yes
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --apply --yes
```
-Affected Neon deployments must complete this cleanup before September 21, 2026. Other PostgreSQL
-providers can keep `pg_search` installed, but removing the retired objects avoids continuing to
-maintain unused BM25 indexes.
+This does not delete chat history or other source data, but you cannot switch directly back to `pg_search` afterward. Complete this step before Neon's deadline for disabling the extension.
+
+## Updating LobeHub later
+
+Keep the application container's progress volume mount, then recreate the application and continuous sync containers using the same new image version. At startup, the application runs PostgreSQL migrations, updates any Elasticsearch indexes that need upgrading, and switches search automatically. Completed indexes are not imported again. The application starts only after migration succeeds and is unavailable during this maintenance.
+
+The official Compose configuration shares the progress volume between the application and migration tools. With a custom Docker configuration, mount the same volume on both. If your initial migration used an existing progress directory, keep mounting that directory instead of switching to an empty volume, and ensure the application container can read and write it.
+
+If migration fails, the application will not start. Check the application container logs and follow the recovery instructions below. Keep the continuous sync container running; a startup migration does not replace it.
+
+## If the migration is interrupted
+
+Keep the `lobehub-search-state` volume. For an interrupted initial manual import, resolve the error and run the import command again without `--fresh-run`. If automatic migration fails during application startup, resolve the error and any retained lock, then restart the application container. It will continue the backfill, catch-up, and switch.
+
+If the migration lock is still held, first confirm that the previous migration process has exited and its Elasticsearch requests have finished. Run the status command to find the lock owner. Replace the import command's final arguments with `--release-lock=<owner-uuid> --yes` to release the lock, then retry the import.
+
+Do not run multiple migration tasks at the same time, delete the progress volume, or skip failed records to bypass an error. If you need help, share the error output with sensitive information removed.
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
index dfa1bc1e0f4..99d33dc6bd2 100644
--- a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
+++ b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
@@ -1,6 +1,6 @@
---
-title: 从 pg_search 迁移到 Elasticsearch(3.x)
-description: 将现有 LobeHub 部署从 PostgreSQL pg_search 安全迁移到 Elasticsearch。
+title: 从 pg_search 迁移到 Elasticsearch
+description: 为使用 Docker 和 Neon 的 LobeHub 部署迁移搜索服务。
tags:
- Elasticsearch
- 搜索
@@ -10,261 +10,126 @@ tags:
# 从 pg\_search 迁移到 Elasticsearch
-本文用于在应用持续可用的情况下,把现有 LobeHub 部署从 PostgreSQL `pg_search` 迁移到
-Elasticsearch。3.x 迁移工具会把 PostgreSQL 中 14 类可搜索数据复制到新的 Elasticsearch 项目。工具会把游标、计数和逐条失败记录原子写入本地 checkpoint 文件,因此中断后使用同一个状态目录重复执行命令即可续跑。
+如果你通过 Docker 部署 LobeHub,数据库使用 Neon,并且当前搜索依赖 `pg_search`,可以按本文将搜索迁移到 Elasticsearch。请在 Neon 停用你所用实例的 `pg_search` 前完成迁移。
-此流程要求数据库已经执行过历史 `pg_search` 迁移,并且当前使用
-`FTS_SEARCH_PROVIDER=pg_search` 提供搜索。搜索后端选择和 Elasticsearch 长期同步链路请先阅读
-[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)。
+如果你的数据库仍支持 `pg_search`,可以继续使用,无需迁移。迁移只更换搜索服务,聊天记录等原始数据仍保存在原来的数据库中。
-<Callout type="warning">
- Neon 已于 2026 年 3 月 19 日停止为新项目提供 `pg_search`,并已通知受影响的现有客户:该扩展将在
- 2026 年 9 月 21 日从 Neon 移除,此后依赖它的查询、索引和应用都会停止工作。请在截止日期前完成本文迁移。
- 对全新数据库设置 `FTS_SEARCH_PROVIDER=elasticsearch` 并不会跳过 LobeHub 的历史 `pg_search` 迁移:
- `bun run db:migrate` 仍会尝试创建扩展和 BM25 索引,并在数据库服务不提供它们时失败。请结合 Neon 的
- [pg\_search 公告](https://neon.com/docs/extensions/pg_search)和
- [扩展列表](https://neon.com/docs/extensions/pg-extensions)核对当前服务状态。
-</Callout>
+## 1. 准备配置
-<Callout type="warning">
- 全量回填命令不会把产品搜索请求切到 Elasticsearch。回填和验收期间,应用必须继续使用 PostgreSQL 搜索。常规数据库迁移会创建 PostgreSQL 增量队列的基础结构和由数据库结构管理的 Memory 扇出 GIN 索引,但不会安装搜索变更采集函数和触发器。只有显式执行 `bun run db:install-fts-search-capture` 或启动 `bun run fts-search:reindex -- --apply` 后才会开始采集,即使增量消费器仍处于暂停状态也是如此。
-</Callout>
+先备份 Neon 数据库,再按[全文搜索配置](/zh/docs/self-hosting/advanced/full-text-search)准备 Elasticsearch。
-## 环境变量
+在服务器上准备迁移使用的 `.env` 文件,填入以下配置。不要把该文件提交到代码仓库。
-| 变量 | 是否必需 | 用途 |
-| ------------------------- | ------- | --------------------------------------------------------------------------------------------------- |
-| `DATABASE_URL` | 是 | PostgreSQL 源数据库和增量变更队列;回填 checkpoint 不写入数据库。 |
-| `ES_URL` | 执行时 | 接收 3.x 搜索索引的新建空 Elasticsearch 目标地址。使用 HTTPS;明文 HTTP 只允许用于回环地址,或在 `ES_ALLOW_INSECURE_HTTP=true` 时使用。 |
-| `ES_API_KEY` | 执行时 | 用于创建索引、批量写入、刷新 / 统计索引和创建别名的 Elasticsearch 密钥,不能使用只读密钥。除 `ES_ALLOW_INSECURE_HTTP=true` 外均为必需。 |
-| `ES_ALLOW_INSECURE_HTTP` | Compose | 仅对关闭安全认证且只能在私有容器网络内访问的 Elasticsearch 节点(例如官方 Compose 的可选服务)设为 `true`。 |
-| `ES_INDEX_NAMESPACE` | 是 | 当前部署长期不变的索引前缀,例如 `lobehub`;会生成 `lobehub-messages` 等别名,续跑时不能修改。 |
-| `FTS_SEARCH_SYNC_ENABLED` | 增量同步 | 只有全量回填就绪后才能设为 `true`,用于启用增量消费器。 |
-| `FTS_SEARCH_PROVIDER` | 切换时 | 回填、追平和验收完成后设为 `elasticsearch`,将用户搜索请求切换到 Elasticsearch。 |
+| 变量 | 设置 |
+| ------------------------- | ------------------------------------------ |
+| `DATABASE_URL` | 当前 Neon 数据库的直连地址,不使用带 `-pooler` 的连接地址 |
+| `DATABASE_DRIVER` | 设为 `node`,使用上面的直连地址 |
+| `ES_REINDEX_STATE_DIR` | 设为 `/app/.elasticsearch-reindex`,并按下文挂载进度卷 |
+| `KEY_VAULTS_SECRET` | 沿用当前 LobeHub 应用的值,不要重新生成 |
+| `ES_URL` | Elasticsearch 地址,必须能从 Docker 容器中访问 |
+| `ES_API_KEY` | 有创建索引和读写权限的 API Key |
+| `ES_INDEX_NAMESPACE` | 索引前缀,例如 `lobehub`;应用和迁移工具保持一致 |
+| `FTS_SEARCH_PROVIDER` | 暂时设为 `pg_search` |
+| `FTS_SEARCH_SYNC_ENABLED` | 暂时设为 `false` |
-只读的 `--status` 命令不需要 `ES_URL` 和 `ES_API_KEY`。
-如果同一个环境中保存了多套 Elasticsearch 目标,可以同时传入 `--elasticsearch-url-env=<变量名>` 和 `--elasticsearch-api-key-env=<变量名>` 显式选择其中一组。两个参数必须成对使用;还可以通过 `--expected-elasticsearch-host-prefix=<主机名前缀>` 在任何回填写入前拒绝错误目标。命令会打印并记录选中的主机名和变量名,但不会记录密钥值。
+外部 Elasticsearch 服务使用 HTTPS 和 API Key。官方 Compose 的私有网络内置节点使用 `ES_ALLOW_INSECURE_HTTP=true`,无需 API Key;使用该节点时,本文的 `docker run` 命令都需要加上 `--network <Elasticsearch 所在网络名>`。容器中的 `localhost` 不是宿主机地址。
-远程 Elasticsearch 目标必须使用 HTTPS。只有本地开发时的 `localhost` 等回环地址可以使用明文 HTTP,避免把 API 密钥通过未加密连接发送到远程主机。唯一的显式例外是
-`ES_ALLOW_INSECURE_HTTP=true`:它允许对私有容器网络内的主机名使用无 API 密钥的明文 HTTP;即便如此,运行时、回填和同步三个客户端都会拒绝通过明文 HTTP 发送 API 密钥。
-
-## 开始前
-
-1. 在正式使用的区域创建一个新的空 Elasticsearch 项目。LobeHub 搜索分析器依赖官方
- [`analysis-icu`](https://www.elastic.co/docs/reference/elasticsearch/plugins/analysis-icu)
- 插件。Elastic Cloud Serverless 已包含核心分析插件;Elastic Cloud Hosted 需要为部署启用官方插件;自行管理的 Elasticsearch 必须在所有节点安装插件并重启所有节点。请在首次执行 `--apply` 前完成。Docker Compose
- 部署也可以改为启用官方 Compose 文件中的可选 `elasticsearch` 服务,其镜像构建时已内置该插件,详见
- [使用 Docker Compose 运行 Elasticsearch](/zh/docs/self-hosting/advanced/full-text-search#使用-docker-compose-运行-elasticsearch)。
-
-2. 在启用 Elasticsearch 采集前创建并验证 PostgreSQL 恢复点,再使用隔离的数据库副本和空
- Elasticsearch 目标演练。演练至少要覆盖每个非空数据类型的一个批次、使用同一 checkpoint
- 续跑、增量追平,以及正式切换时要执行的应用搜索检查。
-
- Neon 用户可以创建子分支进行隔离演练,并为正式根分支创建手动快照或确认时间点恢复窗口。
- 子分支只是隔离的测试副本,本身不能代替正式分支的时间点恢复。请参阅 Neon 的
- [分支文档](https://neon.com/docs/introduction/branching)和
- [备份与恢复文档](https://neon.com/docs/guides/backup-restore)。
-
-3. 执行同一 LobeHub 版本自带的数据库迁移:
-
- ```bash
- bun run db:migrate
- ```
-
- 这一步会创建增量队列的序列、表、普通索引,以及由数据库结构管理的 Memory 扇出 GIN 索引,但不会创建 PostgreSQL 变更采集函数和触发器。只使用 PostgreSQL 搜索的部署可以停在这里:它仍会维护这个 GIN 索引,但不会承担触发器和增量队列的采集写入开销。
-
-4. 在首次回填前安装可选的 PostgreSQL 变更采集:
-
- ```bash
- bun run db:install-fts-search-capture
- ```
-
- 安装器会先严格校验由数据库结构管理的 GIN 索引(不会创建这个索引),再在一个事务中原子安装并验证采集函数和 16 个触发器。完整的预期设施已经存在时可以安全重复执行;如果发现部分对象、被禁用的对象或定义异常,安装器会直接失败,不会静默修复。安装成功后,源数据变更会立即写入增量队列。`bun run fts-search:reindex -- --apply` 也会自动执行这一步;如果希望在准备 Elasticsearch 目标期间就开始采集,可以先显式执行安装命令。若不打算启用 Elasticsearch,不要执行这一步。
-
-5. 保持应用搜索后端为 PostgreSQL,并关闭 Elasticsearch 增量消费。
-
-首次正式映射版本是 `v1`。工具会创建 `lobehub-messages-v1` 这类实体索引;14 类索引全部完成且数量与断点记录一致后,再创建 `lobehub-messages` 这类稳定别名。别名只是 Elasticsearch 内部长期不变的名字,创建别名不会改变用户请求当前使用的搜索后端。
-
-如果稳定别名已经指向另一个物理索引,命令会直接失败,不会移动别名。在线升级索引版本需要另外设计受协调的双写迁移;这套首次迁移工具暂不支持该场景。
-
-## 在源码中运行
-
-包命令会先打包,再用 Node.js 运行回填任务。请使用这里记录的包命令,不要直接执行 TypeScript 入口,以确保运行前准备和临时文件清理方式一致。
-
-只查看状态,不写 Elasticsearch:
+以下命令直接使用官方镜像,数据库连接来自这份配置,不依赖 Compose 内置的 PostgreSQL 服务。在同一个终端执行,并把镜像标签替换为本次部署的版本:
```bash
-bun run fts-search:reindex -- --status
+export LOBE_MIGRATION_IMAGE='lobehub/lobehub:<本次部署的版本标签>'
+docker pull "$LOBE_MIGRATION_IMAGE"
+docker volume create lobehub-search-state
```
-选择可持久保留的本地状态目录,并向空的 Elasticsearch 目标开始一次新回填:
+暂停使用应用,执行该版本的数据库迁移,成功后继续:
```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
- bun run fts-search:reindex -- --apply --fresh-run --yes
-```
-
-只有第一次执行需要 `--fresh-run`。后续使用同一个状态目录续跑:
-
-```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
+docker run --rm --env-file .env \
+ "$LOBE_MIGRATION_IMAGE" /app/docker.cjs
```
-`--apply` 会先创建或校验所有 Elasticsearch 物理索引及其 ICU 分析设置,校验由数据库结构管理的 Memory 扇出 GIN 索引(不会创建这个索引),并以幂等方式安装可选的 PostgreSQL 变更采集设施(如果之前已经安装则复用),然后读取源数据。只读的 `--status` 不会安装或修改这些设施。读取源数据前,`--apply` 会短暂阻挡所有触发器源表的写入,等待持有较旧 Outbox 版本的事务结束;如果三秒内拿不到锁,应先让长事务结束,再重新运行命令。首次回填期间可以暂停增量消费器;PostgreSQL 仍会把变更追加到增量队列,完整快照准备好后再由消费器追平。必须显式传入 `--yes`,用于确认这个会写入数据的操作;命令不会弹出交互确认。
-
-工具还会把 run ID 写入每个物理索引的 mapping 元数据,使用另一份本地 checkpoint 时无法静默继续写入同一组物理索引。禁止在多台机器上并发运行同一份 checkpoint。
+## 2. 导入现有数据
-checkpoint 文件只包含迁移控制状态和脱敏后的失败信息,不保存数据库或 Elasticsearch 密钥。完成验收和增量追平前必须保留整个状态目录;换机器执行时需要一起复制该目录。
-
-如果只想验证 14 类数据都能走通真实回填路径,而不在测试环境跑完整库,可以让每个非空数据类型只执行一个批次,并开启受控并发:
+这一步创建搜索索引并导入现有数据:
```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
- bun run fts-search:reindex -- --apply --yes \
- --expected-elasticsearch-host-prefix=search-dev- \
- --entity-concurrency=4 --bulk-concurrency=2 \
- --batch-size=5000 --entity-batch-size=documents:1000 --bulk-max-bytes=10485760 \
- --max-batches-per-entity=1
+docker run --rm --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \
+ -v lobehub-search-state:/app/.elasticsearch-reindex \
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs \
+ --apply --fresh-run --yes
```
-这条命令会创建 14 类索引,并向其中有源数据的索引写入真实数据。只要至少一类数据超过批次上限,任务就会保持在 `backfilling` 状态且不会创建别名;如果某个小型部署的 14 类数据都能在上限内读完,本次演练仍会正常完成并创建别名,因此必须使用隔离的空 Elasticsearch 目标。使用同一命令再次执行可以验证断点续跑;移除 `--max-batches-per-entity` 后会从当前断点继续,直到所有数据类型完成。
-
-`--entity-concurrency` 控制同时读取多少类 PostgreSQL 数据,`--bulk-concurrency` 控制每个数据类型的单批数据可同时发出多少个按字节拆分的 Elasticsearch 请求。应从较小数值开始,仅在 PostgreSQL 和 Elasticsearch 运行稳定时逐步增加。`--batch-size` 限制每次按主键翻页读取的 PostgreSQL 行数;`--bulk-max-bytes` 按编码后的字节数限制单次 `_bulk` 请求。单个文档超过限制时会被明确记为失败,不会静默跳过。可以重复传入 `--entity-batch-size=<entity>:<rows>`,只缩小超宽数据类型的 PostgreSQL 单页行数,不拖慢其他数据类型。
-
-大规模部署可以重复传入
-`--entity-range-concurrency=<documents|messages>:<workers>`,按 ID 区间并行读取这两类高容量数据。区间模式要求数据库使用逐字节排序规则(`C`、`C.UTF-8` 或 `C.utf8`),命令会在写入前检查。完成的区间只会按 ID 顺序推进持久化游标,因此任务中断后可以安全重放 Elasticsearch 已收到的后续区间。应从较小的并发任务数开始,只在持续观测 PostgreSQL 和 Elasticsearch 均稳定后增加。区间并发不能与 `--max-batches-per-entity` 同时使用。
-
-可以重复传入 `--entity=<entity>`,将一次执行限制到选定的数据类型,例如单独调优 `documents` 和 `messages`。只执行部分类型时不会提前创建别名;只要还有未完成类型,任务就会保持 `backfilling`。选定类型全部完成后,必须再执行一次不带 `--entity` 的续跑,让命令对完整 14 类数据进行最终对账并创建稳定别名。
-
-临时请求失败会先按指数间隔自动重试,再决定是否推进本批游标。默认最多重试 4 次,基础间隔为 500 毫秒,单次请求超时为 30 秒;需要时可通过 `--max-request-retries`、`--retry-base-delay-ms` 和 `--request-timeout-ms` 调整。
-
-每次执行或续跑都会把脱敏后的详细运行事件追加到 `<状态目录>/runs/<run-id>/events.jsonl`,并原子更新 `<状态目录>/runs/<run-id>/summary.json`。日志包含各数据类型和批量请求的耗时、字节数、文档数、重试、游标、失败与最终状态,但不会记录数据库或 Elasticsearch 地址、密钥以及文档正文。迁移或归档任务时,应把这些私有日志和 checkpoint 一起保留。
+迁移进度保存在 `lobehub-search-state` 数据卷中,请保留该数据卷。只有首次导入使用 `--fresh-run`,中断后重试时去掉这个参数。
-只有设置 `ENABLE_TELEMETRY` 后,全量回填命令才会输出 OpenTelemetry 数据。此时必须传入
-`--telemetry-environment=<development|preview|production>`,并配置统一的
-`OTEL_EXPORTER_OTLP_ENDPOINT`,或分别配置指标和链路地址;否则应保持遥测关闭,使用本地事件和汇总文件。
-迁移命令、增量消费器和应用运行时必须显式使用同一个 `ES_INDEX_NAMESPACE`;迁移命令在开发环境也不会为缺失的前缀提供默认值。
-
-## 使用 Docker 镜像运行
-
-官方镜像内置 `/app/fts-search-elasticsearch-reindex.cjs`:
+检查迁移状态:
```bash
-mkdir -m 700 -p .elasticsearch-reindex
-docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
- -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
- -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
- lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --status
-docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
- -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
- -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
- lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --apply --fresh-run --yes
+docker run --rm --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \
+ -v lobehub-search-state:/app/.elasticsearch-reindex \
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs --status
```
-使用 `--rm` 时必须挂载状态目录,否则容器退出后无法续跑。命令使用宿主机当前用户的 ID 运行,使进程可以写入挂载目录,同时不会修改目录所有者。
+当状态显示 `ready_for_incremental_sync`、没有失败记录时,继续下一步。
-## 使用 Docker Compose 运行
+## 3. 启动持续同步
-官方 `docker-compose/deploy/docker-compose.yml` 已将同一条命令定义为 `fts-search-reindex`
-服务,并接入 Compose 内的 PostgreSQL、可选的内部网络 `elasticsearch` 服务,以及保存 checkpoint 的命名卷
-`fts-search-reindex-state`:
+启动同步容器,让后续新增、修改和删除的数据反映到搜索结果中:
```bash
-docker compose run --rm fts-search-reindex --status
-docker compose run --rm fts-search-reindex --apply --fresh-run --yes
+docker run -d --name lobe-fts-search-sync --restart unless-stopped \
+ --env-file .env \
+ -e FTS_SEARCH_SYNC_ENABLED=true \
+ -e MIGRATION_DB=1 \
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-sync.cjs \
+ --max-steps=8 --interval-seconds=15 --yes
```
-额外参数会原样传入,因此上文的演练、`--entity`、`--skip-failure` 和续跑命令都可以直接使用。该服务读取 `.env` 中的
-`ES_URL`、`ES_ALLOW_INSECURE_HTTP` 和 `ES_INDEX_NAMESPACE`;如果目标是外部 Elastic Cloud,请改为在其中设置
-`ES_URL` 和 `ES_API_KEY`,不要设置 `ES_ALLOW_INSECURE_HTTP`,也不要在 `COMPOSE_PROFILES` 中启用 `elasticsearch`
-profile;该服务只依赖 PostgreSQL,因此不会构建或启动内置节点。包含启用节点和同步任务的完整 Compose 流程见
-[使用 Docker Compose 运行 Elasticsearch](/zh/docs/self-hosting/advanced/full-text-search#使用-docker-compose-运行-elasticsearch)。
-
-## 启动增量同步
-
-全量回填状态变为 `ready_for_incremental_sync` 后,设置
-`FTS_SEARCH_SYNC_ENABLED=true`,再运行有明确上限的增量消费器:
+查看日志,确认没有报错:
```bash
-bun run fts-search:sync -- --max-steps=8 --yes
+docker logs --tail 50 lobe-fts-search-sync
```
-每次最多执行 8 轮消费后退出。最终 JSON 中出现 `hasMore: true` 只表示本次达到上限,可以安全再次执行。应使用 cron、容器任务或其他进程管理器持续调度同一条命令,Elasticsearch 承担搜索期间不能停止。消费器会在领取任务前校验 PostgreSQL 采集定义和全部 Elasticsearch 写入别名;采集设施缺失或过期、别名异常、可重试写入失败或死信都会返回非零退出码。消费器不会自动安装触发器,也不会自动删除失败任务。
-省略 `--max-steps` 时只执行一轮;可用范围为 1 到 100。
-
-如果不想依赖外部调度器,可以加上 `--interval-seconds=<1-3600>` 让命令作为长期任务运行:它会重复执行同样的有界消费,`hasMore`
-为 true 时立即继续,否则等待指定秒数,并在收到 `SIGINT` / `SIGTERM` 时完成当前正在进行的那一步消费(而不是整个上限)后正常停止,因此进程管理器的停止超时只需覆盖一步。留下失败或死信任务的那一轮仍会以非零状态退出,因此进程管理器的重启策略和日志能够暴露问题。Compose
-中的 `fts-search-sync` 服务(profile `elasticsearch-sync`)使用的就是这种模式。
-
-官方镜像内置 `/app/fts-search-elasticsearch-sync.cjs`,执行的是同一套有界消费逻辑:
-
-```bash
-docker run --rm --env-file .env \
- -e FTS_SEARCH_SYNC_ENABLED=true \
- -e MIGRATION_DB=1 \
- lobehub/lobehub:latest /app/fts-search-elasticsearch-sync.cjs --max-steps=8 --yes
-```
+再执行上一步的状态检查命令。等待队列中的 `pending`、`ready`、`retrying`、`inFlight`、`dead` 和 `revisionLag` 全部为 `0`,再切换搜索。
-保持持续调度,并反复运行 `bun run fts-search:reindex -- --status`,直到 `pending`、`ready`、`retrying`、`inFlight`、`dead` 和 `revisionLag` 全部为 0。切换查询前必须再检查一次。确认追平后,把 `FTS_SEARCH_PROVIDER` 设为 `elasticsearch` 并重新部署。追平前必须保持 `FTS_SEARCH_PROVIDER=pg_search`。Elasticsearch 出错时会直接暴露给调用方,搜索路径不会静默回退到 PostgreSQL 或 `ilike`。
+切换完成后也要保持这个容器运行,否则后续数据变更不会同步到搜索结果。
-部署后,在约定好的观察窗口内保留旧 BM25 索引和 `pg_search` 扩展。需要确认成功的后端请求都归属于
-`elasticsearch`、没有新增 `pg_search` 请求、增量队列可以反复回到零延迟且没有死信,并完成当前部署实际使用的产品搜索检查。在旧数据库对象仍保留时,回滚只需恢复
-`FTS_SEARCH_PROVIDER=pg_search` 并重新部署;排查 Elasticsearch 期间可以继续运行增量消费任务。如果安装采集后停止消费器,源数据变更会继续在增量队列中累积,直到消费器恢复。
+## 4. 切换搜索
-## 续跑与验收
+为 LobeHub 应用容器也挂载同一个进度卷:`-v lobehub-search-state:/app/.elasticsearch-reindex`,并设置 `ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex`。在应用的部署配置中填写相同的 Elasticsearch 连接信息和索引前缀,将 `FTS_SEARCH_PROVIDER` 改为 `elasticsearch`,然后使用同版本镜像重新创建应用容器。只修改迁移用的 `.env` 文件不会自动更新已运行的应用。
-- 进程崩溃或 Elasticsearch 临时失败后,使用同一个状态目录重新执行 `--apply --yes`,但不要再传 `--fresh-run`。已完成的数据类型会被跳过,未完成的数据类型从本地游标后继续。只要可选的采集设施仍在,暂停期间的变更就会保留在增量队列中,因此可以安全续跑。
-- 整个请求失败时不会推进游标;如果同一批中的部分并发请求成功、另一部分失败,续跑时会安全重放整个数据库批次。逐条写入失败会写入本地 checkpoint,并在该数据类型完成前重试。
-- 任何数据类型或逐条失败尚未完成时,工具都会拒绝创建别名。
-- 最终状态为 `ready_for_incremental_sync`。此时全量快照、别名和增量队列的追平边界已经就绪,但用户查询仍必须留在 PostgreSQL。
+搜索一条已有的聊天记录,再新增一条记录并确认稍后能够搜到。两项都正常,且同步容器没有报错,就可以恢复使用。
-这个修订号只用于观察增量追平进度,不是数据库已经提交的快照边界。增量消费器必须处理队列里的每一条记录,不能仅因修订号小于或等于该值就丢弃记录。
+如果切换后遇到问题,在 Neon 仍支持 `pg_search`、且旧搜索索引尚未清理的情况下,可以将应用的 `FTS_SEARCH_PROVIDER` 改回 `pg_search` 并重新创建应用容器。
-启动上面说明的增量消费器前,运行 `--status`,确认 14 类数据全部为 `completed`、所有 `failedCount` 都是 `0`,且增量队列的 `dead` 为 `0`。增量消费器暂停时,队列中有待处理记录是预期现象;这不代表源数据变更采集已暂停。状态会列出未解决记录的文档标识、是否可重试和尝试次数,不会保存或输出可能包含原文的 Elasticsearch 错误原因。
+## 5. 清理旧搜索
-修正被拒绝的源数据或映射后,再执行 `--apply --yes` 即可重试。如果运维人员明确接受某一条不可重试的数据暂时不进入初始 Elasticsearch 快照,可以显式解除阻塞,然后继续回填:
+确认 Elasticsearch 搜索和持续同步正常后,将迁移用的 `.env` 中 `FTS_SEARCH_PROVIDER` 也改为 `elasticsearch`,检查并清理旧搜索索引和扩展:
```bash
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
- bun run fts-search:reindex -- --skip-failure=agents:document-id --yes
-ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
+docker run --rm --env-file .env \
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --status
+docker run --rm --env-file .env \
+ "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --apply --yes
```
-只有不可重试的失败可以跳过,且跳过不会把该文档计为写入成功。只有在检查源记录,并接受它需要等后续数据变更或增量修复后才能被搜索到时,才能使用这个命令。
-
-回填期间如需暂停写入 Elasticsearch,请使用部署环境提供的增量消费器开关。这只会暂停消费增量队列,不会停止已经安装的 PostgreSQL 采集触发器;源数据变更会继续进入增量队列,消费器重新开启后即可追平。回填进行期间不要禁用或删除触发器,也不要清空增量队列。
+这一步不会删除聊天记录等原始数据,但完成后不能再直接切回 `pg_search`。请在 Neon 要求停用该扩展的时间前完成。
-<Callout type="info">
- 全量回填命令不会代替持续运行的增量消费器,也不会自行宣称应用已经可以切换搜索后端。只要 Elasticsearch 仍在承担搜索,就必须持续调度 `fts-search:sync`。
-</Callout>
+## 后续更新 LobeHub
-## 在 Neon 截止日期前卸载 pg\_search
-
-Elasticsearch 稳定运行并经过观察窗口,且 PostgreSQL 已有当前恢复点后,先查看剩余的 LobeHub 管理对象:
-
-```bash
-bun run scripts/pgSearchCleanup/index.ts --status
-```
+保留应用容器的进度卷挂载,使用同一新版本镜像重新创建应用和持续同步容器即可。应用启动时会先执行 PostgreSQL 迁移,再自动更新需要升级的 Elasticsearch 索引并切换搜索;已完成的索引不会重复导入。迁移成功后才启动应用,期间暂时无法使用。
-确认后通过脚本完成清理,不需要从文档复制 SQL:
+官方 Compose 已让应用与迁移工具共享进度卷。使用自己的 Docker 配置时,两者必须挂载同一个卷;如果首次迁移使用的是已有进度目录,继续挂载该目录,不要换成空卷,并确保应用容器有读写权限。
-```bash
-bun run scripts/pgSearchCleanup/index.ts --apply --yes
-```
+迁移失败时应用不会启动,请查看应用容器日志并按下面的说明恢复。持续同步容器仍需保持运行,它不会由一次启动迁移替代。
-请使用直连 `DATABASE_URL`,不要使用事务池地址。只有
-`FTS_SEARCH_PROVIDER=elasticsearch` 时脚本才允许执行;遇到无法识别的 BM25 索引会拒绝继续。脚本会并发删除
-LobeHub 管理的旧索引,再以不带 `CASCADE` 的方式卸载扩展;中断后可以安全重跑。它不会删除 Elasticsearch
-依赖的增量队列、采集触发器或消费任务。
+## 迁移中断怎么办
-官方镜像内置 `/app/fts-search-pg-search-cleanup.cjs`:
+保留 `lobehub-search-state` 数据卷。首次手动导入中断时,修正错误后重新执行导入命令,去掉 `--fresh-run`。应用启动时的自动迁移失败,则在修正错误、处理残留锁后重新启动应用容器,它会继续完成回填、追平和切换。
-```bash
-docker run --rm --env-file .env \
- lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --status
-docker run --rm --env-file .env \
- lobehub/lobehub:latest /app/fts-search-pg-search-cleanup.cjs --apply --yes
-```
+如果提示迁移锁仍被占用,先确认上一次迁移进程已经退出,且它发出的 Elasticsearch 请求已经结束。再运行状态检查命令,找到锁的 owner,将导入命令最后的参数替换为 `--release-lock=<owner-uuid> --yes` 释放锁,然后重试导入。
-受影响的 Neon 部署必须在 2026 年 9 月 21 日前完成此步骤。其他 PostgreSQL 服务可以保留
-`pg_search`,但删除已停用的对象可以避免继续维护不再使用的 BM25 索引。
+不要同时启动多个迁移任务,也不要通过删除进度数据卷或跳过失败记录来绕过错误。无法解决时,提供脱敏后的错误输出寻求帮助。
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.test.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.test.ts
index 477d43ebf49..5749a274e9e 100644
--- a/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.test.ts
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.test.ts
@@ -1,7 +1,35 @@
import { describe, expect, it } from 'vitest';
+import type { FtsSearchDocumentEntity } from '../../ftsSearchDocument';
+import { FTS_SEARCH_INDEX_DEFINITIONS } from '../../ftsSearchDocument';
import { FTS_SEARCH_BACKEND_ENTITIES } from '../types';
-import { isElasticsearchFtsSearchEntity } from './query-fields';
+import {
+ ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_DOCUMENT_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS,
+ isElasticsearchFtsSearchEntity,
+} from './query-fields';
+
+/** Every query-field list paired with the index definition its field paths must resolve against. */
+const QUERY_FIELDS_BY_INDEX: Array<[FtsSearchDocumentEntity, readonly string[]]> = [
+ ...Object.entries(ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS),
+ ...Object.entries(ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS),
+ ...Object.entries(ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS),
+ ...Object.values(ELASTICSEARCH_FTS_SEARCH_DOCUMENT_QUERY_FIELDS).map(
+ (fields) => ['documents', fields] as const,
+ ),
+] as Array<[FtsSearchDocumentEntity, readonly string[]]>;
+
+const resolveMappingPath = (entity: FtsSearchDocumentEntity, path: string) => {
+ const [field, subfield, ...rest] = path.split('.');
+ if (rest.length > 0) return;
+ const property = FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties[
+ field as keyof (typeof FTS_SEARCH_INDEX_DEFINITIONS)[typeof entity]['mappings']['properties']
+ ] as { fields?: Record<string, { type: string }>; type: string } | undefined;
+ if (!property) return;
+ return subfield ? property.fields?.[subfield] : property;
+};
describe('Elasticsearch query field coverage', () => {
it('covers every full-text search backend entity', () => {
@@ -9,4 +37,24 @@ describe('Elasticsearch query field coverage', () => {
FTS_SEARCH_BACKEND_ENTITIES.filter((entity) => !isElasticsearchFtsSearchEntity(entity)),
).toEqual([]);
});
+
+ it.each(QUERY_FIELDS_BY_INDEX)(
+ 'binds every %s query field to a searchable field in its index mapping',
+ (entity, fields) => {
+ for (const weightedField of fields) {
+ const [path, boost] = weightedField.split('^');
+ const mapping = resolveMappingPath(entity, path);
+
+ expect(
+ mapping,
+ `${entity} query field "${path}" does not exist in FTS_SEARCH_INDEX_DEFINITIONS.${entity}.mappings`,
+ ).toBeDefined();
+ expect(
+ ['keyword', 'text'],
+ `${entity} query field "${path}" is not searchable text`,
+ ).toContain(mapping!.type);
+ if (boost !== undefined) expect(Number(boost)).toBeGreaterThan(0);
+ }
+ },
+ );
});
diff --git a/packages/database/src/repositories/ftsSearchDocument/__tests__/fixtures.ts b/packages/database/src/repositories/ftsSearchDocument/__tests__/fixtures.ts
index 99dede53a61..5ffe33a5c40 100644
--- a/packages/database/src/repositories/ftsSearchDocument/__tests__/fixtures.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/__tests__/fixtures.ts
@@ -1,4 +1,4 @@
-import type { FtsSearchDocumentSourceMap } from '../schema';
+import type { FtsSearchDocumentSourceMap } from '../zodSchema';
const createdAt = '2026-01-01T00:00:00.000Z';
const updatedAt = '2026-01-02T00:00:00.000Z';
diff --git a/packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.json b/packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.json
new file mode 100644
index 00000000000..ea00c5b2f55
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.json
@@ -0,0 +1,60 @@
+{
+ "0000-initial-search-indexes": {
+ "agents": {
+ "fingerprint": "6fd440be1df5ee1437f4a4ec7d22556d1c855ce43bd7fda61ecf0dae32ede233",
+ "schemaVersion": 1
+ },
+ "chatGroups": {
+ "fingerprint": "5b086a9c74ecf70d27334b12cae2de5c5b6412bdc4ad79290514b723b2ec23e2",
+ "schemaVersion": 1
+ },
+ "documents": {
+ "fingerprint": "6d564684eb449d0a70b3c354fa6d9fefe4948cee09d8b46335a7069ac064cde8",
+ "schemaVersion": 1
+ },
+ "files": {
+ "fingerprint": "709e38c13c4684ffc4cb5aec00b4cd276b61a23f0387595bae02466a30291ffc",
+ "schemaVersion": 1
+ },
+ "knowledgeBases": {
+ "fingerprint": "db6e7e1027953600ca9d5d1147f6138ca6868fcd9c58e30e1ce75d2813027320",
+ "schemaVersion": 1
+ },
+ "memoryActivities": {
+ "fingerprint": "ea4665bd0026a75719da8580a350245a8deafa85591d36b577e264e84e32d526",
+ "schemaVersion": 1
+ },
+ "memoryContexts": {
+ "fingerprint": "1b9c24a3ab665a84686c766568d976193f670d469fbd29ff30ab2736f3d23b84",
+ "schemaVersion": 1
+ },
+ "memoryExperiences": {
+ "fingerprint": "9748bd7a25f0f53162ad90e3742244e689b4023c863ad71c226b7d0a9763444c",
+ "schemaVersion": 1
+ },
+ "memoryIdentities": {
+ "fingerprint": "491c3b1a096644552e1486cf6862899bd57042df787f01319442d9e615da0c20",
+ "schemaVersion": 1
+ },
+ "memoryPreferences": {
+ "fingerprint": "e62b555d4548b7f880a6700e0662a3b832a3aa052ad518c869881e1ce99660f7",
+ "schemaVersion": 1
+ },
+ "messages": {
+ "fingerprint": "c1e0a4ea89bd0c3ad7776287deb05eb82a8d286dc851d112a60c729839bc0d4a",
+ "schemaVersion": 1
+ },
+ "personaDocuments": {
+ "fingerprint": "0e627cf7a6a0ce38ae8b06affc5ad6b30c3c443bf93ae19df743f2b652ec323b",
+ "schemaVersion": 1
+ },
+ "topics": {
+ "fingerprint": "362f4b72197fefee4ffb49298aa134c6da6fba9885e7a23840eb55f053a689b8",
+ "schemaVersion": 1
+ },
+ "userMemories": {
+ "fingerprint": "df04d074c1f56b5934891b8612b804917c09302a9042015c394216513093d6e9",
+ "schemaVersion": 1
+ }
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.ts b/packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.ts
new file mode 100644
index 00000000000..24d1a9678f1
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/__tests__/schemaSnapshots.ts
@@ -0,0 +1,15 @@
+import schemaSnapshots from './schemaSnapshots.json';
+
+export interface FtsSearchIndexSchemaSnapshot {
+ fingerprint: string;
+ schemaVersion: number;
+}
+
+/**
+ * Approved physical index schemas, keyed by the source migration batch that introduced them.
+ * Published entries are immutable; append a batch when a mapping or shared analysis changes.
+ */
+export const FTS_SEARCH_INDEX_SCHEMA_SNAPSHOTS: Record<
+ string,
+ Record<string, FtsSearchIndexSchemaSnapshot>
+> = schemaSnapshots;
diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
index b4f4218097f..af0dcce87b6 100644
--- a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
@@ -23,7 +23,7 @@ import {
import type { LobeChatDatabase } from '../../type';
import { FTS_SEARCH_DOCUMENT_FIXTURES } from './__tests__/fixtures';
import { FtsSearchDocumentBuilder } from './builder';
-import { FTS_SEARCH_DOCUMENT_ENTITIES } from './schema';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from './zodSchema';
const userId = 'search-document-user';
const createdAt = new Date('2026-01-01T00:00:00.000Z');
diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.ts b/packages/database/src/repositories/ftsSearchDocument/builder.ts
index 6e854c9ce8b..769812406dc 100644
--- a/packages/database/src/repositories/ftsSearchDocument/builder.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/builder.ts
@@ -23,8 +23,8 @@ import type {
FtsSearchDocumentEntity,
FtsSearchDocumentKey,
FtsSearchDocumentSourceMap,
-} from './schema';
-import { FTS_SEARCH_DOCUMENT_ENTITIES, parseFtsSearchDocumentSource } from './schema';
+} from './zodSchema';
+import { FTS_SEARCH_DOCUMENT_ENTITIES, parseFtsSearchDocumentSource } from './zodSchema';
interface FtsSearchDocumentSelection {
afterId?: string;
diff --git a/packages/database/src/repositories/ftsSearchDocument/fingerprint.test.ts b/packages/database/src/repositories/ftsSearchDocument/fingerprint.test.ts
new file mode 100644
index 00000000000..5c715339c5f
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/fingerprint.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildFtsSearchIndexMeta,
+ findFtsSearchIndexSchemaMismatch,
+ getFtsSearchIndexSchemaFingerprint,
+ sha256Json,
+ stableStringify,
+} from './fingerprint';
+import { FTS_SEARCH_INDEX_ANALYSIS, FTS_SEARCH_INDEX_DEFINITIONS } from './mappings';
+
+describe('stableStringify', () => {
+ it('orders object keys recursively so equivalent inputs hash identically', () => {
+ expect(stableStringify({ b: [{ d: 1, c: 2 }], a: null })).toBe(
+ '{"a":null,"b":[{"c":2,"d":1}]}',
+ );
+ expect(sha256Json({ a: 1, b: 2 })).toBe(sha256Json({ b: 2, a: 1 }));
+ });
+});
+
+describe('getFtsSearchIndexSchemaFingerprint', () => {
+ it('covers both the entity mapping and the shared analysis', () => {
+ expect(getFtsSearchIndexSchemaFingerprint('files')).toBe(
+ sha256Json({
+ analysis: FTS_SEARCH_INDEX_ANALYSIS,
+ mappings: FTS_SEARCH_INDEX_DEFINITIONS.files.mappings,
+ }),
+ );
+ });
+});
+
+describe('buildFtsSearchIndexMeta', () => {
+ it('stamps the declared generation and fingerprint next to the reindex run', () => {
+ expect(buildFtsSearchIndexMeta('agents', 'run-1')).toEqual({
+ reindex_run_id: 'run-1',
+ schema_fingerprint: getFtsSearchIndexSchemaFingerprint('agents'),
+ schema_version: FTS_SEARCH_INDEX_DEFINITIONS.agents.schemaVersion,
+ });
+ });
+});
+
+describe('findFtsSearchIndexSchemaMismatch', () => {
+ const declared = buildFtsSearchIndexMeta('topics', 'run-1');
+
+ it('accepts an index that implements the declared generation', () => {
+ expect(findFtsSearchIndexSchemaMismatch('topics', declared)).toBeUndefined();
+ });
+
+ it('accepts a legacy index without a fingerprint on version alone', () => {
+ expect(
+ findFtsSearchIndexSchemaMismatch('topics', { schema_version: declared.schema_version }),
+ ).toBeUndefined();
+ });
+
+ it('reports a version mismatch before inspecting the fingerprint', () => {
+ expect(
+ findFtsSearchIndexSchemaMismatch('topics', {
+ schema_fingerprint: 'stale',
+ schema_version: declared.schema_version + 1,
+ }),
+ ).toEqual({
+ actual: declared.schema_version + 1,
+ expected: declared.schema_version,
+ kind: 'version',
+ });
+ });
+
+ it('reports drift when the same version carries a different fingerprint', () => {
+ expect(
+ findFtsSearchIndexSchemaMismatch('topics', {
+ schema_fingerprint: 'stale',
+ schema_version: declared.schema_version,
+ }),
+ ).toEqual({ actual: 'stale', expected: declared.schema_fingerprint, kind: 'fingerprint' });
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchDocument/fingerprint.ts b/packages/database/src/repositories/ftsSearchDocument/fingerprint.ts
new file mode 100644
index 00000000000..4b03bc1d027
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/fingerprint.ts
@@ -0,0 +1,81 @@
+import { createHash } from 'node:crypto';
+
+import {
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_INDEX_DEFINITIONS,
+ getFtsSearchIndexSchemaVersion,
+} from './mappings';
+import type { FtsSearchDocumentEntity } from './zodSchema';
+
+/** Deterministic JSON with sorted object keys so semantically equal inputs hash identically. */
+export const stableStringify = (value: unknown): string => {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
+
+ return `{${Object.entries(value)
+ .sort(([leftKey], [rightKey]) => (leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0))
+ .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`)
+ .join(',')}}`;
+};
+
+export const sha256Json = (value: unknown): string =>
+ createHash('sha256').update(stableStringify(value)).digest('hex');
+
+/**
+ * Content hash of everything that shapes a physical index: the entity mapping plus the shared
+ * analysis settings. It is stamped into `_meta.schema_fingerprint` when an index is created so the
+ * runtime can detect drift between the declared target and the live index without diffing
+ * Elasticsearch's normalized mapping response.
+ */
+export const getFtsSearchIndexSchemaFingerprint = (entity: FtsSearchDocumentEntity): string =>
+ sha256Json({
+ analysis: FTS_SEARCH_INDEX_ANALYSIS,
+ mappings: FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings,
+ });
+
+/**
+ * Application metadata stored on every physical index. Elasticsearch never reads `_meta`; it is the
+ * durable record of which declared generation an index implements and which reindex run built it.
+ */
+export interface FtsSearchIndexMeta {
+ reindex_run_id: string;
+ /**
+ * Absent on indexes created before fingerprints existed. Readers treat a missing fingerprint as
+ * legacy and only reject a present fingerprint that differs from the declared one.
+ */
+ schema_fingerprint?: string;
+ schema_version: number;
+}
+
+export const buildFtsSearchIndexMeta = (
+ entity: FtsSearchDocumentEntity,
+ reindexRunId: string,
+): Required<FtsSearchIndexMeta> => ({
+ reindex_run_id: reindexRunId,
+ schema_fingerprint: getFtsSearchIndexSchemaFingerprint(entity),
+ schema_version: getFtsSearchIndexSchemaVersion(entity),
+});
+
+export type FtsSearchIndexSchemaMismatch =
+ | { actual: number; expected: number; kind: 'version' }
+ | { actual: string; expected: string; kind: 'fingerprint' };
+
+/**
+ * Compares a live index's `_meta` against the declared generation for `entity`. Returns the first
+ * mismatch, or `undefined` when the index implements the declared mapping (legacy indexes without a
+ * fingerprint pass on version alone).
+ */
+export const findFtsSearchIndexSchemaMismatch = (
+ entity: FtsSearchDocumentEntity,
+ meta: Pick<FtsSearchIndexMeta, 'schema_fingerprint' | 'schema_version'>,
+): FtsSearchIndexSchemaMismatch | undefined => {
+ const expectedVersion = getFtsSearchIndexSchemaVersion(entity);
+ if (meta.schema_version !== expectedVersion) {
+ return { actual: meta.schema_version, expected: expectedVersion, kind: 'version' };
+ }
+
+ const expectedFingerprint = getFtsSearchIndexSchemaFingerprint(entity);
+ if (meta.schema_fingerprint !== undefined && meta.schema_fingerprint !== expectedFingerprint) {
+ return { actual: meta.schema_fingerprint, expected: expectedFingerprint, kind: 'fingerprint' };
+ }
+};
diff --git a/packages/database/src/repositories/ftsSearchDocument/index.ts b/packages/database/src/repositories/ftsSearchDocument/index.ts
index c175f306ff5..a67fb889817 100644
--- a/packages/database/src/repositories/ftsSearchDocument/index.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/index.ts
@@ -1,3 +1,4 @@
export * from './builder';
+export * from './fingerprint';
export * from './mappings';
-export * from './schema';
+export * from './zodSchema';
diff --git a/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts b/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
index f9b4ad493e2..5511f376e2a 100644
--- a/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
@@ -1,31 +1,72 @@
import { describe, expect, it } from 'vitest';
+import { FTS_SEARCH_INDEX_SCHEMA_SNAPSHOTS } from './__tests__/schemaSnapshots';
+import { getFtsSearchIndexSchemaFingerprint } from './fingerprint';
import {
FTS_SEARCH_INDEX_ANALYSIS,
FTS_SEARCH_INDEX_DEFINITIONS,
FTS_SEARCH_INDEX_SCHEMA_VERSION,
getFtsSearchIndexAlias,
+ getFtsSearchIndexSchemaVersion,
getFtsSearchPhysicalIndexName,
} from './mappings';
+import { FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS } from './migration';
+import { FTS_SEARCH_RETAINED_SOURCE_PROPERTIES } from './policy';
import {
FTS_SEARCH_DOCUMENT_ENTITIES,
FTS_SEARCH_DOCUMENT_SCHEMAS,
FTS_SEARCH_MEMORY_DOCUMENT_ENTITIES,
-} from './schema';
+} from './zodSchema';
+
+describe('search index schema generations', () => {
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)(
+ 'bumps the %s schemaVersion whenever its mapping or analysis fingerprint changes',
+ (entity) => {
+ const actual = {
+ fingerprint: getFtsSearchIndexSchemaFingerprint(entity),
+ schemaVersion: getFtsSearchIndexSchemaVersion(entity),
+ };
+ const migrationId = FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS[entity].id;
+ const snapshot = FTS_SEARCH_INDEX_SCHEMA_SNAPSHOTS[migrationId]?.[entity];
+
+ expect(
+ snapshot,
+ `Add the approved ${migrationId}/${entity} schemaVersion and fingerprint to FTS_SEARCH_INDEX_SCHEMA_SNAPSHOTS.`,
+ ).toBeDefined();
+ expect(actual).toEqual(snapshot);
+ },
+ );
+
+ it('derives distinct fingerprints from the mapping, not from the entity name', () => {
+ expect(getFtsSearchIndexSchemaFingerprint('agents')).not.toBe(
+ getFtsSearchIndexSchemaFingerprint('topics'),
+ );
+ expect(getFtsSearchIndexSchemaFingerprint('agents')).toMatch(/^[\da-f]{64}$/);
+ });
+});
describe('search index mappings', () => {
it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('matches every %s schema field exactly', (entity) => {
const schemaFields = Object.keys(FTS_SEARCH_DOCUMENT_SCHEMAS[entity].shape).sort();
- const mappingFields = Object.keys(
- FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties,
- ).sort();
+ const mappedFields = Object.keys(FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties);
+ const retainedFields = Object.keys(FTS_SEARCH_RETAINED_SOURCE_PROPERTIES[entity]);
- expect(mappingFields).toEqual(schemaFields);
+ expect(mappedFields.filter((field) => retainedFields.includes(field))).toEqual([]);
+ expect([...mappedFields, ...retainedFields].sort()).toEqual(schemaFields);
expect(FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.dynamic).toBe('strict');
});
it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('only queries text fields for %s', (entity) => {
const definition = FTS_SEARCH_INDEX_DEFINITIONS[entity];
+ const retainedFields = new Set(Object.keys(FTS_SEARCH_RETAINED_SOURCE_PROPERTIES[entity]));
+
+ for (const field of [
+ ...('indexedOnlyFields' in definition ? definition.indexedOnlyFields : []),
+ ...('longTextFields' in definition ? definition.longTextFields : []),
+ ...definition.queryFields,
+ ]) {
+ expect(retainedFields.has(field)).toBe(false);
+ }
for (const field of definition.queryFields) {
expect(Object.entries(definition.mappings.properties)).toContainEqual([
@@ -45,12 +86,13 @@ describe('search index mappings', () => {
});
it('provides deployment-neutral versioned alias and physical names', () => {
+ // The first rollout built every entity as v1; later generations move per entity.
expect(FTS_SEARCH_INDEX_SCHEMA_VERSION).toBe(1);
expect(getFtsSearchIndexAlias('lobehub-dev', 'knowledgeBases')).toBe(
'lobehub-dev-knowledge-bases',
);
expect(getFtsSearchPhysicalIndexName('lobehub-dev', 'knowledgeBases')).toBe(
- 'lobehub-dev-knowledge-bases-v1',
+ `lobehub-dev-knowledge-bases-v${getFtsSearchIndexSchemaVersion('knowledgeBases')}`,
);
expect(getFtsSearchPhysicalIndexName('lobehub-dev', 'knowledgeBases', 4)).toBe(
'lobehub-dev-knowledge-bases-v4',
diff --git a/packages/database/src/repositories/ftsSearchDocument/mappings.ts b/packages/database/src/repositories/ftsSearchDocument/mappings.ts
index 9ce9b08fdc8..828e66bb96b 100644
--- a/packages/database/src/repositories/ftsSearchDocument/mappings.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/mappings.ts
@@ -1,456 +1,91 @@
-import type { FtsSearchDocumentEntity, FtsSearchDocumentSourceMap } from './schema';
+import { FTS_SEARCH_CURRENT_MAPPINGS } from './migration';
+import type { ElasticsearchFtsSearchMappingProperty } from './migration/types';
+import type { FTS_SEARCH_RETAINED_SOURCE_PROPERTIES, FtsSearchIndexPolicy } from './policy';
+import { FTS_SEARCH_INDEX_POLICY } from './policy';
+import type { FtsSearchDocumentEntity, FtsSearchDocumentSourceMap } from './zodSchema';
-export type ElasticsearchFtsSearchFieldType = 'boolean' | 'date' | 'integer' | 'keyword' | 'text';
+export { FTS_SEARCH_INDEX_ANALYSIS } from './migration';
+export type {
+ ElasticsearchFtsSearchFieldType,
+ ElasticsearchFtsSearchMappingProperty,
+} from './migration/types';
-export interface ElasticsearchFtsSearchMappingProperty {
- analyzer?: string;
- fields?: Record<string, ElasticsearchFtsSearchMappingProperty>;
- ignore_above?: number;
- type: ElasticsearchFtsSearchFieldType;
-}
-
-export interface FtsSearchIndexDefinition<Entity extends FtsSearchDocumentEntity> {
- indexedOnlyFields?: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
- longTextFields?: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+export interface FtsSearchIndexDefinition<
+ Entity extends FtsSearchDocumentEntity,
+> extends FtsSearchIndexPolicy<Entity> {
mappings: {
dynamic: 'strict';
properties: Record<
- keyof FtsSearchDocumentSourceMap[Entity] & string,
+ Exclude<
+ keyof FtsSearchDocumentSourceMap[Entity] & string,
+ keyof (typeof FTS_SEARCH_RETAINED_SOURCE_PROPERTIES)[Entity]
+ >,
ElasticsearchFtsSearchMappingProperty
>;
};
- queryFields: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+ /**
+ * Physical index generation for this entity. Elasticsearch cannot alter most mapping parameters
+ * in place, so any change to `mappings` or the shared analysis must bump this number; the new
+ * generation is rebuilt from PostgreSQL into `<alias>-v<schemaVersion>` and promoted by moving
+ * the alias. The fingerprint gate test in `mappings.test.ts` enforces the bump.
+ */
+ schemaVersion: number;
}
-const mixedText = { analyzer: 'lobehub_icu_english', type: 'text' } as const;
-const memoryText = { analyzer: 'lobehub_cjk_bigram_english', type: 'text' } as const;
-const memoryTextWithRaw = {
- analyzer: 'lobehub_cjk_bigram_english',
- fields: { raw: { ignore_above: 256, type: 'keyword' } },
- type: 'text',
-} as const;
-const fileNameText = {
- analyzer: 'lobehub_filename',
- fields: {
- raw: { ignore_above: 256, type: 'keyword' },
- words: { analyzer: 'lobehub_icu', type: 'text' },
- },
- type: 'text',
-} as const;
-const icuText = {
- analyzer: 'lobehub_icu',
- fields: { raw: { ignore_above: 256, type: 'keyword' } },
- type: 'text',
-} as const;
-const keyword = { type: 'keyword' } as const;
-const date = { type: 'date' } as const;
-const integer = { type: 'integer' } as const;
-const boolean = { type: 'boolean' } as const;
-
-const ownershipProperties = {
- user_id: keyword,
- visibility: keyword,
- workspace_id: keyword,
-};
-
-const timestampProperties = {
- created_at: date,
- updated_at: date,
-};
-
-const projectionMetadataProperties = {
- fts_search_sync_deleted: boolean,
-};
-
-export const FTS_SEARCH_INDEX_ANALYSIS = {
- analyzer: {
- lobehub_cjk_bigram_english: {
- /** Normalize width and case before generating CJK bigrams so decomposed characters stay intact. */
- filter: [
- 'english_possessive_stemmer',
- 'icu_folding',
- 'cjk_bigram',
- 'english_stop',
- 'english_stemmer',
- ],
- tokenizer: 'standard',
- type: 'custom',
- },
- lobehub_filename: {
- filter: ['icu_folding'],
- tokenizer: 'lobehub_filename',
- type: 'custom',
- },
- lobehub_icu: {
- filter: ['icu_folding'],
- tokenizer: 'icu_tokenizer',
- type: 'custom',
- },
- lobehub_icu_english: {
- filter: ['english_possessive_stemmer', 'icu_folding', 'english_stop', 'english_stemmer'],
- tokenizer: 'icu_tokenizer',
- type: 'custom',
- },
- },
- filter: {
- english_possessive_stemmer: {
- language: 'possessive_english',
- type: 'stemmer',
- },
- english_stemmer: {
- language: 'english',
- type: 'stemmer',
- },
- english_stop: {
- stopwords: '_english_',
- type: 'stop',
- },
- },
- tokenizer: {
- lobehub_filename: {
- tokenize_on_chars: ['whitespace', '-', '_', '/', '.'],
- type: 'char_group',
- },
- },
-} as const;
-
+/** Public current definitions; history and current query metadata have separate owners. */
export const FTS_SEARCH_INDEX_DEFINITIONS = {
- agents: {
- longTextFields: ['system_role'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...ownershipProperties,
- ...projectionMetadataProperties,
- ...timestampProperties,
- description: mixedText,
- id: keyword,
- slug: icuText,
- system_role: mixedText,
- tags: icuText,
- title: mixedText,
- virtual: boolean,
- },
- },
- queryFields: ['title', 'description', 'slug', 'tags', 'system_role'],
- } satisfies FtsSearchIndexDefinition<'agents'>,
- chatGroups: {
- indexedOnlyFields: ['content'],
- longTextFields: ['content'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...ownershipProperties,
- ...projectionMetadataProperties,
- ...timestampProperties,
- content: mixedText,
- description: mixedText,
- group_id: keyword,
- id: keyword,
- title: mixedText,
- },
- },
- queryFields: ['title', 'description', 'content'],
- } satisfies FtsSearchIndexDefinition<'chatGroups'>,
- documents: {
- longTextFields: ['content'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...ownershipProperties,
- ...projectionMetadataProperties,
- ...timestampProperties,
- content: mixedText,
- description: mixedText,
- file_id: keyword,
- file_type: keyword,
- id: keyword,
- knowledge_base_id: keyword,
- knowledge_base_ids: keyword,
- parent_id: keyword,
- slug: icuText,
- source_type: keyword,
- title: mixedText,
- total_char_count: integer,
- },
- },
- queryFields: ['title', 'slug', 'description', 'content'],
- } satisfies FtsSearchIndexDefinition<'documents'>,
- files: {
- mappings: {
- dynamic: 'strict',
- properties: {
- ...ownershipProperties,
- ...projectionMetadataProperties,
- ...timestampProperties,
- file_type: keyword,
- id: keyword,
- knowledge_base_ids: keyword,
- name: fileNameText,
- size: integer,
- source: keyword,
- },
- },
- /** Provider-neutral source field; Elasticsearch-only multi-fields are selected by its backend. */
- queryFields: ['name'],
- } satisfies FtsSearchIndexDefinition<'files'>,
+ agents: { ...FTS_SEARCH_CURRENT_MAPPINGS.agents, ...FTS_SEARCH_INDEX_POLICY.agents },
+ chatGroups: { ...FTS_SEARCH_CURRENT_MAPPINGS.chatGroups, ...FTS_SEARCH_INDEX_POLICY.chatGroups },
+ documents: { ...FTS_SEARCH_CURRENT_MAPPINGS.documents, ...FTS_SEARCH_INDEX_POLICY.documents },
+ files: { ...FTS_SEARCH_CURRENT_MAPPINGS.files, ...FTS_SEARCH_INDEX_POLICY.files },
knowledgeBases: {
- longTextFields: ['description'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...ownershipProperties,
- ...projectionMetadataProperties,
- ...timestampProperties,
- description: mixedText,
- id: keyword,
- is_public: boolean,
- name: icuText,
- type: keyword,
- },
- },
- queryFields: ['name', 'description'],
- } satisfies FtsSearchIndexDefinition<'knowledgeBases'>,
+ ...FTS_SEARCH_CURRENT_MAPPINGS.knowledgeBases,
+ ...FTS_SEARCH_INDEX_POLICY.knowledgeBases,
+ },
memoryActivities: {
- longTextFields: ['notes', 'narrative', 'feedback'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- captured_at: date,
- ends_at: date,
- feedback: memoryText,
- id: keyword,
- narrative: memoryText,
- notes: memoryText,
- parent_details: memoryText,
- parent_memory_categories: keyword,
- parent_summary: memoryText,
- parent_tags: keyword,
- parent_title: memoryText,
- starts_at: date,
- status: keyword,
- tags: keyword,
- type: keyword,
- user_id: keyword,
- user_memory_id: keyword,
- },
- },
- queryFields: [
- 'parent_title',
- 'parent_summary',
- 'parent_details',
- 'narrative',
- 'notes',
- 'feedback',
- ],
- } satisfies FtsSearchIndexDefinition<'memoryActivities'>,
+ ...FTS_SEARCH_CURRENT_MAPPINGS.memoryActivities,
+ ...FTS_SEARCH_INDEX_POLICY.memoryActivities,
+ },
memoryContexts: {
- longTextFields: ['description', 'current_status'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- captured_at: date,
- current_status: memoryTextWithRaw,
- description: memoryText,
- id: keyword,
- parent_text: memoryText,
- parent_memory_categories: keyword,
- parent_tags: keyword,
- tags: keyword,
- title: memoryText,
- type: keyword,
- user_id: keyword,
- user_memory_ids: keyword,
- },
- },
- queryFields: ['parent_text', 'title', 'description', 'current_status'],
- } satisfies FtsSearchIndexDefinition<'memoryContexts'>,
+ ...FTS_SEARCH_CURRENT_MAPPINGS.memoryContexts,
+ ...FTS_SEARCH_INDEX_POLICY.memoryContexts,
+ },
memoryExperiences: {
- longTextFields: ['situation', 'reasoning', 'possible_outcome', 'action', 'key_learning'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- action: memoryText,
- captured_at: date,
- id: keyword,
- key_learning: memoryText,
- parent_details: memoryText,
- parent_memory_categories: keyword,
- parent_summary: memoryText,
- parent_tags: keyword,
- parent_title: memoryText,
- possible_outcome: memoryText,
- reasoning: memoryText,
- situation: memoryText,
- tags: keyword,
- type: keyword,
- user_id: keyword,
- user_memory_id: keyword,
- },
- },
- queryFields: [
- 'parent_title',
- 'parent_summary',
- 'parent_details',
- 'situation',
- 'reasoning',
- 'possible_outcome',
- 'action',
- 'key_learning',
- ],
- } satisfies FtsSearchIndexDefinition<'memoryExperiences'>,
+ ...FTS_SEARCH_CURRENT_MAPPINGS.memoryExperiences,
+ ...FTS_SEARCH_INDEX_POLICY.memoryExperiences,
+ },
memoryIdentities: {
- longTextFields: ['description', 'role'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- captured_at: date,
- description: memoryText,
- episodic_date: date,
- id: keyword,
- parent_details: memoryText,
- parent_memory_categories: keyword,
- parent_summary: memoryText,
- parent_tags: keyword,
- parent_title: memoryText,
- relationship: keyword,
- role: memoryText,
- tags: keyword,
- type: keyword,
- user_id: keyword,
- user_memory_id: keyword,
- },
- },
- queryFields: ['parent_title', 'parent_summary', 'parent_details', 'description', 'role'],
- } satisfies FtsSearchIndexDefinition<'memoryIdentities'>,
+ ...FTS_SEARCH_CURRENT_MAPPINGS.memoryIdentities,
+ ...FTS_SEARCH_INDEX_POLICY.memoryIdentities,
+ },
memoryPreferences: {
- longTextFields: ['conclusion_directives', 'suggestions'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- captured_at: date,
- conclusion_directives: memoryText,
- id: keyword,
- parent_details: memoryText,
- parent_memory_categories: keyword,
- parent_summary: memoryText,
- parent_tags: keyword,
- parent_title: memoryText,
- suggestions: memoryText,
- tags: keyword,
- type: keyword,
- user_id: keyword,
- user_memory_id: keyword,
- },
- },
- queryFields: [
- 'parent_title',
- 'parent_summary',
- 'parent_details',
- 'conclusion_directives',
- 'suggestions',
- ],
- } satisfies FtsSearchIndexDefinition<'memoryPreferences'>,
- messages: {
- indexedOnlyFields: ['summary'],
- longTextFields: ['content', 'summary'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- agent_id: keyword,
- content: mixedText,
- group_id: keyword,
- id: keyword,
- role: keyword,
- session_id: keyword,
- summary: mixedText,
- thread_id: keyword,
- topic_id: keyword,
- user_id: keyword,
- workspace_id: keyword,
- },
- },
- queryFields: ['content', 'summary'],
- } satisfies FtsSearchIndexDefinition<'messages'>,
+ ...FTS_SEARCH_CURRENT_MAPPINGS.memoryPreferences,
+ ...FTS_SEARCH_INDEX_POLICY.memoryPreferences,
+ },
+ messages: { ...FTS_SEARCH_CURRENT_MAPPINGS.messages, ...FTS_SEARCH_INDEX_POLICY.messages },
personaDocuments: {
- longTextFields: ['persona'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- captured_at: date,
- id: keyword,
- persona: memoryText,
- profile: keyword,
- tagline: memoryText,
- user_id: keyword,
- version: integer,
- },
- },
- queryFields: ['tagline', 'persona'],
- } satisfies FtsSearchIndexDefinition<'personaDocuments'>,
- topics: {
- longTextFields: ['content'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- agent_id: keyword,
- content: mixedText,
- description: mixedText,
- group_id: keyword,
- id: keyword,
- session_id: keyword,
- status: keyword,
- title: mixedText,
- user_id: keyword,
- workspace_id: keyword,
- },
- },
- queryFields: ['title', 'content', 'description'],
- } satisfies FtsSearchIndexDefinition<'topics'>,
+ ...FTS_SEARCH_CURRENT_MAPPINGS.personaDocuments,
+ ...FTS_SEARCH_INDEX_POLICY.personaDocuments,
+ },
+ topics: { ...FTS_SEARCH_CURRENT_MAPPINGS.topics, ...FTS_SEARCH_INDEX_POLICY.topics },
userMemories: {
- longTextFields: ['details'],
- mappings: {
- dynamic: 'strict',
- properties: {
- ...projectionMetadataProperties,
- ...timestampProperties,
- captured_at: date,
- details: memoryText,
- id: keyword,
- memory_category: keyword,
- memory_layer: keyword,
- status: keyword,
- summary: memoryText,
- tags: keyword,
- title: memoryText,
- user_id: keyword,
- },
- },
- queryFields: ['title', 'summary', 'details'],
- } satisfies FtsSearchIndexDefinition<'userMemories'>,
-} as const satisfies {
- [Entity in FtsSearchDocumentEntity]: FtsSearchIndexDefinition<Entity>;
-};
+ ...FTS_SEARCH_CURRENT_MAPPINGS.userMemories,
+ ...FTS_SEARCH_INDEX_POLICY.userMemories,
+ },
+} as const satisfies { [Entity in FtsSearchDocumentEntity]: FtsSearchIndexDefinition<Entity> };
-/** First production Elasticsearch mapping version. Development-only iterations were never shipped. */
+/**
+ * Generation of the first production rollout, when every entity was built by one reindex run.
+ * Generations are per entity now and `getFtsSearchIndexSchemaVersion` is the authoritative value;
+ * this constant only identifies that initial checkpoint.
+ *
+ * @deprecated Use `getFtsSearchIndexSchemaVersion(entity)`.
+ */
export const FTS_SEARCH_INDEX_SCHEMA_VERSION = 1;
+export const getFtsSearchIndexSchemaVersion = (entity: FtsSearchDocumentEntity): number =>
+ FTS_SEARCH_INDEX_DEFINITIONS[entity].schemaVersion;
+
const toIndexSegment = (entity: FtsSearchDocumentEntity) =>
entity.replaceAll(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
@@ -461,5 +96,5 @@ export const getFtsSearchIndexAlias = (namespace: string, entity: FtsSearchDocum
export const getFtsSearchPhysicalIndexName = (
namespace: string,
entity: FtsSearchDocumentEntity,
- version: number = FTS_SEARCH_INDEX_SCHEMA_VERSION,
+ version: number = getFtsSearchIndexSchemaVersion(entity),
) => `${getFtsSearchIndexAlias(namespace, entity)}-v${version}`;
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/analysis.ts b/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/analysis.ts
new file mode 100644
index 00000000000..db8e8ae4765
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/analysis.ts
@@ -0,0 +1,51 @@
+export const analysis = {
+ analyzer: {
+ lobehub_cjk_bigram_english: {
+ /** Normalize width and case before generating CJK bigrams so decomposed characters stay intact. */
+ filter: [
+ 'english_possessive_stemmer',
+ 'icu_folding',
+ 'cjk_bigram',
+ 'english_stop',
+ 'english_stemmer',
+ ],
+ tokenizer: 'standard',
+ type: 'custom',
+ },
+ lobehub_filename: {
+ filter: ['icu_folding'],
+ tokenizer: 'lobehub_filename',
+ type: 'custom',
+ },
+ lobehub_icu: {
+ filter: ['icu_folding'],
+ tokenizer: 'icu_tokenizer',
+ type: 'custom',
+ },
+ lobehub_icu_english: {
+ filter: ['english_possessive_stemmer', 'icu_folding', 'english_stop', 'english_stemmer'],
+ tokenizer: 'icu_tokenizer',
+ type: 'custom',
+ },
+ },
+ filter: {
+ english_possessive_stemmer: {
+ language: 'possessive_english',
+ type: 'stemmer',
+ },
+ english_stemmer: {
+ language: 'english',
+ type: 'stemmer',
+ },
+ english_stop: {
+ stopwords: '_english_',
+ type: 'stop',
+ },
+ },
+ tokenizer: {
+ lobehub_filename: {
+ tokenize_on_chars: ['whitespace', '-', '_', '/', '.'],
+ type: 'char_group',
+ },
+ },
+} as const;
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/fields.ts b/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/fields.ts
new file mode 100644
index 00000000000..aa967b893c6
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/fields.ts
@@ -0,0 +1,39 @@
+export const mixedText = { analyzer: 'lobehub_icu_english', type: 'text' } as const;
+export const memoryText = { analyzer: 'lobehub_cjk_bigram_english', type: 'text' } as const;
+export const memoryTextWithRaw = {
+ analyzer: 'lobehub_cjk_bigram_english',
+ fields: { raw: { ignore_above: 256, type: 'keyword' } },
+ type: 'text',
+} as const;
+export const fileNameText = {
+ analyzer: 'lobehub_filename',
+ fields: {
+ raw: { ignore_above: 256, type: 'keyword' },
+ words: { analyzer: 'lobehub_icu', type: 'text' },
+ },
+ type: 'text',
+} as const;
+export const icuText = {
+ analyzer: 'lobehub_icu',
+ fields: { raw: { ignore_above: 256, type: 'keyword' } },
+ type: 'text',
+} as const;
+export const keyword = { type: 'keyword' } as const;
+export const date = { type: 'date' } as const;
+export const integer = { type: 'integer' } as const;
+export const boolean = { type: 'boolean' } as const;
+
+export const ownershipProperties = {
+ user_id: keyword,
+ visibility: keyword,
+ workspace_id: keyword,
+};
+
+export const timestampProperties = {
+ created_at: date,
+ updated_at: date,
+};
+
+export const projectionMetadataProperties = {
+ fts_search_sync_deleted: boolean,
+};
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/mapping.ts b/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/mapping.ts
new file mode 100644
index 00000000000..c9c575d3b01
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/0000-initial-search-indexes/mapping.ts
@@ -0,0 +1,315 @@
+import type { FtsSearchMappingMigration } from '../types';
+import { analysis } from './analysis';
+import {
+ boolean,
+ date,
+ fileNameText,
+ icuText,
+ integer,
+ keyword,
+ memoryText,
+ memoryTextWithRaw,
+ mixedText,
+ ownershipProperties,
+ projectionMetadataProperties,
+ timestampProperties,
+} from './fields';
+
+/** Initial physical snapshots. Published batches retain their fields and analysis unchanged. */
+export const initialSearchIndexes = {
+ id: '0000-initial-search-indexes',
+ analysis,
+ definitions: {
+ agents: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ description: mixedText,
+ id: keyword,
+ slug: icuText,
+ system_role: mixedText,
+ tags: icuText,
+ title: mixedText,
+ virtual: boolean,
+ },
+ },
+ schemaVersion: 1,
+ },
+ chatGroups: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ content: mixedText,
+ description: mixedText,
+ group_id: keyword,
+ id: keyword,
+ title: mixedText,
+ },
+ },
+ schemaVersion: 1,
+ },
+ documents: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ content: mixedText,
+ description: mixedText,
+ file_id: keyword,
+ file_type: keyword,
+ id: keyword,
+ knowledge_base_id: keyword,
+ knowledge_base_ids: keyword,
+ parent_id: keyword,
+ slug: icuText,
+ source_type: keyword,
+ title: mixedText,
+ total_char_count: integer,
+ },
+ },
+ schemaVersion: 1,
+ },
+ files: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ file_type: keyword,
+ id: keyword,
+ knowledge_base_ids: keyword,
+ name: fileNameText,
+ size: integer,
+ source: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ knowledgeBases: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ description: mixedText,
+ id: keyword,
+ is_public: boolean,
+ name: icuText,
+ type: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ memoryActivities: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ ends_at: date,
+ feedback: memoryText,
+ id: keyword,
+ narrative: memoryText,
+ notes: memoryText,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ starts_at: date,
+ status: keyword,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ memoryContexts: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ current_status: memoryTextWithRaw,
+ description: memoryText,
+ id: keyword,
+ parent_text: memoryText,
+ parent_memory_categories: keyword,
+ parent_tags: keyword,
+ tags: keyword,
+ title: memoryText,
+ type: keyword,
+ user_id: keyword,
+ user_memory_ids: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ memoryExperiences: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ action: memoryText,
+ captured_at: date,
+ id: keyword,
+ key_learning: memoryText,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ possible_outcome: memoryText,
+ reasoning: memoryText,
+ situation: memoryText,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ memoryIdentities: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ description: memoryText,
+ episodic_date: date,
+ id: keyword,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ relationship: keyword,
+ role: memoryText,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ memoryPreferences: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ conclusion_directives: memoryText,
+ id: keyword,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ suggestions: memoryText,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ messages: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ agent_id: keyword,
+ content: mixedText,
+ group_id: keyword,
+ id: keyword,
+ role: keyword,
+ session_id: keyword,
+ summary: mixedText,
+ thread_id: keyword,
+ topic_id: keyword,
+ user_id: keyword,
+ workspace_id: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ personaDocuments: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ id: keyword,
+ persona: memoryText,
+ profile: keyword,
+ tagline: memoryText,
+ user_id: keyword,
+ version: integer,
+ },
+ },
+ schemaVersion: 1,
+ },
+ topics: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ agent_id: keyword,
+ content: mixedText,
+ description: mixedText,
+ group_id: keyword,
+ id: keyword,
+ session_id: keyword,
+ status: keyword,
+ title: mixedText,
+ user_id: keyword,
+ workspace_id: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ userMemories: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ details: memoryText,
+ id: keyword,
+ memory_category: keyword,
+ memory_layer: keyword,
+ status: keyword,
+ summary: memoryText,
+ tags: keyword,
+ title: memoryText,
+ user_id: keyword,
+ },
+ },
+ schemaVersion: 1,
+ },
+ },
+} as const satisfies FtsSearchMappingMigration;
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/README.md b/packages/database/src/repositories/ftsSearchDocument/migration/README.md
new file mode 100644
index 00000000000..24f2ab44e2f
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/README.md
@@ -0,0 +1,30 @@
+# Search mapping history
+
+Each numbered directory is a source-history batch, not an executable SQL migration or an entity
+schema version. `0000-initial-search-indexes` contains all initial v1 indexes. Later batches contain
+complete physical definitions only for entities that change.
+
+- `mapping.ts` binds the batch ID, entity definitions and analysis settings.
+- `fields.ts` owns fixed field presets and shared property fragments for that batch.
+- `analysis.ts` owns fixed analysis settings. A later batch can import an unchanged earlier analysis.
+- `index.ts` registers all batches and explicitly selects the current batch for each entity.
+- `../policy.ts` owns current query and document metadata; `../zodSchema.ts` owns current validation.
+- `../mappings.ts` combines current physical definitions and policy for existing consumers.
+
+For a new mapping, add the next numbered directory with a meaningful name, increment each affected
+entity's `schemaVersion`, register the batch and update its current pointers. Retain historical fields
+even when the current Zod schema removes them. Analysis is still global: changing it requires a new
+version for every current entity. Current mapping fields plus explicitly retained source properties
+in `../policy.ts` must match the current Zod schema exactly, without overlap. Retain source fields
+and builder output while any old open index needs them; reindex omits source-only fields from the
+current strict mapping, while sync continues filling older mappings. Only remove the retained
+properties after the old indexes are closed and rollback to their code is no longer needed.
+
+Append approved fingerprints to `../__tests__/schemaSnapshots.json`. The PR history check compares
+the merge result with the target commit: existing batch directories and JSON baseline entries cannot
+change, including when both mapping and fingerprint are edited together. New batches must have
+higher, unique ordinals. Keep this CI job required in repository rules to enforce the guard; tests
+still verify registration, current pointers, field coverage and version/fingerprint consistency.
+
+This catalog does not execute migrations or reconstruct old documents with the current builder.
+Build, promote, rollback, retire and purge continue through the Elasticsearch reindex commands.
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/index.test.ts b/packages/database/src/repositories/ftsSearchDocument/migration/index.test.ts
new file mode 100644
index 00000000000..8c08acffc30
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/index.test.ts
@@ -0,0 +1,107 @@
+import { readdir } from 'node:fs/promises';
+
+import { describe, expect, it } from 'vitest';
+
+import { FTS_SEARCH_INDEX_SCHEMA_SNAPSHOTS } from '../__tests__/schemaSnapshots';
+import { sha256Json } from '../fingerprint';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '../zodSchema';
+import {
+ FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS,
+ FTS_SEARCH_CURRENT_MAPPINGS,
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_MAPPING_MIGRATIONS,
+} from '.';
+import type { FtsSearchMappingMigration, FtsSearchMappingSnapshot } from './types';
+
+const getDefinition = (migration: FtsSearchMappingMigration, entity: string) =>
+ migration.definitions[entity];
+
+const fingerprintOf = (
+ migration: FtsSearchMappingMigration,
+ definition: FtsSearchMappingSnapshot,
+) =>
+ sha256Json({
+ analysis: migration.analysis,
+ mappings: definition.mappings,
+ });
+
+describe('search mapping migration history', () => {
+ it('registers every migration directory in source order', async () => {
+ const entries = await readdir(__dirname, { withFileTypes: true });
+ const directoryIds = entries
+ .filter((entry) => entry.isDirectory() && /^\d{4}-/.test(entry.name))
+ .map((entry) => entry.name)
+ .sort();
+
+ expect(FTS_SEARCH_MAPPING_MIGRATIONS.map(({ id }) => id)).toEqual(directoryIds);
+ });
+
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)(
+ 'selects the latest registered mapping for %s',
+ (entity) => {
+ const migrations = FTS_SEARCH_MAPPING_MIGRATIONS.filter(
+ (migration) => entity in migration.definitions,
+ );
+ const latestMigration = migrations.at(-1);
+
+ expect(latestMigration, `${entity} must have at least one registered mapping`).toBeDefined();
+ expect(FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS[entity]).toBe(latestMigration);
+ expect(FTS_SEARCH_CURRENT_MAPPINGS[entity]).toBe(
+ getDefinition(FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS[entity], entity),
+ );
+ },
+ );
+
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)(
+ 'binds the current %s mapping to the global analysis',
+ (entity) => {
+ expect(FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS[entity].analysis).toEqual(
+ FTS_SEARCH_INDEX_ANALYSIS,
+ );
+ },
+ );
+
+ it('matches every historical definition to its approved fingerprint and version', () => {
+ expect(Object.keys(FTS_SEARCH_INDEX_SCHEMA_SNAPSHOTS)).toEqual(
+ FTS_SEARCH_MAPPING_MIGRATIONS.map(({ id }) => id),
+ );
+
+ for (const migration of FTS_SEARCH_MAPPING_MIGRATIONS) {
+ const definitions = migration.definitions;
+ const snapshots = FTS_SEARCH_INDEX_SCHEMA_SNAPSHOTS[migration.id];
+
+ expect(
+ snapshots,
+ `Add an approved schema snapshot for migration ${migration.id}.`,
+ ).toBeDefined();
+ expect(Object.keys(snapshots ?? {}).sort()).toEqual(Object.keys(definitions).sort());
+
+ for (const [entity, definition] of Object.entries(definitions)) {
+ expect(snapshots?.[entity]).toEqual({
+ fingerprint: fingerprintOf(migration, definition),
+ schemaVersion: definition.schemaVersion,
+ });
+ }
+ }
+ });
+
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)(
+ 'increments %s versions only when the physical fingerprint changes',
+ (entity) => {
+ const history = FTS_SEARCH_MAPPING_MIGRATIONS.flatMap((migration) => {
+ const definition = getDefinition(migration, entity);
+ return definition
+ ? [{ definition, fingerprint: fingerprintOf(migration, definition) }]
+ : [];
+ });
+
+ for (let index = 1; index < history.length; index++) {
+ const previous = history[index - 1];
+ const current = history[index];
+
+ expect(current.definition.schemaVersion).toBe(previous.definition.schemaVersion + 1);
+ expect(current.fingerprint).not.toBe(previous.fingerprint);
+ }
+ },
+ );
+});
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/index.ts b/packages/database/src/repositories/ftsSearchDocument/migration/index.ts
new file mode 100644
index 00000000000..12c62116912
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/index.ts
@@ -0,0 +1,51 @@
+import type { FtsSearchDocumentEntity } from '../zodSchema';
+import { initialSearchIndexes } from './0000-initial-search-indexes/mapping';
+import type { FtsSearchMappingMigration } from './types';
+
+/** Source-history batches, not a sequential migration executor. Register every batch explicitly. */
+export const FTS_SEARCH_MAPPING_MIGRATIONS = [
+ initialSearchIndexes,
+] as const satisfies readonly FtsSearchMappingMigration[];
+
+/** Select the latest batch containing each entity; unaffected entities retain their prior batch. */
+export const FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS = {
+ agents: initialSearchIndexes,
+ chatGroups: initialSearchIndexes,
+ documents: initialSearchIndexes,
+ files: initialSearchIndexes,
+ knowledgeBases: initialSearchIndexes,
+ memoryActivities: initialSearchIndexes,
+ memoryContexts: initialSearchIndexes,
+ memoryExperiences: initialSearchIndexes,
+ memoryIdentities: initialSearchIndexes,
+ memoryPreferences: initialSearchIndexes,
+ messages: initialSearchIndexes,
+ personaDocuments: initialSearchIndexes,
+ topics: initialSearchIndexes,
+ userMemories: initialSearchIndexes,
+} as const satisfies Record<FtsSearchDocumentEntity, FtsSearchMappingMigration>;
+
+/** Analysis remains global: changing it requires new physical versions for every current entity. */
+export const FTS_SEARCH_INDEX_ANALYSIS = initialSearchIndexes.analysis;
+
+export const FTS_SEARCH_CURRENT_MAPPINGS = {
+ agents: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.agents.definitions.agents,
+ chatGroups: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.chatGroups.definitions.chatGroups,
+ documents: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.documents.definitions.documents,
+ files: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.files.definitions.files,
+ knowledgeBases: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.knowledgeBases.definitions.knowledgeBases,
+ memoryActivities:
+ FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.memoryActivities.definitions.memoryActivities,
+ memoryContexts: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.memoryContexts.definitions.memoryContexts,
+ memoryExperiences:
+ FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.memoryExperiences.definitions.memoryExperiences,
+ memoryIdentities:
+ FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.memoryIdentities.definitions.memoryIdentities,
+ memoryPreferences:
+ FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.memoryPreferences.definitions.memoryPreferences,
+ messages: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.messages.definitions.messages,
+ personaDocuments:
+ FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.personaDocuments.definitions.personaDocuments,
+ topics: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.topics.definitions.topics,
+ userMemories: FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS.userMemories.definitions.userMemories,
+} as const;
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/types.ts b/packages/database/src/repositories/ftsSearchDocument/migration/types.ts
new file mode 100644
index 00000000000..1f22f1e48b7
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/types.ts
@@ -0,0 +1,25 @@
+export type ElasticsearchFtsSearchFieldType = 'boolean' | 'date' | 'integer' | 'keyword' | 'text';
+
+export interface ElasticsearchFtsSearchMappingProperty {
+ analyzer?: string;
+ fields?: Record<string, ElasticsearchFtsSearchMappingProperty>;
+ ignore_above?: number;
+ type: ElasticsearchFtsSearchFieldType;
+}
+
+/** Historical fields must remain valid even after they disappear from the current Zod schema. */
+export interface FtsSearchMappingSnapshot {
+ mappings: {
+ dynamic: 'strict';
+ properties: Record<string, ElasticsearchFtsSearchMappingProperty>;
+ };
+ schemaVersion: number;
+}
+
+/** A batch contains complete physical definitions for only the entities changed in that batch. */
+export interface FtsSearchMappingMigration {
+ analysis: Record<string, unknown>;
+ definitions: Record<string, FtsSearchMappingSnapshot>;
+ /** Global source-history ordinal and description, independent of entity schemaVersion. */
+ id: string;
+}
diff --git a/packages/database/src/repositories/ftsSearchDocument/policy.ts b/packages/database/src/repositories/ftsSearchDocument/policy.ts
new file mode 100644
index 00000000000..83f29167225
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/policy.ts
@@ -0,0 +1,119 @@
+import type { ElasticsearchFtsSearchMappingProperty } from './migration/types';
+import type { FtsSearchDocumentEntity, FtsSearchDocumentSourceMap } from './zodSchema';
+
+export interface FtsSearchIndexPolicy<Entity extends FtsSearchDocumentEntity> {
+ indexedOnlyFields?: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+ longTextFields?: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+ queryFields: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+}
+
+type FtsSearchRetainedSourceProperties = {
+ [Entity in FtsSearchDocumentEntity]: Partial<
+ Record<keyof FtsSearchDocumentSourceMap[Entity] & string, ElasticsearchFtsSearchMappingProperty>
+ >;
+};
+
+/**
+ * Fields retained in the current document source only to keep older open generations writable.
+ * They are excluded from the current physical mapping and must not be used by current queries.
+ */
+export const FTS_SEARCH_RETAINED_SOURCE_PROPERTIES = {
+ agents: {},
+ chatGroups: {},
+ documents: {},
+ files: {},
+ knowledgeBases: {},
+ memoryActivities: {},
+ memoryContexts: {},
+ memoryExperiences: {},
+ memoryIdentities: {},
+ memoryPreferences: {},
+ messages: {},
+ personaDocuments: {},
+ topics: {},
+ userMemories: {},
+} as const satisfies FtsSearchRetainedSourceProperties;
+
+/** Current document metadata, independent of physical mapping history. */
+export const FTS_SEARCH_INDEX_POLICY = {
+ agents: {
+ longTextFields: ['system_role'],
+ queryFields: ['title', 'description', 'slug', 'tags', 'system_role'],
+ },
+ chatGroups: {
+ indexedOnlyFields: ['content'],
+ longTextFields: ['content'],
+ queryFields: ['title', 'description', 'content'],
+ },
+ documents: {
+ longTextFields: ['content'],
+ queryFields: ['title', 'slug', 'description', 'content'],
+ },
+ files: {
+ /** Provider-neutral source field; Elasticsearch-only multi-fields are selected by its backend. */
+ queryFields: ['name'],
+ },
+ knowledgeBases: {
+ longTextFields: ['description'],
+ queryFields: ['name', 'description'],
+ },
+ memoryActivities: {
+ longTextFields: ['notes', 'narrative', 'feedback'],
+ queryFields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'narrative',
+ 'notes',
+ 'feedback',
+ ],
+ },
+ memoryContexts: {
+ longTextFields: ['description', 'current_status'],
+ queryFields: ['parent_text', 'title', 'description', 'current_status'],
+ },
+ memoryExperiences: {
+ longTextFields: ['situation', 'reasoning', 'possible_outcome', 'action', 'key_learning'],
+ queryFields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'situation',
+ 'reasoning',
+ 'possible_outcome',
+ 'action',
+ 'key_learning',
+ ],
+ },
+ memoryIdentities: {
+ longTextFields: ['description', 'role'],
+ queryFields: ['parent_title', 'parent_summary', 'parent_details', 'description', 'role'],
+ },
+ memoryPreferences: {
+ longTextFields: ['conclusion_directives', 'suggestions'],
+ queryFields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'conclusion_directives',
+ 'suggestions',
+ ],
+ },
+ messages: {
+ indexedOnlyFields: ['summary'],
+ longTextFields: ['content', 'summary'],
+ queryFields: ['content', 'summary'],
+ },
+ personaDocuments: {
+ longTextFields: ['persona'],
+ queryFields: ['tagline', 'persona'],
+ },
+ topics: {
+ longTextFields: ['content'],
+ queryFields: ['title', 'content', 'description'],
+ },
+ userMemories: {
+ longTextFields: ['details'],
+ queryFields: ['title', 'summary', 'details'],
+ },
+} as const satisfies { [Entity in FtsSearchDocumentEntity]: FtsSearchIndexPolicy<Entity> };
diff --git a/packages/database/src/repositories/ftsSearchDocument/projectionCompatibility.test.ts b/packages/database/src/repositories/ftsSearchDocument/projectionCompatibility.test.ts
new file mode 100644
index 00000000000..ddb11a06f24
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/projectionCompatibility.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ findFtsSearchProjectionIncompatibilities,
+ type FtsSearchTargetMappingProperties,
+ getFtsSearchProjectionCompatibilityForProperties,
+ pruneFtsSearchDocumentForMapping,
+} from './projectionCompatibility';
+
+describe('findFtsSearchProjectionIncompatibilities', () => {
+ it('rejects fields required by an older target after they are removed or renamed', () => {
+ expect(
+ findFtsSearchProjectionIncompatibilities('agents', {
+ legacy_title: { type: 'text' },
+ title: { type: 'text' },
+ }),
+ ).toEqual([
+ {
+ field: 'legacy_title',
+ kind: 'missing_current_field',
+ targetType: 'text',
+ },
+ ]);
+ });
+
+ it('rejects incompatible value type changes', () => {
+ expect(
+ findFtsSearchProjectionIncompatibilities('agents', {
+ virtual: { type: 'keyword' },
+ }),
+ ).toEqual([
+ {
+ currentType: 'boolean',
+ field: 'virtual',
+ kind: 'incompatible_type',
+ targetType: 'keyword',
+ },
+ ]);
+ });
+
+ it('rejects a target field without a concrete value type', () => {
+ expect(
+ findFtsSearchProjectionIncompatibilities('agents', {
+ virtual: {},
+ }),
+ ).toEqual([
+ {
+ currentType: 'boolean',
+ field: 'virtual',
+ kind: 'incompatible_type',
+ targetType: undefined,
+ },
+ ]);
+ });
+
+ it('allows fields added only to the current mapping', () => {
+ expect(
+ findFtsSearchProjectionIncompatibilities('agents', {
+ id: { type: 'keyword' },
+ }),
+ ).toEqual([]);
+ });
+
+ it.each([
+ ['text target for keyword source', { id: { analyzer: 'other', type: 'text' } }],
+ [
+ 'keyword target for text source',
+ {
+ title: {
+ fields: { raw: { ignore_above: 64, type: 'keyword' } },
+ type: 'keyword',
+ },
+ },
+ ],
+ ] satisfies [string, FtsSearchTargetMappingProperties][])('allows %s', (_name, properties) => {
+ expect(findFtsSearchProjectionIncompatibilities('agents', properties)).toEqual([]);
+ });
+
+ it('allows a removed field when the current source retains a compatible bridge property', () => {
+ expect(
+ getFtsSearchProjectionCompatibilityForProperties(
+ { id: { type: 'keyword' }, legacy_title: { type: 'text' } },
+ { id: { type: 'keyword' }, legacy_title: { type: 'keyword' } },
+ ),
+ ).toEqual({ compatible: true, incompatibleFields: [], missingFields: [] });
+ });
+
+ it('prunes source-only fields before writing the current mapping', () => {
+ expect(
+ pruneFtsSearchDocumentForMapping('agents', {
+ id: 'agent-1',
+ legacy_title: 'legacy',
+ title: 'current',
+ }),
+ ).toEqual({ id: 'agent-1', title: 'current' });
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchDocument/projectionCompatibility.ts b/packages/database/src/repositories/ftsSearchDocument/projectionCompatibility.ts
new file mode 100644
index 00000000000..e97cba49f82
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/projectionCompatibility.ts
@@ -0,0 +1,132 @@
+import type {
+ ElasticsearchFtsSearchFieldType,
+ ElasticsearchFtsSearchMappingProperty,
+} from './mappings';
+import { FTS_SEARCH_INDEX_DEFINITIONS } from './mappings';
+import { FTS_SEARCH_RETAINED_SOURCE_PROPERTIES } from './policy';
+import type { FtsSearchDocumentEntity } from './zodSchema';
+
+export type FtsSearchTargetMappingProperties = Record<
+ string,
+ {
+ analyzer?: string;
+ fields?: Record<string, unknown>;
+ type?: string;
+ }
+>;
+
+export type FtsSearchProjectionIncompatibility =
+ | {
+ field: string;
+ kind: 'missing_current_field';
+ targetType: string | undefined;
+ }
+ | {
+ currentType: ElasticsearchFtsSearchFieldType;
+ field: string;
+ kind: 'incompatible_type';
+ targetType: string | undefined;
+ };
+
+export interface FtsSearchProjectionCompatibility {
+ compatible: boolean;
+ incompatibleFields: {
+ currentType: ElasticsearchFtsSearchFieldType;
+ field: string;
+ targetType: string | undefined;
+ }[];
+ missingFields: string[];
+}
+
+const isStringMappingType = (type: string | undefined) => type === 'keyword' || type === 'text';
+
+const findIncompatibilitiesForProperties = (
+ currentProperties: Record<string, ElasticsearchFtsSearchMappingProperty>,
+ targetProperties: FtsSearchTargetMappingProperties,
+): FtsSearchProjectionIncompatibility[] => {
+ const incompatibilities: FtsSearchProjectionIncompatibility[] = [];
+
+ for (const field of Object.keys(targetProperties).sort()) {
+ const targetType = targetProperties[field].type;
+ const currentProperty = currentProperties[field];
+ if (!currentProperty) {
+ incompatibilities.push({ field, kind: 'missing_current_field', targetType });
+ continue;
+ }
+
+ const currentType = currentProperty.type;
+ if (currentType === targetType) continue;
+ if (isStringMappingType(currentType) && isStringMappingType(targetType)) continue;
+
+ incompatibilities.push({
+ currentType,
+ field,
+ kind: 'incompatible_type',
+ targetType,
+ });
+ }
+
+ return incompatibilities;
+};
+
+const summarizeIncompatibilities = (
+ issues: FtsSearchProjectionIncompatibility[],
+): FtsSearchProjectionCompatibility => {
+ const missingFields = issues
+ .filter((issue) => issue.kind === 'missing_current_field')
+ .map((issue) => issue.field);
+ const incompatibleFields = issues
+ .filter((issue) => issue.kind === 'incompatible_type')
+ .map(({ currentType, field, targetType }) => ({ currentType, field, targetType }));
+
+ return {
+ compatible: issues.length === 0,
+ incompatibleFields,
+ missingFields,
+ };
+};
+
+/**
+ * Finds target fields that the current document projection cannot preserve during multi-generation
+ * sync. A target may omit newly added fields, while every field it still maps must exist in the
+ * current source shape with a compatible JSON value type.
+ */
+export const findFtsSearchProjectionIncompatibilities = (
+ entity: FtsSearchDocumentEntity,
+ targetProperties: FtsSearchTargetMappingProperties,
+): FtsSearchProjectionIncompatibility[] => {
+ const currentProperties: Record<string, ElasticsearchFtsSearchMappingProperty> = {
+ ...FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties,
+ ...FTS_SEARCH_RETAINED_SOURCE_PROPERTIES[entity],
+ };
+ return findIncompatibilitiesForProperties(currentProperties, targetProperties);
+};
+
+/** Pure compatibility check used to validate retained-source bridge definitions in isolation. */
+export const getFtsSearchProjectionCompatibilityForProperties = (
+ currentProperties: Record<string, ElasticsearchFtsSearchMappingProperty>,
+ targetProperties: FtsSearchTargetMappingProperties,
+): FtsSearchProjectionCompatibility =>
+ summarizeIncompatibilities(
+ findIncompatibilitiesForProperties(currentProperties, targetProperties),
+ );
+
+/** Summarizes whether the current source projection can populate every target mapping field. */
+export const getFtsSearchProjectionCompatibility = (
+ entity: FtsSearchDocumentEntity,
+ targetProperties: FtsSearchTargetMappingProperties,
+): FtsSearchProjectionCompatibility => {
+ const issues = findFtsSearchProjectionIncompatibilities(entity, targetProperties);
+ return summarizeIncompatibilities(issues);
+};
+
+/** Removes source-only compatibility fields before writing the current physical generation. */
+export const pruneFtsSearchDocumentForMapping = (
+ entity: FtsSearchDocumentEntity,
+ source: Record<string, unknown>,
+): Record<string, unknown> => {
+ const mappedFields = new Set(
+ Object.keys(FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties),
+ );
+ return Object.fromEntries(Object.entries(source).filter(([field]) => mappedFields.has(field)));
+};
diff --git a/packages/database/src/repositories/ftsSearchDocument/schema.test.ts b/packages/database/src/repositories/ftsSearchDocument/zodSchema.test.ts
similarity index 97%
rename from packages/database/src/repositories/ftsSearchDocument/schema.test.ts
rename to packages/database/src/repositories/ftsSearchDocument/zodSchema.test.ts
index fb0dc9fe9cb..7273932d12f 100644
--- a/packages/database/src/repositories/ftsSearchDocument/schema.test.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/zodSchema.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { FTS_SEARCH_DOCUMENT_FIXTURES } from './__tests__/fixtures';
-import { FTS_SEARCH_DOCUMENT_ENTITIES, parseFtsSearchDocumentSource } from './schema';
+import { FTS_SEARCH_DOCUMENT_ENTITIES, parseFtsSearchDocumentSource } from './zodSchema';
describe('search document schemas', () => {
it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('parses the fixed %s fixture', (entity) => {
diff --git a/packages/database/src/repositories/ftsSearchDocument/schema.ts b/packages/database/src/repositories/ftsSearchDocument/zodSchema.ts
similarity index 100%
rename from packages/database/src/repositories/ftsSearchDocument/schema.ts
rename to packages/database/src/repositories/ftsSearchDocument/zodSchema.ts
diff --git a/scripts/dockerComposeDeploy.test.ts b/scripts/dockerComposeDeploy.test.ts
index c426a649fd5..5c667285564 100644
--- a/scripts/dockerComposeDeploy.test.ts
+++ b/scripts/dockerComposeDeploy.test.ts
@@ -117,9 +117,15 @@ describe('deploy docker-compose optional Elasticsearch', () => {
expect(reindex.command).toEqual(['--status']);
expect(reindex.environment).toContain('ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex');
expect(reindex.volumes).toContain('fts-search-reindex-state:/app/.elasticsearch-reindex');
+ expect(compose.services.lobe.volumes).toContain(
+ 'fts-search-reindex-state:/app/.elasticsearch-reindex',
+ );
expect(compose.volumes).toHaveProperty('fts-search-reindex-state');
// The image pre-creates the checkpoint mountpoint so the named volume inherits nextjs ownership.
expect(dockerfile).toContain('mkdir -p /app/.elasticsearch-reindex');
+ expect(compose.services.lobe.environment).toContain(
+ 'ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex',
+ );
expect(sync.image).toBe('lobehub/lobehub');
expect(sync.restart).toBe('always');
diff --git a/scripts/elasticsearchReindex/__tests__/commandOptions.test.ts b/scripts/elasticsearchReindex/__tests__/commandOptions.test.ts
new file mode 100644
index 00000000000..ef9d8acdd4a
--- /dev/null
+++ b/scripts/elasticsearchReindex/__tests__/commandOptions.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { resolveFtsSearchMigrationCommand } from '../commandOptions';
+
+describe('migration command intent', () => {
+ it('defaults to read-only status', () => {
+ expect(resolveFtsSearchMigrationCommand([]).command).toBe('status');
+ });
+
+ it.each(['retire', 'purge', 'promote'])(
+ 'requires explicit confirmation and entities for %s',
+ (command) => {
+ expect(() => resolveFtsSearchMigrationCommand([`--${command}`, '--entity=messages'])).toThrow(
+ '--yes',
+ );
+ expect(() => resolveFtsSearchMigrationCommand([`--${command}`, '--yes'])).toThrow('--entity');
+ expect(
+ resolveFtsSearchMigrationCommand([`--${command}`, '--yes', '--entity=messages']).command,
+ ).toBe(command);
+ },
+ );
+
+ it.each([
+ ['--retire', '--purge'],
+ ['--status', '--apply'],
+ ['--promote', '--retire'],
+ ['--skip-failure=messages:1', '--purge'],
+ ])('rejects combined operations %s %s', (...args) => {
+ expect(() => resolveFtsSearchMigrationCommand([...args, '--yes', '--entity=messages'])).toThrow(
+ 'exactly one',
+ );
+ });
+
+ it('requires an exact lock owner and a separate recovery command', () => {
+ const owner = '00000000-0000-4000-8000-000000000001';
+ expect(resolveFtsSearchMigrationCommand([`--release-lock=${owner}`, '--yes'])).toEqual({
+ command: 'release-lock',
+ releaseLockOwner: owner,
+ });
+ expect(() => resolveFtsSearchMigrationCommand(['--release-lock=', '--yes'])).toThrow('UUID');
+ expect(() =>
+ resolveFtsSearchMigrationCommand([`--release-lock=${owner}`, '--apply', '--yes']),
+ ).toThrow('exactly one');
+ });
+
+ it.each([
+ ['--in-place'],
+ ['--apply', '--in-place', '--fresh-run', '--yes'],
+ ['--fresh-run'],
+ ['--version=2'],
+ ])('rejects misplaced modifiers %s', (...args) => {
+ expect(() => resolveFtsSearchMigrationCommand(args)).toThrow();
+ });
+
+ it('accepts the confirmed startup coordinator command', () => {
+ expect(resolveFtsSearchMigrationCommand(['--startup', '--yes']).command).toBe('startup');
+ expect(() => resolveFtsSearchMigrationCommand(['--startup'])).toThrow('--yes');
+ });
+
+ it.each([
+ '--entity=messages',
+ '--fresh-run',
+ '--in-place',
+ '--max-batches-per-entity=1',
+ '--version=2',
+ ])('rejects partial or operator-only startup option %s', (option) => {
+ expect(() => resolveFtsSearchMigrationCommand(['--startup', '--yes', option])).toThrow(
+ 'cannot be used with --startup',
+ );
+ });
+});
diff --git a/scripts/elasticsearchReindex/__tests__/preparation.test.ts b/scripts/elasticsearchReindex/__tests__/preparation.test.ts
index 134fd52e024..e000dd0f9aa 100644
--- a/scripts/elasticsearchReindex/__tests__/preparation.test.ts
+++ b/scripts/elasticsearchReindex/__tests__/preparation.test.ts
@@ -51,6 +51,21 @@ describe('runFtsSearchReindexCommand', () => {
expect(events).toEqual(['install', 'create-or-resume']);
});
+ it('installs capture before a startup run even when no generation needs backfill', async () => {
+ const events: string[] = [];
+ await runFtsSearchReindexCommand({
+ command: 'startup',
+ installCaptureInfrastructure: async () => {
+ events.push('install');
+ },
+ run: async () => {
+ events.push('run');
+ },
+ runWithLockRetry: async (operation) => operation(),
+ });
+ expect(events).toEqual(['install', 'run']);
+ });
+
it('stops before the checkpoint when capture installation fails', async () => {
const error = new Error('capture install failed');
const installCaptureInfrastructure = vi.fn<() => Promise<void>>().mockRejectedValue(error);
diff --git a/scripts/elasticsearchReindex/__tests__/startupCoordinator.test.ts b/scripts/elasticsearchReindex/__tests__/startupCoordinator.test.ts
new file mode 100644
index 00000000000..61c7b059ac1
--- /dev/null
+++ b/scripts/elasticsearchReindex/__tests__/startupCoordinator.test.ts
@@ -0,0 +1,243 @@
+// @vitest-environment node
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { FtsSearchEntityGenerationStatus } from '../runtime/generationService';
+import { runFtsSearchStartupMigration } from '../startupCoordinator';
+
+const status = (
+ entity: FtsSearchDocumentEntity,
+ classification: FtsSearchEntityGenerationStatus['classification'],
+ options: {
+ backfill?: 'backfilling' | 'completed' | 'unknown';
+ candidate?: boolean;
+ candidateCompatible?: boolean;
+ inPlace?: boolean;
+ version?: number;
+ } = {},
+): FtsSearchEntityGenerationStatus => {
+ const version = options.version ?? 1;
+ const index = `test-${entity}-v${version}`;
+ const generation = {
+ aliased: true,
+ backfill: options.backfill ?? 'completed',
+ fieldCompatibility: { compatible: true, incompatibleFields: [], missingFields: [] },
+ fingerprint: 'fingerprint',
+ index: options.inPlace ? `test-${entity}-v0` : index,
+ matchesDeclared: true,
+ reindexRunId: 'run-id',
+ state: 'open' as const,
+ version,
+ };
+ return {
+ action: 'repair manually',
+ alias: `test-${entity}`,
+ candidates: options.candidate
+ ? [
+ {
+ ...generation,
+ aliased: false,
+ fieldCompatibility:
+ options.candidateCompatible === false
+ ? {
+ compatible: false,
+ incompatibleFields: [],
+ missingFields: ['legacy_field'],
+ }
+ : generation.fieldCompatibility,
+ },
+ ]
+ : [],
+ classification,
+ declared: { fingerprint: 'fingerprint', index, version },
+ entity,
+ live: classification === 'missing' ? null : generation,
+ mappingChange: classification === 'missing' ? null : 'identical',
+ mappingDiff: null,
+ };
+};
+
+const setup = (initial: FtsSearchEntityGenerationStatus, checkpoint = false) => {
+ let current = initial;
+ const applyGeneration = vi.fn(async () => {
+ current = status(initial.entity, 'in_sync');
+ });
+ const promoteEntity = vi.fn(async () => {
+ current = status(initial.entity, 'in_sync');
+ });
+ const drainIncrementalSync = vi.fn(async () => ({ hasMore: false }));
+ const run = () =>
+ runFtsSearchStartupMigration({
+ applyGeneration,
+ describeEntity: async () => current,
+ drainIncrementalSync,
+ generations: [{ entities: [initial.entity], schemaVersion: 1 }],
+ promoteEntity,
+ readCheckpointEntities: async () => (checkpoint ? [initial.entity] : undefined),
+ readOutboxStats: async () => ({ dead: 0, inFlight: 0, pending: 0, retrying: 0 }),
+ });
+ return { applyGeneration, drainIncrementalSync, promoteEntity, run };
+};
+
+describe('startup reindex coordinator', () => {
+ it('automatically treats a wholly empty generation as fresh', async () => {
+ const fixture = setup(status('messages', 'missing'));
+ await fixture.run();
+ expect(fixture.applyGeneration).toHaveBeenCalledWith({
+ freshRun: true,
+ generationEntities: ['messages'],
+ processEntities: ['messages'],
+ schemaVersion: 1,
+ });
+ expect(fixture.promoteEntity).toHaveBeenCalledWith('messages');
+ });
+
+ it('skips a current rebuilt generation even when its old checkpoint is absent', async () => {
+ const fixture = setup(status('messages', 'in_sync', { backfill: 'unknown' }));
+ await fixture.run();
+ expect(fixture.applyGeneration).not.toHaveBeenCalled();
+ expect(fixture.promoteEntity).not.toHaveBeenCalled();
+ expect(fixture.drainIncrementalSync).toHaveBeenCalledOnce();
+ });
+
+ it('resumes an incomplete checkpoint before promotion', async () => {
+ const fixture = setup(status('messages', 'in_sync', { backfill: 'backfilling' }), true);
+ await fixture.run();
+ expect(fixture.applyGeneration).toHaveBeenCalledWith({
+ freshRun: false,
+ generationEntities: ['messages'],
+ processEntities: ['messages'],
+ schemaVersion: 1,
+ });
+ expect(fixture.promoteEntity).toHaveBeenCalledWith('messages');
+ });
+
+ it('rejects a possibly incomplete in-place generation without its checkpoint', async () => {
+ const fixture = setup(status('messages', 'in_sync', { backfill: 'unknown', inPlace: true }));
+ await expect(fixture.run()).rejects.toThrow('no checkpoint proves');
+ expect(fixture.drainIncrementalSync).not.toHaveBeenCalled();
+ });
+
+ it('does not adopt an uncheckpointed detached declared generation', async () => {
+ const fixture = setup(status('messages', 'upgrade_available', { candidate: true }));
+ await expect(fixture.run()).rejects.toThrow('no checkpoint proves');
+ expect(fixture.applyGeneration).not.toHaveBeenCalled();
+ });
+
+ it('rejects an incompatible open non-live generation before sync can write to it', async () => {
+ const fixture = setup(
+ status('messages', 'upgrade_available', {
+ candidate: true,
+ candidateCompatible: false,
+ }),
+ true,
+ );
+ await expect(fixture.run()).rejects.toThrow(
+ 'incompatible with the current document projection',
+ );
+ expect(fixture.applyGeneration).not.toHaveBeenCalled();
+ expect(fixture.drainIncrementalSync).not.toHaveBeenCalled();
+ });
+
+ it('fails when the bounded incremental drain cannot catch up', async () => {
+ const fixture = setup(status('messages', 'in_sync'));
+ fixture.drainIncrementalSync.mockResolvedValue({ hasMore: true });
+ await expect(fixture.run()).rejects.toThrow('exceeded its incremental sync drain bound');
+ });
+
+ it('starts an uncheckpointed shared-version upgrade with only the changed entity', async () => {
+ const statuses = new Map<FtsSearchDocumentEntity, FtsSearchEntityGenerationStatus>([
+ ['agents', status('agents', 'in_sync', { backfill: 'unknown' })],
+ ['messages', status('messages', 'upgrade_available')],
+ ]);
+ let checkpointExists = false;
+ const applyGeneration = vi.fn(async () => {
+ checkpointExists = true;
+ statuses.set('messages', status('messages', 'in_sync'));
+ });
+ const options: Parameters<typeof runFtsSearchStartupMigration>[0] = {
+ applyGeneration,
+ describeEntity: async (entity: FtsSearchDocumentEntity) => statuses.get(entity)!,
+ drainIncrementalSync: async () => ({ hasMore: false }),
+ generations: [{ entities: ['agents', 'messages'], schemaVersion: 1 }],
+ promoteEntity: async (entity: FtsSearchDocumentEntity) => {
+ statuses.set(entity, status(entity, 'in_sync'));
+ },
+ readCheckpointEntities: async () => (checkpointExists ? ['messages'] : undefined),
+ readOutboxStats: async () => ({ dead: 0, inFlight: 0, pending: 0, retrying: 0 }),
+ };
+
+ await runFtsSearchStartupMigration(options);
+ expect(applyGeneration).toHaveBeenCalledWith({
+ freshRun: false,
+ generationEntities: ['messages'],
+ processEntities: ['messages'],
+ schemaVersion: 1,
+ });
+
+ applyGeneration.mockClear();
+ await runFtsSearchStartupMigration(options);
+ expect(applyGeneration).not.toHaveBeenCalled();
+ });
+
+ it('starts a missing shared-version entity fresh without adding its current neighbor', async () => {
+ const statuses = new Map<FtsSearchDocumentEntity, FtsSearchEntityGenerationStatus>([
+ ['agents', status('agents', 'in_sync', { backfill: 'unknown' })],
+ ['messages', status('messages', 'missing')],
+ ]);
+ const applyGeneration = vi.fn(async () => {
+ statuses.set('messages', status('messages', 'in_sync'));
+ });
+
+ await runFtsSearchStartupMigration({
+ applyGeneration,
+ describeEntity: async (entity) => statuses.get(entity)!,
+ drainIncrementalSync: async () => ({ hasMore: false }),
+ generations: [
+ { entities: ['agents', 'messages'] as FtsSearchDocumentEntity[], schemaVersion: 1 },
+ ],
+ promoteEntity: async () => {},
+ readCheckpointEntities: async () => undefined,
+ readOutboxStats: async () => ({ dead: 0, inFlight: 0, pending: 0, retrying: 0 }),
+ });
+
+ expect(applyGeneration).toHaveBeenCalledWith({
+ freshRun: true,
+ generationEntities: ['messages'],
+ processEntities: ['messages'],
+ schemaVersion: 1,
+ });
+ });
+
+ it('drops checkpoint members that moved to another schema generation', async () => {
+ const statuses = new Map<FtsSearchDocumentEntity, FtsSearchEntityGenerationStatus>([
+ ['agents', status('agents', 'in_sync')],
+ ['messages', status('messages', 'in_sync', { version: 2 })],
+ ['topics', status('topics', 'missing')],
+ ]);
+ const applyGeneration = vi.fn(async ({ schemaVersion }: { schemaVersion: number }) => {
+ if (schemaVersion === 1) statuses.set('topics', status('topics', 'in_sync'));
+ });
+
+ await runFtsSearchStartupMigration({
+ applyGeneration,
+ describeEntity: async (entity) => statuses.get(entity)!,
+ drainIncrementalSync: async () => ({ hasMore: false }),
+ generations: [
+ { entities: ['agents', 'topics'], schemaVersion: 1 },
+ { entities: ['messages'], schemaVersion: 2 },
+ ],
+ promoteEntity: async () => {},
+ readCheckpointEntities: async (schemaVersion) =>
+ schemaVersion === 1 ? ['agents', 'messages'] : undefined,
+ readOutboxStats: async () => ({ dead: 0, inFlight: 0, pending: 0, retrying: 0 }),
+ });
+
+ expect(applyGeneration).toHaveBeenCalledExactlyOnceWith({
+ freshRun: false,
+ generationEntities: ['agents', 'topics'],
+ processEntities: ['topics'],
+ schemaVersion: 1,
+ });
+ });
+});
diff --git a/scripts/elasticsearchReindex/commandOptions.ts b/scripts/elasticsearchReindex/commandOptions.ts
new file mode 100644
index 00000000000..f8055c3faaf
--- /dev/null
+++ b/scripts/elasticsearchReindex/commandOptions.ts
@@ -0,0 +1,60 @@
+export type FtsSearchMigrationCommand =
+ 'apply' | 'promote' | 'purge' | 'release-lock' | 'retire' | 'skip-failure' | 'startup' | 'status';
+
+/** Keep destructive intent explicit: retrying retirement must never advance into deletion. */
+export const resolveFtsSearchMigrationCommand = (args: readonly string[]) => {
+ const modes: FtsSearchMigrationCommand[] = [];
+ for (const name of ['apply', 'promote', 'purge', 'retire', 'startup', 'status'] as const) {
+ if (args.includes(`--${name}`)) modes.push(name);
+ }
+ if (args.some((argument) => argument.startsWith('--skip-failure='))) modes.push('skip-failure');
+ const releaseArguments = args.filter((argument) => argument.startsWith('--release-lock='));
+ if (releaseArguments.length > 1) throw new Error('--release-lock may only be provided once');
+ const releaseLockOwner = releaseArguments[0]?.slice('--release-lock='.length);
+ if (releaseLockOwner !== undefined) {
+ if (!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(releaseLockOwner)) {
+ throw new Error('--release-lock requires the exact owner UUID reported by --status');
+ }
+ modes.push('release-lock');
+ }
+ if (modes.length > 1) {
+ throw new Error(
+ 'Choose exactly one migration command: --status, --apply, --startup, --promote, --retire, --purge, --skip-failure, or --release-lock',
+ );
+ }
+ const command = modes[0] ?? 'status';
+ if (command !== 'status' && !args.includes('--yes')) {
+ throw new Error('Mutating commands require --yes after reviewing their documented effects');
+ }
+ if (command === 'startup') {
+ const unsupported = args.find(
+ (argument) =>
+ argument === '--fresh-run' ||
+ argument === '--in-place' ||
+ argument.startsWith('--entity=') ||
+ argument.startsWith('--max-batches-per-entity=') ||
+ argument.startsWith('--version='),
+ );
+ if (unsupported) {
+ throw new Error(`${unsupported.split('=')[0]} cannot be used with --startup`);
+ }
+ }
+ if (args.includes('--fresh-run') && command !== 'apply') {
+ throw new Error('--fresh-run can only be used with --apply');
+ }
+ if (args.includes('--in-place') && (command !== 'apply' || args.includes('--fresh-run'))) {
+ throw new Error('--in-place can only be used with --apply on an existing generation');
+ }
+ if (
+ (['promote', 'retire', 'purge'].includes(command) || args.includes('--in-place')) &&
+ !args.some((argument) => argument.startsWith('--entity='))
+ ) {
+ throw new Error(
+ `${args.includes('--in-place') ? '--in-place' : `--${command}`} requires at least one --entity=<entity>`,
+ );
+ }
+ if (args.some((argument) => argument.startsWith('--version=')) && command !== 'promote') {
+ throw new Error('--version can only be used with --promote');
+ }
+ return { command, releaseLockOwner };
+};
diff --git a/scripts/elasticsearchReindex/index.ts b/scripts/elasticsearchReindex/index.ts
index 9ef3915104f..c2cb200b53a 100644
--- a/scripts/elasticsearchReindex/index.ts
+++ b/scripts/elasticsearchReindex/index.ts
@@ -5,10 +5,14 @@ import type { FtsSearchDocumentEntity } from '@lobechat/types';
import { drizzle } from 'drizzle-orm/node-postgres';
import pg from 'pg';
+import { ElasticsearchFtsSearchHttpClient } from '../../apps/server/src/services/ftsSearch/elasticsearch';
+import { FtsSearchSyncService } from '../../apps/server/src/services/ftsSearchSync/service';
import {
FTS_SEARCH_DOCUMENT_ENTITIES,
- FTS_SEARCH_INDEX_SCHEMA_VERSION,
+ FTS_SEARCH_INDEX_DEFINITIONS,
FtsSearchDocumentBuilder,
+ getFtsSearchIndexAlias,
+ getFtsSearchIndexSchemaVersion,
} from '../../packages/database/src/repositories/ftsSearchDocument';
import { FtsSearchSyncOutboxRepository } from '../../packages/database/src/repositories/ftsSearchSyncOutbox';
import * as schema from '../../packages/database/src/schemas';
@@ -20,7 +24,9 @@ import {
recordFtsSearchReindexReconciliation,
} from '../../packages/observability-otel/src/modules/fts-search-reindex';
import { DiagLogLevel, register, shutdownSafely } from '../../packages/observability-otel/src/node';
+import { runElasticsearchFtsSearchSync } from '../elasticsearchSync';
import { runWithLockRetry } from '../migrateServerDB/retry';
+import { resolveFtsSearchMigrationCommand } from './commandOptions';
import {
assertFtsSearchReindexElasticsearchHostname,
assertFtsSearchReindexRangeCollation,
@@ -33,14 +39,28 @@ import {
} from './options';
import { runFtsSearchReindexCommand } from './preparation';
import {
+ describeEntityGeneration,
type FtsSearchReindexAuditValue,
FtsSearchReindexEntityError,
FtsSearchReindexFileLogger,
FtsSearchReindexFileRepository,
FtsSearchReindexHttpClient,
FtsSearchReindexService,
+ promoteGeneration,
+ retireGenerations,
summarizeFtsSearchReindexError,
} from './runtime';
+import type { FtsSearchGenerationSummary } from './runtime/generationService';
+import {
+ planRetiredGenerations,
+ purgeRetiredGenerations,
+ resolveInPlaceTarget,
+} from './runtime/generationService';
+import { FtsSearchMigrationLockClient, FtsSearchMigrationLockError } from './runtime/migrationLock';
+import {
+ assertFtsSearchStartupGenerationSafe,
+ runFtsSearchStartupMigration,
+} from './startupCoordinator';
const { Pool } = pg;
@@ -71,11 +91,16 @@ const readNonNegativeIntegerArgument = (name: string) => {
};
const args = new Set(process.argv.slice(2));
+const { command, releaseLockOwner } = resolveFtsSearchMigrationCommand(process.argv.slice(2));
const apply = args.has('--apply');
+const startup = args.has('--startup');
const freshRun = args.has('--fresh-run');
+const inPlace = args.has('--in-place');
+const promote = args.has('--promote');
+const retire = args.has('--retire');
+const purge = args.has('--purge');
const skipFailureArgument = process.argv.find((item) => item.startsWith('--skip-failure='));
-const status = args.has('--status');
-const yes = args.has('--yes');
+const promoteVersion = readPositiveIntegerArgument('--version');
const batchSize = readPositiveIntegerArgument('--batch-size');
const bulkConcurrency = readPositiveIntegerArgument('--bulk-concurrency');
const bulkMaxBytes = readPositiveIntegerArgument('--bulk-max-bytes');
@@ -91,7 +116,17 @@ const requestTimeoutMs = readPositiveIntegerArgument('--request-timeout-ms');
const retryBaseDelayMs = readNonNegativeIntegerArgument('--retry-base-delay-ms');
const telemetryEnvironment = resolveFtsSearchReindexTelemetryEnvironment(process.argv.slice(2));
-const knownArguments = new Set(['--apply', '--fresh-run', '--status', '--yes']);
+const knownArguments = new Set([
+ '--apply',
+ '--fresh-run',
+ '--in-place',
+ '--promote',
+ '--retire',
+ '--purge',
+ '--status',
+ '--startup',
+ '--yes',
+]);
const unknownArgument = process.argv
.slice(2)
.find(
@@ -112,20 +147,13 @@ const unknownArgument = process.argv
!item.startsWith('--max-request-retries=') &&
!item.startsWith('--request-timeout-ms=') &&
!item.startsWith('--retry-base-delay-ms=') &&
+ !item.startsWith('--release-lock=') &&
!item.startsWith('--skip-failure=') &&
- !item.startsWith('--telemetry-environment='),
+ !item.startsWith('--telemetry-environment=') &&
+ !item.startsWith('--version='),
);
if (unknownArgument) throw new Error(`Unknown argument: ${unknownArgument}`);
-const mutationModes = [apply, Boolean(skipFailureArgument)].filter(Boolean).length;
-if (mutationModes > 1 || (status && mutationModes > 0)) {
- throw new Error('Choose exactly one of --status, --apply, or --skip-failure');
-}
-if (mutationModes > 0 && !yes) {
- throw new Error('Mutating commands require --yes after reviewing their documented effects');
-}
-if (freshRun && !apply) throw new Error('--fresh-run can only be used with --apply');
-
const readFailureReference = ():
{ documentId: string; entity: FtsSearchDocumentEntity } | undefined => {
if (!skipFailureArgument) return;
@@ -153,15 +181,18 @@ const namespace = process.env.ES_INDEX_NAMESPACE;
const configuredStateDirectory = process.env.ES_REINDEX_STATE_DIR;
const stateDirectory = path.resolve(configuredStateDirectory ?? '.elasticsearch-reindex');
-if (!databaseUrl) throw new Error('DATABASE_URL is required');
+/** Commands that talk to Elasticsearch; `--status` only inspects it when the URL is configured. */
+const elasticsearchMutation = command === 'status' ? null : `--${command}`;
+
+if (!databaseUrl && command !== 'release-lock') throw new Error('DATABASE_URL is required');
if (!namespace) throw new Error('ES_INDEX_NAMESPACE is required');
-if (apply && !elasticsearchApiKey && !allowInsecureHttp) {
- throw new Error(`${apiKeyEnvironmentName} is required with --apply`);
+if (elasticsearchMutation && !elasticsearchApiKey && !allowInsecureHttp) {
+ throw new Error(`${apiKeyEnvironmentName} is required with ${elasticsearchMutation}`);
}
-if (apply && !elasticsearchUrl) {
- throw new Error(`${urlEnvironmentName} is required with --apply`);
+if (elasticsearchMutation && !elasticsearchUrl) {
+ throw new Error(`${urlEnvironmentName} is required with ${elasticsearchMutation}`);
}
-if ((apply || failureReference) && !configuredStateDirectory) {
+if ((apply || startup || failureReference) && !configuredStateDirectory) {
throw new Error('ES_REINDEX_STATE_DIR is required for reindex mutations and resume attempts');
}
if (process.env.ENABLE_TELEMETRY && !telemetryEnvironment) {
@@ -216,14 +247,129 @@ const logErrorSummary = (message: string, error: unknown) => {
console.error(message, summarizeFtsSearchReindexError(error));
};
+let assertMigrationOwnership: (() => Promise<void>) | undefined;
+
+const createMigrationLockClient = () =>
+ new FtsSearchMigrationLockClient({
+ allowInsecureHttp,
+ apiKey: elasticsearchApiKey,
+ namespace,
+ requestTimeoutMs,
+ url: elasticsearchUrl!,
+ });
+
+const createElasticsearchClient = () =>
+ new FtsSearchReindexHttpClient({
+ allowInsecureHttp,
+ apiKey: elasticsearchApiKey,
+ beforeMutation: assertMigrationOwnership,
+ requestTimeoutMs,
+ url: elasticsearchUrl!,
+ });
+
+/** Every schema generation the deployed code declares, ascending, with the entities on each. */
+const declaredGenerations = (): Array<[number, FtsSearchDocumentEntity[]]> => {
+ const groups = new Map<number, FtsSearchDocumentEntity[]>();
+ for (const entity of FTS_SEARCH_DOCUMENT_ENTITIES) {
+ const version = getFtsSearchIndexSchemaVersion(entity);
+ groups.set(version, [...(groups.get(version) ?? []), entity]);
+ }
+ return [...groups].sort(([left], [right]) => left - right);
+};
+
+const readCheckpoint = (checkpointNamespace: string, schemaVersion: number) =>
+ repository.getTargetRun(checkpointNamespace, schemaVersion);
+
+const generationAuditValue = (generation: FtsSearchGenerationSummary) => ({
+ ...generation,
+ fieldCompatibility: generation.fieldCompatibility
+ ? {
+ ...generation.fieldCompatibility,
+ incompatibleFields: generation.fieldCompatibility.incompatibleFields.map((field) => ({
+ ...field,
+ targetType: field.targetType ?? null,
+ })),
+ }
+ : null,
+});
+
const readStatus = async () => {
- const state = await repository.getTargetRun(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
- const unresolvedFailures = state ? await repository.listUnresolvedFailures(state.run.id) : [];
+ const runs = [];
+ for (const [schemaVersion] of declaredGenerations()) {
+ const state = await repository.getTargetRun(namespace, schemaVersion);
+ if (!state) continue;
+ const unresolvedFailures = await repository.listUnresolvedFailures(state.run.id);
+ runs.push({
+ baseRevision: state.run.baseRevision,
+ backfillHighWaterRevision: state.run.backfillHighWaterRevision,
+ entities: state.progress.map((progress) => ({
+ cursor: progress.cursor,
+ entity: progress.entity,
+ failedCount: progress.failedCount,
+ indexedCount: progress.indexedCount,
+ physicalIndex: progress.physicalIndex,
+ processedCount: progress.processedCount,
+ status: progress.status,
+ })),
+ id: state.run.id,
+ schemaVersion: state.run.schemaVersion,
+ status: state.run.status,
+ unresolvedFailures: unresolvedFailures.map(
+ ({ attempts, documentId, entity, error, retryable }) => ({
+ attempts,
+ documentId,
+ entity,
+ errorSummary: summarizeFtsSearchReindexError(error),
+ retryable,
+ }),
+ ),
+ });
+ }
const outboxStats = await outbox.stats();
const entityStats: Record<string, FtsSearchReindexAuditValue> = Object.fromEntries(
Object.entries(outboxStats.entities).map(([entity, stats]) => [entity, { ...stats }]),
);
+
+ /**
+ * Generation state lives in Elasticsearch (`_meta` plus the alias), so it can only be reported
+ * when the endpoint is configured. Checkpoints alone cannot tell which generation is live.
+ */
+ let generations: FtsSearchReindexAuditValue = null;
+ if (elasticsearchUrl) {
+ const client = createElasticsearchClient();
+ const statuses = [];
+ for (const entity of entities ?? FTS_SEARCH_DOCUMENT_ENTITIES) {
+ const entityStatus = await describeEntityGeneration({
+ client,
+ entity,
+ namespace,
+ readCheckpoint,
+ });
+ statuses.push({
+ action: entityStatus.action,
+ alias: entityStatus.alias,
+ candidates: entityStatus.candidates.map(generationAuditValue),
+ classification: entityStatus.classification,
+ declared: entityStatus.declared,
+ entity: entityStatus.entity,
+ live: entityStatus.live ? generationAuditValue(entityStatus.live) : null,
+ mappingChange: entityStatus.mappingChange,
+ mappingDiff: entityStatus.mappingDiff
+ ? {
+ ...entityStatus.mappingDiff,
+ changed: entityStatus.mappingDiff.changed.map((field) => ({ ...field })),
+ }
+ : null,
+ retirementPlan: { ...planRetiredGenerations(entityStatus) },
+ });
+ }
+ generations = statuses;
+ }
+
+ const migrationLock = elasticsearchUrl ? await createMigrationLockClient().read() : null;
return {
+ generations,
+ migrationLock: migrationLock ? { ...migrationLock } : null,
namespace,
outbox: {
dead: outboxStats.dead,
@@ -238,33 +384,7 @@ const readStatus = async () => {
revisionLag: outboxStats.revisionLag,
retrying: outboxStats.retrying,
},
- run: state
- ? {
- baseRevision: state.run.baseRevision,
- backfillHighWaterRevision: state.run.backfillHighWaterRevision,
- entities: state.progress.map((progress) => ({
- cursor: progress.cursor,
- entity: progress.entity,
- failedCount: progress.failedCount,
- indexedCount: progress.indexedCount,
- physicalIndex: progress.physicalIndex,
- processedCount: progress.processedCount,
- status: progress.status,
- })),
- id: state.run.id,
- schemaVersion: state.run.schemaVersion,
- status: state.run.status,
- unresolvedFailures: unresolvedFailures.map(
- ({ attempts, documentId, entity, error, retryable }) => ({
- attempts,
- documentId,
- entity,
- errorSummary: summarizeFtsSearchReindexError(error),
- retryable,
- }),
- ),
- }
- : null,
+ runs,
stateDirectory,
};
};
@@ -285,7 +405,10 @@ const run = async () => {
installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
runWithLockRetry,
run: async () => {
- const state = await repository.getTargetRun(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ const state = await repository.getTargetRun(
+ namespace,
+ getFtsSearchIndexSchemaVersion(failureReference.entity),
+ );
if (!state) throw new Error(`No reindex run exists for namespace ${namespace}`);
const skipped = await repository.skipFailure(
state.run.id,
@@ -301,6 +424,138 @@ const run = async () => {
return;
}
+ if (promote || retire || purge) {
+ const client = createElasticsearchClient();
+ const endpointHostname = new URL(elasticsearchUrl!).hostname;
+ assertFtsSearchReindexElasticsearchHostname(endpointHostname, expectedHostPrefix);
+ await runFtsSearchReindexCommand({
+ command: promote ? 'promote' : purge ? 'purge' : 'retire',
+ installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
+ runWithLockRetry,
+ run: async () => {
+ for (const entity of entities!) {
+ if (promote) {
+ const result = await promoteGeneration({
+ client,
+ entity,
+ namespace,
+ outboxStats: await outbox.stats(),
+ readCheckpoint,
+ version: promoteVersion,
+ });
+ console.log(JSON.stringify({ ...result, entity, type: 'generation_promoted' }));
+ } else if (purge) {
+ const result = await purgeRetiredGenerations({
+ client,
+ entity,
+ namespace,
+ readCheckpoint,
+ });
+ console.log(JSON.stringify({ ...result, entity, type: 'generations_purged' }));
+ } else {
+ const result = await retireGenerations({ client, entity, namespace, readCheckpoint });
+ console.log(JSON.stringify({ ...result, entity, type: 'generations_retired' }));
+ }
+ }
+ await printStatus();
+ },
+ });
+ return;
+ }
+
+ if (startup) {
+ const endpointHostname = new URL(elasticsearchUrl!).hostname;
+ assertFtsSearchReindexElasticsearchHostname(endpointHostname, expectedHostPrefix);
+ const client = createElasticsearchClient();
+ const syncClient = new ElasticsearchFtsSearchHttpClient({
+ allowInsecureHttp,
+ apiKey: elasticsearchApiKey,
+ indexNamespace: namespace,
+ requestTimeoutMs: requestTimeoutMs ?? 20_000,
+ url: elasticsearchUrl!,
+ });
+ const syncService = new FtsSearchSyncService(
+ new FtsSearchDocumentBuilder(db),
+ outbox,
+ {
+ bulk: async (body) => {
+ await assertMigrationOwnership?.();
+ return syncClient.bulk(body);
+ },
+ getFtsSearchSyncGenerationTargets: (aliases) =>
+ syncClient.getFtsSearchSyncGenerationTargets(aliases),
+ getFtsSearchSyncIndexFields: (entitiesByIndex) =>
+ syncClient.getFtsSearchSyncIndexFields(entitiesByIndex),
+ },
+ namespace,
+ );
+ await runFtsSearchReindexCommand({
+ command: 'startup',
+ installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
+ runWithLockRetry,
+ run: () =>
+ runFtsSearchStartupMigration({
+ applyGeneration: ({ freshRun, generationEntities, processEntities, schemaVersion }) =>
+ applyGeneration({
+ client,
+ endpointHostname,
+ freshRunForGeneration: freshRun,
+ generationEntities,
+ processEntities,
+ schemaVersion,
+ }),
+ describeEntity: (entity) =>
+ describeEntityGeneration({
+ client,
+ entity,
+ namespace,
+ readCheckpoint,
+ }),
+ drainIncrementalSync: async () => {
+ const aliases = FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) =>
+ getFtsSearchIndexAlias(namespace, entity),
+ );
+ const summary = await runElasticsearchFtsSearchSync({
+ loadRuntime: async () => ({
+ getFtsSearchSyncService: () => syncService,
+ verifyFtsSearchSyncReadiness: async () => {
+ await outbox.assertCaptureInfrastructure();
+ await syncClient.assertFtsSearchSyncAliases(aliases);
+ },
+ }),
+ logStep: (step) =>
+ console.log(JSON.stringify({ ...step, type: 'fts_search_startup_sync_step' })),
+ maxSteps: 10_000,
+ });
+ return { hasMore: summary.hasMore };
+ },
+ generations: declaredGenerations().map(([schemaVersion, generationEntities]) => ({
+ entities: generationEntities,
+ schemaVersion,
+ })),
+ maxDrainRounds: 60,
+ promoteEntity: async (entity) => {
+ const result = await promoteGeneration({
+ client,
+ entity,
+ namespace,
+ outboxStats: await outbox.stats(),
+ readCheckpoint,
+ });
+ console.log(JSON.stringify({ ...result, entity, type: 'generation_promoted' }));
+ },
+ readCheckpointEntities: async (schemaVersion) => {
+ const checkpoint = await repository.getTargetRun(namespace, schemaVersion);
+ return checkpoint?.progress.map(({ entity }) => entity);
+ },
+ readOutboxStats: () => outbox.stats(),
+ waitForOutbox: () => new Promise((resolve) => setTimeout(resolve, 1000)),
+ }),
+ });
+ await printStatus();
+ return;
+ }
+
if (!apply) {
await runFtsSearchReindexCommand({
command: 'status',
@@ -322,15 +577,137 @@ const run = async () => {
const endpointHostname = new URL(elasticsearchUrl!).hostname;
assertFtsSearchReindexElasticsearchHostname(endpointHostname, expectedHostPrefix);
- const existing = await repository.getTargetRun(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
- if (!existing && !freshRun) {
- throw new Error(
- `No checkpoint exists in ${stateDirectory}; pass --fresh-run only for a new, empty Elasticsearch target`,
- );
+ const client = createElasticsearchClient();
+
+ /** Preserve old source fields while any open generation can still receive full-document writes. */
+ for (const entity of entities ?? FTS_SEARCH_DOCUMENT_ENTITIES) {
+ const generation = await describeEntityGeneration({
+ client,
+ entity,
+ namespace,
+ readCheckpoint,
+ });
+ for (const target of [
+ ...generation.candidates,
+ ...(generation.live ? [generation.live] : []),
+ ]) {
+ if (target.state !== 'open') continue;
+ if (!target.fieldCompatibility?.compatible) {
+ throw new Error(
+ `${target.index} cannot receive the current document projection; retain its source fields and compatible types until it is retired. Inspect --status fieldCompatibility before upgrading.`,
+ );
+ }
+ }
+ }
+
+ /**
+ * Each declared schema generation is backfilled by its own checkpoint. A first install has one
+ * generation covering every entity; after a mapping bump only the bumped entities form a new,
+ * higher generation that is built next to the live one and promoted separately.
+ */
+ const requestedEntities = new Set(entities ?? FTS_SEARCH_DOCUMENT_ENTITIES);
+ const generations = declaredGenerations().filter(([, generationEntities]) =>
+ generationEntities.some((entity) => requestedEntities.has(entity)),
+ );
+ for (const [schemaVersion, generationEntities] of generations) {
+ await applyGeneration({
+ client,
+ endpointHostname,
+ generationEntities,
+ processEntities: generationEntities.filter((entity) => requestedEntities.has(entity)),
+ schemaVersion,
+ });
}
- if (existing && freshRun) {
- throw new Error(`Checkpoint ${existing.run.id} already exists; omit --fresh-run to resume it`);
+};
+
+const applyGeneration = async ({
+ client,
+ endpointHostname,
+ generationEntities,
+ freshRunForGeneration = freshRun,
+ processEntities,
+ schemaVersion,
+}: {
+ client: FtsSearchReindexHttpClient;
+ endpointHostname: string;
+ generationEntities: FtsSearchDocumentEntity[];
+ freshRunForGeneration?: boolean;
+ processEntities: FtsSearchDocumentEntity[];
+ schemaVersion: number;
+}) => {
+ const existing = await repository.getTargetRun(namespace, schemaVersion);
+ /**
+ * `--in-place` pins each requested entity to the index its alias serves today instead of a new
+ * `<alias>-v<schemaVersion>`; the checkpoint remembers that choice, so a resume needs no flag.
+ */
+ const physicalIndexes: Partial<Record<FtsSearchDocumentEntity, string>> = {};
+ if (inPlace) {
+ for (const entity of processEntities) {
+ const pinned = existing?.progress.find((progress) => progress.entity === entity);
+ if (pinned) {
+ physicalIndexes[entity] = pinned.physicalIndex;
+ continue;
+ }
+ const status = await describeEntityGeneration({ client, entity, namespace, readCheckpoint });
+ const inPlaceIndex = resolveInPlaceTarget(status);
+ /**
+ * Widen the live index before the checkpoint reserves its base revision. From here on the
+ * consumer writes the new fields into this index, so every change newer than the base
+ * revision already carries them and the backfill only has to fill in older documents.
+ * `prepareIndices` restamps `_meta.reindex_run_id` once the run exists.
+ */
+ await client.putMapping(inPlaceIndex, {
+ _meta: {
+ reindex_run_id: status.live!.reindexRunId!,
+ schema_fingerprint: status.declared.fingerprint,
+ schema_version: status.declared.version,
+ },
+ properties: FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties,
+ });
+ physicalIndexes[entity] = inPlaceIndex;
+ }
}
+ let mode: 'fresh' | 'resume' | 'upgrade' | 'upgrade_in_place';
+ if (existing) {
+ if (freshRunForGeneration) {
+ throw new Error(
+ `Checkpoint ${existing.run.id} already exists; omit --fresh-run to resume it`,
+ );
+ }
+ mode = 'resume';
+ } else {
+ /**
+ * Without a checkpoint, the live aliases decide what this generation is: none exist on a
+ * fresh install (which must be confirmed with --fresh-run), all exist when a mapping bump
+ * needs a new generation built beside the live one. A mixed state is not something this tool
+ * created and needs an operator.
+ */
+ const aliased = new Set<FtsSearchDocumentEntity>();
+ for (const entity of generationEntities) {
+ const described = await client.describeGenerations(getFtsSearchIndexAlias(namespace, entity));
+ if (described.some((generation) => generation.isWriteIndex)) aliased.add(entity);
+ }
+ if (aliased.size === 0) {
+ if (!freshRunForGeneration) {
+ throw new Error(
+ `No checkpoint exists in ${stateDirectory} for v${schemaVersion}; pass --fresh-run only for a new, empty Elasticsearch target`,
+ );
+ }
+ mode = 'fresh';
+ } else if (aliased.size === generationEntities.length) {
+ if (freshRunForGeneration) {
+ throw new Error(
+ `Aliases already exist for the v${schemaVersion} entities; this is a generation upgrade, omit --fresh-run`,
+ );
+ }
+ mode = inPlace ? 'upgrade_in_place' : 'upgrade';
+ } else {
+ throw new Error(
+ `Only some v${schemaVersion} entities have aliases (${[...aliased].join(', ')}); repair the aliases before continuing`,
+ );
+ }
+ }
+
const prepared = await runFtsSearchReindexCommand({
command: 'apply',
installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
@@ -341,10 +718,16 @@ const run = async () => {
endpointEnvName: urlEnvironmentName,
endpointHostname,
expectedHostPrefix: expectedHostPrefix ?? null,
+ schemaVersion,
type: 'reindex_target',
}),
);
- return repository.createOrResume(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ return repository.createOrResume(
+ namespace,
+ schemaVersion,
+ generationEntities,
+ physicalIndexes,
+ );
},
});
if (existing && existing.run.status !== 'ready_for_incremental_sync') {
@@ -365,12 +748,12 @@ const run = async () => {
endpointEnvName: urlEnvironmentName,
expectedHostPrefix: expectedHostPrefix ?? null,
batchSizeByEntity,
- entities: entities ?? [...FTS_SEARCH_DOCUMENT_ENTITIES],
+ entities: processEntities,
entityConcurrency: entityConcurrency ?? 1,
rangeConcurrencyByEntity,
maxBatchesPerEntity: maxBatchesPerEntity ?? null,
maxRequestRetries: maxRequestRetries ?? 4,
- mode: existing ? 'resume' : 'fresh',
+ mode,
requestTimeoutMs: requestTimeoutMs ?? 30_000,
retryBaseDelayMs: retryBaseDelayMs ?? 500,
schemaVersion: prepared.run.schemaVersion,
@@ -387,12 +770,6 @@ const run = async () => {
}),
);
- const client = new FtsSearchReindexHttpClient({
- allowInsecureHttp,
- apiKey: elasticsearchApiKey,
- requestTimeoutMs,
- url: elasticsearchUrl!,
- });
const service = new FtsSearchReindexService(
new FtsSearchDocumentBuilder(db),
repository,
@@ -402,7 +779,7 @@ const run = async () => {
bulkConcurrency,
bulkMaxBytes,
batchSizeByEntity,
- entities,
+ entities: processEntities,
entityConcurrency,
rangeConcurrencyByEntity,
maxBatchesPerEntity,
@@ -433,7 +810,7 @@ const run = async () => {
validateIncrementalSyncSource: () => outbox.assertCaptureInfrastructure(),
},
);
- const result = await service.run(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ const result = await service.run(namespace, schemaVersion, generationEntities);
console.log(JSON.stringify(result));
const currentStatus = await printStatus();
await auditLogger.append({
@@ -448,14 +825,53 @@ const run = async () => {
});
};
-observeFtsSearchReindexRun(run)
+/** A lock never expires: a paused process must not overlap an automatic replacement worker. */
+const runWithMigrationLock = async () => {
+ if (command === 'status') return run();
+ assertFtsSearchReindexElasticsearchHostname(
+ new URL(elasticsearchUrl!).hostname,
+ expectedHostPrefix,
+ );
+ const lock = createMigrationLockClient();
+ if (command === 'release-lock') {
+ const result = await lock.release(releaseLockOwner!);
+ console.log(JSON.stringify({ result, type: 'migration_lock_released' }));
+ return;
+ }
+ if (command === 'startup') {
+ await pool.query('SELECT 1');
+ const client = createElasticsearchClient();
+ for (const entity of FTS_SEARCH_DOCUMENT_ENTITIES) {
+ assertFtsSearchStartupGenerationSafe(
+ await describeEntityGeneration({ client, entity, namespace, readCheckpoint }),
+ );
+ }
+ }
+ return lock.withLock(command, async (handle) => {
+ assertMigrationOwnership = () => lock.assertOwner(handle);
+ try {
+ return await run();
+ } finally {
+ assertMigrationOwnership = undefined;
+ }
+ });
+};
+
+observeFtsSearchReindexRun(runWithMigrationLock)
.catch(async (error) => {
- const rootError = error instanceof FtsSearchReindexEntityError ? error.cause : error;
+ const operationError =
+ error instanceof FtsSearchMigrationLockError && error.cause !== undefined
+ ? error.cause
+ : error;
+ const rootError =
+ operationError instanceof FtsSearchReindexEntityError ? operationError.cause : operationError;
logErrorSummary('❌ Elasticsearch reindex failed:', rootError);
+ if (operationError !== error) logErrorSummary('Migration lock recovery:', error);
if (auditLogger) {
const failure = {
elapsedMs: Date.now() - executionStartedAt,
- entity: error instanceof FtsSearchReindexEntityError ? error.entity : null,
+ entity:
+ operationError instanceof FtsSearchReindexEntityError ? operationError.entity : null,
errorSummary: summarizeFtsSearchReindexError(rootError),
errorType: rootError instanceof Error ? rootError.name.slice(0, 128) : 'UnknownError',
type: 'session_failed' as const,
diff --git a/scripts/elasticsearchReindex/preparation.ts b/scripts/elasticsearchReindex/preparation.ts
index cb08e4b6b28..18b47d21e1f 100644
--- a/scripts/elasticsearchReindex/preparation.ts
+++ b/scripts/elasticsearchReindex/preparation.ts
@@ -1,4 +1,5 @@
-export type FtsSearchReindexCommand = 'apply' | 'skip-failure' | 'status';
+export type FtsSearchReindexCommand =
+ 'apply' | 'promote' | 'purge' | 'retire' | 'skip-failure' | 'startup' | 'status';
interface RunFtsSearchReindexCommandOptions<T> {
command: FtsSearchReindexCommand;
@@ -10,8 +11,9 @@ interface RunFtsSearchReindexCommandOptions<T> {
/**
* Runs one reindex command while keeping capture installation ahead of every apply mutation.
*
- * Status and failure-skipping commands intentionally execute without installing database
- * triggers, so PG-only self-hosted instances do not pay the Elasticsearch capture overhead.
+ * Status, failure-skipping, promote, and retire commands intentionally execute without installing
+ * database triggers, so PG-only self-hosted instances do not pay the Elasticsearch capture
+ * overhead; promote already requires a drained Outbox, which implies capture is installed.
*/
export const runFtsSearchReindexCommand = async <T>({
command,
@@ -19,7 +21,7 @@ export const runFtsSearchReindexCommand = async <T>({
run,
runWithLockRetry,
}: RunFtsSearchReindexCommandOptions<T>): Promise<T> => {
- if (command === 'apply') {
+ if (command === 'apply' || command === 'startup') {
await runWithLockRetry(installCaptureInfrastructure);
}
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
index 4246a14a7a4..694a682a11c 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
@@ -162,9 +162,58 @@ describe('FtsSearchReindexFileRepository', () => {
it('refuses to mark a run ready while entities are incomplete', async () => {
const state = await repository.createOrResume('not-ready-search', 1);
- await expect(repository.markReadyForIncrementalSync(state.run.id)).rejects.toThrow(
- 'Cannot create aliases',
- );
+ await expect(
+ repository.markReadyForIncrementalSync(state.run.id, FTS_SEARCH_DOCUMENT_ENTITIES),
+ ).rejects.toThrow('Cannot create aliases');
+ });
+
+ it('gates readiness on current generation failures while preserving superseded history', async () => {
+ const state = await repository.createOrResume('membership-search', 1, ['topics', 'agents']);
+ await repository.checkpointBatch({
+ cursor: 'topic-1',
+ entity: 'topics',
+ failures: [{ documentId: 'topic-1', error: new Error('old mapping'), retryable: false }],
+ indexedCount: 0,
+ previousCursor: null,
+ processedCount: 1,
+ runId: state.run.id,
+ });
+ await repository.completeEntity(state.run.id, 'agents');
+
+ await expect(
+ repository.markReadyForIncrementalSync(state.run.id, ['agents']),
+ ).resolves.toBeUndefined();
+ await expect(repository.listUnresolvedFailures(state.run.id)).resolves.toEqual([
+ expect.objectContaining({ documentId: 'topic-1', entity: 'topics', resolvedAt: null }),
+ ]);
+ await expect(
+ repository.createOrResume('membership-search', 1, ['agents']),
+ ).resolves.toMatchObject({ run: { status: 'ready_for_incremental_sync' } });
+
+ const rejoined = await repository.createOrResume('membership-search', 1, ['agents', 'topics']);
+ expect(rejoined).toMatchObject({
+ progress: expect.arrayContaining([
+ expect.objectContaining({ cursor: 'topic-1', entity: 'topics', status: 'backfilling' }),
+ ]),
+ run: { status: 'backfilling' },
+ });
+ await expect(
+ repository.markReadyForIncrementalSync(state.run.id, ['agents', 'topics']),
+ ).rejects.toThrow('Cannot create aliases');
+
+ const blocked = await repository.createOrResume('current-failure-search', 1, ['agents']);
+ await repository.checkpointBatch({
+ cursor: 'agent-1',
+ entity: 'agents',
+ failures: [{ documentId: 'agent-1', error: new Error('current mapping'), retryable: false }],
+ indexedCount: 0,
+ previousCursor: null,
+ processedCount: 1,
+ runId: blocked.run.id,
+ });
+ await expect(
+ repository.markReadyForIncrementalSync(blocked.run.id, ['agents']),
+ ).rejects.toThrow('Cannot create aliases');
});
it('lets an operator skip a failed document without counting it as indexed', async () => {
@@ -215,7 +264,7 @@ describe('FtsSearchReindexFileRepository', () => {
await repository.completeEntity(state.run.id, entity);
}
- await repository.markReadyForIncrementalSync(state.run.id);
+ await repository.markReadyForIncrementalSync(state.run.id, FTS_SEARCH_DOCUMENT_ENTITIES);
const ready = await repository.getRun(state.run.id);
expect(ready?.run).toMatchObject({
@@ -224,4 +273,165 @@ describe('FtsSearchReindexFileRepository', () => {
});
expect(ready!.run.backfillHighWaterRevision).toBeGreaterThanOrEqual(state.run.baseRevision);
});
+
+ it('covers only the requested entities when creating an upgrade generation', async () => {
+ const state = await repository.createOrResume('subset-search', 2, ['topics', 'agents']);
+
+ expect(state.progress.map(({ entity }) => entity)).toEqual(['topics', 'agents']);
+ expect(state.progress.map(({ physicalIndex }) => physicalIndex)).toEqual([
+ 'subset-search-topics-v2',
+ 'subset-search-agents-v2',
+ ]);
+ expect(state.progress.every(({ status }) => status === 'pending')).toBe(true);
+ expect(state.run).toMatchObject({ namespace: 'subset-search', schemaVersion: 2 });
+
+ const checkpointFiles = await readdir(stateDirectory);
+ expect(checkpointFiles).toHaveLength(1);
+ expect(checkpointFiles[0]).toMatch(/^reindex-subset-search-[a-f\d]{12}-v2\.json$/);
+ });
+
+ it('refuses to create a generation that covers no entity', async () => {
+ await expect(repository.createOrResume('empty-search', 2, [])).rejects.toThrow(
+ 'A reindex generation must cover at least one entity',
+ );
+
+ await expect(readdir(stateDirectory)).resolves.toEqual([]);
+ /** The base revision write fence must not be spent on a generation that cannot exist. */
+ expect(revision).toBe(10);
+ });
+
+ it('appends a newly covered entity and reopens a ready generation', async () => {
+ const created = await repository.createOrResume('growing-search', 1, ['topics']);
+ await repository.completeEntity(created.run.id, 'topics');
+ await repository.markReadyForIncrementalSync(created.run.id, ['topics']);
+
+ const resumed = await repository.createOrResume('growing-search', 1, ['topics', 'agents']);
+
+ expect(resumed.run.id).toBe(created.run.id);
+ expect(resumed.run.status).toBe('backfilling');
+ expect(resumed.progress).toEqual([
+ expect.objectContaining({ entity: 'topics', status: 'completed' }),
+ expect.objectContaining({
+ cursor: null,
+ entity: 'agents',
+ indexedCount: 0,
+ physicalIndex: 'growing-search-agents-v1',
+ status: 'pending',
+ }),
+ ]);
+ expect(resumed.run.backfillHighWaterRevision).toBe(revision);
+ await expect(readdir(stateDirectory)).resolves.toHaveLength(1);
+ });
+
+ it('leaves a ready generation untouched when it already covers the requested entities', async () => {
+ const created = await repository.createOrResume('stable-search', 1, ['topics']);
+ await repository.completeEntity(created.run.id, 'topics');
+ await repository.markReadyForIncrementalSync(created.run.id, ['topics']);
+ const ready = await repository.getRun(created.run.id);
+
+ const resumed = await repository.createOrResume('stable-search', 1, ['topics']);
+
+ expect(resumed.run.status).toBe('ready_for_incremental_sync');
+ /** Nothing is rewritten, so even `updatedAt` stays identical. */
+ expect(resumed).toEqual(ready);
+ });
+
+ it('rejects a checkpoint that tracks one entity twice', async () => {
+ await repository.createOrResume('duplicate-search', 1, ['topics']);
+ const [checkpointFile] = await readdir(stateDirectory);
+ const checkpointPath = path.join(stateDirectory, checkpointFile);
+ const checkpoint = JSON.parse(await readFile(checkpointPath, 'utf8'));
+ checkpoint.progress.push({ ...checkpoint.progress[0] });
+ await writeFile(checkpointPath, JSON.stringify(checkpoint));
+
+ const error = await repository.getTargetRun('duplicate-search', 1).catch((cause) => cause);
+
+ expect(error).toMatchObject({ message: expect.stringContaining('checkpoint is invalid') });
+ expect(String(error.cause)).toContain('must contain each entity at most once');
+ });
+
+ it('pins an in-place upgraded entity to the index its alias already serves', async () => {
+ const state = await repository.createOrResume('in-place-search', 2, ['topics', 'agents'], {
+ topics: 'in-place-search-topics-v1',
+ });
+
+ expect(state.progress).toEqual([
+ expect.objectContaining({
+ entity: 'topics',
+ physicalIndex: 'in-place-search-topics-v1',
+ status: 'pending',
+ }),
+ expect.objectContaining({
+ entity: 'agents',
+ physicalIndex: 'in-place-search-agents-v2',
+ status: 'pending',
+ }),
+ ]);
+ });
+
+ it('refuses to resume a tracked entity into a different physical index', async () => {
+ const created = await repository.createOrResume('switch-search', 2, ['topics'], {
+ topics: 'switch-search-topics-v1',
+ });
+
+ await expect(
+ repository.createOrResume('switch-search', 2, ['topics', 'agents'], {
+ topics: 'switch-search-topics-v2',
+ }),
+ ).rejects.toThrow('cannot switch to switch-search-topics-v2');
+ /** The rejected resume must not append the newly requested entity either. */
+ await expect(repository.getTargetRun('switch-search', 2)).resolves.toEqual(created);
+ });
+
+ it('resumes an in-place generation that keeps the same physical index', async () => {
+ const created = await repository.createOrResume('resumed-in-place-search', 2, ['topics'], {
+ topics: 'resumed-in-place-search-topics-v1',
+ });
+
+ const resumed = await repository.createOrResume('resumed-in-place-search', 2, ['topics'], {
+ topics: 'resumed-in-place-search-topics-v1',
+ });
+
+ expect(resumed).toEqual(created);
+ });
+
+ it('accepts an older generation index but no newer or foreign one', async () => {
+ await repository.createOrResume('pinned-search', 2, ['topics']);
+ const [checkpointFile] = await readdir(stateDirectory);
+ const checkpointPath = path.join(stateDirectory, checkpointFile);
+ const checkpoint = JSON.parse(await readFile(checkpointPath, 'utf8'));
+ const writeTarget = async (physicalIndex: string) => {
+ checkpoint.progress[0].physicalIndex = physicalIndex;
+ await writeFile(checkpointPath, JSON.stringify(checkpoint));
+ return repository.getTargetRun('pinned-search', 2).catch((cause) => cause);
+ };
+
+ await expect(writeTarget('pinned-search-topics-v1')).resolves.toMatchObject({
+ progress: [expect.objectContaining({ physicalIndex: 'pinned-search-topics-v1' })],
+ });
+
+ const newer = await writeTarget('pinned-search-topics-v3');
+ expect(newer).toMatchObject({ message: expect.stringContaining('checkpoint is invalid') });
+ expect(String(newer.cause)).toContain(
+ 'Expected physical index pinned-search-topics-v<n> with n <= 2',
+ );
+
+ const foreign = await writeTarget('other-search-topics-v1');
+ expect(String(foreign.cause)).toContain(
+ 'Expected physical index pinned-search-topics-v<n> with n <= 2',
+ );
+ });
+
+ it('rejects a checkpoint whose generation covers no entity', async () => {
+ await repository.createOrResume('emptied-search', 1, ['topics']);
+ const [checkpointFile] = await readdir(stateDirectory);
+ const checkpointPath = path.join(stateDirectory, checkpointFile);
+ const checkpoint = JSON.parse(await readFile(checkpointPath, 'utf8'));
+ checkpoint.progress = [];
+ await writeFile(checkpointPath, JSON.stringify(checkpoint));
+
+ await expect(repository.createOrResume('emptied-search', 1, ['topics'])).rejects.toThrow(
+ 'FTS reindex checkpoint is invalid',
+ );
+ });
});
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
index f0ceef2be8e..a48b1144651 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
@@ -2,11 +2,13 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
+ buildFtsSearchIndexMeta,
FTS_SEARCH_INDEX_ANALYSIS,
FTS_SEARCH_INDEX_DEFINITIONS,
} from '../../../../packages/database/src/repositories/ftsSearchDocument';
-import { FtsSearchReindexHttpClient } from '../elasticsearchClient';
+import { FtsSearchReindexHttpClient, parseGenerationVersion } from '../elasticsearchClient';
import type { FtsSearchReindexIndexBody } from '../reindexService';
+import { getRetiredIndexProtectionTemplateName } from '../retiredIndexProtection';
const response = (body: unknown, status = 200) =>
new Response(body === undefined ? undefined : JSON.stringify(body), {
@@ -14,7 +16,7 @@ const response = (body: unknown, status = 200) =>
status,
});
-const reindexMeta = { reindex_run_id: '00000000-0000-4000-8000-000000000001', schema_version: 1 };
+const reindexMeta = buildFtsSearchIndexMeta('agents', '00000000-0000-4000-8000-000000000001');
const agentsIndexBody: FtsSearchReindexIndexBody = {
mappings: { ...FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings, _meta: reindexMeta },
settings: { analysis: FTS_SEARCH_INDEX_ANALYSIS },
@@ -229,6 +231,61 @@ describe('FtsSearchReindexHttpClient', () => {
);
});
+ it('resumes a legacy index whose _meta predates schema fingerprints', async () => {
+ const { schema_fingerprint: _fingerprint, ...legacyMeta } = reindexMeta;
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ mappings: { _meta: legacyMeta, ...FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings },
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.ensureIndex('lobehub-messages-v1', agentsIndexBody),
+ ).resolves.toBeUndefined();
+ });
+
+ it('refuses to resume an index built from a drifted mapping of the same schema version', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ mappings: {
+ _meta: { ...reindexMeta, schema_fingerprint: 'f'.repeat(64) },
+ ...FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings,
+ },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureIndex('lobehub-messages-v1', agentsIndexBody)).rejects.toThrow(
+ 'was built from a different v1 mapping than the code declares',
+ );
+ });
+
it('keeps an alias that already targets the expected writable index', async () => {
const fetchMock = vi.fn().mockResolvedValue(
response({
@@ -243,13 +300,34 @@ describe('FtsSearchReindexHttpClient', () => {
url: 'https://search.example.com',
});
- await expect(
- client.ensureAlias('lobehub-messages', 'lobehub-messages-v1'),
- ).resolves.toBeUndefined();
+ await expect(client.ensureAlias('lobehub-messages', 'lobehub-messages-v1')).resolves.toBe(
+ 'existing',
+ );
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(String(fetchMock.mock.calls[0][0])).toBe(
+ 'https://search.example.com/_alias/lobehub-messages',
+ );
+ });
+
+ it('keeps an alias that targets the expected index without an explicit write flag', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ response({ 'lobehub-messages-v1': { aliases: { 'lobehub-messages': {} } } }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureAlias('lobehub-messages', 'lobehub-messages-v1')).resolves.toBe(
+ 'existing',
+ );
expect(fetchMock).toHaveBeenCalledOnce();
});
- it('refuses to advance an alias that targets an older schema version', async () => {
+ it('keeps an alias that still serves another generation of the same entity', async () => {
const fetchMock = vi.fn().mockResolvedValue(
response({
'lobehub-messages-v1': {
@@ -263,9 +341,698 @@ describe('FtsSearchReindexHttpClient', () => {
url: 'https://search.example.com',
});
+ await expect(client.ensureAlias('lobehub-messages', 'lobehub-messages-v2')).resolves.toBe(
+ 'kept_other_generation',
+ );
+ // Promotion is an explicit later step, so the backfill must not mutate the alias here.
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock.mock.calls[0][1].method).toBe('GET');
+ expect(String(fetchMock.mock.calls[0][0])).toBe(
+ 'https://search.example.com/_alias/lobehub-messages',
+ );
+ });
+
+ it('refuses an alias that targets an index outside the generation naming scheme', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ response({
+ 'legacy-messages-index': {
+ aliases: { 'lobehub-messages': { is_write_index: true } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
await expect(client.ensureAlias('lobehub-messages', 'lobehub-messages-v2')).rejects.toThrow(
- 'Elasticsearch alias lobehub-messages already points to a different index',
+ 'Elasticsearch alias lobehub-messages points to legacy-messages-index instead of a single writable lobehub-messages-v<n> generation',
);
expect(fetchMock).toHaveBeenCalledOnce();
});
+
+ it('creates a missing alias as the write index of the given generation', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined, 404))
+ .mockResolvedValueOnce(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureAlias('lobehub-messages', 'lobehub-messages-v2')).resolves.toBe(
+ 'created',
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const [endpoint, init] = fetchMock.mock.calls[1];
+ expect(String(endpoint)).toBe('https://search.example.com/_aliases');
+ expect(init.method).toBe('POST');
+ expect(JSON.parse(init.body)).toEqual({
+ actions: [
+ { add: { alias: 'lobehub-messages', index: 'lobehub-messages-v2', is_write_index: true } },
+ ],
+ });
+ });
+
+ it('describes open and closed generations of an alias', async () => {
+ const openDetail = {
+ 'lobehub-messages-v1': {
+ mappings: {
+ _meta: { ...reindexMeta, schema_version: 1 },
+ dynamic: 'strict',
+ properties: { id: { type: 'keyword' } },
+ },
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ 'lobehub-messages-v2': {
+ mappings: {
+ _meta: { ...reindexMeta, schema_version: 2 },
+ dynamic: 'strict',
+ properties: { id: { type: 'keyword' } },
+ },
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ };
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ response([
+ { index: 'lobehub-messages-v2', status: 'open' },
+ { index: 'lobehub-messages-v1', status: 'close' },
+ ]),
+ )
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v2': { aliases: { 'lobehub-messages': { is_write_index: true } } },
+ }),
+ )
+ .mockResolvedValueOnce(response(openDetail));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.describeGenerations('lobehub-messages')).resolves.toEqual([
+ {
+ aliased: false,
+ analysis: FTS_SEARCH_INDEX_ANALYSIS,
+ index: 'lobehub-messages-v1',
+ isWriteIndex: false,
+ mappings: openDetail['lobehub-messages-v1'].mappings,
+ meta: { ...reindexMeta, schema_version: 1 },
+ state: 'closed',
+ version: 1,
+ },
+ {
+ aliased: true,
+ analysis: FTS_SEARCH_INDEX_ANALYSIS,
+ index: 'lobehub-messages-v2',
+ isWriteIndex: true,
+ mappings: openDetail['lobehub-messages-v2'].mappings,
+ meta: { ...reindexMeta, schema_version: 2 },
+ state: 'open',
+ version: 2,
+ },
+ ]);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(String(fetchMock.mock.calls[0][0])).toBe(
+ 'https://search.example.com/_cat/indices/lobehub-messages-v*?format=json&h=index,status&expand_wildcards=all&allow_no_indices=true',
+ );
+ expect(String(fetchMock.mock.calls[1][0])).toBe(
+ 'https://search.example.com/_alias/lobehub-messages',
+ );
+ expect(String(fetchMock.mock.calls[2][0])).toBe(
+ 'https://search.example.com/lobehub-messages-v2,lobehub-messages-v1?expand_wildcards=all&filter_path=*.mappings,*.settings.index.analysis',
+ );
+ });
+
+ it('describes generations of an entity whose alias does not exist yet', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response([{ index: 'lobehub-messages-v1', status: 'open' }]))
+ .mockResolvedValueOnce(response(undefined, 404))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ mappings: { _meta: reindexMeta, dynamic: 'strict', properties: {} },
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.describeGenerations('lobehub-messages')).resolves.toEqual([
+ {
+ aliased: false,
+ analysis: FTS_SEARCH_INDEX_ANALYSIS,
+ index: 'lobehub-messages-v1',
+ isWriteIndex: false,
+ mappings: { _meta: reindexMeta, dynamic: 'strict', properties: {} },
+ meta: reindexMeta,
+ state: 'open',
+ version: 1,
+ },
+ ]);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('describes no generation when the entity has no physical index', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response([]))
+ .mockResolvedValueOnce(response(undefined, 404));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.describeGenerations('lobehub-messages')).resolves.toEqual([]);
+ // Without an open index there is nothing to inspect, so no detail request is issued.
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores a listed index that is outside the generation naming scheme', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ response([
+ { index: 'lobehub-messages-vnext', status: 'open' },
+ { index: 'lobehub-messages-v3', status: 'open' },
+ ]),
+ )
+ .mockResolvedValueOnce(response(undefined, 404))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v3': {
+ mappings: { _meta: reindexMeta, dynamic: 'strict', properties: {} },
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ const generations = await client.describeGenerations('lobehub-messages');
+
+ expect(generations.map(({ index }) => index)).toEqual(['lobehub-messages-v3']);
+ expect(String(fetchMock.mock.calls[2][0])).toBe(
+ 'https://search.example.com/lobehub-messages-v3?expand_wildcards=all&filter_path=*.mappings,*.settings.index.analysis',
+ );
+ });
+
+ it('describes an aliased index that is outside the generation naming scheme', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response([]))
+ .mockResolvedValueOnce(
+ response({ 'lobehub-messages-legacy': { aliases: { 'lobehub-messages': {} } } }),
+ )
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-legacy': {
+ mappings: { _meta: reindexMeta, dynamic: 'strict', properties: {} },
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.describeGenerations('lobehub-messages')).resolves.toMatchObject([
+ {
+ aliased: true,
+ index: 'lobehub-messages-legacy',
+ isWriteIndex: true,
+ state: 'open',
+ version: null,
+ },
+ ]);
+ expect(String(fetchMock.mock.calls[2][0])).toBe(
+ 'https://search.example.com/lobehub-messages-legacy?expand_wildcards=all&filter_path=*.mappings,*.settings.index.analysis',
+ );
+ });
+
+ it('reports the stamped generation of an index upgraded in place', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response([{ index: 'lobehub-messages-v1', status: 'open' }]))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': { aliases: { 'lobehub-messages': { is_write_index: true } } },
+ }),
+ )
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ mappings: {
+ _meta: { ...reindexMeta, schema_version: 2 },
+ dynamic: 'strict',
+ properties: {},
+ },
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ // The `-v1` suffix only records which generation built the index, not the one it implements.
+ await expect(client.describeGenerations('lobehub-messages')).resolves.toMatchObject([
+ { index: 'lobehub-messages-v1', isWriteIndex: true, version: 2 },
+ ]);
+ });
+
+ it('reports no generation for a stamped index outside the naming scheme', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response([]))
+ .mockResolvedValueOnce(
+ response({ 'lobehub-messages-restored': { aliases: { 'lobehub-messages': {} } } }),
+ )
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-restored': {
+ mappings: {
+ _meta: { ...reindexMeta, schema_version: 3 },
+ dynamic: 'strict',
+ properties: {},
+ },
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.describeGenerations('lobehub-messages')).resolves.toMatchObject([
+ { index: 'lobehub-messages-restored', meta: { schema_version: 3 }, version: null },
+ ]);
+ });
+
+ it('applies an additive mapping upgrade to a live index', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.putMapping('lobehub-messages-v1', {
+ _meta: reindexMeta,
+ properties: FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings.properties,
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [endpoint, init] = fetchMock.mock.calls[0];
+ expect(String(endpoint)).toBe('https://search.example.com/lobehub-messages-v1/_mapping');
+ expect(init.method).toBe('PUT');
+ expect(JSON.parse(init.body)).toEqual({
+ _meta: reindexMeta,
+ properties: FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings.properties,
+ });
+ });
+
+ it('reports a rejected mapping upgrade', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ error: 'illegal_argument' }, 400));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.putMapping('lobehub-messages-v1', {
+ _meta: reindexMeta,
+ properties: FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings.properties,
+ }),
+ ).rejects.toThrow('Elasticsearch mapping upgrade failed for lobehub-messages-v1 (400)');
+ });
+
+ it('promotes a generation and removes the alias from every previous generation', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.promoteAlias(
+ 'lobehub-messages',
+ ['lobehub-messages-v1', 'lobehub-messages-v2'],
+ 'lobehub-messages-v3',
+ ),
+ ).resolves.toBeUndefined();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [endpoint, init] = fetchMock.mock.calls[0];
+ expect(String(endpoint)).toBe('https://search.example.com/_aliases');
+ expect(init.method).toBe('POST');
+ expect(JSON.parse(init.body)).toEqual({
+ actions: [
+ { remove: { alias: 'lobehub-messages', index: 'lobehub-messages-v1' } },
+ { remove: { alias: 'lobehub-messages', index: 'lobehub-messages-v2' } },
+ { add: { alias: 'lobehub-messages', index: 'lobehub-messages-v3', is_write_index: true } },
+ ],
+ });
+ });
+
+ it('does not remove the alias from the generation it promotes', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await client.promoteAlias(
+ 'lobehub-messages',
+ ['lobehub-messages-v1', 'lobehub-messages-v2'],
+ 'lobehub-messages-v2',
+ );
+
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
+ actions: [
+ { remove: { alias: 'lobehub-messages', index: 'lobehub-messages-v1' } },
+ { add: { alias: 'lobehub-messages', index: 'lobehub-messages-v2', is_write_index: true } },
+ ],
+ });
+ });
+
+ it('closes a retired generation', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.closeIndex('lobehub-messages-v1')).resolves.toBeUndefined();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [endpoint, init] = fetchMock.mock.calls[0];
+ expect(String(endpoint)).toBe('https://search.example.com/lobehub-messages-v1/_close');
+ expect(init.method).toBe('POST');
+ });
+
+ it('reports a failed close of a retired generation', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ error: 'forbidden' }, 403));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.closeIndex('lobehub-messages-v1')).rejects.toThrow(
+ 'Elasticsearch index close failed for lobehub-messages-v1 (403)',
+ );
+ });
+
+ it('deletes a retired generation', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.deleteIndex('lobehub-messages-v1')).resolves.toBeUndefined();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [endpoint, init] = fetchMock.mock.calls[0];
+ expect(String(endpoint)).toBe('https://search.example.com/lobehub-messages-v1');
+ expect(init.method).toBe('DELETE');
+ });
+
+ it('installs an exact-index auto-create tombstone before deletion', async () => {
+ const index = 'lobehub-messages-v1';
+ const templateName = getRetiredIndexProtectionTemplateName(index);
+ const template = {
+ _meta: { index, owner: 'lobehub-fts-search-retirement' },
+ allow_auto_create: false,
+ index_patterns: [index],
+ priority: 1_000_000,
+ template: {},
+ };
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response({ index_templates: [] }))
+ .mockResolvedValueOnce(response({ acknowledged: true }))
+ .mockResolvedValueOnce(
+ response({ index_templates: [{ index_template: template, name: templateName }] }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const beforeMutation = vi.fn().mockResolvedValue(undefined);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ beforeMutation,
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureRetiredIndexProtection(index)).resolves.toBeUndefined();
+
+ expect(beforeMutation).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(String(fetchMock.mock.calls[1][0])).toBe(
+ `https://search.example.com/_index_template/${templateName}?create=true`,
+ );
+ expect(fetchMock.mock.calls[1][1].method).toBe('PUT');
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual(template);
+ });
+
+ it('refuses a retired-index selector containing wildcards', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureRetiredIndexProtection('lobehub-messages-v*')).rejects.toThrow(
+ 'must be one exact physical index name',
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('accepts an existing owned tombstone with Elasticsearch defaults', async () => {
+ const index = 'lobehub-messages-v1';
+ const templateName = getRetiredIndexProtectionTemplateName(index);
+ const fetchMock = vi.fn().mockResolvedValue(
+ response({
+ index_templates: [
+ {
+ index_template: {
+ _meta: { index, owner: 'lobehub-fts-search-retirement' },
+ allow_auto_create: false,
+ composed_of: [],
+ index_patterns: [index],
+ priority: 1_000_000,
+ template: {},
+ },
+ name: templateName,
+ },
+ ],
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const beforeMutation = vi.fn().mockResolvedValue(undefined);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ beforeMutation,
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureRetiredIndexProtection(index)).resolves.toBeUndefined();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(beforeMutation).not.toHaveBeenCalled();
+ });
+
+ it('refuses to shadow an external template matching the retired index', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ response({
+ index_templates: [
+ {
+ index_template: { index_patterns: ['lobehub-*'], priority: 500, template: {} },
+ name: 'operator-defaults',
+ },
+ ],
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureRetiredIndexProtection('lobehub-messages-v1')).rejects.toThrow(
+ 'overlaps external index template operator-defaults',
+ );
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
+ it('refuses an unowned collision at the deterministic tombstone name', async () => {
+ const index = 'lobehub-messages-v1';
+ const templateName = getRetiredIndexProtectionTemplateName(index);
+ const fetchMock = vi.fn().mockResolvedValue(
+ response({
+ index_templates: [
+ {
+ index_template: { index_patterns: [index], template: {} },
+ name: templateName,
+ },
+ ],
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureRetiredIndexProtection(index)).rejects.toThrow(
+ `index template ${templateName} already exists but is not owned`,
+ );
+ });
+
+ it('blocks deletion when Elasticsearch does not acknowledge it', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ acknowledged: false }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.deleteIndex('lobehub-messages-v1')).rejects.toThrow(
+ 'did not acknowledge deletion',
+ );
+ });
+
+ it.each([
+ {
+ expected: 'alias creation for lobehub-messages',
+ name: 'alias creation',
+ preflight404: true,
+ run: (client: FtsSearchReindexHttpClient) =>
+ client.ensureAlias('lobehub-messages', 'lobehub-messages-v1'),
+ },
+ {
+ expected: 'alias promotion for lobehub-messages',
+ name: 'alias promotion',
+ preflight404: false,
+ run: (client: FtsSearchReindexHttpClient) =>
+ client.promoteAlias('lobehub-messages', ['lobehub-messages-v1'], 'lobehub-messages-v2'),
+ },
+ {
+ expected: 'index close for lobehub-messages-v1',
+ name: 'index close',
+ preflight404: false,
+ run: (client: FtsSearchReindexHttpClient) => client.closeIndex('lobehub-messages-v1'),
+ },
+ {
+ expected: 'mapping upgrade for lobehub-messages-v1',
+ name: 'mapping upgrade',
+ preflight404: false,
+ run: (client: FtsSearchReindexHttpClient) =>
+ client.putMapping('lobehub-messages-v1', {
+ _meta: reindexMeta,
+ properties: FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings.properties,
+ }),
+ },
+ {
+ expected: 'index creation for lobehub-messages-v1',
+ name: 'index creation',
+ preflight404: true,
+ run: (client: FtsSearchReindexHttpClient) =>
+ client.ensureIndex('lobehub-messages-v1', agentsIndexBody),
+ },
+ ])(
+ 'blocks $name when Elasticsearch does not acknowledge it',
+ async ({ expected, preflight404, run }) => {
+ const fetchMock = vi.fn();
+ if (preflight404) fetchMock.mockResolvedValueOnce(response(undefined, 404));
+ fetchMock.mockResolvedValueOnce(response({ acknowledged: false }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(run(client)).rejects.toThrow(`Elasticsearch did not acknowledge ${expected}`);
+ },
+ );
+
+ it('runs the mutation guard immediately before mutable requests', async () => {
+ const events: string[] = [];
+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
+ events.push(`request:${init?.method}`);
+ return response({ acknowledged: true });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ beforeMutation: async () => {
+ events.push('guard');
+ },
+ url: 'https://search.example.com',
+ });
+
+ await client.closeIndex('lobehub-messages-v1');
+ expect(events).toEqual(['guard', 'request:POST']);
+ });
+
+ it('reports a failed deletion of a retired generation', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({ error: 'not found' }, 404));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.deleteIndex('lobehub-messages-v1')).rejects.toThrow(
+ 'Elasticsearch index deletion failed for lobehub-messages-v1 (404)',
+ );
+ });
+});
+
+describe('parseGenerationVersion', () => {
+ it('parses the generation of an index that follows the alias naming scheme', () => {
+ expect(parseGenerationVersion('lobehub-messages', 'lobehub-messages-v1')).toBe(1);
+ expect(parseGenerationVersion('lobehub-messages', 'lobehub-messages-v12')).toBe(12);
+ });
+
+ it('returns undefined for an index outside the alias naming scheme', () => {
+ expect(parseGenerationVersion('lobehub-messages', 'lobehub-messages')).toBeUndefined();
+ expect(parseGenerationVersion('lobehub-messages', 'lobehub-messages-vnext')).toBeUndefined();
+ expect(
+ parseGenerationVersion('lobehub-messages', 'lobehub-messages-v1-restored'),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for a generation of a foreign alias prefix', () => {
+ expect(parseGenerationVersion('lobehub-messages', 'lobehub-agents-v1')).toBeUndefined();
+ expect(
+ parseGenerationVersion('lobehub-messages', 'shadow-lobehub-messages-v1'),
+ ).toBeUndefined();
+ });
});
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
new file mode 100644
index 00000000000..b4b3dcccb91
--- /dev/null
+++ b/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
@@ -0,0 +1,946 @@
+// @vitest-environment node
+import type { FtsSearchDocumentEntity, FtsSearchReindexEntityStatus } from '@lobechat/types';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_INDEX_DEFINITIONS,
+ getFtsSearchIndexAlias,
+ getFtsSearchIndexSchemaFingerprint,
+ getFtsSearchIndexSchemaVersion,
+ getFtsSearchPhysicalIndexName,
+} from '../../../../packages/database/src/repositories/ftsSearchDocument';
+import type {
+ FtsSearchSyncOutboxEntityStats,
+ FtsSearchSyncOutboxStats,
+} from '../../../../packages/database/src/repositories/ftsSearchSyncOutbox';
+import type { FtsSearchReindexRunState } from '../checkpointRepository';
+import type { FtsSearchReindexGenerationDescription } from '../elasticsearchClient';
+import { parseGenerationVersion } from '../elasticsearchClient';
+import type {
+ FtsSearchGenerationCheckpointReader,
+ FtsSearchGenerationElasticsearchClient,
+} from '../generationService';
+import {
+ classifyMappingChange,
+ describeEntityGeneration,
+ planRetiredGenerations,
+ promoteGeneration,
+ purgeRetiredGenerations,
+ resolveInPlaceTarget,
+ retireGenerations,
+} from '../generationService';
+import { diffFtsSearchMappings } from '../mappingDiff';
+
+const NAMESPACE = 'lobehub';
+const ENTITY: FtsSearchDocumentEntity = 'topics';
+const ALIAS = getFtsSearchIndexAlias(NAMESPACE, ENTITY);
+const DECLARED_FINGERPRINT = getFtsSearchIndexSchemaFingerprint(ENTITY);
+const IDLE_OUTBOX_ENTITY: FtsSearchSyncOutboxEntityStats = {
+ dead: 0,
+ expiredLeases: 0,
+ inFlight: 0,
+ oldestReadyAgeSeconds: 0,
+ pending: 0,
+ ready: 0,
+ retrying: 0,
+};
+
+const createOutboxStats = (
+ overrides: Partial<Record<FtsSearchDocumentEntity, Partial<FtsSearchSyncOutboxEntityStats>>> = {},
+): FtsSearchSyncOutboxStats => {
+ const entities = Object.fromEntries(
+ FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => [
+ entity,
+ { ...IDLE_OUTBOX_ENTITY, ...overrides[entity] },
+ ]),
+ ) as Record<FtsSearchDocumentEntity, FtsSearchSyncOutboxEntityStats>;
+ const totals = Object.values(entities).reduce(
+ (stats, entity) => ({
+ dead: stats.dead + entity.dead,
+ expiredLeases: stats.expiredLeases + entity.expiredLeases,
+ inFlight: stats.inFlight + entity.inFlight,
+ oldestReadyAgeSeconds: Math.max(stats.oldestReadyAgeSeconds, entity.oldestReadyAgeSeconds),
+ pending: stats.pending + entity.pending,
+ ready: stats.ready + entity.ready,
+ retrying: stats.retrying + entity.retrying,
+ }),
+ { ...IDLE_OUTBOX_ENTITY },
+ );
+
+ return {
+ ...totals,
+ entities,
+ highWaterRevision: 0,
+ oldestActiveRevision: null,
+ revisionLag: 0,
+ };
+};
+
+const IDLE_OUTBOX = createOutboxStats();
+
+type LiveMappings = NonNullable<FtsSearchReindexGenerationDescription['mappings']>;
+
+/** Mapping an index built from the declared definition reports back, cloned so tests can mutate it. */
+const declaredMappings = (entity: FtsSearchDocumentEntity = ENTITY): LiveMappings =>
+ structuredClone(FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings) as unknown as LiveMappings;
+
+const declaredAnalysis = (): Record<string, unknown> =>
+ structuredClone(FTS_SEARCH_INDEX_ANALYSIS) as unknown as Record<string, unknown>;
+
+const physicalIndex = (version: number, entity: FtsSearchDocumentEntity = ENTITY) =>
+ getFtsSearchPhysicalIndexName(NAMESPACE, entity, version);
+
+/**
+ * Every entity currently declares `schemaVersion: 1`, so version-skew scenarios raise the declared
+ * version at runtime. The fingerprint only hashes `mappings` plus the shared analysis, so the
+ * declared fingerprint is unaffected; the global `afterEach` restores every definition.
+ */
+const setDeclaredVersion = (entity: FtsSearchDocumentEntity, version: number) => {
+ (FTS_SEARCH_INDEX_DEFINITIONS[entity] as unknown as { schemaVersion: number }).schemaVersion =
+ version;
+};
+
+const originalDeclaredVersions = FTS_SEARCH_DOCUMENT_ENTITIES.map(
+ (entity) => [entity, getFtsSearchIndexSchemaVersion(entity)] as const,
+);
+
+const buildMeta = ({
+ fingerprint = DECLARED_FINGERPRINT,
+ reindexRunId = '00000000-0000-4000-8000-000000000001',
+ version,
+}: {
+ fingerprint?: string | null;
+ reindexRunId?: string;
+ version: number;
+}): NonNullable<FtsSearchReindexGenerationDescription['meta']> => ({
+ reindex_run_id: reindexRunId,
+ schema_version: version,
+ ...(fingerprint === null ? {} : { schema_fingerprint: fingerprint }),
+});
+
+const buildGeneration = (
+ index: string,
+ overrides: Partial<FtsSearchReindexGenerationDescription> = {},
+ entity: FtsSearchDocumentEntity = ENTITY,
+): FtsSearchReindexGenerationDescription => ({
+ aliased: true,
+ analysis: declaredAnalysis(),
+ index,
+ isWriteIndex: false,
+ mappings: declaredMappings(entity),
+ meta: null,
+ state: 'open',
+ version: parseGenerationVersion(getFtsSearchIndexAlias(NAMESPACE, entity), index) ?? null,
+ ...overrides,
+});
+
+/** A generation the tool built for `version` and that carries the declared fingerprint. */
+const buildManagedGeneration = (
+ version: number,
+ overrides: Partial<FtsSearchReindexGenerationDescription> = {},
+ entity: FtsSearchDocumentEntity = ENTITY,
+) =>
+ buildGeneration(
+ physicalIndex(version, entity),
+ {
+ meta: buildMeta({ fingerprint: getFtsSearchIndexSchemaFingerprint(entity), version }),
+ ...overrides,
+ },
+ entity,
+ );
+
+const createClient = (generations: FtsSearchReindexGenerationDescription[]) => ({
+ closeIndex: vi.fn<FtsSearchGenerationElasticsearchClient['closeIndex']>().mockResolvedValue(),
+ deleteIndex: vi.fn<FtsSearchGenerationElasticsearchClient['deleteIndex']>().mockResolvedValue(),
+ describeGenerations: vi
+ .fn<FtsSearchGenerationElasticsearchClient['describeGenerations']>()
+ .mockResolvedValue(generations),
+ ensureRetiredIndexProtection: vi
+ .fn<FtsSearchGenerationElasticsearchClient['ensureRetiredIndexProtection']>()
+ .mockResolvedValue(),
+ promoteAlias: vi.fn<FtsSearchGenerationElasticsearchClient['promoteAlias']>().mockResolvedValue(),
+});
+
+/** Checkpoint left behind by an `--apply` run that targeted `<namespace>-<entity>-v<version>`. */
+const createRunState = (
+ version: number,
+ status: FtsSearchReindexEntityStatus,
+): FtsSearchReindexRunState => ({
+ progress: FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => ({
+ completedAt: status === 'completed' ? '2026-09-01T00:00:00.000Z' : null,
+ cursor: null,
+ entity,
+ failedCount: 0,
+ indexedCount: 0,
+ physicalIndex: physicalIndex(version, entity),
+ processedCount: 0,
+ status,
+ })),
+ run: {
+ aliasesCreatedAt: null,
+ backfillHighWaterRevision: null,
+ baseRevision: 10,
+ captureFingerprint: 'capture-v1',
+ createdAt: '2026-09-01T00:00:00.000Z',
+ id: `run-v${version}`,
+ namespace: NAMESPACE,
+ schemaVersion: version,
+ status: status === 'completed' ? 'ready_for_incremental_sync' : 'backfilling',
+ updatedAt: '2026-09-01T00:00:00.000Z',
+ },
+});
+
+const createCheckpointReader = (
+ states: Record<number, FtsSearchReindexRunState | undefined> = {},
+): FtsSearchGenerationCheckpointReader => vi.fn(async (_namespace, version) => states[version]);
+
+beforeEach(() => vi.clearAllMocks());
+afterEach(() => {
+ for (const [entity, version] of originalDeclaredVersions) setDeclaredVersion(entity, version);
+});
+
+describe('classifyMappingChange', () => {
+ it('treats an index built from the declared definition as identical', () => {
+ expect(classifyMappingChange(ENTITY, declaredMappings(), declaredAnalysis())).toBe('identical');
+ });
+
+ it('treats a declared mapping that only adds a top-level field as additive', () => {
+ const live = declaredMappings();
+ delete live.properties.description;
+
+ expect(classifyMappingChange(ENTITY, live, declaredAnalysis())).toBe('additive');
+ });
+
+ it('treats changed analysis settings as breaking', () => {
+ /** An index created before the custom analyzers existed reports none of them. */
+ const legacyAnalysis = { analyzer: {}, filter: {}, tokenizer: {} };
+
+ expect(classifyMappingChange(ENTITY, declaredMappings(), legacyAnalysis)).toBe('breaking');
+ });
+
+ it('treats a changed dynamic setting as breaking', () => {
+ const live = { ...declaredMappings(), dynamic: 'true' };
+
+ expect(classifyMappingChange(ENTITY, live, declaredAnalysis())).toBe('breaking');
+ });
+
+ it('treats a live field the code no longer declares as breaking', () => {
+ const live = declaredMappings();
+ live.properties.legacy_field = { type: 'keyword' };
+
+ expect(classifyMappingChange(ENTITY, live, declaredAnalysis())).toBe('breaking');
+ });
+
+ it('treats a changed analyzer on an existing field as breaking', () => {
+ const live = declaredMappings();
+ live.properties.title.analyzer = 'standard';
+
+ expect(classifyMappingChange(ENTITY, live, declaredAnalysis())).toBe('breaking');
+ });
+});
+
+describe('diffFtsSearchMappings', () => {
+ it('reports a deterministic field-level diff with actionable reasons', () => {
+ const live = declaredMappings();
+ delete live.properties.description;
+ live.properties.legacy_field = { type: 'keyword' };
+ live.properties.title = {
+ analyzer: 'standard',
+ fields: { legacy: { type: 'keyword' } },
+ ignore_above: 512,
+ type: 'keyword',
+ };
+
+ expect(
+ diffFtsSearchMappings({
+ declared: declaredMappings(),
+ declaredAnalysis: declaredAnalysis(),
+ live,
+ liveAnalysis: { analyzer: {} },
+ }),
+ ).toEqual({
+ added: ['description'],
+ analysisChanged: true,
+ changed: [
+ {
+ field: 'title',
+ reasons: ['type', 'analyzer', 'ignore_above', 'multifields'],
+ },
+ ],
+ dynamicChanged: false,
+ removed: ['legacy_field'],
+ });
+ });
+});
+
+describe('describeEntityGeneration', () => {
+ const describeFor = (
+ generations: FtsSearchReindexGenerationDescription[],
+ states: Record<number, FtsSearchReindexRunState | undefined> = {},
+ ) => {
+ const client = createClient(generations);
+ return {
+ client,
+ status: describeEntityGeneration({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader(states),
+ }),
+ };
+ };
+
+ it('reports missing when the alias has no generation', async () => {
+ const { client, status } = describeFor([]);
+
+ await expect(status).resolves.toMatchObject({
+ alias: ALIAS,
+ candidates: [],
+ classification: 'missing',
+ declared: { fingerprint: DECLARED_FINGERPRINT, index: physicalIndex(1), version: 1 },
+ live: null,
+ mappingChange: null,
+ });
+ expect((await status).action).toContain('--fresh-run');
+ expect(client.describeGenerations).toHaveBeenCalledWith(ALIAS);
+ });
+
+ it('reports unmanaged when the write index carries no reindex _meta', async () => {
+ /** A hand-created index: outside the `<alias>-v<n>` scheme and without `_meta`. */
+ const legacyIndex = buildGeneration(ALIAS, { isWriteIndex: true });
+ const { status } = describeFor([legacyIndex]);
+
+ await expect(status).resolves.toMatchObject({
+ candidates: [],
+ classification: 'unmanaged',
+ live: { fingerprint: null, index: ALIAS, reindexRunId: null, version: null },
+ });
+ expect((await status).action).toContain('carries no reindex _meta');
+ });
+
+ it('reports in_sync when the live generation matches the declared fingerprint', async () => {
+ const { status } = describeFor([buildManagedGeneration(1, { isWriteIndex: true })], {
+ 1: createRunState(1, 'completed'),
+ });
+
+ await expect(status).resolves.toMatchObject({
+ action: 'No action',
+ candidates: [],
+ classification: 'in_sync',
+ live: {
+ backfill: 'completed',
+ fingerprint: DECLARED_FINGERPRINT,
+ index: physicalIndex(1),
+ matchesDeclared: true,
+ version: 1,
+ },
+ mappingChange: 'identical',
+ });
+ });
+
+ it('reports drift when the live generation changed without a version bump', async () => {
+ const live = buildGeneration(physicalIndex(1), {
+ isWriteIndex: true,
+ meta: buildMeta({ fingerprint: 'stale-fingerprint', version: 1 }),
+ });
+ const { status } = describeFor([live], { 1: createRunState(1, 'completed') });
+
+ await expect(status).resolves.toMatchObject({
+ classification: 'drift',
+ live: { fingerprint: 'stale-fingerprint', matchesDeclared: false },
+ });
+ expect((await status).action).toContain('changed without a version bump');
+ });
+
+ it('reports upgrade_available and points at the completed newer generation', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const { status } = describeFor(
+ [buildManagedGeneration(1, { isWriteIndex: true }), buildManagedGeneration(2)],
+ { 1: createRunState(1, 'completed'), 2: createRunState(2, 'completed') },
+ );
+
+ await expect(status).resolves.toMatchObject({
+ action: `Run --promote --entity=${ENTITY} once the Outbox is drained`,
+ candidates: [
+ { backfill: 'completed', index: physicalIndex(2), matchesDeclared: true, version: 2 },
+ ],
+ classification: 'upgrade_available',
+ declared: { index: physicalIndex(2), version: 2 },
+ live: { index: physicalIndex(1), matchesDeclared: false, version: 1 },
+ });
+ });
+
+ it('reports rollback_required when the alias serves a newer generation than the code', async () => {
+ const { status } = describeFor([buildManagedGeneration(2, { isWriteIndex: true })], {
+ 2: createRunState(2, 'completed'),
+ });
+
+ await expect(status).resolves.toMatchObject({
+ classification: 'rollback_required',
+ live: { index: physicalIndex(2), version: 2 },
+ });
+ expect((await status).action).toContain('--version=1');
+ });
+
+ it('accepts a legacy _meta without a fingerprint on the declared version', async () => {
+ const live = buildGeneration(physicalIndex(1), {
+ isWriteIndex: true,
+ meta: buildMeta({ fingerprint: null, version: 1 }),
+ });
+ const { status } = describeFor([live], { 1: createRunState(1, 'completed') });
+
+ await expect(status).resolves.toMatchObject({
+ classification: 'in_sync',
+ live: { fingerprint: null, matchesDeclared: true },
+ });
+ });
+
+ it.each([
+ { backfill: 'completed', name: 'a completed run', state: createRunState(1, 'completed') },
+ {
+ backfill: 'backfilling',
+ name: 'a running backfill',
+ state: createRunState(1, 'backfilling'),
+ },
+ { backfill: 'unknown', name: 'a discarded checkpoint', state: undefined },
+ ])('summarizes the backfill of $name as $backfill', async ({ backfill, state }) => {
+ const { status } = describeFor([buildManagedGeneration(1, { isWriteIndex: true })], {
+ 1: state,
+ });
+
+ await expect(status).resolves.toMatchObject({ live: { backfill } });
+ });
+});
+
+describe('promoteGeneration', () => {
+ /** The declared generation is v2 so promotion targets a generation newer than the live one. */
+ beforeEach(() => setDeclaredVersion(ENTITY, 2));
+
+ const promote = ({
+ entity = ENTITY,
+ generations,
+ outboxStats = IDLE_OUTBOX,
+ states = {},
+ version,
+ }: {
+ entity?: FtsSearchDocumentEntity;
+ generations: FtsSearchReindexGenerationDescription[];
+ outboxStats?: FtsSearchSyncOutboxStats;
+ states?: Record<number, FtsSearchReindexRunState | undefined>;
+ version?: number;
+ }) => {
+ const client = createClient(generations);
+ return {
+ client,
+ result: promoteGeneration({
+ client,
+ entity,
+ namespace: NAMESPACE,
+ outboxStats,
+ readCheckpoint: createCheckpointReader(states),
+ version,
+ }),
+ };
+ };
+
+ it('moves the alias to a fully backfilled newer generation', async () => {
+ const { client, result } = promote({
+ generations: [buildManagedGeneration(1, { isWriteIndex: true }), buildManagedGeneration(2)],
+ states: { 1: createRunState(1, 'completed'), 2: createRunState(2, 'completed') },
+ });
+
+ await expect(result).resolves.toEqual({
+ alias: ALIAS,
+ from: [physicalIndex(1)],
+ outcome: 'promoted',
+ to: physicalIndex(2),
+ });
+ expect(client.promoteAlias).toHaveBeenCalledExactlyOnceWith(
+ ALIAS,
+ [physicalIndex(1)],
+ physicalIndex(2),
+ );
+ });
+
+ it('rejects when the target generation does not exist', async () => {
+ const { client, result } = promote({
+ generations: [buildManagedGeneration(1, { isWriteIndex: true })],
+ states: { 1: createRunState(1, 'completed') },
+ });
+
+ await expect(result).rejects.toThrow(`No v2 generation exists for ${ALIAS}`);
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('returns already_live without checkpoint or Outbox gates when a valid target is live', async () => {
+ const { client, result } = promote({
+ generations: [buildManagedGeneration(2, { isWriteIndex: true })],
+ outboxStats: { ...IDLE_OUTBOX, dead: 1, pending: 2 },
+ });
+
+ await expect(result).resolves.toEqual({
+ alias: ALIAS,
+ from: [],
+ outcome: 'already_live',
+ to: physicalIndex(2),
+ });
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('rejects an already-live target whose backfill is still running', async () => {
+ const { client, result } = promote({
+ generations: [buildManagedGeneration(2, { isWriteIndex: true })],
+ states: { 2: createRunState(2, 'backfilling') },
+ });
+
+ await expect(result).rejects.toThrow(`${physicalIndex(2)} backfill is incomplete`);
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('rejects an already-live target whose declared mapping drifted', async () => {
+ const target = buildGeneration(physicalIndex(2), {
+ isWriteIndex: true,
+ meta: buildMeta({ fingerprint: 'stale-fingerprint', version: 2 }),
+ });
+ const { client, result } = promote({ generations: [target] });
+
+ await expect(result).rejects.toThrow(
+ `${physicalIndex(2)} was not built from the declared v2 mapping`,
+ );
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('rejects when the target index is closed', async () => {
+ const { client, result } = promote({
+ generations: [
+ buildManagedGeneration(1, { isWriteIndex: true }),
+ buildManagedGeneration(2, { state: 'closed' }),
+ ],
+ states: { 1: createRunState(1, 'completed'), 2: createRunState(2, 'completed') },
+ });
+
+ await expect(result).rejects.toThrow(`${physicalIndex(2)} is closed (being retired)`);
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('rejects when the target was not built from the declared mapping', async () => {
+ const target = buildGeneration(physicalIndex(2), {
+ meta: buildMeta({ fingerprint: 'stale-fingerprint', version: 2 }),
+ });
+ const { client, result } = promote({
+ generations: [buildManagedGeneration(1, { isWriteIndex: true }), target],
+ states: { 1: createRunState(1, 'completed'), 2: createRunState(2, 'completed') },
+ });
+
+ await expect(result).rejects.toThrow(
+ `${physicalIndex(2)} was not built from the declared v2 mapping`,
+ );
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('rejects when the target backfill is still running', async () => {
+ const { client, result } = promote({
+ generations: [buildManagedGeneration(1, { isWriteIndex: true }), buildManagedGeneration(2)],
+ states: { 1: createRunState(1, 'completed'), 2: createRunState(2, 'backfilling') },
+ });
+
+ await expect(result).rejects.toThrow(`${physicalIndex(2)} backfill is incomplete`);
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('rejects when no checkpoint proves the target finished its backfill', async () => {
+ const { client, result } = promote({
+ generations: [buildManagedGeneration(1, { isWriteIndex: true }), buildManagedGeneration(2)],
+ states: { 1: createRunState(1, 'completed') },
+ });
+
+ await expect(result).rejects.toThrow(
+ `No checkpoint proves ${physicalIndex(2)} finished its backfill`,
+ );
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { name: 'pending rows', stats: { pending: 3 } },
+ { name: 'leased rows', stats: { inFlight: 1 } },
+ { name: 'dead rows', stats: { dead: 2 } },
+ ])('rejects when the target entity Outbox still has $name', async ({ stats }) => {
+ const entity = 'messages';
+ setDeclaredVersion(entity, 2);
+ const { client, result } = promote({
+ entity,
+ generations: [
+ buildManagedGeneration(1, { isWriteIndex: true }, entity),
+ buildManagedGeneration(2, {}, entity),
+ ],
+ outboxStats: createOutboxStats({ [entity]: stats }),
+ states: { 1: createRunState(1, 'completed'), 2: createRunState(2, 'completed') },
+ });
+
+ await expect(result).rejects.toThrow('Outbox is not idle');
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('ignores pending and dead Outbox rows owned by another entity', async () => {
+ const entity = 'messages';
+ setDeclaredVersion(entity, 2);
+ const { client, result } = promote({
+ entity,
+ generations: [
+ buildManagedGeneration(1, { isWriteIndex: true }, entity),
+ buildManagedGeneration(2, {}, entity),
+ ],
+ outboxStats: createOutboxStats({ agents: { dead: 2, pending: 3 } }),
+ states: { 1: createRunState(1, 'completed'), 2: createRunState(2, 'completed') },
+ });
+
+ await expect(result).resolves.toMatchObject({ outcome: 'promoted' });
+ expect(client.promoteAlias).toHaveBeenCalledExactlyOnceWith(
+ getFtsSearchIndexAlias(NAMESPACE, entity),
+ [physicalIndex(1, entity)],
+ physicalIndex(2, entity),
+ );
+ });
+
+ it('rolls back to an older generation that carries reindex _meta', async () => {
+ /** The previous generation predates the declared fingerprint and has no checkpoint left. */
+ const previous = buildGeneration(physicalIndex(1), {
+ meta: buildMeta({ fingerprint: 'legacy-fingerprint', reindexRunId: 'run-v1', version: 1 }),
+ });
+ const { client, result } = promote({
+ generations: [previous, buildManagedGeneration(2, { isWriteIndex: true })],
+ states: { 2: createRunState(2, 'completed') },
+ version: 1,
+ });
+
+ await expect(result).resolves.toEqual({
+ alias: ALIAS,
+ from: [physicalIndex(2)],
+ outcome: 'promoted',
+ to: physicalIndex(1),
+ });
+ expect(client.promoteAlias).toHaveBeenCalledExactlyOnceWith(
+ ALIAS,
+ [physicalIndex(2)],
+ physicalIndex(1),
+ );
+ });
+
+ it('rejects a rollback target without reindex _meta', async () => {
+ const { client, result } = promote({
+ generations: [
+ buildGeneration(physicalIndex(1)),
+ buildManagedGeneration(2, { isWriteIndex: true }),
+ ],
+ states: { 2: createRunState(2, 'completed') },
+ version: 1,
+ });
+
+ await expect(result).rejects.toThrow(
+ `${physicalIndex(1)} has no checkpoint and no reindex _meta`,
+ );
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+
+ it('rejects a rollback target that requires a source field the current projection removed', async () => {
+ const previousMappings = declaredMappings();
+ previousMappings.properties.legacy_title = { type: 'text' };
+ const previous = buildGeneration(physicalIndex(1), {
+ mappings: previousMappings,
+ meta: buildMeta({ fingerprint: 'legacy-fingerprint', reindexRunId: 'run-v1', version: 1 }),
+ });
+ const { client, result } = promote({
+ generations: [previous, buildManagedGeneration(2, { isWriteIndex: true })],
+ states: { 2: createRunState(2, 'completed') },
+ version: 1,
+ });
+
+ await expect(result).rejects.toThrow(
+ `${physicalIndex(1)} requires source fields the current projection cannot preserve: legacy_title (missing)`,
+ );
+ expect(client.promoteAlias).not.toHaveBeenCalled();
+ });
+});
+
+describe('retireGenerations', () => {
+ const retire = ({
+ generations,
+ states = {},
+ }: {
+ generations: FtsSearchReindexGenerationDescription[];
+ states?: Record<number, FtsSearchReindexRunState | undefined>;
+ }) => {
+ const client = createClient(generations);
+ return {
+ client,
+ result: retireGenerations({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader(states),
+ }),
+ };
+ };
+
+ it('rejects when the alias has no live generation', async () => {
+ const { client, result } = retire({ generations: [] });
+
+ await expect(result).rejects.toThrow(`${ALIAS} has no live generation`);
+ expect(client.closeIndex).not.toHaveBeenCalled();
+ expect(client.deleteIndex).not.toHaveBeenCalled();
+ });
+
+ it('rejects when the live generation is not in sync', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const { client, result } = retire({
+ generations: [buildManagedGeneration(1, { isWriteIndex: true }), buildManagedGeneration(2)],
+ states: { 1: createRunState(1, 'completed'), 2: createRunState(2, 'completed') },
+ });
+
+ await expect(result).rejects.toThrow(`${ALIAS} is upgrade_available; retire only after`);
+ expect(client.closeIndex).not.toHaveBeenCalled();
+ expect(client.deleteIndex).not.toHaveBeenCalled();
+ });
+
+ it('closes open generations and leaves already closed ones for explicit purge', async () => {
+ setDeclaredVersion(ENTITY, 3);
+ const { client, result } = retire({
+ generations: [
+ buildManagedGeneration(1, { aliased: false, state: 'open' }),
+ buildManagedGeneration(2, { aliased: false, state: 'closed' }),
+ buildManagedGeneration(3, { isWriteIndex: true }),
+ ],
+ states: { 3: createRunState(3, 'completed') },
+ });
+
+ await expect(result).resolves.toEqual({
+ alreadyClosed: [physicalIndex(2)],
+ alias: ALIAS,
+ closed: [physicalIndex(1)],
+ deleted: [],
+ kept: physicalIndex(3),
+ });
+ expect(client.closeIndex).toHaveBeenCalledExactlyOnceWith(physicalIndex(1));
+ expect(client.deleteIndex).not.toHaveBeenCalled();
+ });
+
+ it.each(['open', 'closed'] as const)(
+ 'preserves an alias-attached generation in the %s state alongside the write index',
+ async (state) => {
+ setDeclaredVersion(ENTITY, 2);
+ const { client, result } = retire({
+ generations: [
+ buildManagedGeneration(1, { aliased: true, state }),
+ buildManagedGeneration(2, { isWriteIndex: true }),
+ ],
+ });
+
+ await expect(result).resolves.toEqual({
+ alreadyClosed: [],
+ alias: ALIAS,
+ closed: [],
+ deleted: [],
+ kept: physicalIndex(2),
+ });
+ expect(client.closeIndex).not.toHaveBeenCalled();
+ expect(client.deleteIndex).not.toHaveBeenCalled();
+ },
+ );
+
+ it('preserves both alias targets when the description marks both as writable', async () => {
+ const { client, result } = retire({
+ generations: [
+ buildManagedGeneration(1, { isWriteIndex: true }),
+ buildManagedGeneration(2, { isWriteIndex: true }),
+ ],
+ });
+
+ await expect(result).resolves.toEqual({
+ alreadyClosed: [],
+ alias: ALIAS,
+ closed: [],
+ deleted: [],
+ kept: physicalIndex(1),
+ });
+ expect(client.closeIndex).not.toHaveBeenCalled();
+ expect(client.deleteIndex).not.toHaveBeenCalled();
+ });
+});
+
+describe('purgeRetiredGenerations', () => {
+ it('deletes only closed, detached, managed generations after installing deletion protection', async () => {
+ setDeclaredVersion(ENTITY, 3);
+ const unmanaged = buildGeneration(physicalIndex(0), { aliased: false, state: 'closed' });
+ const client = createClient([
+ unmanaged,
+ buildManagedGeneration(1, { aliased: false, state: 'open' }),
+ buildManagedGeneration(2, { aliased: false, state: 'closed' }),
+ buildManagedGeneration(3, { isWriteIndex: true }),
+ ]);
+
+ await expect(
+ purgeRetiredGenerations({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader({ 3: createRunState(3, 'completed') }),
+ }),
+ ).resolves.toEqual({ alias: ALIAS, deleted: [physicalIndex(2)], kept: physicalIndex(3) });
+ expect(client.ensureRetiredIndexProtection).toHaveBeenCalledExactlyOnceWith(physicalIndex(2));
+ expect(client.deleteIndex).toHaveBeenCalledExactlyOnceWith(physicalIndex(2));
+ });
+
+ it('rejects deletion while the retired generation checkpoint is still backfilling', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const client = createClient([
+ buildManagedGeneration(1, { aliased: false, state: 'closed' }),
+ buildManagedGeneration(2, { isWriteIndex: true }),
+ ]);
+
+ await expect(
+ purgeRetiredGenerations({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader({
+ 1: createRunState(1, 'backfilling'),
+ 2: createRunState(2, 'completed'),
+ }),
+ }),
+ ).rejects.toThrow(`${physicalIndex(1)} backfill is still running`);
+ expect(client.ensureRetiredIndexProtection).not.toHaveBeenCalled();
+ expect(client.deleteIndex).not.toHaveBeenCalled();
+ });
+});
+
+describe('planRetiredGenerations', () => {
+ it('previews close and purge work with explicit blockers and no side effects', async () => {
+ setDeclaredVersion(ENTITY, 3);
+ const unmanaged = buildGeneration(physicalIndex(0), { aliased: false, state: 'closed' });
+ const client = createClient([
+ unmanaged,
+ buildManagedGeneration(1, { aliased: false, state: 'open' }),
+ buildManagedGeneration(2, { aliased: false, state: 'closed' }),
+ buildManagedGeneration(3, { isWriteIndex: true }),
+ buildManagedGeneration(4, { aliased: false, state: 'open' }),
+ ]);
+ const status = await describeEntityGeneration({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader({ 3: createRunState(3, 'completed') }),
+ });
+
+ expect(planRetiredGenerations(status)).toEqual({
+ alreadyClosed: [physicalIndex(2)],
+ blockedBy: [
+ `${physicalIndex(0)} has no known managed reindex identity`,
+ `${physicalIndex(4)} is not older than the live generation`,
+ ],
+ close: [physicalIndex(1)],
+ purgeCandidates: [physicalIndex(2)],
+ });
+ expect(client.closeIndex).not.toHaveBeenCalled();
+ expect(client.deleteIndex).not.toHaveBeenCalled();
+ });
+
+ it('does not close an older generation while its checkpoint is backfilling', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const client = createClient([
+ buildManagedGeneration(1, { aliased: false, state: 'open' }),
+ buildManagedGeneration(2, { isWriteIndex: true }),
+ ]);
+ const status = await describeEntityGeneration({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader({
+ 1: createRunState(1, 'backfilling'),
+ 2: createRunState(2, 'completed'),
+ }),
+ });
+
+ expect(planRetiredGenerations(status)).toMatchObject({
+ blockedBy: [`${physicalIndex(1)} backfill is still running`],
+ close: [],
+ });
+ });
+});
+
+describe('resolveInPlaceTarget', () => {
+ it('uses the live index for a normal additive version upgrade', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const mappings = declaredMappings();
+ delete mappings.properties.title;
+ const client = createClient([buildManagedGeneration(1, { isWriteIndex: true, mappings })]);
+ const status = await describeEntityGeneration({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader(),
+ });
+
+ expect(status).toMatchObject({
+ classification: 'upgrade_available',
+ mappingChange: 'additive',
+ });
+ expect(resolveInPlaceTarget(status)).toBe(physicalIndex(1));
+ });
+
+ it('rejects a normal breaking version upgrade', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const mappings = declaredMappings();
+ mappings.properties.title.type = 'keyword';
+ const client = createClient([buildManagedGeneration(1, { isWriteIndex: true, mappings })]);
+ const status = await describeEntityGeneration({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader(),
+ });
+
+ expect(status).toMatchObject({
+ classification: 'upgrade_available',
+ mappingChange: 'breaking',
+ });
+ expect(() => resolveInPlaceTarget(status)).toThrow('cannot be upgraded in place');
+ });
+
+ it('resumes the crash window after restamping and before checkpoint creation', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const client = createClient([
+ buildManagedGeneration(2, { index: physicalIndex(1), isWriteIndex: true }),
+ ]);
+ const status = await describeEntityGeneration({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader(),
+ });
+
+ expect(resolveInPlaceTarget(status)).toBe(physicalIndex(1));
+ });
+
+ it('rejects a same-version live index with real physical mapping drift', async () => {
+ setDeclaredVersion(ENTITY, 2);
+ const mappings = declaredMappings();
+ mappings.properties.title.analyzer = 'standard';
+ const client = createClient([
+ buildManagedGeneration(2, {
+ index: physicalIndex(1),
+ isWriteIndex: true,
+ mappings,
+ }),
+ ]);
+ const status = await describeEntityGeneration({
+ client,
+ entity: ENTITY,
+ namespace: NAMESPACE,
+ readCheckpoint: createCheckpointReader(),
+ });
+
+ expect(() => resolveInPlaceTarget(status)).toThrow('physical mapping differs');
+ });
+});
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/migrationLock.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/migrationLock.test.ts
new file mode 100644
index 00000000000..1249d9507d1
--- /dev/null
+++ b/scripts/elasticsearchReindex/runtime/__tests__/migrationLock.test.ts
@@ -0,0 +1,385 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { FtsSearchMigrationLockClient, FtsSearchMigrationLockError } from '../migrationLock';
+
+interface StoredDocument {
+ primaryTerm: number;
+ seqNo: number;
+ source: { acquiredAt: string; command: string; owner: string };
+}
+
+interface StoredIndex {
+ document?: StoredDocument;
+ mappings: Record<string, unknown>;
+}
+
+const jsonResponse = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), {
+ headers: { 'Content-Type': 'application/json' },
+ status,
+ });
+
+class StatefulElasticsearch {
+ readonly indexes = new Map<string, StoredIndex>();
+ readonly requests: Array<{ body?: string; method: string; pathname: string }> = [];
+
+ beforeNextDelete?: () => void;
+ createAcknowledged = true;
+ lockCreateError?: Error;
+ lockDeleteBody?: unknown;
+ lockReadBody?: unknown;
+ lockReadStatus?: number;
+
+ fetch = async (input: string | URL | Request, init: RequestInit = {}) => {
+ const url = new URL(input instanceof Request ? input.url : input.toString());
+ const method = init.method ?? 'GET';
+ this.requests.push({
+ body: typeof init.body === 'string' ? init.body : undefined,
+ method,
+ pathname: `${url.pathname}${url.search}`,
+ });
+ const [rawIndex, operation, rawDocumentId] = url.pathname.split('/').filter(Boolean);
+ const indexName = rawIndex ? decodeURIComponent(rawIndex) : '';
+ const index = this.indexes.get(indexName);
+
+ if (method === 'PUT' && operation === undefined) {
+ if (index) return jsonResponse({ error: { type: 'resource_already_exists_exception' } }, 400);
+ const body = JSON.parse(String(init.body)) as { mappings: Record<string, unknown> };
+ this.indexes.set(indexName, { mappings: body.mappings });
+ return jsonResponse({ acknowledged: this.createAcknowledged, index: indexName });
+ }
+
+ if (method === 'GET' && operation === '_mapping') {
+ if (!index) return jsonResponse({ found: false }, 404);
+ return jsonResponse({ [indexName]: { mappings: index.mappings } });
+ }
+
+ if (method === 'PUT' && operation === '_create' && rawDocumentId === 'migration-lock') {
+ if (this.lockCreateError) throw this.lockCreateError;
+ if (!index) return jsonResponse({ found: false }, 404);
+ if (index.document)
+ return jsonResponse({ error: { type: 'version_conflict_engine_exception' } }, 409);
+ index.document = {
+ primaryTerm: 1,
+ seqNo: 0,
+ source: JSON.parse(String(init.body)),
+ };
+ return jsonResponse({ _primary_term: 1, _seq_no: 0, result: 'created' }, 201);
+ }
+
+ if (method === 'GET' && operation === '_doc' && rawDocumentId === 'migration-lock') {
+ if (this.lockReadStatus) return jsonResponse(this.lockReadBody ?? {}, this.lockReadStatus);
+ if (this.lockReadBody !== undefined) return jsonResponse(this.lockReadBody);
+ if (!index?.document) return jsonResponse({ found: false }, 404);
+ return jsonResponse({
+ _primary_term: index.document.primaryTerm,
+ _seq_no: index.document.seqNo,
+ _source: index.document.source,
+ found: true,
+ });
+ }
+
+ if (method === 'DELETE' && operation === '_doc' && rawDocumentId === 'migration-lock') {
+ this.beforeNextDelete?.();
+ this.beforeNextDelete = undefined;
+ const current = this.indexes.get(indexName)?.document;
+ if (!current) return jsonResponse({ result: 'not_found' }, 404);
+ if (
+ Number(url.searchParams.get('if_seq_no')) !== current.seqNo ||
+ Number(url.searchParams.get('if_primary_term')) !== current.primaryTerm
+ ) {
+ return jsonResponse({ error: { type: 'version_conflict_engine_exception' } }, 409);
+ }
+ delete this.indexes.get(indexName)?.document;
+ return jsonResponse(this.lockDeleteBody ?? { result: 'deleted' });
+ }
+
+ return jsonResponse({ error: { type: 'unhandled_request' } }, 500);
+ };
+}
+
+const createClient = (namespace: string) =>
+ new FtsSearchMigrationLockClient({
+ allowInsecureHttp: true,
+ namespace,
+ url: 'http://localhost:9200',
+ });
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('FtsSearchMigrationLockClient', () => {
+ it('allows only one owner across clients that use the same namespace', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const first = createClient('shared');
+ const second = createClient('shared');
+
+ const results = await Promise.allSettled([
+ first.acquire('--apply --checkpoint-dir=/first'),
+ second.acquire('--apply --checkpoint-dir=/second'),
+ ]);
+
+ expect(results.filter(({ status }) => status === 'fulfilled')).toHaveLength(1);
+ const rejected = results.find(({ status }) => status === 'rejected');
+ expect(rejected).toMatchObject({
+ reason: expect.objectContaining({
+ message: expect.stringContaining('already locked by owner'),
+ status: 409,
+ }),
+ });
+ });
+
+ it('isolates locks by namespace', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+
+ const [first, second] = await Promise.all([
+ createClient('preview-a').acquire('--apply'),
+ createClient('preview-b').acquire('--apply'),
+ ]);
+
+ expect(first.owner).not.toBe(second.owner);
+ expect(elasticsearch.indexes.has('preview-a-fts-search-control')).toBe(true);
+ expect(elasticsearch.indexes.has('preview-b-fts-search-control')).toBe(true);
+ });
+
+ it('creates a strict, owned one-shard control index and releases after success', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const client = createClient('test');
+
+ const result = await client.withLock('--status', async (handle) => {
+ await client.assertOwner(handle);
+ return 'done';
+ });
+
+ expect(result).toBe('done');
+ expect(await client.read()).toBeNull();
+ const createRequest = elasticsearch.requests.find(
+ ({ method, pathname }) => method === 'PUT' && pathname === '/test-fts-search-control',
+ );
+ expect(JSON.parse(createRequest?.body ?? '{}')).toEqual({
+ mappings: {
+ _meta: { lobehub_fts_search_control: true, schema_version: 1 },
+ dynamic: 'strict',
+ properties: {
+ acquiredAt: { type: 'date' },
+ command: { type: 'keyword' },
+ owner: { type: 'keyword' },
+ },
+ },
+ settings: { number_of_shards: 1 },
+ });
+ });
+
+ it('retains the lock when the callback fails and supports explicit recovery', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const client = createClient('test');
+ const failure = new Error('request timed out');
+
+ const error = await client
+ .withLock('--promote', async () => {
+ throw failure;
+ })
+ .catch((cause: unknown) => cause);
+
+ expect(error).toBeInstanceOf(FtsSearchMigrationLockError);
+ if (!(error instanceof FtsSearchMigrationLockError)) throw error;
+ expect(error).toMatchObject({ cause: failure, recoveryOwner: expect.any(String) });
+ expect(error.message).toContain('non-expiring lock was retained');
+ const current = await client.read();
+ expect(current?.owner).toBe(error.recoveryOwner);
+ if (!error.recoveryOwner) throw new Error('Expected a recovery owner');
+ expect(await client.release(error.recoveryOwner)).toBe('released');
+ });
+
+ it('does not take over a residual lock', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const first = createClient('test');
+ const residual = await first.acquire('--apply');
+
+ await expect(createClient('test').acquire('--retire')).rejects.toThrow(
+ `already locked by owner ${residual.owner}`,
+ );
+ expect((await first.read())?.owner).toBe(residual.owner);
+ });
+
+ it('rejects a wrong owner and uses sequence-number CAS for release', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const client = createClient('test');
+ const handle = await client.acquire('--apply');
+
+ await expect(client.release('wrong-owner')).rejects.toThrow('refusing release for owner');
+
+ elasticsearch.beforeNextDelete = () => {
+ const document = elasticsearch.indexes.get(client.controlIndex)?.document;
+ if (document) document.seqNo += 1;
+ };
+ await expect(client.release(handle.owner)).rejects.toMatchObject({ status: 409 });
+ expect((await client.read())?.owner).toBe(handle.owner);
+ });
+
+ it('detects a stale ownership handle', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const client = createClient('test');
+ const handle = await client.acquire('--apply');
+ const document = elasticsearch.indexes.get(client.controlIndex)?.document;
+ if (document) document.seqNo += 1;
+
+ await expect(client.assertOwner(handle)).rejects.toThrow('ownership was lost');
+ });
+
+ it('returns already_released when the lock is absent', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+
+ await expect(createClient('test').release('known-owner')).resolves.toBe('already_released');
+ });
+
+ it('fails closed for a malformed successful release response', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const client = createClient('test');
+ const handle = await client.acquire('--apply');
+ elasticsearch.lockDeleteBody = { result: 'noop' };
+
+ await expect(client.release(handle.owner)).rejects.toThrow('invalid shape');
+ });
+
+ it('reads missing status without creating anything', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const client = createClient('test');
+
+ await expect(client.read()).resolves.toBeNull();
+ expect(elasticsearch.requests).toEqual([
+ { method: 'GET', pathname: '/test-fts-search-control/_doc/migration-lock' },
+ ]);
+ expect(elasticsearch.indexes).toHaveLength(0);
+ });
+
+ it.each(['', '_all', '-preview', '+preview', 'Preview', 'preview/current', 'preview,*'])(
+ 'rejects an unsafe namespace %j without making a request',
+ (namespace) => {
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+
+ expect(() => createClient(namespace)).toThrow('one legal lowercase Elasticsearch index name');
+ expect(fetch).not.toHaveBeenCalled();
+ },
+ );
+
+ it('rejects control index names longer than 255 UTF-8 bytes without making a request', () => {
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+
+ expect(() => createClient('界'.repeat(80))).toThrow(
+ 'one legal lowercase Elasticsearch index name',
+ );
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('fails closed for forbidden and malformed status responses', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+ const client = createClient('test');
+
+ elasticsearch.lockReadStatus = 403;
+ await expect(client.read()).rejects.toMatchObject({ status: 403 });
+
+ elasticsearch.lockReadStatus = undefined;
+ elasticsearch.lockReadBody = { found: false };
+ await expect(client.read()).rejects.toThrow('invalid shape');
+ });
+
+ it('refuses an existing foreign or incompatible control index', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ elasticsearch.indexes.set('test-fts-search-control', {
+ mappings: { dynamic: 'strict', properties: { owner: { type: 'keyword' } } },
+ });
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+
+ await expect(createClient('test').acquire('--apply')).rejects.toThrow(
+ 'refusing to overwrite it',
+ );
+ expect(elasticsearch.indexes.get('test-fts-search-control')?.document).toBeUndefined();
+ });
+
+ it('refuses to release a matching lock document from a foreign control index', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ elasticsearch.indexes.set('test-fts-search-control', {
+ document: {
+ primaryTerm: 1,
+ seqNo: 0,
+ source: {
+ acquiredAt: '2026-09-08T00:00:00.000Z',
+ command: '--apply',
+ owner: 'matching-owner',
+ },
+ },
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ acquiredAt: { type: 'date' },
+ command: { type: 'keyword' },
+ owner: { type: 'keyword' },
+ },
+ },
+ });
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+
+ await expect(createClient('test').release('matching-owner')).rejects.toThrow(
+ 'refusing to overwrite it',
+ );
+ expect(elasticsearch.indexes.get('test-fts-search-control')?.document).toBeDefined();
+ expect(elasticsearch.requests.some(({ method }) => method === 'DELETE')).toBe(false);
+ });
+
+ it('does not accept an unacknowledged control index creation', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ elasticsearch.createAcknowledged = false;
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+
+ await expect(createClient('test').acquire('--apply')).rejects.toThrow('not acknowledged');
+ });
+
+ it('reports the recovery owner when acquisition has an unknown outcome', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ elasticsearch.lockCreateError = new Error('socket closed');
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+
+ const error = await createClient('test')
+ .acquire('--apply')
+ .catch((cause: unknown) => cause);
+
+ expect(error).toMatchObject({ recoveryOwner: expect.any(String) });
+ if (!(error instanceof FtsSearchMigrationLockError)) throw error;
+ expect(error.message).toContain(`recover with owner ${error.recoveryOwner}`);
+ });
+
+ it('does not expose API keys or Elasticsearch error bodies', async () => {
+ const secret = 'secret-api-key';
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => jsonResponse({ error: `rejected ${secret}` }, 403)),
+ );
+ const client = new FtsSearchMigrationLockClient({
+ apiKey: secret,
+ namespace: 'test',
+ url: 'https://search.example.com',
+ });
+
+ const error = await client.read().catch((cause: unknown) => cause);
+
+ if (!(error instanceof FtsSearchMigrationLockError)) throw error;
+ expect(error.message).toBe('Elasticsearch migration lock status failed (403)');
+ expect(error.message).not.toContain(secret);
+ });
+});
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
index 2ff650ab273..298d88ccbeb 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
@@ -1,15 +1,49 @@
// @vitest-environment node
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
import type { FtsSearchDocumentEntity } from '@lobechat/types';
import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as FtsSearchDocumentRepository from '../../../../packages/database/src/repositories/ftsSearchDocument';
+import {
+ buildFtsSearchIndexMeta,
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_INDEX_DEFINITIONS,
+ getFtsSearchIndexSchemaFingerprint,
+ getFtsSearchPhysicalIndexName,
+} from '../../../../packages/database/src/repositories/ftsSearchDocument';
import type { FtsSearchReindexFailure, FtsSearchReindexRunState } from '../checkpointRepository';
+import { FtsSearchReindexFileRepository } from '../checkpointRepository';
+import type { FtsSearchReindexGenerationDescription } from '../elasticsearchClient';
import type {
FtsSearchReindexElasticsearchClient,
FtsSearchReindexProgressEvent,
FtsSearchReindexStateRepository,
} from '../reindexService';
-import { FtsSearchReindexService } from '../reindexService';
+import { FtsSearchReindexEntityError, FtsSearchReindexService } from '../reindexService';
+
+/**
+ * Every real search entity currently declares schema version 1, so overriding one entity's declared
+ * version is the only way to exercise a checkpoint generation that an entity has already left.
+ */
+const { declaredSchemaVersions } = vi.hoisted(() => ({
+ declaredSchemaVersions: new Map<string, number>(),
+}));
+
+vi.mock(
+ '../../../../packages/database/src/repositories/ftsSearchDocument',
+ async (importActual) => {
+ const actual = await importActual<typeof FtsSearchDocumentRepository>();
+ return {
+ ...actual,
+ getFtsSearchIndexSchemaVersion: (entity: FtsSearchDocumentEntity) =>
+ declaredSchemaVersions.get(entity) ?? actual.getFtsSearchIndexSchemaVersion(entity),
+ };
+ },
+);
const createState = (): FtsSearchReindexRunState => ({
progress: FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => ({
@@ -18,7 +52,7 @@ const createState = (): FtsSearchReindexRunState => ({
entity,
failedCount: 0,
indexedCount: 0,
- physicalIndex: `test-${entity}-v1`,
+ physicalIndex: getFtsSearchPhysicalIndexName('test', entity, 1),
processedCount: 0,
status: 'pending',
})),
@@ -36,6 +70,60 @@ const createState = (): FtsSearchReindexRunState => ({
},
});
+type FtsSearchReindexLiveMappings = NonNullable<FtsSearchReindexGenerationDescription['mappings']>;
+
+/**
+ * Mapping the live `topics` index reports back: the declared field set minus `description`, so the
+ * declared generation only adds one top-level field and stays applicable in place.
+ */
+const upgradableTopicsMappings = (): FtsSearchReindexLiveMappings => {
+ const mappings = structuredClone(
+ FTS_SEARCH_INDEX_DEFINITIONS.topics.mappings,
+ ) as unknown as FtsSearchReindexLiveMappings;
+ delete mappings.properties.description;
+ return mappings;
+};
+
+/** Generation description Elasticsearch reports for an open index the alias serves for writes. */
+const createGeneration = (
+ index: string,
+ overrides: Partial<FtsSearchReindexGenerationDescription> = {},
+): FtsSearchReindexGenerationDescription => ({
+ aliased: true,
+ analysis: structuredClone(FTS_SEARCH_INDEX_ANALYSIS) as unknown as Record<string, unknown>,
+ index,
+ isWriteIndex: true,
+ mappings: null,
+ meta: null,
+ state: 'open',
+ version: 1,
+ ...overrides,
+});
+
+const createLiveTopicsGeneration = (
+ overrides: Partial<FtsSearchReindexGenerationDescription> = {},
+) =>
+ createGeneration('test-topics-v1', {
+ mappings: upgradableTopicsMappings(),
+ meta: buildFtsSearchIndexMeta('topics', 'run-0'),
+ ...overrides,
+ });
+
+/**
+ * Turns the state into a v2 generation that upgrades `topics` in place: every other entity targets
+ * its rebuilt v2 index while `topics` stays pinned to the v1 index the alias already serves.
+ */
+const pinTopicsInPlace = (state: FtsSearchReindexRunState) => {
+ declaredSchemaVersions.set('topics', 2);
+ state.run.schemaVersion = 2;
+ for (const progress of state.progress) {
+ progress.physicalIndex = getFtsSearchPhysicalIndexName('test', progress.entity, 2);
+ }
+ const topics = state.progress.find(({ entity }) => entity === 'topics')!;
+ topics.physicalIndex = getFtsSearchPhysicalIndexName('test', 'topics', 1);
+ return topics;
+};
+
const createFailure = (
entity: FtsSearchDocumentEntity,
documentId: string,
@@ -59,8 +147,10 @@ const createDependencies = () => {
const client: FtsSearchReindexElasticsearchClient = {
bulk: vi.fn().mockResolvedValue([]),
count: vi.fn().mockResolvedValue(0),
- ensureAlias: vi.fn().mockResolvedValue(undefined),
+ describeGenerations: vi.fn().mockResolvedValue([]),
+ ensureAlias: vi.fn().mockResolvedValue('created'),
ensureIndex: vi.fn().mockResolvedValue(undefined),
+ putMapping: vi.fn().mockResolvedValue(undefined),
refresh: vi.fn().mockResolvedValue(undefined),
};
const repository: FtsSearchReindexStateRepository = {
@@ -92,12 +182,37 @@ const createDependencies = () => {
}),
resolveFailures: vi.fn().mockResolvedValue(0),
};
- return { builder, client, repository, state };
+ return { builder, client, failures, repository, state };
};
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ declaredSchemaVersions.clear();
+ vi.clearAllMocks();
+});
describe('FtsSearchReindexService', () => {
+ it('omits source fields retained for older generations from current strict-mapping bulk writes', async () => {
+ const { builder, client, repository } = createDependencies();
+ const source = { id: 'message-1', content: 'current text', legacy_content: 'rollback text' };
+ builder.buildBatch.mockImplementation(async (entity, { afterId }) =>
+ entity === 'messages' && !afterId ? [{ entity, id: source.id, source }] : [],
+ );
+ vi.mocked(client.bulk).mockResolvedValue([{ status: 201 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index === 'test-messages-v1' ? 1 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await service.run('test', 1);
+
+ const body = vi.mocked(client.bulk).mock.calls[0][0];
+ expect(JSON.parse(body.trim().split('\n')[1])).toEqual({
+ id: source.id,
+ content: source.content,
+ });
+ expect(source.legacy_content).toBe('rollback text');
+ });
+
it('uses defaults when optional batch limits are undefined', async () => {
const { builder, client, repository } = createDependencies();
const service = new FtsSearchReindexService(builder, repository, client, {
@@ -124,7 +239,7 @@ describe('FtsSearchReindexService', () => {
});
vi.mocked(client.bulk).mockResolvedValue([{ status: 201 }]);
vi.mocked(client.count).mockImplementation(async (index) =>
- index.includes('-documents-') ? 2 : 0,
+ index === getFtsSearchPhysicalIndexName('test', 'documents', 1) ? 2 : 0,
);
const service = new FtsSearchReindexService(builder, repository, client, {
batchSize: 2,
@@ -211,6 +326,7 @@ describe('FtsSearchReindexService', () => {
});
vi.mocked(client.ensureAlias).mockImplementation(async () => {
lifecycle.push('create-alias');
+ return 'created';
});
const service = new FtsSearchReindexService(builder, repository, client, {
onProgress: (event) => {
@@ -228,7 +344,11 @@ describe('FtsSearchReindexService', () => {
'test-agents-v1',
expect.objectContaining({
mappings: expect.objectContaining({
- _meta: { reindex_run_id: 'run-1', schema_version: 1 },
+ _meta: {
+ reindex_run_id: 'run-1',
+ schema_fingerprint: getFtsSearchIndexSchemaFingerprint('agents'),
+ schema_version: 1,
+ },
}),
}),
{ createIfMissing: true },
@@ -360,7 +480,7 @@ describe('FtsSearchReindexService', () => {
return Array.from({ length: 4 }, (_, index) => ({
entity: 'agents' as const,
id: `agent-${index}`,
- source: { content: 'x'.repeat(100), id: `agent-${index}` },
+ source: { id: `agent-${index}`, system_role: 'x'.repeat(100) },
}));
});
let active = 0;
@@ -436,7 +556,7 @@ describe('FtsSearchReindexService', () => {
entity: 'agents' as const,
id: `agent-${index}`,
source: {
- get content() {
+ get system_role() {
if (index === 2) {
thirdDocumentEncodedAfterRequestStarted = firstRequestStarted;
}
@@ -557,7 +677,7 @@ describe('FtsSearchReindexService', () => {
const documents = Array.from({ length: 2 }, (_, index) => ({
entity: 'agents' as const,
id: `agent-${index}`,
- source: { content: 'x'.repeat(100), id: `agent-${index}` },
+ source: { id: `agent-${index}`, system_role: 'x'.repeat(100) },
}));
builder.buildBatch.mockImplementation(async (entity, { afterId }) =>
entity === 'agents' && !afterId ? documents : [],
@@ -759,4 +879,371 @@ describe('FtsSearchReindexService', () => {
);
expect(persistedErrors.join('\n')).not.toContain('private source text');
});
+
+ it('reports the entities whose alias still serves an older generation', async () => {
+ const { builder, client, repository } = createDependencies();
+ const events: FtsSearchReindexProgressEvent[] = [];
+ const keptAliases = new Set(['test-agents', 'test-topics']);
+ vi.mocked(client.ensureAlias).mockImplementation(async (alias) =>
+ keptAliases.has(alias) ? 'kept_other_generation' : 'created',
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ onProgress: (event) => {
+ events.push(event);
+ },
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(events).toContainEqual({ entities: ['agents', 'topics'], type: 'promotion_pending' });
+ /** The remaining 12 aliases were created for this generation, so the cutover still happened. */
+ expect(events).toContainEqual({ type: 'aliases_created' });
+ expect(repository.markReadyForIncrementalSync).toHaveBeenCalledOnce();
+ });
+
+ it('does not announce a cutover when every alias still serves an older generation', async () => {
+ const { builder, client, repository } = createDependencies();
+ const events: FtsSearchReindexProgressEvent[] = [];
+ vi.mocked(client.ensureAlias).mockResolvedValue('kept_other_generation');
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ onProgress: (event) => {
+ events.push(event);
+ },
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(events).toContainEqual({
+ entities: [...FTS_SEARCH_DOCUMENT_ENTITIES],
+ type: 'promotion_pending',
+ });
+ expect(events).not.toContainEqual({ type: 'aliases_created' });
+ });
+
+ it('emits no alias event when every alias already points at this generation', async () => {
+ const { builder, client, repository } = createDependencies();
+ const events: FtsSearchReindexProgressEvent[] = [];
+ vi.mocked(client.ensureAlias).mockResolvedValue('existing');
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ onProgress: (event) => {
+ events.push(event);
+ },
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(client.ensureAlias).toHaveBeenCalledTimes(14);
+ expect(repository.markReadyForIncrementalSync).toHaveBeenCalledOnce();
+ expect(
+ events.filter(({ type }) => type === 'aliases_created' || type === 'promotion_pending'),
+ ).toEqual([]);
+ });
+
+ it('scopes the generation to the run entities and backfills only the selected ones', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const runEntities: FtsSearchDocumentEntity[] = ['topics', 'agents'];
+ /** The checkpoint owns the generation, so it only hands back the requested entities. */
+ state.progress = state.progress.filter(({ entity }) => runEntities.includes(entity));
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ });
+
+ await expect(service.run('test', 1, runEntities)).resolves.toMatchObject({
+ status: 'backfilling',
+ });
+
+ expect(repository.createOrResume).toHaveBeenCalledWith('test', 1, runEntities);
+ expect(client.ensureIndex).toHaveBeenCalledTimes(2);
+ expect(builder.buildBatch).toHaveBeenCalledOnce();
+ expect(builder.buildBatch).toHaveBeenCalledWith('topics', { afterId: undefined, limit: 500 });
+ expect(state.progress).toEqual([
+ expect.objectContaining({ entity: 'agents', status: 'pending' }),
+ expect.objectContaining({ entity: 'topics', status: 'completed' }),
+ ]);
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ });
+
+ it('skips an entity whose declared version moved to a newer generation', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ declaredSchemaVersions.set('topics', 2);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['agents'],
+ });
+
+ await service.prepareIndices(state);
+
+ expect(client.ensureIndex).toHaveBeenCalledTimes(13);
+ expect(client.ensureIndex).not.toHaveBeenCalledWith(
+ 'test-topics-v1',
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('finishes the current generation without cutting over a superseded checkpoint member', async () => {
+ const { builder, client, failures, repository, state } = createDependencies();
+ declaredSchemaVersions.set('topics', 2);
+ state.progress = state.progress.filter(
+ ({ entity }) => entity === 'topics' || entity === 'agents',
+ );
+ failures.set('topics', [{ documentId: 'superseded-topic' }]);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['agents'],
+ });
+
+ await expect(service.run('test', 1, ['agents'])).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(state.progress.find(({ entity }) => entity === 'topics')).toMatchObject({
+ status: 'pending',
+ });
+ expect(client.ensureAlias).toHaveBeenCalledOnce();
+ expect(client.ensureAlias).toHaveBeenCalledWith('test-agents', 'test-agents-v1');
+ expect(client.ensureAlias).not.toHaveBeenCalledWith('test-topics', expect.anything());
+ expect(repository.markReadyForIncrementalSync).toHaveBeenCalledWith('run-1', ['agents']);
+ });
+
+ it('backfills a pending checkpoint member when it rejoins a ready generation', async () => {
+ const stateDirectory = await mkdtemp(path.join(tmpdir(), 'search-reindex-rejoin-test-'));
+ const repository = new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: vi.fn(async () => 'capture-v1'),
+ readHighWaterRevision: vi.fn(async () => 12),
+ reserveRevisionWithWriteFence: vi.fn(async () => 11),
+ stateDirectory,
+ });
+ try {
+ const initial = await repository.createOrResume('test', 1, ['agents', 'topics']);
+ await repository.completeEntity(initial.run.id, 'agents');
+ await repository.markReadyForIncrementalSync(initial.run.id, ['agents']);
+ const { builder, client } = createDependencies();
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ });
+
+ await expect(service.run('test', 1, ['agents', 'topics'])).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(builder.buildBatch).toHaveBeenCalledOnce();
+ expect(builder.buildBatch).toHaveBeenCalledWith('topics', {
+ afterId: undefined,
+ limit: 500,
+ });
+ expect(client.ensureAlias).toHaveBeenCalledTimes(2);
+ await expect(repository.getRun(initial.run.id)).resolves.toMatchObject({
+ progress: expect.arrayContaining([
+ expect.objectContaining({ entity: 'agents', status: 'completed' }),
+ expect.objectContaining({ entity: 'topics', status: 'completed' }),
+ ]),
+ run: { status: 'ready_for_incremental_sync' },
+ });
+ } finally {
+ await rm(stateDirectory, { force: true, recursive: true });
+ }
+ });
+
+ it('refuses to reuse an old generation for an entity that declared a new version', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ declaredSchemaVersions.set('topics', 2);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ entityConcurrency: 1,
+ });
+
+ await expect(service.prepareIndices(state)).rejects.toMatchObject({
+ entity: 'topics',
+ message: expect.stringContaining(
+ 'Checkpoint targets schema version 1 but the code declares v2 for topics',
+ ),
+ });
+ expect(client.ensureIndex).not.toHaveBeenCalledWith(
+ 'test-topics-v1',
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('adds the new fields to the live index instead of building the next generation', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ pinTopicsInPlace(state);
+ vi.mocked(client.describeGenerations).mockResolvedValue([createLiveTopicsGeneration()]);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ entityConcurrency: 1,
+ });
+
+ await service.prepareIndices(state);
+
+ expect(client.describeGenerations).toHaveBeenCalledWith('test-topics');
+ expect(client.putMapping).toHaveBeenCalledOnce();
+ /**
+ * The upgrade restamps `_meta` from the declared definition, so the live index records the run
+ * that widened it and the fingerprint of the mapping it now implements.
+ */
+ expect(client.putMapping).toHaveBeenCalledWith('test-topics-v1', {
+ _meta: buildFtsSearchIndexMeta('topics', 'run-1'),
+ properties: FTS_SEARCH_INDEX_DEFINITIONS.topics.mappings.properties,
+ });
+ expect(buildFtsSearchIndexMeta('topics', 'run-1')).toMatchObject({
+ reindex_run_id: 'run-1',
+ schema_fingerprint: getFtsSearchIndexSchemaFingerprint('topics'),
+ });
+ /** The pinned index already exists, so preparation must never recreate it. */
+ expect(client.ensureIndex).toHaveBeenCalledOnce();
+ expect(client.ensureIndex).toHaveBeenCalledWith('test-topics-v1', expect.any(Object), {
+ createIfMissing: false,
+ });
+ });
+
+ it('refuses an in-place upgrade when the live mapping change is not additive', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ pinTopicsInPlace(state);
+ const mappings = upgradableTopicsMappings();
+ /** Elasticsearch cannot re-analyze an existing field, so a changed analyzer needs a rebuild. */
+ mappings.properties.title = { analyzer: 'lobehub_icu', type: 'text' };
+ vi.mocked(client.describeGenerations).mockResolvedValue([
+ createLiveTopicsGeneration({ mappings }),
+ ]);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ entityConcurrency: 1,
+ });
+
+ const error = await service.run('test', 2, ['topics']).catch((cause) => cause);
+
+ expect(error).toBeInstanceOf(FtsSearchReindexEntityError);
+ expect(error).toMatchObject({ entity: 'topics' });
+ expect(String((error as FtsSearchReindexEntityError).cause)).toContain(
+ 'The topics mapping change is not additive',
+ );
+ expect(client.putMapping).not.toHaveBeenCalled();
+ expect(client.ensureIndex).not.toHaveBeenCalled();
+ });
+
+ it('refuses an in-place upgrade of an index the alias does not serve for writes', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ pinTopicsInPlace(state);
+ vi.mocked(client.describeGenerations).mockResolvedValue([
+ createLiveTopicsGeneration({ isWriteIndex: false }),
+ ]);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ entityConcurrency: 1,
+ });
+
+ await expect(service.prepareIndices(state)).rejects.toMatchObject({
+ entity: 'topics',
+ message: expect.stringContaining('Elasticsearch alias test-topics does not serve'),
+ });
+ expect(client.putMapping).not.toHaveBeenCalled();
+ });
+
+ it('refuses an in-place upgrade of an index that is not an open generation', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ pinTopicsInPlace(state);
+ vi.mocked(client.describeGenerations).mockResolvedValue([
+ createGeneration('test-topics-v2', { mappings: upgradableTopicsMappings(), version: 2 }),
+ ]);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ entityConcurrency: 1,
+ });
+
+ await expect(service.prepareIndices(state)).rejects.toMatchObject({
+ entity: 'topics',
+ message: expect.stringContaining(
+ 'Elasticsearch index test-topics-v1 is not an open generation of test-topics',
+ ),
+ });
+ expect(client.putMapping).not.toHaveBeenCalled();
+ });
+
+ it('does not restamp an in-place upgrade the checkpoint already completed', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const topics = pinTopicsInPlace(state);
+ topics.completedAt = '2026-08-28T00:01:00.000Z';
+ topics.status = 'completed';
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['topics'],
+ entityConcurrency: 1,
+ });
+
+ await service.prepareIndices(state);
+
+ expect(client.describeGenerations).not.toHaveBeenCalled();
+ expect(client.putMapping).not.toHaveBeenCalled();
+ expect(client.ensureIndex).toHaveBeenCalledWith('test-topics-v1', expect.any(Object), {
+ createIfMissing: false,
+ });
+ });
+
+ it('accepts documents incremental sync wrote into an aliased generation', async () => {
+ const { builder, client, repository } = createDependencies();
+ const events: FtsSearchReindexProgressEvent[] = [];
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 1 : 0,
+ );
+ vi.mocked(client.describeGenerations).mockImplementation(async (alias) => [
+ createGeneration(`${alias}-v1`),
+ ]);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ onProgress: (event) => {
+ events.push(event);
+ },
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(events).toContainEqual({
+ checkpointCount: 0,
+ drift: 1,
+ elasticsearchCount: 1,
+ entity: 'agents',
+ type: 'reconciliation',
+ });
+ });
+
+ it('still blocks a shortfall while incremental sync writes to the generation', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ state.progress.find(({ entity }) => entity === 'agents')!.indexedCount = 2;
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 1 : 0,
+ );
+ vi.mocked(client.describeGenerations).mockImplementation(async (alias) => [
+ createGeneration(`${alias}-v1`),
+ ]);
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await expect(service.run('test', 1)).rejects.toThrow(
+ 'Reindex count mismatch for agents: checkpoint=2, Elasticsearch=1',
+ );
+
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ });
+
+ it('blocks any drift on a fresh install whose generation no alias serves yet', async () => {
+ const { builder, client, repository } = createDependencies();
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 1 : 0,
+ );
+ vi.mocked(client.describeGenerations).mockImplementation(async (alias) => [
+ createGeneration(`${alias}-v1`, { aliased: false, isWriteIndex: false }),
+ ]);
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await expect(service.run('test', 1)).rejects.toThrow(
+ 'Reindex count mismatch for agents: checkpoint=0, Elasticsearch=1',
+ );
+
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ });
});
diff --git a/scripts/elasticsearchReindex/runtime/checkpointRepository.ts b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
index 4b5df5700f9..6d115eaa3e4 100644
--- a/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
+++ b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
@@ -11,7 +11,10 @@ import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import { z } from 'zod';
-import { getFtsSearchPhysicalIndexName } from '../../../packages/database/src/repositories/ftsSearchDocument';
+import {
+ getFtsSearchIndexAlias,
+ getFtsSearchPhysicalIndexName,
+} from '../../../packages/database/src/repositories/ftsSearchDocument';
export interface FtsSearchReindexBatchFailure {
documentId: string;
@@ -128,28 +131,38 @@ const checkpointSchema = z
.object({
failures: z.array(failureSchema),
formatVersion: z.literal(CHECKPOINT_FORMAT_VERSION),
- progress: z.array(progressSchema).length(FTS_SEARCH_DOCUMENT_ENTITIES.length),
+ /**
+ * One checkpoint tracks one schema generation. The first generation covers every entity; an
+ * upgrade generation only covers the entities whose declared version was bumped, so the list
+ * is a non-empty subset rather than a fixed length.
+ */
+ progress: z.array(progressSchema).min(1),
run: runSchema,
})
.superRefine((checkpoint, context) => {
const entities = new Set(checkpoint.progress.map(({ entity }) => entity));
- if (entities.size !== FTS_SEARCH_DOCUMENT_ENTITIES.length) {
+ if (entities.size !== checkpoint.progress.length) {
context.addIssue({
code: 'custom',
- message: 'FTS reindex checkpoint must contain each entity exactly once',
+ message: 'FTS reindex checkpoint must contain each entity at most once',
path: ['progress'],
});
}
for (const progress of checkpoint.progress) {
- const expectedIndex = getFtsSearchPhysicalIndexName(
- checkpoint.run.namespace,
- progress.entity,
- checkpoint.run.schemaVersion,
- );
- if (progress.physicalIndex !== expectedIndex) {
+ /**
+ * A rebuilt generation lives in `<alias>-v<schemaVersion>`. An in-place upgrade keeps the
+ * older physical index and only advances its `_meta`, so any older generation name of the
+ * same alias is also a valid target; a newer one or a foreign index never is.
+ */
+ const alias = getFtsSearchIndexAlias(checkpoint.run.namespace, progress.entity);
+ const suffix = progress.physicalIndex.startsWith(`${alias}-v`)
+ ? progress.physicalIndex.slice(alias.length + 2)
+ : '';
+ const version = /^\d+$/.test(suffix) ? Number(suffix) : Number.NaN;
+ if (!(version >= 1 && version <= checkpoint.run.schemaVersion)) {
context.addIssue({
code: 'custom',
- message: `Expected physical index ${expectedIndex}`,
+ message: `Expected physical index ${alias}-v<n> with n <= ${checkpoint.run.schemaVersion}`,
path: ['progress', progress.entity, 'physicalIndex'],
});
}
@@ -180,6 +193,22 @@ const unresolvedFailureCount = (
) =>
checkpoint.failures.filter((failure) => failure.entity === entity && !failure.resolvedAt).length;
+const pendingProgress = (
+ namespace: string,
+ schemaVersion: number,
+ entity: FtsSearchDocumentEntity,
+ physicalIndex = getFtsSearchPhysicalIndexName(namespace, entity, schemaVersion),
+): FtsSearchReindexEntityProgress => ({
+ completedAt: null,
+ cursor: null,
+ entity,
+ failedCount: 0,
+ indexedCount: 0,
+ physicalIndex,
+ processedCount: 0,
+ status: 'pending',
+});
+
const isMissingFileError = (error: unknown) => isRecord(error) && error.code === 'ENOENT';
const isExistingFileError = (error: unknown) => isRecord(error) && error.code === 'EEXIST';
@@ -419,15 +448,77 @@ export class FtsSearchReindexFileRepository {
});
}
+ /**
+ * Creates the checkpoint for one schema generation or resumes it. `entities` is the set the
+ * generation covers; when a later code change moves more entities onto an existing generation,
+ * they are appended as pending so the same checkpoint keeps tracking that generation.
+ * `physicalIndexes` pins an entity to an existing older index for an in-place upgrade instead of
+ * the generation's own `<alias>-v<schemaVersion>`; a resumed entity must keep the same target.
+ */
async createOrResume(
namespace: string,
schemaVersion: number,
+ entities: readonly FtsSearchDocumentEntity[] = FTS_SEARCH_DOCUMENT_ENTITIES,
+ physicalIndexes: Partial<Record<FtsSearchDocumentEntity, string>> = {},
): Promise<FtsSearchReindexRunState> {
+ if (entities.length === 0)
+ throw new Error('A reindex generation must cover at least one entity');
+ const progressFor = (entity: FtsSearchDocumentEntity) =>
+ pendingProgress(namespace, schemaVersion, entity, physicalIndexes[entity]);
+ const assertTargets = (checkpoint: FtsSearchReindexCheckpointFile) => {
+ for (const progress of checkpoint.progress) {
+ const pinned = physicalIndexes[progress.entity];
+ if (pinned !== undefined && pinned !== progress.physicalIndex) {
+ throw new Error(
+ `Checkpoint ${checkpoint.run.id} already backfills ${progress.entity} into ${progress.physicalIndex}; it cannot switch to ${pinned}`,
+ );
+ }
+ }
+ };
+ const needsBackfill = (checkpoint: FtsSearchReindexCheckpointFile) => {
+ const generationEntitySet = new Set(entities);
+ return (
+ checkpoint.progress.some(
+ (progress) => generationEntitySet.has(progress.entity) && progress.status !== 'completed',
+ ) ||
+ checkpoint.failures.some(
+ (failure) => generationEntitySet.has(failure.entity) && !failure.resolvedAt,
+ )
+ );
+ };
+ const reconcileGeneration = (checkpoint: FtsSearchReindexCheckpointFile) => {
+ let changed = false;
+ for (const entity of entities) {
+ if (checkpoint.progress.some((progress) => progress.entity === entity)) continue;
+ checkpoint.progress.push(progressFor(entity));
+ changed = true;
+ }
+ if (checkpoint.run.status === 'ready_for_incremental_sync' && needsBackfill(checkpoint)) {
+ checkpoint.run.status = 'backfilling';
+ changed = true;
+ }
+ return changed;
+ };
const checkpointPath = this.checkpointPath(namespace, schemaVersion);
const existing = await this.readCheckpointIfExists(checkpointPath);
if (existing) {
this.assertCaptureFingerprint(existing, await this.readCaptureFingerprint());
- return this.stateOf(checkpointPath, existing);
+ assertTargets(existing);
+ const missing = entities.filter(
+ (entity) => !existing.progress.some((progress) => progress.entity === entity),
+ );
+ const needsReopen =
+ existing.run.status === 'ready_for_incremental_sync' && needsBackfill(existing);
+ if (missing.length === 0 && !needsReopen) return this.stateOf(checkpointPath, existing);
+ return this.withCheckpointLock(checkpointPath, async () => {
+ const checkpoint = await this.readCheckpoint(checkpointPath);
+ assertTargets(checkpoint);
+ // Recheck under the lock in case another process completed or appended work meanwhile.
+ if (!reconcileGeneration(checkpoint)) return this.stateOf(checkpointPath, checkpoint);
+ checkpoint.run.updatedAt = now();
+ await this.writeCheckpoint(checkpointPath, checkpoint);
+ return this.stateOf(checkpointPath, checkpoint);
+ });
}
/** Reserve outside the file lock so a slow database connection cannot stale the local lock. */
@@ -440,6 +531,11 @@ export class FtsSearchReindexFileRepository {
const captureFingerprint = await this.readCaptureFingerprint();
if (concurrentlyCreated) {
this.assertCaptureFingerprint(concurrentlyCreated, captureFingerprint);
+ assertTargets(concurrentlyCreated);
+ if (reconcileGeneration(concurrentlyCreated)) {
+ concurrentlyCreated.run.updatedAt = now();
+ await this.writeCheckpoint(checkpointPath, concurrentlyCreated);
+ }
return this.stateOf(checkpointPath, concurrentlyCreated);
}
@@ -447,16 +543,7 @@ export class FtsSearchReindexFileRepository {
const checkpoint: FtsSearchReindexCheckpointFile = {
failures: [],
formatVersion: CHECKPOINT_FORMAT_VERSION,
- progress: FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => ({
- completedAt: null,
- cursor: null,
- entity,
- failedCount: 0,
- indexedCount: 0,
- physicalIndex: getFtsSearchPhysicalIndexName(namespace, entity, schemaVersion),
- processedCount: 0,
- status: 'pending',
- })),
+ progress: entities.map(progressFor),
run: {
aliasesCreatedAt: null,
backfillHighWaterRevision: null,
@@ -499,15 +586,34 @@ export class FtsSearchReindexFileRepository {
);
}
- async markReadyForIncrementalSync(runId: string): Promise<void> {
+ /**
+ * Marks the current generation ready without discarding progress or failures retained for an
+ * entity that has since moved to another declared schema version.
+ */
+ async markReadyForIncrementalSync(
+ runId: string,
+ generationEntities: readonly FtsSearchDocumentEntity[],
+ ): Promise<void> {
+ if (generationEntities.length === 0) {
+ throw new Error('A reindex generation must cover at least one entity');
+ }
/** Read outside the file lock so a slow database connection cannot stale the local lock. */
const highWaterRevision = await this.options.readHighWaterRevision();
if (!Number.isSafeInteger(highWaterRevision) || highWaterRevision < 0) {
throw new Error('Failed to read a valid search reindex high-water revision');
}
await this.updateCheckpoint(runId, (checkpoint) => {
- const incomplete = checkpoint.progress.find((progress) => progress.status !== 'completed');
- const unresolved = checkpoint.failures.find((failure) => !failure.resolvedAt);
+ const generationEntitySet = new Set(generationEntities);
+ const missing = generationEntities.find(
+ (entity) => !checkpoint.progress.some((progress) => progress.entity === entity),
+ );
+ if (missing) throw new Error(`Missing reindex progress for ${missing}`);
+ const incomplete = checkpoint.progress.find(
+ (progress) => generationEntitySet.has(progress.entity) && progress.status !== 'completed',
+ );
+ const unresolved = checkpoint.failures.find(
+ (failure) => generationEntitySet.has(failure.entity) && !failure.resolvedAt,
+ );
if (incomplete || unresolved) {
throw new Error(
'Cannot create aliases before every reindex entity and failure is complete',
diff --git a/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
index c6a7f0fcd9a..b8549d102d0 100644
--- a/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
+++ b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
@@ -4,11 +4,20 @@ import { z } from 'zod';
import { resolveElasticsearchTransport } from '../../../packages/database/src/repositories/ftsSearch/elasticsearch/url';
import type {
+ FtsSearchReindexAliasOutcome,
FtsSearchReindexBulkItemResult,
FtsSearchReindexElasticsearchClient,
FtsSearchReindexIndexBody,
FtsSearchReindexIndexOptions,
+ FtsSearchReindexMappingUpgrade,
} from './reindexService';
+import {
+ assertExactRetiredIndexName,
+ assertRetiredIndexProtection,
+ getRetiredIndexProtectionTemplate,
+ getRetiredIndexProtectionTemplateName,
+ indexTemplateListResponseSchema,
+} from './retiredIndexProtection';
const bulkResponseSchema = z.object({
items: z.array(
@@ -19,6 +28,7 @@ const bulkResponseSchema = z.object({
});
const countResponseSchema = z.object({ count: z.number().int().nonnegative() });
+const acknowledgedResponseSchema = z.object({ acknowledged: z.literal(true) });
const aliasResponseSchema = z.record(
z.string(),
@@ -30,7 +40,7 @@ const aliasResponseSchema = z.record(
}),
);
-interface ElasticsearchFtsSearchMappingPropertyResponse {
+export interface ElasticsearchFtsSearchMappingPropertyResponse {
analyzer?: string;
fields?: Record<string, ElasticsearchFtsSearchMappingPropertyResponse>;
ignore_above?: number;
@@ -54,6 +64,7 @@ const mappingResponseSchema = z.record(
_meta: z
.object({
reindex_run_id: z.string().optional(),
+ schema_fingerprint: z.string().optional(),
schema_version: z.number().int().positive().optional(),
})
.optional(),
@@ -63,6 +74,66 @@ const mappingResponseSchema = z.record(
}),
);
+const catIndicesResponseSchema = z.array(z.object({ index: z.string(), status: z.string() }));
+
+const generationDetailSchema = z.record(
+ z.string(),
+ z.object({
+ mappings: z.object({
+ _meta: z
+ .object({
+ reindex_run_id: z.string().optional(),
+ schema_fingerprint: z.string().optional(),
+ schema_version: z.number().int().positive().optional(),
+ })
+ .passthrough()
+ .optional(),
+ dynamic: z.union([z.boolean(), z.string()]).optional(),
+ properties: z.record(z.string(), mappingPropertyResponseSchema).default({}),
+ }),
+ settings: z.object({
+ index: z.object({ analysis: z.record(z.string(), z.unknown()).default({}) }),
+ }),
+ }),
+);
+
+export interface FtsSearchReindexGenerationDescription {
+ aliased: boolean;
+ analysis: Record<string, unknown> | null;
+ index: string;
+ isWriteIndex: boolean;
+ mappings: z.infer<typeof generationDetailSchema>[string]['mappings'] | null;
+ meta: {
+ reindex_run_id?: string;
+ schema_fingerprint?: string;
+ schema_version?: number;
+ } | null;
+ /** Closed generations are mid-retirement: sync no longer targets them, deletion comes next. */
+ state: 'closed' | 'open';
+ /**
+ * Schema generation the index implements: `_meta.schema_version` when stamped, otherwise parsed
+ * from `<alias>-v<n>`; `null` for an aliased index outside that naming scheme.
+ */
+ version: number | null;
+}
+
+/**
+ * Version a managed generation implements. Indexes outside the `<alias>-v<n>` naming scheme are
+ * never managed, whatever `_meta` they carry (for example a snapshot restored under another name).
+ */
+const generationVersion = (alias: string, index: string, stampedVersion: number | undefined) => {
+ const built = parseGenerationVersion(alias, index);
+ if (built === undefined) return null;
+ return stampedVersion ?? built;
+};
+
+/** Generation number of `index` if it is named `<alias>-v<n>`. */
+export const parseGenerationVersion = (alias: string, index: string): number | undefined => {
+ if (!index.startsWith(`${alias}-v`)) return;
+ const suffix = index.slice(alias.length + 2);
+ return /^\d+$/.test(suffix) ? Number(suffix) : undefined;
+};
+
const settingsResponseSchema = z.record(
z.string(),
z.object({
@@ -77,6 +148,8 @@ export interface FtsSearchReindexHttpClientOptions {
allowInsecureHttp?: boolean;
/** Required unless `allowInsecureHttp` is enabled; never sent over plaintext HTTP. */
apiKey?: string;
+ /** Verifies that the caller still owns the operation lock immediately before a cluster write. */
+ beforeMutation?: () => Promise<void>;
requestTimeoutMs?: number;
url: string;
}
@@ -94,17 +167,20 @@ export class FtsSearchReindexRequestError extends Error {
/** Minimal credential-safe Elasticsearch transport for the self-host reindex command. */
export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearchClient {
private readonly authorizationHeader: string | undefined;
+ private readonly beforeMutation: () => Promise<void>;
private readonly requestTimeoutMs: number;
private readonly url: URL;
constructor({
allowInsecureHttp,
apiKey,
+ beforeMutation = async () => {},
requestTimeoutMs = 30_000,
url,
}: FtsSearchReindexHttpClientOptions) {
const transport = resolveElasticsearchTransport({ allowInsecureHttp, apiKey, url });
this.authorizationHeader = transport.authorizationHeader;
+ this.beforeMutation = beforeMutation;
this.requestTimeoutMs = requestTimeoutMs;
this.url = transport.url;
}
@@ -120,6 +196,17 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
});
}
+ private async assertAcknowledged(response: Response, operation: string) {
+ const parsed = acknowledgedResponseSchema.safeParse(await response.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch did not acknowledge ${operation}`,
+ response.status,
+ parsed.error,
+ );
+ }
+ }
+
private assertMappingProperty(
field: string,
actual: ElasticsearchFtsSearchMappingPropertyResponse | undefined,
@@ -173,6 +260,15 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
`Elasticsearch index mapping or reindex run identity is incompatible for ${index}; restore the matching checkpoint or use a clean target`,
);
}
+ // Indexes created before fingerprints existed carry none; only a differing fingerprint is drift.
+ if (
+ actual._meta?.schema_fingerprint !== undefined &&
+ actual._meta.schema_fingerprint !== expected.mappings._meta.schema_fingerprint
+ ) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index ${index} was built from a different v${expected.mappings._meta.schema_version} mapping than the code declares; bump the schema version and rebuild instead of resuming`,
+ );
+ }
for (const [field, expectedProperty] of Object.entries(expected.mappings.properties)) {
this.assertMappingProperty(field, actual.properties[field], expectedProperty);
}
@@ -207,6 +303,7 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
}
async bulk(body: string): Promise<FtsSearchReindexBulkItemResult[]> {
+ await this.beforeMutation();
const response = await this.request('/_bulk', {
body,
headers: { 'Content-Type': 'application/x-ndjson' },
@@ -250,7 +347,7 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
return parsed.data.count;
}
- async ensureAlias(alias: string, physicalIndex: string): Promise<void> {
+ async ensureAlias(alias: string, physicalIndex: string): Promise<FtsSearchReindexAliasOutcome> {
const response = await this.request(`/_alias/${encodeURIComponent(alias)}`, { method: 'GET' });
if (response.ok) {
const parsed = aliasResponseSchema.safeParse(await response.json());
@@ -269,17 +366,25 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
targets[0][0] === physicalIndex &&
targets[0][1].aliases[alias].is_write_index !== false
) {
- return;
+ return 'existing';
}
/**
- * Incremental sync writes only through the stable alias. Moving that alias while a resumable
- * backfill is running could acknowledge a change in the old index without replaying it into
- * the new one. Online schema upgrades therefore require a separate durable dual-write
- * protocol; this initial migration fails closed instead of pretending the cutover is safe.
+ * Incremental sync writes every change to all live generations of an entity, so a newer
+ * generation can be backfilled while the alias keeps serving an older one. Moving the alias
+ * is the explicit promote step, gated on the backfill and the Outbox catching up; a backfill
+ * never moves it. Anything that is not another generation of this entity is an operator
+ * error and fails closed.
*/
+ if (
+ targets.length === 1 &&
+ parseGenerationVersion(alias, targets[0][0]) !== undefined &&
+ targets[0][1].aliases[alias].is_write_index !== false
+ ) {
+ return 'kept_other_generation';
+ }
throw new FtsSearchReindexRequestError(
- `Elasticsearch alias ${alias} already points to a different index`,
+ `Elasticsearch alias ${alias} points to ${targets.map(([index]) => index).join(', ') || 'no index'} instead of a single writable ${alias}-v<n> generation`,
);
}
if (response.status !== 404) {
@@ -289,6 +394,7 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
);
}
+ await this.beforeMutation();
const createResponse = await this.request('/_aliases', {
body: JSON.stringify({
actions: [{ add: { alias, index: physicalIndex, is_write_index: true } }],
@@ -302,6 +408,239 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
createResponse.status,
);
}
+ await this.assertAcknowledged(createResponse, `alias creation for ${alias}`);
+ return 'created';
+ }
+
+ /**
+ * Describes every physical generation of `alias`, including the `_meta`, mapping, and analysis of
+ * closed generations so a purge can prove their managed identity before deletion. It also includes
+ * the index the alias currently serves if an operator named it outside the `-v<n>` scheme.
+ */
+ async describeGenerations(alias: string): Promise<FtsSearchReindexGenerationDescription[]> {
+ const pattern = encodeURIComponent(`${alias}-v*`);
+ const [catResponse, aliasResponse] = await Promise.all([
+ this.request(
+ `/_cat/indices/${pattern}?format=json&h=index,status&expand_wildcards=all&allow_no_indices=true`,
+ { method: 'GET' },
+ ),
+ this.request(`/_alias/${encodeURIComponent(alias)}`, { method: 'GET' }),
+ ]);
+ if (!catResponse.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch generation listing failed for ${alias} (${catResponse.status})`,
+ catResponse.status,
+ );
+ }
+ const catParsed = catIndicesResponseSchema.safeParse(await catResponse.json());
+ if (!catParsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch generation listing has an invalid shape for ${alias}`,
+ catResponse.status,
+ catParsed.error,
+ );
+ }
+
+ let aliasTargets: Record<string, { is_write_index?: boolean }> = {};
+ if (aliasResponse.ok) {
+ const parsed = aliasResponseSchema.safeParse(await aliasResponse.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch alias response has an invalid shape for ${alias}`,
+ aliasResponse.status,
+ parsed.error,
+ );
+ }
+ aliasTargets = Object.fromEntries(
+ Object.entries(parsed.data)
+ .filter(([, value]) => Object.hasOwn(value.aliases, alias))
+ .map(([index, value]) => [index, value.aliases[alias]]),
+ );
+ } else if (aliasResponse.status !== 404) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch alias check failed for ${alias} (${aliasResponse.status})`,
+ aliasResponse.status,
+ );
+ }
+
+ const states = new Map(
+ catParsed.data
+ .filter(({ index }) => parseGenerationVersion(alias, index) !== undefined)
+ .map(({ index, status }) => [index, status === 'close' ? 'closed' : 'open'] as const),
+ );
+ for (const index of Object.keys(aliasTargets)) {
+ if (!states.has(index)) states.set(index, 'open');
+ }
+
+ const indexes = [...states].map(([index]) => index);
+ const details = new Map<string, z.infer<typeof generationDetailSchema>[string]>();
+ if (indexes.length > 0) {
+ const detailPath = indexes.map(encodeURIComponent).join(',');
+ const detailResponse = await this.request(
+ `/${detailPath}?expand_wildcards=all&filter_path=*.mappings,*.settings.index.analysis`,
+ { method: 'GET' },
+ );
+ if (!detailResponse.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch generation inspection failed for ${alias} (${detailResponse.status})`,
+ detailResponse.status,
+ );
+ }
+ const parsed = generationDetailSchema.safeParse(await detailResponse.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch generation inspection has an invalid shape for ${alias}`,
+ detailResponse.status,
+ parsed.error,
+ );
+ }
+ for (const [index, detail] of Object.entries(parsed.data)) details.set(index, detail);
+ }
+
+ return [...states]
+ .map(([index, state]): FtsSearchReindexGenerationDescription => {
+ const detail = details.get(index);
+ return {
+ aliased: Object.hasOwn(aliasTargets, index),
+ analysis: detail?.settings.index.analysis ?? null,
+ index,
+ isWriteIndex:
+ aliasTargets[index]?.is_write_index !== false && Object.hasOwn(aliasTargets, index),
+ mappings: detail?.mappings ?? null,
+ meta: detail?.mappings._meta ?? null,
+ state,
+ /**
+ * An in-place upgrade advances `_meta.schema_version` without renaming the index, so the
+ * stamped version wins over the `-v<n>` suffix, which only records the generation that
+ * originally built the index.
+ */
+ version: generationVersion(alias, index, detail?.mappings._meta?.schema_version),
+ };
+ })
+ .sort(
+ (left, right) =>
+ (left.version ?? -1) - (right.version ?? -1) || left.index.localeCompare(right.index),
+ );
+ }
+
+ /** Atomically repoints `alias` at `to` (as write index) and removes it from every `from` index. */
+ async promoteAlias(alias: string, from: readonly string[], to: string): Promise<void> {
+ await this.beforeMutation();
+ const response = await this.request('/_aliases', {
+ body: JSON.stringify({
+ actions: [
+ ...from.filter((index) => index !== to).map((index) => ({ remove: { alias, index } })),
+ { add: { alias, index: to, is_write_index: true } },
+ ],
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch alias promotion failed for ${alias} (${response.status})`,
+ response.status,
+ );
+ }
+ await this.assertAcknowledged(response, `alias promotion for ${alias}`);
+ }
+
+ async closeIndex(index: string): Promise<void> {
+ await this.beforeMutation();
+ const response = await this.request(`/${encodeURIComponent(index)}/_close`, { method: 'POST' });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index close failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ await this.assertAcknowledged(response, `index close for ${index}`);
+ }
+
+ async deleteIndex(index: string): Promise<void> {
+ assertExactRetiredIndexName(index);
+ await this.beforeMutation();
+ const response = await this.request(`/${encodeURIComponent(index)}`, { method: 'DELETE' });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index deletion failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ await this.assertAcknowledged(response, `deletion of ${index}`);
+ }
+
+ /**
+ * Installs a persistent exact-index tombstone so a stale bulk writer cannot auto-create a retired
+ * physical index after deletion. The template deliberately remains after the index is deleted.
+ */
+ async ensureRetiredIndexProtection(index: string): Promise<void> {
+ assertExactRetiredIndexName(index);
+ const name = getRetiredIndexProtectionTemplateName(index);
+ const loadTemplates = async () => {
+ const response = await this.request('/_index_template', { method: 'GET' });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index template inspection failed for retired index ${index} (${response.status}); the reindex credential needs manage_index_templates`,
+ response.status,
+ );
+ }
+ const parsed = indexTemplateListResponseSchema.safeParse(await response.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index template response has an invalid shape for retired index ${index}`,
+ response.status,
+ parsed.error,
+ );
+ }
+ return parsed.data.index_templates;
+ };
+
+ if (assertRetiredIndexProtection(index, await loadTemplates())) return;
+
+ await this.beforeMutation();
+ const createResponse = await this.request(
+ `/_index_template/${encodeURIComponent(name)}?create=true`,
+ {
+ body: JSON.stringify(getRetiredIndexProtectionTemplate(index)),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PUT',
+ },
+ );
+ if (!createResponse.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch retired-index protection creation failed for ${index} (${createResponse.status}); verify composable templates support allow_auto_create and the credential has manage_index_templates`,
+ createResponse.status,
+ );
+ }
+ await this.assertAcknowledged(createResponse, `retired-index protection for ${index}`);
+
+ if (!assertRetiredIndexProtection(index, await loadTemplates())) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch retired-index protection is not effective for ${index}`,
+ );
+ }
+ }
+
+ /**
+ * Applies an additive mapping upgrade to a live index: Elasticsearch accepts new fields and a
+ * new `_meta` on an existing index, but never a changed field. Callers classify the change first;
+ * a non-additive change fails here with Elasticsearch's own error.
+ */
+ async putMapping(index: string, mappings: FtsSearchReindexMappingUpgrade): Promise<void> {
+ await this.beforeMutation();
+ const response = await this.request(`/${encodeURIComponent(index)}/_mapping`, {
+ body: JSON.stringify(mappings),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PUT',
+ });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch mapping upgrade failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ await this.assertAcknowledged(response, `mapping upgrade for ${index}`);
}
async ensureIndex(
@@ -328,6 +667,7 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
);
}
+ await this.beforeMutation();
const response = await this.request(`/${encodeURIComponent(index)}`, {
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
@@ -339,9 +679,11 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
response.status,
);
}
+ await this.assertAcknowledged(response, `index creation for ${index}`);
}
async refresh(index: string): Promise<void> {
+ await this.beforeMutation();
const response = await this.request(`/${encodeURIComponent(index)}/_refresh`, {
method: 'POST',
});
diff --git a/scripts/elasticsearchReindex/runtime/generationService.ts b/scripts/elasticsearchReindex/runtime/generationService.ts
new file mode 100644
index 00000000000..3bb45535c79
--- /dev/null
+++ b/scripts/elasticsearchReindex/runtime/generationService.ts
@@ -0,0 +1,544 @@
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+
+import {
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_INDEX_DEFINITIONS,
+ getFtsSearchIndexAlias,
+ getFtsSearchIndexSchemaFingerprint,
+ getFtsSearchIndexSchemaVersion,
+ getFtsSearchPhysicalIndexName,
+} from '../../../packages/database/src/repositories/ftsSearchDocument';
+import type { FtsSearchProjectionCompatibility } from '../../../packages/database/src/repositories/ftsSearchDocument/projectionCompatibility';
+import { getFtsSearchProjectionCompatibility } from '../../../packages/database/src/repositories/ftsSearchDocument/projectionCompatibility';
+import type { FtsSearchSyncOutboxStats } from '../../../packages/database/src/repositories/ftsSearchSyncOutbox';
+import type { FtsSearchReindexRunState } from './checkpointRepository';
+import type { FtsSearchReindexGenerationDescription } from './elasticsearchClient';
+import type { FtsSearchMappingDiff } from './mappingDiff';
+import { diffFtsSearchMappings } from './mappingDiff';
+
+export interface FtsSearchGenerationElasticsearchClient {
+ closeIndex: (index: string) => Promise<void>;
+ deleteIndex: (index: string) => Promise<void>;
+ describeGenerations: (alias: string) => Promise<FtsSearchReindexGenerationDescription[]>;
+ ensureRetiredIndexProtection: (index: string) => Promise<void>;
+ promoteAlias: (alias: string, from: readonly string[], to: string) => Promise<void>;
+}
+
+/** Reads the checkpoint that tracks one generation, if the operator kept it. */
+export type FtsSearchGenerationCheckpointReader = (
+ namespace: string,
+ schemaVersion: number,
+) => Promise<FtsSearchReindexRunState | undefined>;
+
+/**
+ * How the live mapping differs from the declared one.
+ * - `identical`: same fields, same parameters.
+ * - `additive`: the declared mapping only adds fields; Elasticsearch could accept it in place.
+ * - `breaking`: a field or the shared analysis changed; only a rebuild can apply it.
+ */
+export type FtsSearchMappingChange = 'additive' | 'breaking' | 'identical';
+
+/**
+ * - `missing`: no alias yet; a first backfill is required.
+ * - `unmanaged`: the alias points at an index without reindex `_meta`; the tool never built it.
+ * - `in_sync`: the live generation implements the declared version.
+ * - `drift`: same version, different fingerprint. A mapping changed without a version bump.
+ * - `upgrade_available`: the code declares a newer version than the alias serves.
+ * - `rollback_required`: the alias serves a newer version than the deployed code declares.
+ */
+export type FtsSearchGenerationClassification =
+ 'drift' | 'in_sync' | 'missing' | 'rollback_required' | 'unmanaged' | 'upgrade_available';
+
+export interface FtsSearchGenerationSummary {
+ /** Still attached to the entity's read alias, even when it is not the write index. */
+ aliased: boolean;
+ /** Backfill state from the generation's checkpoint; `unknown` when no checkpoint is available. */
+ backfill: 'backfilling' | 'completed' | 'unknown';
+ /** Whether the current document source can still populate every field this generation maps. */
+ fieldCompatibility: FtsSearchProjectionCompatibility | null;
+ fingerprint: string | null;
+ index: string;
+ /** Whether `_meta.schema_fingerprint` equals the declared fingerprint (legacy: version only). */
+ matchesDeclared: boolean;
+ reindexRunId: string | null;
+ state: 'closed' | 'open';
+ version: number | null;
+}
+
+export interface FtsSearchEntityGenerationStatus {
+ action: string;
+ alias: string;
+ /** Generations other than the one the alias serves, oldest first. */
+ candidates: FtsSearchGenerationSummary[];
+ classification: FtsSearchGenerationClassification;
+ declared: { fingerprint: string; index: string; version: number };
+ entity: FtsSearchDocumentEntity;
+ live: FtsSearchGenerationSummary | null;
+ /** Difference between the live mapping and the declared one; `null` without a live generation. */
+ mappingChange: FtsSearchMappingChange | null;
+ /** Deterministic field-level details behind `mappingChange`. */
+ mappingDiff: FtsSearchMappingDiff | null;
+}
+
+/**
+ * Classifies the live mapping of `entity` against the declared one. Only whole new top-level
+ * fields count as additive: Elasticsearch cannot change an existing field's type or analyzer, and
+ * new multi-fields on an existing field would leave existing documents unsearchable through them
+ * until they are rewritten, so they are treated as breaking to keep the rebuild path honest.
+ */
+export const classifyMappingChange = (
+ entity: FtsSearchDocumentEntity,
+ live: NonNullable<FtsSearchReindexGenerationDescription['mappings']>,
+ liveAnalysis: Record<string, unknown> | null,
+): FtsSearchMappingChange => {
+ const declared = FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings;
+ const diff = diffFtsSearchMappings({
+ declared,
+ declaredAnalysis: FTS_SEARCH_INDEX_ANALYSIS,
+ live,
+ liveAnalysis,
+ });
+ if (
+ diff.analysisChanged ||
+ diff.dynamicChanged ||
+ diff.removed.length > 0 ||
+ diff.changed.length > 0
+ ) {
+ return 'breaking';
+ }
+ return diff.added.length > 0 ? 'additive' : 'identical';
+};
+
+const summarize = (
+ entity: FtsSearchDocumentEntity,
+ generation: FtsSearchReindexGenerationDescription,
+ checkpoint: FtsSearchReindexRunState | undefined,
+): FtsSearchGenerationSummary => {
+ const progress = checkpoint?.progress.find((item) => item.entity === entity);
+ const fingerprint = generation.meta?.schema_fingerprint ?? null;
+ return {
+ aliased: generation.aliased,
+ backfill:
+ progress?.physicalIndex === generation.index
+ ? progress.status === 'completed'
+ ? 'completed'
+ : 'backfilling'
+ : 'unknown',
+ fieldCompatibility:
+ generation.state === 'open' && generation.mappings
+ ? getFtsSearchProjectionCompatibility(entity, generation.mappings.properties)
+ : null,
+ fingerprint,
+ index: generation.index,
+ matchesDeclared:
+ generation.meta?.schema_version === getFtsSearchIndexSchemaVersion(entity) &&
+ (fingerprint === null || fingerprint === getFtsSearchIndexSchemaFingerprint(entity)),
+ reindexRunId: generation.meta?.reindex_run_id ?? null,
+ state: generation.state,
+ version: generation.meta?.schema_version ?? generation.version,
+ };
+};
+
+export const describeEntityGeneration = async ({
+ client,
+ entity,
+ namespace,
+ readCheckpoint,
+}: {
+ client: Pick<FtsSearchGenerationElasticsearchClient, 'describeGenerations'>;
+ entity: FtsSearchDocumentEntity;
+ namespace: string;
+ readCheckpoint: FtsSearchGenerationCheckpointReader;
+}): Promise<FtsSearchEntityGenerationStatus> => {
+ const alias = getFtsSearchIndexAlias(namespace, entity);
+ const declaredVersion = getFtsSearchIndexSchemaVersion(entity);
+ const declared = {
+ fingerprint: getFtsSearchIndexSchemaFingerprint(entity),
+ index: getFtsSearchPhysicalIndexName(namespace, entity),
+ version: declaredVersion,
+ };
+ const generations = await client.describeGenerations(alias);
+
+ const checkpoints = new Map<number, FtsSearchReindexRunState | undefined>();
+ const checkpointFor = async (version: number | null) => {
+ if (version === null) return;
+ if (!checkpoints.has(version)) {
+ checkpoints.set(version, await readCheckpoint(namespace, version));
+ }
+ return checkpoints.get(version);
+ };
+
+ const liveGeneration = generations.find((generation) => generation.isWriteIndex);
+ const live = liveGeneration
+ ? summarize(entity, liveGeneration, await checkpointFor(liveGeneration.version))
+ : null;
+ const candidates: FtsSearchGenerationSummary[] = [];
+ for (const generation of generations) {
+ if (generation === liveGeneration) continue;
+ candidates.push(summarize(entity, generation, await checkpointFor(generation.version)));
+ }
+ const mappingDiff =
+ liveGeneration?.mappings && liveGeneration.state === 'open'
+ ? diffFtsSearchMappings({
+ declared: FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings,
+ declaredAnalysis: FTS_SEARCH_INDEX_ANALYSIS,
+ live: liveGeneration.mappings,
+ liveAnalysis: liveGeneration.analysis,
+ })
+ : null;
+ const mappingChange =
+ liveGeneration?.mappings && liveGeneration.state === 'open'
+ ? classifyMappingChange(entity, liveGeneration.mappings, liveGeneration.analysis)
+ : null;
+
+ const declaredCandidate = candidates.find((candidate) => candidate.version === declaredVersion);
+ let classification: FtsSearchGenerationClassification;
+ let action: string;
+ if (!live) {
+ classification = 'missing';
+ action = `Run --apply --fresh-run to build ${declared.index} and create ${alias}`;
+ } else if (live.version === null || live.reindexRunId === null) {
+ classification = 'unmanaged';
+ action = `${live.index} carries no reindex _meta; rebuild it with this tool before relying on generation checks`;
+ } else if (live.version === declaredVersion) {
+ classification = live.matchesDeclared ? 'in_sync' : 'drift';
+ if (!live.matchesDeclared) {
+ action = `The v${declaredVersion} mapping changed without a version bump; bump schemaVersion, then --apply and --promote`;
+ } else if (live.backfill !== 'completed' && live.backfill !== 'unknown') {
+ // An in-place upgrade restamps the live index first and backfills the new fields afterwards.
+ action = `Finish --apply --entity=${entity} to backfill the in-place upgrade of ${live.index}`;
+ } else {
+ action = 'No action';
+ }
+ } else if (live.version < declaredVersion) {
+ classification = 'upgrade_available';
+ if (declaredCandidate) {
+ action =
+ declaredCandidate.backfill === 'completed' && declaredCandidate.matchesDeclared
+ ? `Run --promote --entity=${entity} once the Outbox is drained`
+ : `Finish --apply --entity=${entity} to complete ${declaredCandidate.index}`;
+ } else if (mappingChange === 'additive') {
+ action = `Run --apply --entity=${entity} to build ${declared.index}, or --apply --in-place --entity=${entity} to add the new fields to ${live.index}`;
+ } else {
+ action = `Run --apply --entity=${entity} to build ${declared.index}`;
+ }
+ } else {
+ classification = 'rollback_required';
+ action = `${alias} serves v${live.version} but the deployed code declares v${declaredVersion}; deploy matching code or --promote --entity=${entity} --version=${declaredVersion}`;
+ }
+
+ return {
+ action,
+ alias,
+ candidates,
+ classification,
+ declared,
+ entity,
+ live,
+ mappingChange,
+ mappingDiff,
+ };
+};
+
+export interface FtsSearchPromoteGenerationOptions {
+ client: FtsSearchGenerationElasticsearchClient;
+ entity: FtsSearchDocumentEntity;
+ namespace: string;
+ outboxStats: FtsSearchSyncOutboxStats;
+ readCheckpoint: FtsSearchGenerationCheckpointReader;
+ /** Target generation; defaults to the declared version. Any other existing version is a rollback. */
+ version?: number;
+}
+
+export interface FtsSearchPromoteGenerationResult {
+ alias: string;
+ from: string[];
+ outcome: 'already_live' | 'promoted';
+ to: string;
+}
+
+/**
+ * Atomically points the entity alias at a generation. Preconditions fail closed: the target must
+ * exist and be open, be fully backfilled according to its checkpoint (or, for rollbacks to a
+ * previously promoted generation, already carry reindex `_meta`), and the Outbox must be idle so
+ * every change captured so far has reached the target.
+ */
+export const promoteGeneration = async ({
+ client,
+ entity,
+ namespace,
+ outboxStats,
+ readCheckpoint,
+ version = getFtsSearchIndexSchemaVersion(entity),
+}: FtsSearchPromoteGenerationOptions): Promise<FtsSearchPromoteGenerationResult> => {
+ const alias = getFtsSearchIndexAlias(namespace, entity);
+ const status = await describeEntityGeneration({ client, entity, namespace, readCheckpoint });
+ const target = [...status.candidates, ...(status.live ? [status.live] : [])].find(
+ (generation) => generation.version === version,
+ );
+ if (!target) {
+ throw new Error(`No v${version} generation exists for ${alias}; run --apply first`);
+ }
+ if (target.state !== 'open') {
+ throw new Error(`${target.index} is closed (being retired) and cannot be promoted`);
+ }
+ if (!target.fieldCompatibility) {
+ throw new Error(
+ `${target.index} mapping could not be inspected; retry status before promoting`,
+ );
+ }
+ if (!target.fieldCompatibility.compatible) {
+ const details = [
+ ...target.fieldCompatibility.missingFields.map((field) => `${field} (missing)`),
+ ...target.fieldCompatibility.incompatibleFields.map(
+ ({ currentType, field, targetType }) => `${field} (${currentType} -> ${targetType})`,
+ ),
+ ].join(', ');
+ throw new Error(
+ `${target.index} requires source fields the current projection cannot preserve: ${details}; retain compatible source bridge fields before promoting`,
+ );
+ }
+ if (version === getFtsSearchIndexSchemaVersion(entity) && !target.matchesDeclared) {
+ throw new Error(
+ `${target.index} was not built from the declared v${version} mapping; rebuild it before promoting`,
+ );
+ }
+ if (
+ status.live?.index === target.index &&
+ version === getFtsSearchIndexSchemaVersion(entity) &&
+ status.mappingChange !== 'identical'
+ ) {
+ throw new Error(
+ `${target.index} physical mapping differs from the declared v${version} mapping`,
+ );
+ }
+ if (target.backfill === 'backfilling') {
+ throw new Error(`${target.index} backfill is incomplete; finish --apply --entity=${entity}`);
+ }
+ if (status.live?.index === target.index) {
+ if (target.reindexRunId === null || target.version === null) {
+ throw new Error(`${target.index} carries no managed reindex identity and cannot be promoted`);
+ }
+ return { alias, from: [], outcome: 'already_live', to: target.index };
+ }
+ if (target.backfill === 'unknown' && target.reindexRunId === null) {
+ throw new Error(
+ `${target.index} has no checkpoint and no reindex _meta, so its contents cannot be trusted`,
+ );
+ }
+ if (target.backfill === 'unknown' && version > (status.live?.version ?? 0)) {
+ throw new Error(
+ `No checkpoint proves ${target.index} finished its backfill; keep ES_REINDEX_STATE_DIR from the --apply run`,
+ );
+ }
+ const entityOutboxStats = outboxStats.entities[entity];
+ const pendingWork =
+ entityOutboxStats.pending + entityOutboxStats.retrying + entityOutboxStats.inFlight;
+ if (entityOutboxStats.dead > 0 || pendingWork > 0) {
+ throw new Error(
+ `${target.index}: Outbox is not idle (pending=${entityOutboxStats.pending}, retrying=${entityOutboxStats.retrying}, inFlight=${entityOutboxStats.inFlight}, dead=${entityOutboxStats.dead}); let fts-search:sync drain before promoting`,
+ );
+ }
+
+ const from = status.live ? [status.live.index] : [];
+ await client.promoteAlias(alias, from, target.index);
+ return { alias, from, outcome: 'promoted', to: target.index };
+};
+
+export interface FtsSearchRetireGenerationsOptions {
+ client: FtsSearchGenerationElasticsearchClient;
+ entity: FtsSearchDocumentEntity;
+ namespace: string;
+ readCheckpoint: FtsSearchGenerationCheckpointReader;
+}
+
+export interface FtsSearchRetireGenerationsResult {
+ alias: string;
+ alreadyClosed: string[];
+ closed: string[];
+ /** @deprecated Retirement never deletes indexes; use `purgeRetiredGenerations`. */
+ deleted: string[];
+ kept: string;
+}
+
+export interface FtsSearchRetirementPlan {
+ alreadyClosed: string[];
+ blockedBy: string[];
+ close: string[];
+ purgeCandidates: string[];
+}
+
+const isKnownManagedGeneration = (
+ alias: string,
+ generation: FtsSearchGenerationSummary,
+): boolean => {
+ const suffix = generation.index.slice(`${alias}-v`.length);
+ return (
+ generation.index.startsWith(`${alias}-v`) &&
+ /^\d+$/.test(suffix) &&
+ generation.reindexRunId !== null &&
+ generation.version !== null
+ );
+};
+
+/** Shared candidate boundary; state and backfill readiness are checked by each operation. */
+const isRetirementCandidate = (
+ status: FtsSearchEntityGenerationStatus,
+ candidate: FtsSearchGenerationSummary,
+): boolean => {
+ const liveVersion = status.live?.version;
+ return (
+ !candidate.aliased &&
+ candidate.index !== status.live?.index &&
+ isKnownManagedGeneration(status.alias, candidate) &&
+ liveVersion !== null &&
+ liveVersion !== undefined &&
+ candidate.version !== null &&
+ candidate.version < liveVersion
+ );
+};
+
+/** Builds a side-effect-free preview for closing and later purging retired generations. */
+export const planRetiredGenerations = (
+ status: FtsSearchEntityGenerationStatus,
+): FtsSearchRetirementPlan => {
+ const blockedBy: string[] = [];
+ if (!status.live) blockedBy.push(`${status.alias} has no live generation`);
+ if (status.live && status.classification !== 'in_sync') {
+ blockedBy.push(`${status.alias} is ${status.classification}`);
+ }
+
+ const detached = status.candidates.filter(
+ (candidate) => !candidate.aliased && candidate.index !== status.live?.index,
+ );
+ const close: string[] = [];
+ const alreadyClosed: string[] = [];
+ const purgeCandidates: string[] = [];
+ for (const candidate of detached) {
+ if (!isKnownManagedGeneration(status.alias, candidate)) {
+ blockedBy.push(`${candidate.index} has no known managed reindex identity`);
+ continue;
+ }
+ if (!isRetirementCandidate(status, candidate)) {
+ blockedBy.push(`${candidate.index} is not older than the live generation`);
+ continue;
+ }
+ if (candidate.backfill === 'backfilling') {
+ blockedBy.push(`${candidate.index} backfill is still running`);
+ continue;
+ }
+ if (candidate.state === 'open') {
+ close.push(candidate.index);
+ } else {
+ alreadyClosed.push(candidate.index);
+ purgeCandidates.push(candidate.index);
+ }
+ }
+ return { alreadyClosed, blockedBy, close, purgeCandidates };
+};
+
+/**
+ * Closes open generations detached from the alias. Deletion is a separate explicit operation so
+ * stale sync workers have time to stop targeting the retired index.
+ */
+export const retireGenerations = async ({
+ client,
+ entity,
+ namespace,
+ readCheckpoint,
+}: FtsSearchRetireGenerationsOptions): Promise<FtsSearchRetireGenerationsResult> => {
+ const status = await describeEntityGeneration({ client, entity, namespace, readCheckpoint });
+ if (!status.live) {
+ throw new Error(`${status.alias} has no live generation; nothing is safe to retire`);
+ }
+ if (status.classification !== 'in_sync') {
+ throw new Error(
+ `${status.alias} is ${status.classification}; retire only after the declared generation is promoted`,
+ );
+ }
+ const plan = planRetiredGenerations(status);
+ const closed: string[] = [];
+ const deleted: string[] = [];
+ for (const index of plan.close) {
+ await client.closeIndex(index);
+ closed.push(index);
+ }
+ return {
+ alreadyClosed: plan.alreadyClosed,
+ alias: status.alias,
+ closed,
+ deleted,
+ kept: status.live.index,
+ };
+};
+
+export interface FtsSearchPurgeRetiredGenerationsResult {
+ alias: string;
+ deleted: string[];
+ kept: string;
+}
+
+/** Permanently deletes closed, detached generations after installing an exact-index write guard. */
+export const purgeRetiredGenerations = async ({
+ client,
+ entity,
+ namespace,
+ readCheckpoint,
+}: FtsSearchRetireGenerationsOptions): Promise<FtsSearchPurgeRetiredGenerationsResult> => {
+ const status = await describeEntityGeneration({ client, entity, namespace, readCheckpoint });
+ if (!status.live) {
+ throw new Error(`${status.alias} has no live generation; nothing is safe to purge`);
+ }
+ if (status.classification !== 'in_sync') {
+ throw new Error(
+ `${status.alias} is ${status.classification}; purge only after the declared generation is promoted`,
+ );
+ }
+
+ const plan = planRetiredGenerations(status);
+ const backfilling = status.candidates.find(
+ (candidate) =>
+ isRetirementCandidate(status, candidate) &&
+ candidate.state === 'closed' &&
+ candidate.backfill === 'backfilling',
+ );
+ if (backfilling) {
+ throw new Error(`${backfilling.index} backfill is still running; it cannot be purged`);
+ }
+
+ const deleted: string[] = [];
+ for (const index of plan.purgeCandidates) {
+ await client.ensureRetiredIndexProtection(index);
+ await client.deleteIndex(index);
+ deleted.push(index);
+ }
+ return { alias: status.alias, deleted, kept: status.live.index };
+};
+
+/**
+ * Resolves the index for a new or resumed in-place run, including the crash window after the live
+ * index was restamped but before its checkpoint was persisted.
+ */
+export const resolveInPlaceTarget = (status: FtsSearchEntityGenerationStatus): string => {
+ if (
+ status.classification === 'upgrade_available' &&
+ status.mappingChange === 'additive' &&
+ status.live
+ ) {
+ return status.live.index;
+ }
+ if (
+ status.classification === 'in_sync' &&
+ status.live?.matchesDeclared &&
+ status.live.reindexRunId !== null &&
+ status.live.index !== status.declared.index
+ ) {
+ if (status.mappingChange !== 'identical') {
+ throw new Error(`${status.live.index} physical mapping differs from the declared mapping`);
+ }
+ return status.live.index;
+ }
+ throw new Error(
+ `${status.entity} cannot be upgraded in place (${status.classification}, mapping change: ${status.mappingChange ?? 'unknown'}); ${status.action}`,
+ );
+};
diff --git a/scripts/elasticsearchReindex/runtime/index.ts b/scripts/elasticsearchReindex/runtime/index.ts
index 7885c05511b..2c7c2810235 100644
--- a/scripts/elasticsearchReindex/runtime/index.ts
+++ b/scripts/elasticsearchReindex/runtime/index.ts
@@ -1,4 +1,5 @@
export * from './auditLogger';
export * from './checkpointRepository';
export * from './elasticsearchClient';
+export * from './generationService';
export * from './reindexService';
diff --git a/scripts/elasticsearchReindex/runtime/mappingDiff.ts b/scripts/elasticsearchReindex/runtime/mappingDiff.ts
new file mode 100644
index 00000000000..41d7f3ad424
--- /dev/null
+++ b/scripts/elasticsearchReindex/runtime/mappingDiff.ts
@@ -0,0 +1,86 @@
+import { isDeepStrictEqual } from 'node:util';
+
+import type {
+ ElasticsearchFtsSearchMappingPropertyResponse,
+ FtsSearchReindexGenerationDescription,
+} from './elasticsearchClient';
+
+export type FtsSearchMappingFieldChangeReason =
+ 'analyzer' | 'ignore_above' | 'multifields' | 'type';
+
+export interface FtsSearchMappingFieldChange {
+ field: string;
+ reasons: FtsSearchMappingFieldChangeReason[];
+}
+
+export interface FtsSearchMappingDiff {
+ /** Fields present in the declared mapping but absent from the live mapping. */
+ added: string[];
+ analysisChanged: boolean;
+ changed: FtsSearchMappingFieldChange[];
+ dynamicChanged: boolean;
+ /** Fields present in the live mapping but absent from the declared mapping. */
+ removed: string[];
+}
+
+type FtsSearchMappings = NonNullable<FtsSearchReindexGenerationDescription['mappings']>;
+
+const FIELD_REASON_ORDER: readonly FtsSearchMappingFieldChangeReason[] = [
+ 'type',
+ 'analyzer',
+ 'ignore_above',
+ 'multifields',
+];
+
+const fieldChangeReasons = (
+ live: ElasticsearchFtsSearchMappingPropertyResponse,
+ declared: ElasticsearchFtsSearchMappingPropertyResponse,
+): FtsSearchMappingFieldChangeReason[] =>
+ FIELD_REASON_ORDER.filter((reason) => {
+ switch (reason) {
+ case 'type': {
+ return live.type !== declared.type;
+ }
+ case 'analyzer': {
+ return live.analyzer !== declared.analyzer;
+ }
+ case 'ignore_above': {
+ return live.ignore_above !== declared.ignore_above;
+ }
+ case 'multifields': {
+ return !isDeepStrictEqual(live.fields ?? {}, declared.fields ?? {});
+ }
+ }
+ });
+
+/** Produces a stable, field-level explanation of a live-to-declared mapping change. */
+export const diffFtsSearchMappings = ({
+ declared,
+ declaredAnalysis,
+ live,
+ liveAnalysis,
+}: {
+ declared: FtsSearchMappings;
+ declaredAnalysis: Record<string, unknown>;
+ live: FtsSearchMappings;
+ liveAnalysis: Record<string, unknown> | null;
+}): FtsSearchMappingDiff => {
+ const declaredFields = Object.keys(declared.properties).sort();
+ const liveFields = Object.keys(live.properties).sort();
+ const added = declaredFields.filter((field) => !(field in live.properties));
+ const removed = liveFields.filter((field) => !(field in declared.properties));
+ const changed = declaredFields.flatMap((field): FtsSearchMappingFieldChange[] => {
+ const liveProperty = live.properties[field];
+ if (!liveProperty) return [];
+ const reasons = fieldChangeReasons(liveProperty, declared.properties[field]);
+ return reasons.length > 0 ? [{ field, reasons }] : [];
+ });
+
+ return {
+ added,
+ analysisChanged: !isDeepStrictEqual(liveAnalysis, declaredAnalysis),
+ changed,
+ dynamicChanged: live.dynamic !== declared.dynamic,
+ removed,
+ };
+};
diff --git a/scripts/elasticsearchReindex/runtime/migrationLock.ts b/scripts/elasticsearchReindex/runtime/migrationLock.ts
new file mode 100644
index 00000000000..7728cdb146c
--- /dev/null
+++ b/scripts/elasticsearchReindex/runtime/migrationLock.ts
@@ -0,0 +1,429 @@
+import { randomUUID } from 'node:crypto';
+
+import { z } from 'zod';
+
+import { resolveElasticsearchTransport } from '../../../packages/database/src/repositories/ftsSearch/elasticsearch/url';
+
+const CONTROL_INDEX_MARKER = 'lobehub_fts_search_control';
+const CONTROL_INDEX_SCHEMA_VERSION = 1;
+const LOCK_DOCUMENT_ID = 'migration-lock';
+const MAX_INDEX_NAME_BYTES = 255;
+const INVALID_INDEX_NAME_CHARACTERS = /[\\/*?"<>|,\s#:]/u;
+
+const controlMapping = {
+ _meta: {
+ [CONTROL_INDEX_MARKER]: true,
+ schema_version: CONTROL_INDEX_SCHEMA_VERSION,
+ },
+ dynamic: 'strict',
+ properties: {
+ acquiredAt: { type: 'date' },
+ command: { type: 'keyword' },
+ owner: { type: 'keyword' },
+ },
+} as const;
+
+const lockSourceSchema = z.object({
+ acquiredAt: z.string().datetime(),
+ command: z.string().min(1),
+ owner: z.string().min(1),
+});
+
+const lockWriteResponseSchema = z.object({
+ _primary_term: z.number().int().nonnegative(),
+ _seq_no: z.number().int().nonnegative(),
+});
+
+const createIndexResponseSchema = z.object({ acknowledged: z.literal(true) });
+const deleteLockResponseSchema = z.object({ result: z.literal('deleted') });
+
+const lockReadResponseSchema = lockWriteResponseSchema.extend({
+ _source: lockSourceSchema,
+ found: z.literal(true),
+});
+
+const controlMappingResponseSchema = z.record(
+ z.string(),
+ z.object({
+ mappings: z.object({
+ _meta: z.record(z.string(), z.unknown()).optional(),
+ dynamic: z.union([z.boolean(), z.string()]).optional(),
+ properties: z.record(z.string(), z.object({ type: z.string().optional() }).passthrough()),
+ }),
+ }),
+);
+
+export interface FtsSearchMigrationLockClientOptions {
+ /** 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;
+ namespace: string;
+ requestTimeoutMs?: number;
+ url: string;
+}
+
+export interface FtsSearchMigrationLockStatus {
+ acquiredAt: string;
+ command: string;
+ owner: string;
+ primaryTerm: number;
+ seqNo: number;
+}
+
+export type FtsSearchMigrationLockHandle = FtsSearchMigrationLockStatus;
+export type FtsSearchMigrationLockReleaseOutcome = 'already_released' | 'released';
+
+export class FtsSearchMigrationLockError extends Error {
+ readonly recoveryOwner?: string;
+ readonly status?: number;
+
+ constructor(
+ message: string,
+ options: { cause?: unknown; recoveryOwner?: string; status?: number } = {},
+ ) {
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
+ this.name = 'FtsSearchMigrationLockError';
+ this.recoveryOwner = options.recoveryOwner;
+ this.status = options.status;
+ }
+}
+
+const describeLock = (lock: FtsSearchMigrationLockStatus) =>
+ `owner ${lock.owner}, command ${lock.command}, acquired at ${lock.acquiredAt}`;
+
+const assertLegalIndexName = (index: string) => {
+ const byteLength = new TextEncoder().encode(index).byteLength;
+ if (
+ index.length === 0 ||
+ index === '.' ||
+ index === '..' ||
+ index !== index.toLowerCase() ||
+ ['-', '_', '+'].some((prefix) => index.startsWith(prefix)) ||
+ INVALID_INDEX_NAME_CHARACTERS.test(index) ||
+ byteLength > MAX_INDEX_NAME_BYTES
+ ) {
+ throw new FtsSearchMigrationLockError(
+ 'FTS search migration namespace must produce one legal lowercase Elasticsearch index name',
+ );
+ }
+};
+
+/**
+ * A namespace-wide, non-expiring Elasticsearch mutex for mapping migration operations.
+ *
+ * The lock deliberately has no lease or automatic takeover. An operator must establish that the
+ * previous owner has stopped before releasing a residual lock with its exact owner token.
+ */
+export class FtsSearchMigrationLockClient {
+ readonly controlIndex: string;
+
+ private readonly authorizationHeader: string | undefined;
+ private readonly requestTimeoutMs: number;
+ private readonly url: URL;
+
+ constructor({
+ allowInsecureHttp,
+ apiKey,
+ namespace,
+ requestTimeoutMs = 30_000,
+ url,
+ }: FtsSearchMigrationLockClientOptions) {
+ const controlIndex = `${namespace}-fts-search-control`;
+ assertLegalIndexName(controlIndex);
+ const transport = resolveElasticsearchTransport({ allowInsecureHttp, apiKey, url });
+ this.authorizationHeader = transport.authorizationHeader;
+ this.controlIndex = controlIndex;
+ this.requestTimeoutMs = requestTimeoutMs;
+ this.url = transport.url;
+ }
+
+ private async request(path: string, init: RequestInit = {}) {
+ return fetch(new URL(path, this.url), {
+ ...init,
+ headers: {
+ ...(this.authorizationHeader ? { Authorization: this.authorizationHeader } : {}),
+ ...init.headers,
+ },
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
+ });
+ }
+
+ private async readResponse(response: Response): Promise<FtsSearchMigrationLockStatus> {
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch (cause) {
+ throw new FtsSearchMigrationLockError(
+ 'Elasticsearch migration lock response has invalid JSON',
+ { cause, status: response.status },
+ );
+ }
+ const parsed = lockReadResponseSchema.safeParse(body);
+ if (!parsed.success) {
+ throw new FtsSearchMigrationLockError(
+ 'Elasticsearch migration lock response has an invalid shape',
+ { cause: parsed.error, status: response.status },
+ );
+ }
+ return {
+ ...parsed.data._source,
+ primaryTerm: parsed.data._primary_term,
+ seqNo: parsed.data._seq_no,
+ };
+ }
+
+ private async assertControlIndexMapping(): Promise<void> {
+ const response = await this.request(`/${encodeURIComponent(this.controlIndex)}/_mapping`, {
+ method: 'GET',
+ });
+ if (!response.ok) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration control index verification failed (${response.status})`,
+ { status: response.status },
+ );
+ }
+
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch (cause) {
+ throw new FtsSearchMigrationLockError(
+ 'Elasticsearch migration control index mapping has invalid JSON',
+ { cause, status: response.status },
+ );
+ }
+ const parsed = controlMappingResponseSchema.safeParse(body);
+ const mappings = parsed.success ? parsed.data[this.controlIndex]?.mappings : undefined;
+ const expectedTypes = controlMapping.properties;
+ const actualKeys = mappings ? Object.keys(mappings.properties).sort() : [];
+ const expectedKeys = Object.keys(expectedTypes).sort();
+ const isOwned = mappings?._meta?.[CONTROL_INDEX_MARKER] === true;
+ const isCompatible =
+ mappings?.dynamic === controlMapping.dynamic &&
+ mappings?._meta?.schema_version === CONTROL_INDEX_SCHEMA_VERSION &&
+ actualKeys.length === expectedKeys.length &&
+ actualKeys.every((key, index) => key === expectedKeys[index]) &&
+ expectedKeys.every(
+ (key) =>
+ mappings?.properties[key]?.type === expectedTypes[key as keyof typeof expectedTypes].type,
+ );
+
+ if (!parsed.success || !isOwned || !isCompatible) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch index ${this.controlIndex} is not a compatible LobeHub FTS migration control index; refusing to overwrite it`,
+ );
+ }
+ }
+
+ private async ensureControlIndex(): Promise<void> {
+ const response = await this.request(`/${encodeURIComponent(this.controlIndex)}`, {
+ body: JSON.stringify({
+ mappings: controlMapping,
+ settings: { number_of_shards: 1 },
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PUT',
+ });
+ if (response.ok) {
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch (cause) {
+ throw new FtsSearchMigrationLockError(
+ 'Elasticsearch migration control index creation response has invalid JSON',
+ { cause, status: response.status },
+ );
+ }
+ const parsed = createIndexResponseSchema.safeParse(body);
+ if (!parsed.success) {
+ throw new FtsSearchMigrationLockError(
+ 'Elasticsearch migration control index creation was not acknowledged',
+ { cause: parsed.error, status: response.status },
+ );
+ }
+ return;
+ }
+
+ // Concurrent creators and an already-present index both reach this path. Verification is
+ // authoritative: authentication and transport failures must never be interpreted as existence.
+ if (response.status === 400 || response.status === 409) {
+ await this.assertControlIndexMapping();
+ return;
+ }
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration control index creation failed (${response.status})`,
+ { status: response.status },
+ );
+ }
+
+ async acquire(command: string): Promise<FtsSearchMigrationLockHandle> {
+ if (command.trim().length === 0) {
+ throw new FtsSearchMigrationLockError('Migration lock command must not be empty');
+ }
+ await this.ensureControlIndex();
+
+ const owner = randomUUID();
+ const source = { acquiredAt: new Date().toISOString(), command, owner };
+ let response: Response;
+ try {
+ response = await this.request(
+ `/${encodeURIComponent(this.controlIndex)}/_create/${LOCK_DOCUMENT_ID}?refresh=wait_for`,
+ {
+ body: JSON.stringify(source),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PUT',
+ },
+ );
+ } catch (cause) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock acquisition outcome is unknown; after confirming this process stopped, inspect the lock and recover with owner ${owner}`,
+ { cause, recoveryOwner: owner },
+ );
+ }
+
+ if (response.status === 409) {
+ const current = await this.read();
+ if (!current) {
+ throw new FtsSearchMigrationLockError(
+ 'Elasticsearch reported a migration lock conflict but the current lock could not be found; retry status inspection before proceeding',
+ { status: response.status },
+ );
+ }
+ throw new FtsSearchMigrationLockError(
+ `FTS search migration is already locked by ${describeLock(current)}; confirm that owner has stopped before releasing its exact token`,
+ { status: response.status },
+ );
+ }
+ if (!response.ok) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock acquisition failed (${response.status})`,
+ { status: response.status },
+ );
+ }
+
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch (cause) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock was created for owner ${owner}, but its response has invalid JSON; inspect and recover that owner after confirming this process stopped`,
+ { cause, recoveryOwner: owner, status: response.status },
+ );
+ }
+ const parsed = lockWriteResponseSchema.safeParse(body);
+ if (!parsed.success) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock was created for owner ${owner}, but its response has an invalid shape; inspect and recover that owner after confirming this process stopped`,
+ { cause: parsed.error, recoveryOwner: owner, status: response.status },
+ );
+ }
+ return {
+ ...source,
+ primaryTerm: parsed.data._primary_term,
+ seqNo: parsed.data._seq_no,
+ };
+ }
+
+ /** Reads lock status without creating the control index or lock document. */
+ async read(): Promise<FtsSearchMigrationLockStatus | null> {
+ const response = await this.request(
+ `/${encodeURIComponent(this.controlIndex)}/_doc/${LOCK_DOCUMENT_ID}`,
+ { method: 'GET' },
+ );
+ if (response.status === 404) return null;
+ if (!response.ok) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock status failed (${response.status})`,
+ { status: response.status },
+ );
+ }
+ return this.readResponse(response);
+ }
+
+ async assertOwner(handle: FtsSearchMigrationLockHandle): Promise<void> {
+ const current = await this.read();
+ if (
+ !current ||
+ current.owner !== handle.owner ||
+ current.seqNo !== handle.seqNo ||
+ current.primaryTerm !== handle.primaryTerm
+ ) {
+ throw new FtsSearchMigrationLockError(
+ `FTS search migration lock ownership was lost for owner ${handle.owner}; stop before making further changes`,
+ );
+ }
+ }
+
+ async release(owner: string): Promise<FtsSearchMigrationLockReleaseOutcome> {
+ const current = await this.read();
+ if (!current) return 'already_released';
+ await this.assertControlIndexMapping();
+ if (current.owner !== owner) {
+ throw new FtsSearchMigrationLockError(
+ `FTS search migration lock belongs to ${describeLock(current)}; refusing release for owner ${owner}`,
+ );
+ }
+
+ const response = await this.request(
+ `/${encodeURIComponent(this.controlIndex)}/_doc/${LOCK_DOCUMENT_ID}?if_seq_no=${current.seqNo}&if_primary_term=${current.primaryTerm}&refresh=wait_for`,
+ { method: 'DELETE' },
+ );
+ if (response.status === 404) return 'already_released';
+ if (response.status === 409) {
+ throw new FtsSearchMigrationLockError(
+ `FTS search migration lock changed while releasing owner ${owner}; inspect current status and do not retry with a different token`,
+ { status: response.status },
+ );
+ }
+ if (!response.ok) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock release failed (${response.status})`,
+ { status: response.status },
+ );
+ }
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch (cause) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock release response has invalid JSON for owner ${owner}; inspect current status before retrying`,
+ { cause, status: response.status },
+ );
+ }
+ const parsed = deleteLockResponseSchema.safeParse(body);
+ if (!parsed.success) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration lock release response has an invalid shape for owner ${owner}; inspect current status before retrying`,
+ { cause: parsed.error, status: response.status },
+ );
+ }
+ return 'released';
+ }
+
+ async withLock<Result>(
+ command: string,
+ callback: (handle: FtsSearchMigrationLockHandle) => Promise<Result>,
+ ): Promise<Result> {
+ const handle = await this.acquire(command);
+ let result: Result;
+ try {
+ result = await callback(handle);
+ } catch (primaryError) {
+ /**
+ * A timed-out Elasticsearch mutation may still complete server-side. Retaining the lock keeps
+ * a second owner from racing that unknown operation. Recovery is explicit after the previous
+ * process is known to have stopped. Validation failures also retain the lock: this generic
+ * callback can mutate checkpoints and PostgreSQL, so absence of an Elasticsearch write alone
+ * cannot establish that automatic release is safe.
+ */
+ throw new FtsSearchMigrationLockError(
+ `FTS search migration failed while holding owner ${handle.owner}; the non-expiring lock was retained, so confirm this process and any Elasticsearch request have stopped before releasing that exact owner`,
+ { cause: primaryError, recoveryOwner: handle.owner },
+ );
+ }
+
+ await this.release(handle.owner);
+ return result;
+ }
+}
diff --git a/scripts/elasticsearchReindex/runtime/reindexService.ts b/scripts/elasticsearchReindex/runtime/reindexService.ts
index 7192d839e0e..f52631be7a4 100644
--- a/scripts/elasticsearchReindex/runtime/reindexService.ts
+++ b/scripts/elasticsearchReindex/runtime/reindexService.ts
@@ -2,42 +2,66 @@ import type { FtsSearchDocumentEntity } from '@lobechat/types';
import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
-import type { FtsSearchDocumentBuilder } from '../../../packages/database/src/repositories/ftsSearchDocument';
+import type {
+ FtsSearchDocumentBuilder,
+ FtsSearchIndexMeta,
+} from '../../../packages/database/src/repositories/ftsSearchDocument';
import {
+ buildFtsSearchIndexMeta,
FTS_SEARCH_INDEX_ANALYSIS,
FTS_SEARCH_INDEX_DEFINITIONS,
getFtsSearchIndexAlias,
+ getFtsSearchIndexSchemaVersion,
+ getFtsSearchPhysicalIndexName,
} from '../../../packages/database/src/repositories/ftsSearchDocument';
+import { pruneFtsSearchDocumentForMapping } from '../../../packages/database/src/repositories/ftsSearchDocument/projectionCompatibility';
import type {
FtsSearchReindexBatchFailure,
FtsSearchReindexFileRepository,
FtsSearchReindexRunState,
} from './checkpointRepository';
+import type { FtsSearchReindexGenerationDescription } from './elasticsearchClient';
+import { classifyMappingChange } from './generationService';
export interface FtsSearchReindexBulkItemResult {
error?: unknown;
status: number;
}
+/**
+ * `created`: the alias did not exist and now points at the generation. `existing`: it already did.
+ * `kept_other_generation`: it points at another generation of the same entity and was left alone;
+ * moving it is the explicit promote step.
+ */
+export type FtsSearchReindexAliasOutcome = 'created' | 'existing' | 'kept_other_generation';
+
export interface FtsSearchReindexElasticsearchClient {
bulk: (body: string) => Promise<FtsSearchReindexBulkItemResult[]>;
count: (index: string) => Promise<number>;
- ensureAlias: (alias: string, physicalIndex: string) => Promise<void>;
+ describeGenerations: (alias: string) => Promise<FtsSearchReindexGenerationDescription[]>;
+ ensureAlias: (alias: string, physicalIndex: string) => Promise<FtsSearchReindexAliasOutcome>;
ensureIndex: (
index: string,
body: FtsSearchReindexIndexBody,
options?: FtsSearchReindexIndexOptions,
) => Promise<void>;
+ putMapping: (index: string, mappings: FtsSearchReindexMappingUpgrade) => Promise<void>;
refresh: (index: string) => Promise<void>;
}
+/** Additive mapping upgrade applied to a live index: the full declared field set plus new `_meta`. */
+export interface FtsSearchReindexMappingUpgrade {
+ _meta: Required<FtsSearchIndexMeta>;
+ properties: (typeof FTS_SEARCH_INDEX_DEFINITIONS)[FtsSearchDocumentEntity]['mappings']['properties'];
+}
+
export interface FtsSearchReindexIndexOptions {
createIfMissing?: boolean;
}
export interface FtsSearchReindexIndexBody {
mappings: (typeof FTS_SEARCH_INDEX_DEFINITIONS)[FtsSearchDocumentEntity]['mappings'] & {
- _meta: { reindex_run_id: string; schema_version: number };
+ _meta: Required<FtsSearchIndexMeta>;
};
settings: { analysis: typeof FTS_SEARCH_INDEX_ANALYSIS };
}
@@ -119,6 +143,8 @@ export type FtsSearchReindexProgressEvent =
type: 'reconciliation';
}
| { type: 'aliases_created' }
+ /** Backfill finished but the alias still serves an older generation; run `--promote`. */
+ | { entities: FtsSearchDocumentEntity[]; type: 'promotion_pending' }
| { type: 'run_paused' };
export interface FtsSearchReindexResult {
@@ -373,19 +399,33 @@ export class FtsSearchReindexService {
this.options.entityConcurrency,
async ({ entity, physicalIndex, status }) => {
try {
+ if (getFtsSearchIndexSchemaVersion(entity) !== state.run.schemaVersion) {
+ /**
+ * An entity whose declared version moved on is owned by a newer generation's
+ * checkpoint. Skip it unless this invocation explicitly asked to process it, in which
+ * case the checkpoint must not silently stamp the new version onto the old index.
+ */
+ if (!this.options.entities.includes(entity)) return;
+ throw new Error(
+ `Checkpoint targets schema version ${state.run.schemaVersion} but the code declares v${getFtsSearchIndexSchemaVersion(entity)} for ${entity}; start a new run for the declared generation`,
+ );
+ }
+ const meta = buildFtsSearchIndexMeta(entity, state.run.id);
+ const rebuildIndex = getFtsSearchPhysicalIndexName(
+ state.run.namespace,
+ entity,
+ state.run.schemaVersion,
+ );
+ if (physicalIndex !== rebuildIndex && status !== 'completed') {
+ await this.upgradeIndexInPlace(state.run.namespace, entity, physicalIndex, meta);
+ }
await this.client.ensureIndex(
physicalIndex,
{
- mappings: {
- ...FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings,
- _meta: {
- reindex_run_id: state.run.id,
- schema_version: state.run.schemaVersion,
- },
- },
+ mappings: { ...FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings, _meta: meta },
settings: { analysis: FTS_SEARCH_INDEX_ANALYSIS },
},
- { createIfMissing: status !== 'completed' },
+ { createIfMissing: physicalIndex === rebuildIndex && status !== 'completed' },
);
} catch (error) {
throw new FtsSearchReindexEntityError(entity, error);
@@ -395,6 +435,43 @@ export class FtsSearchReindexService {
this.preparedRunId = state.run.id;
}
+ /**
+ * An in-place upgrade keeps the older physical index that the alias already serves and widens
+ * its mapping to the declared generation. Only an additive change qualifies; on resume the live
+ * mapping is already identical and the step is a no-op apart from restamping `_meta`. Anything
+ * else means the index was changed behind the checkpoint and needs a rebuild instead.
+ */
+ private async upgradeIndexInPlace(
+ namespace: string,
+ entity: FtsSearchDocumentEntity,
+ physicalIndex: string,
+ meta: FtsSearchReindexIndexBody['mappings']['_meta'],
+ ) {
+ const alias = getFtsSearchIndexAlias(namespace, entity);
+ const generations = await this.client.describeGenerations(alias);
+ const live = generations.find((generation) => generation.index === physicalIndex);
+ if (!live || live.state !== 'open' || !live.mappings) {
+ throw new Error(
+ `Elasticsearch index ${physicalIndex} is not an open generation of ${alias}; an in-place upgrade needs the live index`,
+ );
+ }
+ if (!live.isWriteIndex) {
+ throw new Error(
+ `Elasticsearch alias ${alias} does not serve ${physicalIndex}; upgrade the live generation in place or rebuild`,
+ );
+ }
+ const change = classifyMappingChange(entity, live.mappings, live.analysis);
+ if (change === 'breaking') {
+ throw new Error(
+ `The ${entity} mapping change is not additive; Elasticsearch cannot apply it to ${physicalIndex} in place, rebuild the generation instead`,
+ );
+ }
+ await this.client.putMapping(physicalIndex, {
+ _meta: meta,
+ properties: FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties,
+ });
+ }
+
private async flushBulk(
entity: FtsSearchDocumentEntity,
operations: BulkOperation[],
@@ -527,7 +604,12 @@ export class FtsSearchReindexService {
};
for (const document of documents) {
- const operation = buildBulkOperation(document.id, physicalIndex, revision, document.source);
+ const operation = buildBulkOperation(
+ document.id,
+ physicalIndex,
+ revision,
+ pruneFtsSearchDocumentForMapping(entity, document.source),
+ );
if (operation.bytes > this.options.bulkMaxBytes) {
failures.push({
documentId: document.id,
@@ -805,7 +887,21 @@ export class FtsSearchReindexService {
entity,
type: 'reconciliation',
});
- if (indexedCount !== finalProgress.indexedCount) {
+ /**
+ * A first install backfills into indexes nothing else writes to, so the counts must agree
+ * exactly. Once an alias serves the entity, incremental sync writes every change to all open
+ * generations while the backfill runs, so the index legitimately holds documents the backfill
+ * never saw (rows created after its scan passed, soft-delete markers). Only a shortfall is a
+ * defect then.
+ */
+ const generations = await this.client.describeGenerations(
+ getFtsSearchIndexAlias(state.run.namespace, entity),
+ );
+ const syncWritesConcurrently = generations.some((generation) => generation.aliased);
+ const mismatch = syncWritesConcurrently
+ ? indexedCount < finalProgress.indexedCount
+ : indexedCount !== finalProgress.indexedCount;
+ if (mismatch) {
throw new Error(
`Reindex count mismatch for ${entity}: checkpoint=${finalProgress.indexedCount}, Elasticsearch=${indexedCount}`,
);
@@ -911,8 +1007,22 @@ export class FtsSearchReindexService {
return this.completeEntity(state, entity);
}
- async run(namespace: string, schemaVersion: number): Promise<FtsSearchReindexResult> {
- const initialState = await this.repository.createOrResume(namespace, schemaVersion);
+ /**
+ * Backfills the `schemaVersion` generation of `runEntities` (default: every entity). Only the
+ * entities selected in `options.entities` are processed in this invocation; aliases are created
+ * once every entity of the generation is complete, and an alias already serving an older
+ * generation is left in place for `--promote`.
+ */
+ async run(
+ namespace: string,
+ schemaVersion: number,
+ runEntities: readonly FtsSearchDocumentEntity[] = FTS_SEARCH_DOCUMENT_ENTITIES,
+ ): Promise<FtsSearchReindexResult> {
+ const initialState = await this.repository.createOrResume(
+ namespace,
+ schemaVersion,
+ runEntities,
+ );
if (initialState.run.status === 'ready_for_incremental_sync') {
return {
runId: initialState.run.id,
@@ -922,8 +1032,9 @@ export class FtsSearchReindexService {
await this.prepareIndices(initialState);
+ const generationEntities = new Set(runEntities);
await mapWithConcurrency(
- this.options.entities,
+ this.options.entities.filter((entity) => generationEntities.has(entity)),
this.options.entityConcurrency,
async (entity) => {
const currentState = await this.repository.getRun(initialState.run.id);
@@ -938,20 +1049,41 @@ export class FtsSearchReindexService {
const currentState = await this.repository.getRun(initialState.run.id);
if (!currentState) throw new Error(`Missing reindex run ${initialState.run.id}`);
- if (currentState.progress.some(({ status }) => status !== 'completed')) {
+ const currentGenerationProgress = currentState.progress.filter(({ entity }) =>
+ generationEntities.has(entity),
+ );
+ if (currentGenerationProgress.length !== generationEntities.size) {
+ const missing = [...generationEntities].find(
+ (entity) => !currentGenerationProgress.some((progress) => progress.entity === entity),
+ );
+ throw new Error(`Missing reindex progress for ${missing}`);
+ }
+ if (currentGenerationProgress.some(({ status }) => status !== 'completed')) {
await this.emitProgress({ type: 'run_paused' });
return { runId: initialState.run.id, status: 'backfilling' };
}
await this.options.validateIncrementalSyncSource();
- for (const progress of currentState.progress) {
- await this.client.ensureAlias(
- getFtsSearchIndexAlias(namespace, progress.entity),
- progress.physicalIndex,
+ const outcomes = new Map<FtsSearchDocumentEntity, FtsSearchReindexAliasOutcome>();
+ for (const progress of currentGenerationProgress) {
+ outcomes.set(
+ progress.entity,
+ await this.client.ensureAlias(
+ getFtsSearchIndexAlias(namespace, progress.entity),
+ progress.physicalIndex,
+ ),
);
}
- await this.repository.markReadyForIncrementalSync(initialState.run.id);
- await this.emitProgress({ type: 'aliases_created' });
+ await this.repository.markReadyForIncrementalSync(initialState.run.id, [...generationEntities]);
+ if ([...outcomes.values()].includes('created')) {
+ await this.emitProgress({ type: 'aliases_created' });
+ }
+ const pendingPromotion = [...outcomes]
+ .filter(([, outcome]) => outcome === 'kept_other_generation')
+ .map(([entity]) => entity);
+ if (pendingPromotion.length > 0) {
+ await this.emitProgress({ entities: pendingPromotion, type: 'promotion_pending' });
+ }
return {
runId: initialState.run.id,
diff --git a/scripts/elasticsearchReindex/runtime/retiredIndexProtection.ts b/scripts/elasticsearchReindex/runtime/retiredIndexProtection.ts
new file mode 100644
index 00000000000..c73eb6ec8fc
--- /dev/null
+++ b/scripts/elasticsearchReindex/runtime/retiredIndexProtection.ts
@@ -0,0 +1,112 @@
+import { createHash } from 'node:crypto';
+
+import { z } from 'zod';
+
+export const RETIRED_INDEX_PROTECTION_OWNER = 'lobehub-fts-search-retirement';
+export const RETIRED_INDEX_PROTECTION_PRIORITY = 1_000_000;
+
+const indexTemplateSchema = z.object({
+ index_template: z
+ .object({
+ _meta: z.record(z.string(), z.unknown()).optional(),
+ allow_auto_create: z.boolean().optional(),
+ composed_of: z.array(z.string()).optional(),
+ data_stream: z.unknown().optional(),
+ index_patterns: z.array(z.string()),
+ priority: z.number().int().optional(),
+ template: z.record(z.string(), z.unknown()).optional(),
+ })
+ .passthrough(),
+ name: z.string(),
+});
+
+export const indexTemplateListResponseSchema = z.object({
+ index_templates: z.array(indexTemplateSchema),
+});
+
+export type RetiredIndexProtectionTemplate = {
+ _meta: { index: string; owner: typeof RETIRED_INDEX_PROTECTION_OWNER };
+ allow_auto_create: false;
+ index_patterns: [string];
+ priority: typeof RETIRED_INDEX_PROTECTION_PRIORITY;
+ template: Record<string, never>;
+};
+
+export const assertExactRetiredIndexName = (index: string) => {
+ if (!index || index === '_all' || /[*?,]/.test(index)) {
+ throw new Error(`Retired index target must be one exact physical index name: ${index}`);
+ }
+};
+
+export const getRetiredIndexProtectionTemplateName = (index: string) => {
+ const digest = createHash('sha256').update(index).digest('hex').slice(0, 20);
+ return `lobehub-fts-retired-${digest}`;
+};
+
+export const getRetiredIndexProtectionTemplate = (
+ index: string,
+): RetiredIndexProtectionTemplate => ({
+ _meta: { index, owner: RETIRED_INDEX_PROTECTION_OWNER },
+ allow_auto_create: false,
+ index_patterns: [index],
+ priority: RETIRED_INDEX_PROTECTION_PRIORITY,
+ template: {},
+});
+
+const wildcardMatches = (pattern: string, value: string) => {
+ const expression = [...pattern]
+ .map((character) => {
+ if (character === '*') return '.*';
+ if (character === '?') return '.';
+ return character.replaceAll(/[\\^$.*+?()[\]{}|]/g, '\\$&');
+ })
+ .join('');
+ return new RegExp(`^${expression}$`).test(value);
+};
+
+/**
+ * Confirms that the deterministic tombstone is the only composable template matching the retired
+ * physical index. This makes its `allow_auto_create: false` policy the effective winner without
+ * taking precedence over templates owned by an operator.
+ */
+export const assertRetiredIndexProtection = (
+ index: string,
+ templates: z.infer<typeof indexTemplateListResponseSchema>['index_templates'],
+) => {
+ const name = getRetiredIndexProtectionTemplateName(index);
+ const expected = getRetiredIndexProtectionTemplate(index);
+ const named = templates.find((candidate) => candidate.name === name);
+
+ const namedTemplate = named?.index_template;
+ const isOwnedAndEffective =
+ namedTemplate?._meta?.owner === RETIRED_INDEX_PROTECTION_OWNER &&
+ namedTemplate._meta.index === index &&
+ namedTemplate.allow_auto_create === false &&
+ namedTemplate.priority === RETIRED_INDEX_PROTECTION_PRIORITY &&
+ namedTemplate.data_stream === undefined &&
+ (namedTemplate.composed_of === undefined || namedTemplate.composed_of.length === 0) &&
+ isEmptyRecord(namedTemplate.template ?? {}) &&
+ namedTemplate.index_patterns.length === 1 &&
+ namedTemplate.index_patterns[0] === expected.index_patterns[0];
+
+ if (named && !isOwnedAndEffective) {
+ throw new Error(
+ `Elasticsearch index template ${name} already exists but is not owned by LobeHub retirement protection or has drifted`,
+ );
+ }
+
+ const overlapping = templates.filter(
+ (candidate) =>
+ candidate.name !== name &&
+ candidate.index_template.index_patterns.some((pattern) => wildcardMatches(pattern, index)),
+ );
+ if (overlapping.length > 0) {
+ throw new Error(
+ `Retired index ${index} overlaps external index template ${overlapping.map(({ name: candidateName }) => candidateName).join(', ')}; remove or narrow the overlap before purging`,
+ );
+ }
+
+ return named !== undefined;
+};
+
+const isEmptyRecord = (value: Record<string, unknown>) => Object.keys(value).length === 0;
diff --git a/scripts/elasticsearchReindex/startupCoordinator.ts b/scripts/elasticsearchReindex/startupCoordinator.ts
new file mode 100644
index 00000000000..aeca5220fe3
--- /dev/null
+++ b/scripts/elasticsearchReindex/startupCoordinator.ts
@@ -0,0 +1,171 @@
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+
+import type { FtsSearchEntityGenerationStatus } from './runtime/generationService';
+
+export interface FtsSearchStartupGeneration {
+ entities: FtsSearchDocumentEntity[];
+ schemaVersion: number;
+}
+
+export interface FtsSearchStartupApplyGeneration {
+ freshRun: boolean;
+ generationEntities: FtsSearchDocumentEntity[];
+ processEntities: FtsSearchDocumentEntity[];
+ schemaVersion: number;
+}
+
+interface FtsSearchStartupOutboxStats {
+ dead: number;
+ inFlight: number;
+ pending: number;
+ retrying: number;
+}
+
+interface FtsSearchStartupDrainResult {
+ hasMore: boolean;
+}
+
+interface FtsSearchStartupCoordinatorOptions {
+ applyGeneration: (options: FtsSearchStartupApplyGeneration) => Promise<void>;
+ describeEntity: (entity: FtsSearchDocumentEntity) => Promise<FtsSearchEntityGenerationStatus>;
+ drainIncrementalSync: () => Promise<FtsSearchStartupDrainResult>;
+ generations: FtsSearchStartupGeneration[];
+ maxDrainRounds?: number;
+ promoteEntity: (entity: FtsSearchDocumentEntity) => Promise<void>;
+ readCheckpointEntities: (schemaVersion: number) => Promise<FtsSearchDocumentEntity[] | undefined>;
+ readOutboxStats: () => Promise<FtsSearchStartupOutboxStats>;
+ waitForOutbox?: () => Promise<void>;
+}
+
+const unsafeClassification = new Set<FtsSearchEntityGenerationStatus['classification']>([
+ 'drift',
+ 'rollback_required',
+ 'unmanaged',
+]);
+
+/** Read-only preflight for generation states that startup automation must never repair implicitly. */
+export const assertFtsSearchStartupGenerationSafe = (status: FtsSearchEntityGenerationStatus) => {
+ if (unsafeClassification.has(status.classification)) {
+ throw new Error(
+ `Cannot automatically migrate ${status.entity}: generation is ${status.classification}. ${status.action}`,
+ );
+ }
+ for (const generation of [...status.candidates, ...(status.live ? [status.live] : [])]) {
+ if (generation.state === 'open' && !generation.fieldCompatibility?.compatible) {
+ throw new Error(
+ `Cannot automatically migrate ${status.entity}: ${generation.index} is incompatible with the current document projection`,
+ );
+ }
+ }
+ if (
+ status.classification === 'in_sync' &&
+ status.live?.backfill === 'unknown' &&
+ status.live.index !== status.declared.index
+ ) {
+ throw new Error(
+ `${status.live.index} has current in-place metadata but no checkpoint proves its backfill completed`,
+ );
+ }
+};
+
+const assertOutboxIdle = (stats: FtsSearchStartupOutboxStats) => {
+ if (stats.dead + stats.inFlight + stats.pending + stats.retrying === 0) return;
+ throw new Error(
+ `Elasticsearch startup migration left Outbox work (pending=${stats.pending}, retrying=${stats.retrying}, inFlight=${stats.inFlight}, dead=${stats.dead})`,
+ );
+};
+
+/** Runs the complete fail-closed startup migration while its caller holds the namespace lock. */
+export const runFtsSearchStartupMigration = async ({
+ applyGeneration,
+ describeEntity,
+ drainIncrementalSync,
+ generations,
+ maxDrainRounds = 1,
+ promoteEntity,
+ readCheckpointEntities,
+ readOutboxStats,
+ waitForOutbox = async () => {},
+}: FtsSearchStartupCoordinatorOptions): Promise<void> => {
+ const initialStatuses = new Map<FtsSearchDocumentEntity, FtsSearchEntityGenerationStatus>();
+ for (const { entities } of generations) {
+ for (const entity of entities) {
+ const status = await describeEntity(entity);
+ assertFtsSearchStartupGenerationSafe(status);
+ initialStatuses.set(entity, status);
+ }
+ }
+
+ for (const generation of generations) {
+ const statuses = generation.entities.map((entity) => initialStatuses.get(entity)!);
+ const changed = statuses.filter(
+ (status) => status.classification !== 'in_sync' || status.live?.backfill === 'backfilling',
+ );
+ if (changed.length === 0) continue;
+
+ const checkpointEntities = await readCheckpointEntities(generation.schemaVersion);
+ const checkpointExists = checkpointEntities !== undefined;
+ const uncheckpointedIndex = changed.find(
+ (status) =>
+ !checkpointExists &&
+ status.candidates.some((candidate) => candidate.version === status.declared.version),
+ );
+ if (uncheckpointedIndex) {
+ throw new Error(
+ `${uncheckpointedIndex.entity} has a declared generation but no checkpoint proves its backfill completed`,
+ );
+ }
+
+ const allChangedMissingAndEmpty = changed.every(
+ (status) =>
+ status.classification === 'missing' &&
+ status.live === null &&
+ status.candidates.length === 0,
+ );
+
+ await applyGeneration({
+ freshRun: !checkpointExists && allChangedMissingAndEmpty,
+ generationEntities: checkpointExists
+ ? [
+ ...new Set([
+ ...checkpointEntities.filter((entity) => generation.entities.includes(entity)),
+ ...changed.map(({ entity }) => entity),
+ ]),
+ ]
+ : changed.map(({ entity }) => entity),
+ processEntities: changed.map(({ entity }) => entity),
+ schemaVersion: generation.schemaVersion,
+ });
+ }
+
+ let caughtUp = false;
+ for (let round = 0; round < maxDrainRounds; round += 1) {
+ const drain = await drainIncrementalSync();
+ const stats = await readOutboxStats();
+ if (stats.dead > 0) assertOutboxIdle(stats);
+ if (!drain.hasMore && stats.inFlight + stats.pending + stats.retrying === 0) {
+ caughtUp = true;
+ break;
+ }
+ if (round + 1 < maxDrainRounds) await waitForOutbox();
+ }
+ if (!caughtUp) {
+ throw new Error('Elasticsearch startup migration exceeded its incremental sync drain bound');
+ }
+
+ for (const [entity, status] of initialStatuses) {
+ if (status.classification !== 'in_sync' || status.live?.backfill === 'backfilling') {
+ await promoteEntity(entity);
+ }
+ }
+
+ assertOutboxIdle(await readOutboxStats());
+ for (const entity of initialStatuses.keys()) {
+ const status = await describeEntity(entity);
+ if (status.classification !== 'in_sync' || status.live?.backfill === 'backfilling') {
+ throw new Error(
+ `Elasticsearch startup migration did not make ${entity} current (${status.classification})`,
+ );
+ }
+ }
+};
diff --git a/scripts/serverLauncher/startServer.js b/scripts/serverLauncher/startServer.js
index e1019661a14..e0618d3d007 100644
--- a/scripts/serverLauncher/startServer.js
+++ b/scripts/serverLauncher/startServer.js
@@ -15,6 +15,7 @@ const { checkDeprecatedAuth } = require(sharedModulePath);
// Set file paths
const DB_MIGRATION_SCRIPT_PATH = '/app/docker.cjs';
+const ES_MIGRATION_SCRIPT_PATH = '/app/fts-search-elasticsearch-reindex.cjs';
const SERVER_SCRIPT_PATH = '/app/server.js';
const PROXYCHAINS_CONF_PATH = '/etc/proxychains4.conf';
@@ -114,12 +115,13 @@ ${protocol} ${ip} ${port} ${user} ${pass}
};
// Function to execute a script with child process spawn
-const runScript = (scriptPath, useProxy = false) => {
+const runScript = (scriptPath, useProxy = false, args = []) => {
const command = useProxy
- ? ['/bin/proxychains', '-q', '/bin/node', scriptPath]
- : ['/bin/node', scriptPath];
+ ? ['/bin/proxychains', '-q', '/bin/node', scriptPath, ...args]
+ : ['/bin/node', scriptPath, ...args];
return new Promise((resolve, reject) => {
const process = spawn(command.shift(), command, { stdio: 'inherit' });
+ process.on('error', reject);
process.on('close', (code) =>
code === 0 ? resolve() : reject(new Error(`🔴 Process exited with code ${code}`)),
);
@@ -243,13 +245,14 @@ const runServer = async () => {
console.log('🌐 DNS Server:', dns.getServers());
console.log('-------------------------------------');
- if (process.env.DATABASE_DRIVER) {
+ const migrateElasticsearch = process.env.FTS_SEARCH_PROVIDER === 'elasticsearch';
+ if (process.env.DATABASE_DRIVER || migrateElasticsearch) {
try {
await fs.access(DB_MIGRATION_SCRIPT_PATH);
await runScript(DB_MIGRATION_SCRIPT_PATH);
} catch (err) {
- if (err.code === 'ENOENT') {
+ if (err.code === 'ENOENT' && !migrateElasticsearch) {
console.log(
`⚠️ DB Migration: Not found ${DB_MIGRATION_SCRIPT_PATH}. Skipping DB migration. Ensure to migrate database manually.`,
);
@@ -262,6 +265,19 @@ const runServer = async () => {
}
}
+ /** Search indexes must be ready before the application can accept requests. */
+ if (migrateElasticsearch) {
+ try {
+ const args = ['--startup', '--yes'];
+ if (process.env.ENABLE_TELEMETRY) args.push('--telemetry-environment=production');
+ await runScript(ES_MIGRATION_SCRIPT_PATH, false, args);
+ } catch (err) {
+ console.error('❌ Elasticsearch migration failed; application startup stopped.');
+ console.error(err);
+ process.exit(1);
+ }
+ }
+
// Start gateway in background after server is ready
startGateway();
diff --git a/scripts/serverLauncher/startServer.test.ts b/scripts/serverLauncher/startServer.test.ts
new file mode 100644
index 00000000000..78e701f4a5a
--- /dev/null
+++ b/scripts/serverLauncher/startServer.test.ts
@@ -0,0 +1,106 @@
+import { EventEmitter } from 'node:events';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import vm from 'node:vm';
+
+import { describe, expect, it } from 'vitest';
+
+const launcher = path.join(import.meta.dirname, 'startServer.js');
+
+/** Exercise the real launcher with child processes replaced by deterministic exits. */
+const launch = async (env: Record<string, string>, failure?: { code: number; script: string }) => {
+ const commands: string[][] = [];
+ const exits: number[] = [];
+ const source = await readFile(launcher, 'utf8');
+ const modules: Record<string, unknown> = {
+ 'node:child_process': {
+ spawn: (executable: string, args: string[]) => {
+ commands.push([executable, ...args]);
+ const child = new EventEmitter();
+ queueMicrotask(() => child.emit('close', args[0] === failure?.script ? failure.code : 0));
+ return child;
+ },
+ },
+ 'node:dns': { promises: { getServers: () => [] } },
+ 'node:fs': { existsSync: () => true, promises: { access: async () => undefined } },
+ 'node:path': { join: (...parts: string[]) => parts.join('/') },
+ };
+ await vm
+ .runInNewContext(source, {
+ __dirname: '/app',
+ console: { error: () => undefined, log: () => undefined, warn: () => undefined },
+ process: {
+ env,
+ exit: (code: number) => {
+ exits.push(code);
+ throw new Error('launcher exited');
+ },
+ },
+ require: (name: string) => modules[name] ?? { checkDeprecatedAuth: () => undefined },
+ })
+ .catch((error: Error) => {
+ if (error.message !== 'launcher exited') throw error;
+ });
+ return { commands, exits };
+};
+
+describe('Docker startup migrations', () => {
+ it('finishes PostgreSQL and Elasticsearch migrations before serving requests', async () => {
+ const result = await launch({ DATABASE_DRIVER: 'node', FTS_SEARCH_PROVIDER: 'elasticsearch' });
+ expect(result.commands).toEqual([
+ ['/bin/node', '/app/docker.cjs'],
+ ['/bin/node', '/app/fts-search-elasticsearch-reindex.cjs', '--startup', '--yes'],
+ ['/bin/node', '/app/server.js'],
+ ]);
+ expect(result.exits).toEqual([]);
+ });
+
+ it('runs PostgreSQL first for Elasticsearch even without an explicit driver', async () => {
+ const result = await launch({ FTS_SEARCH_PROVIDER: 'elasticsearch' });
+ expect(result.commands.map((command) => command[1])).toEqual([
+ '/app/docker.cjs',
+ '/app/fts-search-elasticsearch-reindex.cjs',
+ '/app/server.js',
+ ]);
+ });
+
+ it('supplies the migration telemetry environment when Docker telemetry is enabled', async () => {
+ const result = await launch({
+ ENABLE_TELEMETRY: '1',
+ FTS_SEARCH_PROVIDER: 'elasticsearch',
+ OTEL_EXPORTER_OTLP_ENDPOINT: 'http://collector:4318',
+ });
+ expect(result.commands).toEqual([
+ ['/bin/node', '/app/docker.cjs'],
+ [
+ '/bin/node',
+ '/app/fts-search-elasticsearch-reindex.cjs',
+ '--startup',
+ '--yes',
+ '--telemetry-environment=production',
+ ],
+ ['/bin/node', '/app/server.js'],
+ ]);
+ expect(result.exits).toEqual([]);
+ });
+
+ it('keeps PostgreSQL-only startup free of Elasticsearch operations', async () => {
+ const result = await launch({ DATABASE_DRIVER: 'node', FTS_SEARCH_PROVIDER: 'pg_search' });
+ expect(result.commands.map((command) => command[1])).toEqual([
+ '/app/docker.cjs',
+ '/app/server.js',
+ ]);
+ });
+
+ it.each(['/app/docker.cjs', '/app/fts-search-elasticsearch-reindex.cjs'])(
+ 'does not serve requests when %s fails',
+ async (script) => {
+ const result = await launch(
+ { DATABASE_DRIVER: 'node', FTS_SEARCH_PROVIDER: 'elasticsearch' },
+ { code: 1, script },
+ );
+ expect(result.commands.some((command) => command[1] === '/app/server.js')).toBe(false);
+ expect(result.exits).toEqual([1]);
+ },
+ );
+});