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(search): support current-version Elasticsearch rebuilds (#19759)

YuTengjing480c5357e53f
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index 6ad6c741c8e..de7d1c08cc0 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -152,8 +152,9 @@ declares the target and Elasticsearch records the live state, per entity:
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
+- Every physical index `<alias>-v<n>` or same-schema rebuild `<alias>-v<n>-r<runId>` carries
+ `_meta.{reindex_run_id, schema_version, schema_fingerprint}`; the alias marks the live generation.
+ A rebuild suffix is physical identity, not a schema-version bump. 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.
@@ -163,7 +164,8 @@ schema_fingerprint}`; the alias marks the live generation. Indexes created befor
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.
+- Canonical migration checkpoints remain keyed by `(namespace, schemaVersion)`. Explicit current-version
+ rebuild checkpoints add `reindexRunId`, so repeated v1 rebuilds never reuse a completed v1 cursor.
`--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
@@ -174,6 +176,13 @@ schema_fingerprint}`; the alias marks the live generation. Indexes created befor
`--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.
+- Use `--apply --rebuild-current --entity=<entity> --yes` when projection or capture semantics changed
+ without a physical mapping change and historical documents must be regenerated from PostgreSQL.
+ Deploy runtime support first: sync must recognize `-r<runId>` generations before one is created.
+ Resume with the reported `--run-id=<uuid>`. Promote with the exact
+ `--generation=<alias>-v<n>-r<uuid>` because version-only selection is ambiguous. The old generation
+ remains dual-written for rollback and becomes same-version retirement-eligible only after the
+ promotion records which live run superseded it.
- 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.
diff --git a/.agents/skills/full-text-search/references/mapping-migrations.md b/.agents/skills/full-text-search/references/mapping-migrations.md
index ad36eb6aa09..d69d4ebedb5 100644
--- a/.agents/skills/full-text-search/references/mapping-migrations.md
+++ b/.agents/skills/full-text-search/references/mapping-migrations.md
@@ -20,6 +20,10 @@ For initial provider cutover and complete environment setup, use
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.
+- Rebuild the current schema generation after a projection, eligibility, or capture behavior change
+ with `--apply --rebuild-current --entity=<entity> --yes`. This reads PostgreSQL through the current
+ document builder into `<alias>-v<n>-r<runId>` while sync dual-writes all open generations. It does
+ not bump `schemaVersion`; do not use it for a physical mapping change.
- 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;
@@ -42,6 +46,23 @@ For explicit operator control, use `bun run fts-search:reindex -- --apply --enti
target entity and confirmation. See `scripts/elasticsearchReindex/commandOptions.ts` for supported
combinations and `runtime/generationService.ts` for the operation gates.
+For a current-version rebuild, deploy the code that recognizes run-suffixed generations to every
+application and sync worker first. Then run:
+
+```bash
+bun run fts-search:reindex -- --apply --rebuild-current --entity=$ENTITY --yes
+# If interrupted, reuse the run ID printed above:
+bun run fts-search:reindex -- --apply --rebuild-current --run-id=$RUN_ID --entity=$ENTITY --yes
+# After backfill completes and the entity Outbox is idle:
+bun run fts-search:reindex -- --promote --entity=$ENTITY --generation=$INDEX --yes
+```
+
+The rebuild starts only from `in_sync` with an identical live mapping. A second unfinished
+same-version candidate blocks creation; resume its checkpoint instead of allocating another. Keep
+the old generation open through the observation window for alias rollback. Promotion stamps the old
+generation with the replacing run ID before moving the alias; only that relationship makes a detached
+same-version generation eligible for ordinary `--retire` and later `--purge`.
+
- 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
@@ -75,14 +96,16 @@ combinations and `runtime/generationService.ts` for the operation gates.
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. |
+| 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. |
+| Current-version rebuild interrupted | Resume with both `--rebuild-current` and the printed `--run-id`; omitting it requests a distinct physical generation and fails if an unfinished candidate exists. |
+| Current-version rebuild promoted | The alias and `_meta.schema_version` remain stable; only the physical name gains `-r<runId>`. Select rollback and promotion targets by exact generation. |
+| 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
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.test.ts b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
index 39a6a33d5ba..1d9a1fb9598 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.test.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
@@ -391,6 +391,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
});
it('lists every live generation behind each alias, including the writable index', async () => {
+ const rebuildRunId = '00000000-0000-4000-8000-000000000003';
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
@@ -405,6 +406,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
'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-r${rebuildRunId}`]: { aliases: {} },
'lobehub-agents-v3-backup': { aliases: {} },
}),
);
@@ -417,7 +419,12 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
await expect(
client.getFtsSearchSyncGenerationTargets(['lobehub-topics', 'lobehub-agents']),
).resolves.toEqual({
- 'lobehub-agents': ['lobehub-agents-v1', 'lobehub-agents-v2', 'lobehub-agents-v3'],
+ 'lobehub-agents': [
+ 'lobehub-agents-v1',
+ 'lobehub-agents-v2',
+ 'lobehub-agents-v3',
+ `lobehub-agents-v3-r${rebuildRunId}`,
+ ],
'lobehub-topics': ['custom-topics'],
});
expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
@@ -765,7 +772,38 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
incompatibilities: [],
});
expect(fetchMock.mock.calls[0][0].toString()).toBe(
- 'https://search.example.com/lobehub-topics-v1,lobehub-topics-v2/_mapping?filter_path=*.mappings.properties',
+ 'https://search.example.com/lobehub-topics-v1,lobehub-topics-v2/_mapping?filter_path=*.mappings._meta,*.mappings.properties',
+ );
+ });
+
+ it('validates the run identity of a same-schema rebuild target before syncing it', async () => {
+ const runId = '00000000-0000-4000-8000-000000000003';
+ const index = `lobehub-topics-v1-r${runId}`;
+ const response = (reindexRunId: string) =>
+ Response.json({
+ [index]: {
+ mappings: {
+ _meta: { reindex_run_id: reindexRunId, schema_version: 1 },
+ properties: { id: { type: 'keyword' }, title: { type: 'text' } },
+ },
+ },
+ });
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(runId))
+ .mockResolvedValueOnce(response('00000000-0000-4000-8000-000000000004'));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.getFtsSearchSyncIndexFields({ [index]: 'topics' })).resolves.toMatchObject({
+ fieldsByIndex: { [index]: ['id', 'title'] },
+ });
+ await expect(client.getFtsSearchSyncIndexFields({ [index]: 'topics' })).rejects.toThrow(
+ 'has incompatible reindex metadata',
);
});
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.ts b/apps/server/src/services/ftsSearch/elasticsearch.ts
index ae613a5c7e0..83db2545981 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.ts
@@ -14,6 +14,7 @@ import {
findFtsSearchIndexSchemaMismatch,
FTS_SEARCH_DOCUMENT_ENTITIES,
getFtsSearchIndexAlias,
+ parseFtsSearchPhysicalIndexName,
sha256Json,
} from '@/database/repositories/ftsSearchDocument';
import type { FtsSearchTargetMappingProperties } from '@/database/repositories/ftsSearchDocument/projectionCompatibility';
@@ -53,8 +54,6 @@ const bulkResponseSchema = z.object({
),
});
-const escapeRegExp = (value: string) => value.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`);
-
const aliasResponseSchema = z.record(
z.string(),
z.object({
@@ -69,6 +68,13 @@ const syncMappingResponseSchema = z.record(
z.string(),
z.object({
mappings: z.object({
+ _meta: z
+ .object({
+ reindex_run_id: z.string().uuid(),
+ schema_version: z.number().int().positive(),
+ })
+ .passthrough()
+ .optional(),
properties: z
.record(z.string(), z.object({ type: z.string().optional() }).passthrough())
.default({}),
@@ -392,9 +398,9 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
/**
* 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.
+ * them. Generations follow `<alias>-v<n>` or `<alias>-v<n>-r<run-id>`; the alias's writable index
+ * is always included even if it was named differently by an operator. Only open indexes count: a
+ * generation being retired is closed first, which drops it from this list before it is deleted.
*
* Resolved on every drain rather than cached so a generation created by a running rebuild starts
* receiving writes on the next batch, and a retired one stops without a restart.
@@ -413,9 +419,10 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
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)),
+ Object.keys(generationTable).filter(
+ (index) => parseFtsSearchPhysicalIndexName(alias, index) !== undefined,
+ ),
);
generations.add(writeIndex);
targets[alias] = [...generations].sort();
@@ -436,7 +443,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
const response = await fetch(
new URL(
- `/${indexes.map(encodeURIComponent).join(',')}/_mapping?filter_path=*.mappings.properties`,
+ `/${indexes.map(encodeURIComponent).join(',')}/_mapping?filter_path=*.mappings._meta,*.mappings.properties`,
this.url,
),
{
@@ -470,6 +477,23 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
);
}
const entity = entitiesByIndex[index];
+ if (this.indexNamespace) {
+ const identity = parseFtsSearchPhysicalIndexName(
+ getFtsSearchIndexAlias(this.indexNamespace, entity),
+ index,
+ );
+ if (identity?.reindexRunId) {
+ const meta = payload.data[index]?.mappings._meta;
+ if (
+ meta?.reindex_run_id !== identity.reindexRunId ||
+ meta.schema_version < identity.builtSchemaVersion
+ ) {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch full-text search rebuild generation ${index} has incompatible reindex metadata`,
+ );
+ }
+ }
+ }
const compatibility = getFtsSearchProjectionCompatibility(
entity,
properties satisfies FtsSearchTargetMappingProperties,
diff --git a/docs/self-hosting/advanced/full-text-search.mdx b/docs/self-hosting/advanced/full-text-search.mdx
index 203c8117f7f..d7e842a8252 100644
--- a/docs/self-hosting/advanced/full-text-search.mdx
+++ b/docs/self-hosting/advanced/full-text-search.mdx
@@ -233,6 +233,32 @@ PostgreSQL, not on the bundled node. To run them against Elastic Cloud instead,
`elasticsearch` profile out of `COMPOSE_PROFILES`, set `ES_URL` and `ES_API_KEY` in `.env`, and do
not set `ES_ALLOW_INSECURE_HTTP`; steps 2 to 4 are otherwise identical.
+### Rebuild the current Elasticsearch schema generation
+
+When a projection or capture behavior change requires every historical document to be regenerated,
+first upgrade every application and continuous-sync worker. Then build a new physical generation
+from PostgreSQL without changing the mapping version:
+
+```bash
+docker compose run --rm fts-search-reindex \
+ --apply --rebuild-current --entity=messages --yes
+```
+
+The command prints a run ID and an index such as `<namespace>-messages-v1-r<run-id>`. If interrupted,
+run the same command with `--run-id=<run-id>`. Continuous sync writes both the existing and rebuilding
+generations; do not pause application writes or the sync worker. After the backfill reports
+`ready_for_incremental_sync` and the `messages` Outbox is idle, promote the exact physical index:
+
+```bash
+docker compose run --rm fts-search-reindex \
+ --promote --entity=messages --generation=<exact-index> --yes
+```
+
+The alias and logical schema version remain unchanged. Keep the previous generation during an
+observation window so the alias can be promoted back to its exact name. Run
+`--retire --entity=messages --yes` and later `--purge --entity=messages --yes` only after rollback is
+no longer needed.
+
Security boundary of this mode: `ES_ALLOW_INSECURE_HTTP=true` permits plaintext HTTP to a
non-loopback host and lets `ES_API_KEY` be omitted. It never permits sending an API key over
plaintext HTTP, so do not combine it with `ES_API_KEY` and an `http://` URL. The Elasticsearch
diff --git a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
index 09bd3d8aeb8..654148571b9 100644
--- a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
+++ b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
@@ -190,6 +190,24 @@ Elasticsearch 单独预留至少 2 GB 内存。Linux 宿主机必须设置 `vm.m
Cloud,请不要在 `COMPOSE_PROFILES` 中启用 `elasticsearch` profile,在 `.env` 中设置 `ES_URL` 和 `ES_API_KEY`,
且不要设置 `ES_ALLOW_INSECURE_HTTP`;第 2 到第 4 步完全相同。
+### 重建当前 Elasticsearch schema generation
+
+如果投影或 capture 行为的改动要求重新生成全部历史文档,先升级所有应用和持续同步 worker,再从 PostgreSQL 创建一个 mapping 版本不变的新物理 generation:
+
+```bash
+docker compose run --rm fts-search-reindex \
+ --apply --rebuild-current --entity=messages --yes
+```
+
+命令会输出 run ID,以及类似 `<namespace>-messages-v1-r<run-id>` 的索引名。若任务中断,使用相同命令并增加 `--run-id=<run-id>` 继续。持续同步会同时写入现有 generation 和重建 generation;不要暂停应用写入或同步 worker。回填显示 `ready_for_incremental_sync` 且 `messages` Outbox 空闲后,按精确物理索引名切换:
+
+```bash
+docker compose run --rm fts-search-reindex \
+ --promote --entity=messages --generation=<精确索引名> --yes
+```
+
+alias 和逻辑 schema 版本保持不变。观察期内保留旧 generation,出现问题时可按其精确名称切回。确认无需回滚后,再依次执行 `--retire --entity=messages --yes` 和 `--purge --entity=messages --yes`。
+
这一模式的安全边界:`ES_ALLOW_INSECURE_HTTP=true` 允许向非回环主机使用明文 HTTP,并允许省略
`ES_API_KEY`;但它永远不允许通过明文 HTTP 发送 API 密钥,因此不要把它与 `ES_API_KEY` 和 `http://`
地址同时使用。Elasticsearch 服务没有公开端口,也不要为它添加端口,因为该节点接受未认证的请求。Elastic Cloud
diff --git a/packages/database/src/repositories/ftsSearchDocument/fingerprint.ts b/packages/database/src/repositories/ftsSearchDocument/fingerprint.ts
index 4b03bc1d027..0eae503f007 100644
--- a/packages/database/src/repositories/ftsSearchDocument/fingerprint.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/fingerprint.ts
@@ -45,12 +45,18 @@ export interface FtsSearchIndexMeta {
*/
schema_fingerprint?: string;
schema_version: number;
+ /** Last live run that replaced this generation; meaningful only while this index is detached. */
+ superseded_by_reindex_run_id?: string;
}
+export type FtsSearchBuiltIndexMeta = Required<
+ Pick<FtsSearchIndexMeta, 'reindex_run_id' | 'schema_fingerprint' | 'schema_version'>
+>;
+
export const buildFtsSearchIndexMeta = (
entity: FtsSearchDocumentEntity,
reindexRunId: string,
-): Required<FtsSearchIndexMeta> => ({
+): FtsSearchBuiltIndexMeta => ({
reindex_run_id: reindexRunId,
schema_fingerprint: getFtsSearchIndexSchemaFingerprint(entity),
schema_version: getFtsSearchIndexSchemaVersion(entity),
diff --git a/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts b/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
index 5511f376e2a..88784712e8f 100644
--- a/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
@@ -9,6 +9,7 @@ import {
getFtsSearchIndexAlias,
getFtsSearchIndexSchemaVersion,
getFtsSearchPhysicalIndexName,
+ parseFtsSearchPhysicalIndexName,
} from './mappings';
import { FTS_SEARCH_CURRENT_MAPPING_MIGRATIONS } from './migration';
import { FTS_SEARCH_RETAINED_SOURCE_PROPERTIES } from './policy';
@@ -97,6 +98,19 @@ describe('search index mappings', () => {
expect(getFtsSearchPhysicalIndexName('lobehub-dev', 'knowledgeBases', 4)).toBe(
'lobehub-dev-knowledge-bases-v4',
);
+ const runId = '00000000-0000-4000-8000-000000000001';
+ const rebuilt = getFtsSearchPhysicalIndexName('lobehub-dev', 'knowledgeBases', 4, runId);
+ expect(rebuilt).toBe(`lobehub-dev-knowledge-bases-v4-r${runId}`);
+ expect(parseFtsSearchPhysicalIndexName('lobehub-dev-knowledge-bases', rebuilt)).toEqual({
+ builtSchemaVersion: 4,
+ reindexRunId: runId,
+ });
+ expect(
+ parseFtsSearchPhysicalIndexName(
+ 'lobehub-dev-knowledge-bases',
+ 'lobehub-dev-knowledge-bases-v4-rnot-a-run',
+ ),
+ ).toBeUndefined();
});
it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('maps the soft-delete marker for %s', (entity) => {
diff --git a/packages/database/src/repositories/ftsSearchDocument/mappings.ts b/packages/database/src/repositories/ftsSearchDocument/mappings.ts
index 828e66bb96b..a29a1cfa27c 100644
--- a/packages/database/src/repositories/ftsSearchDocument/mappings.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/mappings.ts
@@ -93,8 +93,37 @@ const toIndexSegment = (entity: FtsSearchDocumentEntity) =>
export const getFtsSearchIndexAlias = (namespace: string, entity: FtsSearchDocumentEntity) =>
`${namespace}-${toIndexSegment(entity)}`;
+export interface FtsSearchPhysicalIndexIdentity {
+ /** Schema generation used when this physical index was first built. */
+ builtSchemaVersion: number;
+ /** Present for an explicit rebuild of the current schema generation. */
+ reindexRunId?: string;
+}
+
+const REINDEX_RUN_ID_PATTERN =
+ '[\\da-f]{8}-[\\da-f]{4}-[1-8][\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}';
+
export const getFtsSearchPhysicalIndexName = (
namespace: string,
entity: FtsSearchDocumentEntity,
version: number = getFtsSearchIndexSchemaVersion(entity),
-) => `${getFtsSearchIndexAlias(namespace, entity)}-v${version}`;
+ reindexRunId?: string,
+) =>
+ `${getFtsSearchIndexAlias(namespace, entity)}-v${version}${reindexRunId ? `-r${reindexRunId}` : ''}`;
+
+/** Parses canonical `<alias>-v<n>` and same-schema rebuild `<alias>-v<n>-r<uuid>` names. */
+export const parseFtsSearchPhysicalIndexName = (
+ alias: string,
+ index: string,
+): FtsSearchPhysicalIndexIdentity | undefined => {
+ if (!index.startsWith(`${alias}-v`)) return;
+ const suffix = index.slice(alias.length + 2);
+ const match = new RegExp(`^(\\d+)(?:-r(${REINDEX_RUN_ID_PATTERN}))?$`, 'i').exec(suffix);
+ if (!match) return;
+ const builtSchemaVersion = Number(match[1]);
+ if (!Number.isSafeInteger(builtSchemaVersion) || builtSchemaVersion < 1) return;
+ return {
+ builtSchemaVersion,
+ ...(match[2] ? { reindexRunId: match[2].toLowerCase() } : {}),
+ };
+};
diff --git a/packages/database/src/repositories/ftsSearchDocument/migration/README.md b/packages/database/src/repositories/ftsSearchDocument/migration/README.md
index 24f2ab44e2f..9cad5002807 100644
--- a/packages/database/src/repositories/ftsSearchDocument/migration/README.md
+++ b/packages/database/src/repositories/ftsSearchDocument/migration/README.md
@@ -28,3 +28,6 @@ still verify registration, current pointers, field coverage and version/fingerpr
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.
+When mapping version is unchanged but projection or capture semantics require historical repair, the
+same command can build `<alias>-v<n>-r<runId>` from PostgreSQL. The suffix identifies a physical
+generation; `_meta.schema_version` remains `n`, and the numbered mapping catalog is unchanged.
diff --git a/scripts/elasticsearchReindex/__tests__/commandOptions.test.ts b/scripts/elasticsearchReindex/__tests__/commandOptions.test.ts
index ef9d8acdd4a..866417d9149 100644
--- a/scripts/elasticsearchReindex/__tests__/commandOptions.test.ts
+++ b/scripts/elasticsearchReindex/__tests__/commandOptions.test.ts
@@ -49,10 +49,34 @@ describe('migration command intent', () => {
['--apply', '--in-place', '--fresh-run', '--yes'],
['--fresh-run'],
['--version=2'],
+ ['--apply', '--rebuild-current', '--yes'],
+ ['--apply', '--rebuild-current', '--fresh-run', '--entity=messages', '--yes'],
+ ['--apply', '--run-id=00000000-0000-4000-8000-000000000001', '--yes'],
+ ['--promote', '--generation=search-messages-v1', '--version=1', '--entity=messages', '--yes'],
])('rejects misplaced modifiers %s', (...args) => {
expect(() => resolveFtsSearchMigrationCommand(args)).toThrow();
});
+ it('accepts an explicit current-version rebuild and its run-id resume', () => {
+ expect(
+ resolveFtsSearchMigrationCommand([
+ '--apply',
+ '--rebuild-current',
+ '--entity=messages',
+ '--yes',
+ ]).command,
+ ).toBe('apply');
+ expect(
+ resolveFtsSearchMigrationCommand([
+ '--apply',
+ '--rebuild-current',
+ '--run-id=00000000-0000-4000-8000-000000000001',
+ '--entity=messages',
+ '--yes',
+ ]).command,
+ ).toBe('apply');
+ });
+
it('accepts the confirmed startup coordinator command', () => {
expect(resolveFtsSearchMigrationCommand(['--startup', '--yes']).command).toBe('startup');
expect(() => resolveFtsSearchMigrationCommand(['--startup'])).toThrow('--yes');
@@ -64,6 +88,7 @@ describe('migration command intent', () => {
'--in-place',
'--max-batches-per-entity=1',
'--version=2',
+ '--rebuild-current',
])('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__/startupCoordinator.test.ts b/scripts/elasticsearchReindex/__tests__/startupCoordinator.test.ts
index 61c7b059ac1..6094bae478e 100644
--- a/scripts/elasticsearchReindex/__tests__/startupCoordinator.test.ts
+++ b/scripts/elasticsearchReindex/__tests__/startupCoordinator.test.ts
@@ -27,6 +27,7 @@ const status = (
matchesDeclared: true,
reindexRunId: 'run-id',
state: 'open' as const,
+ supersededByReindexRunId: null,
version,
};
return {
diff --git a/scripts/elasticsearchReindex/commandOptions.ts b/scripts/elasticsearchReindex/commandOptions.ts
index f8055c3faaf..15c6b0ef9ce 100644
--- a/scripts/elasticsearchReindex/commandOptions.ts
+++ b/scripts/elasticsearchReindex/commandOptions.ts
@@ -31,8 +31,11 @@ export const resolveFtsSearchMigrationCommand = (args: readonly string[]) => {
(argument) =>
argument === '--fresh-run' ||
argument === '--in-place' ||
+ argument === '--rebuild-current' ||
argument.startsWith('--entity=') ||
+ argument.startsWith('--generation=') ||
argument.startsWith('--max-batches-per-entity=') ||
+ argument.startsWith('--run-id=') ||
argument.startsWith('--version='),
);
if (unsupported) {
@@ -45,6 +48,18 @@ export const resolveFtsSearchMigrationCommand = (args: readonly string[]) => {
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 (
+ args.includes('--rebuild-current') &&
+ (command !== 'apply' || args.includes('--fresh-run') || args.includes('--in-place'))
+ ) {
+ throw new Error('--rebuild-current can only be used with --apply by itself');
+ }
+ if (
+ args.includes('--rebuild-current') &&
+ !args.some((argument) => argument.startsWith('--entity='))
+ ) {
+ throw new Error('--rebuild-current requires at least one --entity=<entity>');
+ }
if (
(['promote', 'retire', 'purge'].includes(command) || args.includes('--in-place')) &&
!args.some((argument) => argument.startsWith('--entity='))
@@ -56,5 +71,20 @@ export const resolveFtsSearchMigrationCommand = (args: readonly string[]) => {
if (args.some((argument) => argument.startsWith('--version=')) && command !== 'promote') {
throw new Error('--version can only be used with --promote');
}
+ if (args.some((argument) => argument.startsWith('--generation=')) && command !== 'promote') {
+ throw new Error('--generation can only be used with --promote');
+ }
+ if (
+ args.some((argument) => argument.startsWith('--generation=')) &&
+ args.some((argument) => argument.startsWith('--version='))
+ ) {
+ throw new Error('--generation and --version cannot be combined');
+ }
+ if (
+ args.some((argument) => argument.startsWith('--run-id=')) &&
+ !((command === 'apply' && args.includes('--rebuild-current')) || command === 'skip-failure')
+ ) {
+ throw new Error('--run-id can only resume --apply --rebuild-current or select --skip-failure');
+ }
return { command, releaseLockOwner };
};
diff --git a/scripts/elasticsearchReindex/index.ts b/scripts/elasticsearchReindex/index.ts
index c2cb200b53a..a0f8436afdf 100644
--- a/scripts/elasticsearchReindex/index.ts
+++ b/scripts/elasticsearchReindex/index.ts
@@ -13,6 +13,7 @@ import {
FtsSearchDocumentBuilder,
getFtsSearchIndexAlias,
getFtsSearchIndexSchemaVersion,
+ getFtsSearchPhysicalIndexName,
} from '../../packages/database/src/repositories/ftsSearchDocument';
import { FtsSearchSyncOutboxRepository } from '../../packages/database/src/repositories/ftsSearchSyncOutbox';
import * as schema from '../../packages/database/src/schemas';
@@ -90,17 +91,39 @@ const readNonNegativeIntegerArgument = (name: string) => {
return value;
};
+const readStringArgument = (name: string) => {
+ const argumentsForName = process.argv.filter((item) => item.startsWith(`${name}=`));
+ if (argumentsForName.length > 1) throw new Error(`${name} may only be provided once`);
+ const value = argumentsForName[0]?.slice(name.length + 1);
+ if (value !== undefined && value.length === 0) throw new Error(`${name} requires a value`);
+ return value;
+};
+
+const readUuidArgument = (name: string) => {
+ const value = readStringArgument(name);
+ if (
+ value !== undefined &&
+ !/^[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i.test(value)
+ ) {
+ throw new Error(`${name} must be a UUID`);
+ }
+ return value?.toLowerCase();
+};
+
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 rebuildCurrent = args.has('--rebuild-current');
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 promoteVersion = readPositiveIntegerArgument('--version');
+const promoteGenerationName = readStringArgument('--generation');
+const rebuildRunId = readUuidArgument('--run-id');
const batchSize = readPositiveIntegerArgument('--batch-size');
const bulkConcurrency = readPositiveIntegerArgument('--bulk-concurrency');
const bulkMaxBytes = readPositiveIntegerArgument('--bulk-max-bytes');
@@ -120,6 +143,7 @@ const knownArguments = new Set([
'--apply',
'--fresh-run',
'--in-place',
+ '--rebuild-current',
'--promote',
'--retire',
'--purge',
@@ -140,6 +164,7 @@ const unknownArgument = process.argv
!item.startsWith('--entity=') &&
!item.startsWith('--entity-concurrency=') &&
!item.startsWith('--entity-range-concurrency=') &&
+ !item.startsWith('--generation=') &&
!item.startsWith('--elasticsearch-api-key-env=') &&
!item.startsWith('--elasticsearch-url-env=') &&
!item.startsWith('--expected-elasticsearch-host-prefix=') &&
@@ -147,6 +172,7 @@ const unknownArgument = process.argv
!item.startsWith('--max-request-retries=') &&
!item.startsWith('--request-timeout-ms=') &&
!item.startsWith('--retry-base-delay-ms=') &&
+ !item.startsWith('--run-id=') &&
!item.startsWith('--release-lock=') &&
!item.startsWith('--skip-failure=') &&
!item.startsWith('--telemetry-environment=') &&
@@ -277,8 +303,11 @@ const declaredGenerations = (): Array<[number, FtsSearchDocumentEntity[]]> => {
return [...groups].sort(([left], [right]) => left - right);
};
-const readCheckpoint = (checkpointNamespace: string, schemaVersion: number) =>
- repository.getTargetRun(checkpointNamespace, schemaVersion);
+const readCheckpoint = (
+ checkpointNamespace: string,
+ schemaVersion: number,
+ reindexRunId: string | null,
+) => repository.getGenerationRun(checkpointNamespace, schemaVersion, reindexRunId);
const generationAuditValue = (generation: FtsSearchGenerationSummary) => ({
...generation,
@@ -295,9 +324,7 @@ const generationAuditValue = (generation: FtsSearchGenerationSummary) => ({
const readStatus = async () => {
const runs = [];
- for (const [schemaVersion] of declaredGenerations()) {
- const state = await repository.getTargetRun(namespace, schemaVersion);
- if (!state) continue;
+ for (const state of await repository.listRuns(namespace)) {
const unresolvedFailures = await repository.listUnresolvedFailures(state.run.id);
runs.push({
baseRevision: state.run.baseRevision,
@@ -405,10 +432,12 @@ const run = async () => {
installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
runWithLockRetry,
run: async () => {
- const state = await repository.getTargetRun(
- namespace,
- getFtsSearchIndexSchemaVersion(failureReference.entity),
- );
+ const state = rebuildRunId
+ ? await repository.getRun(rebuildRunId)
+ : 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,
@@ -438,9 +467,11 @@ const run = async () => {
const result = await promoteGeneration({
client,
entity,
+ generation: promoteGenerationName,
namespace,
outboxStats: await outbox.stats(),
readCheckpoint,
+ validateCheckpointCapture: (runId) => repository.assertRunCaptureFingerprint(runId),
version: promoteVersion,
});
console.log(JSON.stringify({ ...result, entity, type: 'generation_promoted' }));
@@ -541,6 +572,7 @@ const run = async () => {
namespace,
outboxStats: await outbox.stats(),
readCheckpoint,
+ validateCheckpointCapture: (runId) => repository.assertRunCaptureFingerprint(runId),
});
console.log(JSON.stringify({ ...result, entity, type: 'generation_promoted' }));
},
@@ -609,12 +641,18 @@ const run = async () => {
const generations = declaredGenerations().filter(([, generationEntities]) =>
generationEntities.some((entity) => requestedEntities.has(entity)),
);
+ if (rebuildCurrent && rebuildRunId && generations.length !== 1) {
+ throw new Error('--run-id can only resume entities from one declared schema version');
+ }
for (const [schemaVersion, generationEntities] of generations) {
+ const processEntities = generationEntities.filter((entity) => requestedEntities.has(entity));
await applyGeneration({
client,
endpointHostname,
- generationEntities,
- processEntities: generationEntities.filter((entity) => requestedEntities.has(entity)),
+ generationEntities: rebuildCurrent ? processEntities : generationEntities,
+ processEntities,
+ rebuildCurrentForGeneration: rebuildCurrent,
+ rebuildRunIdForGeneration: rebuildRunId,
schemaVersion,
});
}
@@ -626,6 +664,8 @@ const applyGeneration = async ({
generationEntities,
freshRunForGeneration = freshRun,
processEntities,
+ rebuildCurrentForGeneration = false,
+ rebuildRunIdForGeneration,
schemaVersion,
}: {
client: FtsSearchReindexHttpClient;
@@ -633,15 +673,81 @@ const applyGeneration = async ({
generationEntities: FtsSearchDocumentEntity[];
freshRunForGeneration?: boolean;
processEntities: FtsSearchDocumentEntity[];
+ rebuildCurrentForGeneration?: boolean;
+ rebuildRunIdForGeneration?: string;
schemaVersion: number;
}) => {
- const existing = await repository.getTargetRun(namespace, schemaVersion);
+ const existing = rebuildCurrentForGeneration
+ ? rebuildRunIdForGeneration
+ ? await repository.getRun(rebuildRunIdForGeneration)
+ : undefined
+ : await repository.getTargetRun(namespace, schemaVersion);
+ if (
+ existing &&
+ (existing.run.namespace !== namespace || existing.run.schemaVersion !== schemaVersion)
+ ) {
+ throw new Error(
+ `Reindex run ${existing.run.id} belongs to ${existing.run.namespace} v${existing.run.schemaVersion}, not ${namespace} v${schemaVersion}`,
+ );
+ }
+ if (rebuildCurrentForGeneration && rebuildRunIdForGeneration && !existing) {
+ throw new Error(
+ `No checkpoint exists for rebuild run ${rebuildRunIdForGeneration}; restore its checkpoint or start without --run-id after removing the orphan target`,
+ );
+ }
+ const trackedEntities = existing
+ ? existing.progress.map(({ entity }) => entity)
+ : generationEntities;
+ const runEntities = rebuildCurrentForGeneration ? trackedEntities : generationEntities;
+ const missingRequestedEntity = processEntities.find(
+ (entity) => !trackedEntities.includes(entity),
+ );
+ if (missingRequestedEntity) {
+ throw new Error(
+ `Reindex run ${existing?.run.id} does not cover ${missingRequestedEntity}; start a separate current-version rebuild`,
+ );
+ }
/**
* `--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) {
+ let currentRebuildRunId: string | undefined;
+ if (rebuildCurrentForGeneration) {
+ currentRebuildRunId = existing?.run.id ?? randomUUID();
+ for (const entity of trackedEntities) {
+ const status = await describeEntityGeneration({ client, entity, namespace, readCheckpoint });
+ if (
+ status.classification !== 'in_sync' ||
+ status.mappingChange !== 'identical' ||
+ !status.live
+ ) {
+ throw new Error(
+ `${entity} cannot rebuild its current version while ${status.alias} is ${status.classification} with mapping change ${status.mappingChange ?? 'unknown'}; finish the existing schema migration first`,
+ );
+ }
+ const expectedIndex = getFtsSearchPhysicalIndexName(
+ namespace,
+ entity,
+ schemaVersion,
+ currentRebuildRunId,
+ );
+ const conflicting = status.candidates.find(
+ (candidate) =>
+ candidate.state === 'open' &&
+ candidate.version === schemaVersion &&
+ candidate.index !== expectedIndex &&
+ candidate.supersededByReindexRunId !== status.live?.reindexRunId,
+ );
+ if (conflicting) {
+ throw new Error(
+ `${conflicting.index} is an unfinished same-version generation; resume it with --run-id=${conflicting.reindexRunId ?? '<run-id>'} or retire it before starting another rebuild`,
+ );
+ }
+ const pinned = existing?.progress.find((progress) => progress.entity === entity);
+ physicalIndexes[entity] = pinned?.physicalIndex ?? expectedIndex;
+ }
+ } else if (inPlace) {
for (const entity of processEntities) {
const pinned = existing?.progress.find((progress) => progress.entity === entity);
if (pinned) {
@@ -667,7 +773,7 @@ const applyGeneration = async ({
physicalIndexes[entity] = inPlaceIndex;
}
}
- let mode: 'fresh' | 'resume' | 'upgrade' | 'upgrade_in_place';
+ let mode: 'fresh' | 'rebuild_current' | 'resume' | 'upgrade' | 'upgrade_in_place';
if (existing) {
if (freshRunForGeneration) {
throw new Error(
@@ -675,6 +781,8 @@ const applyGeneration = async ({
);
}
mode = 'resume';
+ } else if (rebuildCurrentForGeneration) {
+ mode = 'rebuild_current';
} else {
/**
* Without a checkpoint, the live aliases decide what this generation is: none exist on a
@@ -725,8 +833,9 @@ const applyGeneration = async ({
return repository.createOrResume(
namespace,
schemaVersion,
- generationEntities,
+ runEntities,
physicalIndexes,
+ currentRebuildRunId,
);
},
});
@@ -810,7 +919,7 @@ const applyGeneration = async ({
validateIncrementalSyncSource: () => outbox.assertCaptureInfrastructure(),
},
);
- const result = await service.run(namespace, schemaVersion, generationEntities);
+ const result = await service.run(namespace, schemaVersion, runEntities, prepared.run.id);
console.log(JSON.stringify(result));
const currentStatus = await printStatus();
await auditLogger.append({
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
index 694a682a11c..1d8e07d298b 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
@@ -290,6 +290,45 @@ describe('FtsSearchReindexFileRepository', () => {
expect(checkpointFiles[0]).toMatch(/^reindex-subset-search-[a-f\d]{12}-v2\.json$/);
});
+ it('keeps same-schema rebuild checkpoints separate by run ID and restores them by identity', async () => {
+ const firstRunId = '00000000-0000-4000-8000-000000000001';
+ const secondRunId = '00000000-0000-4000-8000-000000000002';
+ const first = await repository.createOrResume(
+ 'rebuild-search',
+ 1,
+ ['messages'],
+ { messages: `rebuild-search-messages-v1-r${firstRunId}` },
+ firstRunId,
+ );
+ const second = await repository.createOrResume(
+ 'rebuild-search',
+ 1,
+ ['messages'],
+ { messages: `rebuild-search-messages-v1-r${secondRunId}` },
+ secondRunId,
+ );
+
+ expect(first.run.id).toBe(firstRunId);
+ expect(second.run.id).toBe(secondRunId);
+ await expect(repository.listRuns('rebuild-search')).resolves.toHaveLength(2);
+
+ const restarted = new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: vi.fn(async () => captureFingerprint),
+ readHighWaterRevision: vi.fn(async () => revision),
+ reserveRevisionWithWriteFence: vi.fn(async () => ++revision),
+ stateDirectory,
+ });
+ await expect(restarted.getRun(secondRunId)).resolves.toMatchObject({
+ progress: [
+ expect.objectContaining({ physicalIndex: `rebuild-search-messages-v1-r${secondRunId}` }),
+ ],
+ run: { id: secondRunId },
+ });
+ await expect(
+ restarted.getGenerationRun('rebuild-search', 1, firstRunId),
+ ).resolves.toMatchObject({ run: { id: firstRunId } });
+ });
+
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',
@@ -413,12 +452,12 @@ describe('FtsSearchReindexFileRepository', () => {
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',
+ 'Expected physical index pinned-search-topics-v<n>[-r<run-id>] 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',
+ 'Expected physical index pinned-search-topics-v<n>[-r<run-id>] with n <= 2',
);
});
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
index a48b1144651..a3c46b7064a 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
@@ -367,7 +367,7 @@ describe('FtsSearchReindexHttpClient', () => {
});
await expect(client.ensureAlias('lobehub-messages', 'lobehub-messages-v2')).rejects.toThrow(
- 'Elasticsearch alias lobehub-messages points to legacy-messages-index instead of a single writable lobehub-messages-v<n> generation',
+ 'Elasticsearch alias lobehub-messages points to legacy-messages-index instead of a single writable lobehub-messages-v<n>[-r<run-id>] generation',
);
expect(fetchMock).toHaveBeenCalledOnce();
});
@@ -691,6 +691,29 @@ describe('FtsSearchReindexHttpClient', () => {
).rejects.toThrow('Elasticsearch mapping upgrade failed for lobehub-messages-v1 (400)');
});
+ it('marks a detached generation with the run that superseded it', async () => {
+ const successor = '00000000-0000-4000-8000-000000000002';
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ response({ 'lobehub-messages-v1': { mappings: { _meta: reindexMeta } } }),
+ )
+ .mockResolvedValueOnce(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.markGenerationSuperseded('lobehub-messages-v1', successor),
+ ).resolves.toBeUndefined();
+ expect(String(fetchMock.mock.calls[0][0])).toContain('filter_path=*.mappings._meta');
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
+ _meta: { ...reindexMeta, superseded_by_reindex_run_id: successor },
+ });
+ });
+
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);
@@ -1019,6 +1042,12 @@ 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);
+ expect(
+ parseGenerationVersion(
+ 'lobehub-messages',
+ 'lobehub-messages-v1-r00000000-0000-4000-8000-000000000001',
+ ),
+ ).toBe(1);
});
it('returns undefined for an index outside the alias naming scheme', () => {
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
index b4b3dcccb91..d11f5b612f3 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
@@ -109,15 +109,18 @@ const originalDeclaredVersions = FTS_SEARCH_DOCUMENT_ENTITIES.map(
const buildMeta = ({
fingerprint = DECLARED_FINGERPRINT,
reindexRunId = '00000000-0000-4000-8000-000000000001',
+ supersededByReindexRunId,
version,
}: {
fingerprint?: string | null;
reindexRunId?: string;
+ supersededByReindexRunId?: string;
version: number;
}): NonNullable<FtsSearchReindexGenerationDescription['meta']> => ({
reindex_run_id: reindexRunId,
schema_version: version,
...(fingerprint === null ? {} : { schema_fingerprint: fingerprint }),
+ ...(supersededByReindexRunId ? { superseded_by_reindex_run_id: supersededByReindexRunId } : {}),
});
const buildGeneration = (
@@ -160,6 +163,9 @@ const createClient = (generations: FtsSearchReindexGenerationDescription[]) => (
ensureRetiredIndexProtection: vi
.fn<FtsSearchGenerationElasticsearchClient['ensureRetiredIndexProtection']>()
.mockResolvedValue(),
+ markGenerationSuperseded: vi
+ .fn<FtsSearchGenerationElasticsearchClient['markGenerationSuperseded']>()
+ .mockResolvedValue(),
promoteAlias: vi.fn<FtsSearchGenerationElasticsearchClient['promoteAlias']>().mockResolvedValue(),
});
@@ -193,8 +199,11 @@ const createRunState = (
});
const createCheckpointReader = (
- states: Record<number, FtsSearchReindexRunState | undefined> = {},
-): FtsSearchGenerationCheckpointReader => vi.fn(async (_namespace, version) => states[version]);
+ states: Record<string | number, FtsSearchReindexRunState | undefined> = {},
+): FtsSearchGenerationCheckpointReader =>
+ vi.fn(async (_namespace, version, runId) =>
+ runId && Object.hasOwn(states, runId) ? states[runId] : states[version],
+ );
beforeEach(() => vi.clearAllMocks());
afterEach(() => {
@@ -420,15 +429,19 @@ describe('promoteGeneration', () => {
const promote = ({
entity = ENTITY,
+ generation,
generations,
outboxStats = IDLE_OUTBOX,
states = {},
+ validateCheckpointCapture = vi.fn(async () => {}),
version,
}: {
entity?: FtsSearchDocumentEntity;
+ generation?: string;
generations: FtsSearchReindexGenerationDescription[];
outboxStats?: FtsSearchSyncOutboxStats;
- states?: Record<number, FtsSearchReindexRunState | undefined>;
+ states?: Record<string | number, FtsSearchReindexRunState | undefined>;
+ validateCheckpointCapture?: (runId: string) => Promise<void>;
version?: number;
}) => {
const client = createClient(generations);
@@ -437,9 +450,11 @@ describe('promoteGeneration', () => {
result: promoteGeneration({
client,
entity,
+ generation,
namespace: NAMESPACE,
outboxStats,
readCheckpoint: createCheckpointReader(states),
+ validateCheckpointCapture,
version,
}),
};
@@ -462,6 +477,53 @@ describe('promoteGeneration', () => {
[physicalIndex(1)],
physicalIndex(2),
);
+ expect(client.markGenerationSuperseded).toHaveBeenCalledExactlyOnceWith(
+ physicalIndex(1),
+ '00000000-0000-4000-8000-000000000001',
+ );
+ });
+
+ it('requires and promotes an exact physical generation when the schema version is unchanged', async () => {
+ setDeclaredVersion(ENTITY, 1);
+ const liveRunId = '00000000-0000-4000-8000-000000000001';
+ const rebuildRunId = '00000000-0000-4000-8000-000000000002';
+ const rebuildIndex = getFtsSearchPhysicalIndexName(NAMESPACE, ENTITY, 1, rebuildRunId);
+ const rebuildState = createRunState(1, 'completed');
+ rebuildState.run.id = rebuildRunId;
+ rebuildState.progress.find(({ entity }) => entity === ENTITY)!.physicalIndex = rebuildIndex;
+ const validateCheckpointCapture = vi.fn(async () => {});
+ const generations = [
+ buildManagedGeneration(1, {
+ isWriteIndex: true,
+ meta: buildMeta({ reindexRunId: liveRunId, version: 1 }),
+ }),
+ buildManagedGeneration(1, {
+ aliased: false,
+ index: rebuildIndex,
+ meta: buildMeta({ reindexRunId: rebuildRunId, version: 1 }),
+ }),
+ ];
+
+ const ambiguous = promote({ generations, states: { [rebuildRunId]: rebuildState } });
+ await expect(ambiguous.result).rejects.toThrow('Multiple v1 generations exist');
+
+ const selected = promote({
+ generation: rebuildIndex,
+ generations,
+ states: { [rebuildRunId]: rebuildState },
+ validateCheckpointCapture,
+ });
+ await expect(selected.result).resolves.toEqual({
+ alias: ALIAS,
+ from: [physicalIndex(1)],
+ outcome: 'promoted',
+ to: rebuildIndex,
+ });
+ expect(validateCheckpointCapture).toHaveBeenCalledExactlyOnceWith(rebuildRunId);
+ expect(selected.client.markGenerationSuperseded).toHaveBeenCalledExactlyOnceWith(
+ physicalIndex(1),
+ rebuildRunId,
+ );
});
it('rejects when the target generation does not exist', async () => {
@@ -726,6 +788,30 @@ describe('retireGenerations', () => {
expect(client.deleteIndex).not.toHaveBeenCalled();
});
+ it('retires a same-version generation only after the live run marked it superseded', async () => {
+ const liveRunId = '00000000-0000-4000-8000-000000000002';
+ const rebuiltIndex = getFtsSearchPhysicalIndexName(NAMESPACE, ENTITY, 1, liveRunId);
+ const previous = buildManagedGeneration(1, {
+ aliased: false,
+ meta: buildMeta({ supersededByReindexRunId: liveRunId, version: 1 }),
+ });
+ const live = buildManagedGeneration(1, {
+ index: rebuiltIndex,
+ isWriteIndex: true,
+ meta: buildMeta({ reindexRunId: liveRunId, version: 1 }),
+ });
+ const { client, result } = retire({ generations: [previous, live] });
+
+ await expect(result).resolves.toMatchObject({ closed: [physicalIndex(1)], kept: rebuiltIndex });
+ expect(client.closeIndex).toHaveBeenCalledExactlyOnceWith(physicalIndex(1));
+
+ const unmarked = retire({
+ generations: [buildManagedGeneration(1, { aliased: false }), live],
+ });
+ await expect(unmarked.result).resolves.toMatchObject({ closed: [] });
+ expect(unmarked.client.closeIndex).not.toHaveBeenCalled();
+ });
+
it.each(['open', 'closed'] as const)(
'preserves an alias-attached generation in the %s state alongside the write index',
async (state) => {
@@ -837,7 +923,7 @@ describe('planRetiredGenerations', () => {
alreadyClosed: [physicalIndex(2)],
blockedBy: [
`${physicalIndex(0)} has no known managed reindex identity`,
- `${physicalIndex(4)} is not older than the live generation`,
+ `${physicalIndex(4)} is neither older than the live generation nor marked as superseded by it`,
],
close: [physicalIndex(1)],
purgeCandidates: [physicalIndex(2)],
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
index 298d88ccbeb..7f04bcef827 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
@@ -439,6 +439,24 @@ describe('FtsSearchReindexService', () => {
});
});
+ it('creates a run-suffixed same-schema generation instead of treating it as in-place', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const runId = '00000000-0000-4000-8000-000000000001';
+ state.run.id = runId;
+ state.progress.find(({ entity }) => entity === 'agents')!.physicalIndex =
+ `test-agents-v1-r${runId}`;
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await service.prepareIndices(state);
+
+ expect(client.ensureIndex).toHaveBeenCalledWith(
+ `test-agents-v1-r${runId}`,
+ expect.any(Object),
+ { createIfMissing: true },
+ );
+ expect(client.putMapping).not.toHaveBeenCalled();
+ });
+
it('attributes index preparation failures to their entity', async () => {
const { builder, client, repository, state } = createDependencies();
vi.mocked(client.ensureIndex).mockImplementation(async (index) => {
diff --git a/scripts/elasticsearchReindex/runtime/checkpointRepository.ts b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
index 6d115eaa3e4..e6e8050e25e 100644
--- a/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
+++ b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
@@ -1,5 +1,5 @@
import { createHash, randomUUID } from 'node:crypto';
-import { mkdir, open, readFile, rename, stat, unlink } from 'node:fs/promises';
+import { mkdir, open, readdir, readFile, rename, stat, unlink } from 'node:fs/promises';
import path from 'node:path';
import type {
@@ -14,6 +14,7 @@ import { z } from 'zod';
import {
getFtsSearchIndexAlias,
getFtsSearchPhysicalIndexName,
+ parseFtsSearchPhysicalIndexName,
} from '../../../packages/database/src/repositories/ftsSearchDocument';
export interface FtsSearchReindexBatchFailure {
@@ -155,14 +156,19 @@ const checkpointSchema = z
* 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)) {
+ const identity = parseFtsSearchPhysicalIndexName(alias, progress.physicalIndex);
+ const validVersion =
+ identity &&
+ identity.builtSchemaVersion >= 1 &&
+ identity.builtSchemaVersion <= checkpoint.run.schemaVersion;
+ const validRunIdentity =
+ !identity?.reindexRunId ||
+ identity.builtSchemaVersion < checkpoint.run.schemaVersion ||
+ identity.reindexRunId === checkpoint.run.id;
+ if (!validVersion || !validRunIdentity) {
context.addIssue({
code: 'custom',
- message: `Expected physical index ${alias}-v<n> with n <= ${checkpoint.run.schemaVersion}`,
+ message: `Expected physical index ${alias}-v<n>[-r<run-id>] with n <= ${checkpoint.run.schemaVersion} and the checkpoint run ID on same-version rebuilds`,
path: ['progress', progress.entity, 'physicalIndex'],
});
}
@@ -176,10 +182,10 @@ const errorMessage = (error: unknown) =>
const now = () => new Date().toISOString();
-const checkpointFileName = (namespace: string, schemaVersion: number) => {
+const checkpointFileName = (namespace: string, schemaVersion: number, runId?: string) => {
const safeNamespace = namespace.replaceAll(/[^\w-]/g, '_').slice(0, 80) || 'search';
const namespaceHash = createHash('sha256').update(namespace).digest('hex').slice(0, 12);
- return `${CHECKPOINT_FILE_PREFIX}${safeNamespace}-${namespaceHash}-v${schemaVersion}.json`;
+ return `${CHECKPOINT_FILE_PREFIX}${safeNamespace}-${namespaceHash}-v${schemaVersion}${runId ? `-r${runId}` : ''}.json`;
};
const stateOf = ({ progress, run }: FtsSearchReindexCheckpointFile): FtsSearchReindexRunState => ({
@@ -221,18 +227,39 @@ export class FtsSearchReindexFileRepository {
this.stateDirectory = path.resolve(options.stateDirectory);
}
- private checkpointPath(namespace: string, schemaVersion: number) {
- return path.join(this.stateDirectory, checkpointFileName(namespace, schemaVersion));
+ private checkpointPath(namespace: string, schemaVersion: number, runId?: string) {
+ return path.join(this.stateDirectory, checkpointFileName(namespace, schemaVersion, runId));
}
private async findCheckpointPath(runId: string): Promise<string | undefined> {
const checkpointPath = this.runPaths.get(runId);
- if (!checkpointPath) return;
- const checkpoint = await this.readCheckpoint(checkpointPath);
+ if (checkpointPath) {
+ const checkpoint = await this.readCheckpoint(checkpointPath);
+ if (checkpoint.run.id !== runId) {
+ throw new Error(`FTS reindex checkpoint run ID changed unexpectedly: ${checkpointPath}`);
+ }
+ return checkpointPath;
+ }
+ const files = await readdir(this.stateDirectory).catch((error) => {
+ if (isMissingFileError(error)) return [];
+ throw error;
+ });
+ const matching = files.filter(
+ (file) => file.startsWith(CHECKPOINT_FILE_PREFIX) && file.endsWith(`-r${runId}.json`),
+ );
+ if (matching.length > 1) {
+ throw new Error(`Multiple FTS reindex checkpoints claim run ${runId}`);
+ }
+ if (matching.length === 0) return;
+ const discoveredPath = path.join(this.stateDirectory, matching[0]);
+ const checkpoint = await this.readCheckpoint(discoveredPath);
if (checkpoint.run.id !== runId) {
- throw new Error(`FTS reindex checkpoint run ID changed unexpectedly: ${checkpointPath}`);
+ throw new Error(
+ `FTS reindex checkpoint run ID does not match its filename: ${discoveredPath}`,
+ );
}
- return checkpointPath;
+ this.runPaths.set(runId, discoveredPath);
+ return discoveredPath;
}
private stateOf(
@@ -460,6 +487,7 @@ export class FtsSearchReindexFileRepository {
schemaVersion: number,
entities: readonly FtsSearchDocumentEntity[] = FTS_SEARCH_DOCUMENT_ENTITIES,
physicalIndexes: Partial<Record<FtsSearchDocumentEntity, string>> = {},
+ runId?: string,
): Promise<FtsSearchReindexRunState> {
if (entities.length === 0)
throw new Error('A reindex generation must cover at least one entity');
@@ -499,7 +527,7 @@ export class FtsSearchReindexFileRepository {
}
return changed;
};
- const checkpointPath = this.checkpointPath(namespace, schemaVersion);
+ const checkpointPath = this.checkpointPath(namespace, schemaVersion, runId);
const existing = await this.readCheckpointIfExists(checkpointPath);
if (existing) {
this.assertCaptureFingerprint(existing, await this.readCaptureFingerprint());
@@ -550,7 +578,7 @@ export class FtsSearchReindexFileRepository {
baseRevision,
captureFingerprint,
createdAt: timestamp,
- id: randomUUID(),
+ id: runId ?? randomUUID(),
namespace,
schemaVersion,
status: 'backfilling',
@@ -565,18 +593,57 @@ export class FtsSearchReindexFileRepository {
async getTargetRun(
namespace: string,
schemaVersion: number,
+ runId?: string,
): Promise<FtsSearchReindexRunState | undefined> {
- const checkpointPath = this.checkpointPath(namespace, schemaVersion);
+ const checkpointPath = this.checkpointPath(namespace, schemaVersion, runId);
const checkpoint = await this.readCheckpointIfExists(checkpointPath);
return checkpoint ? this.stateOf(checkpointPath, checkpoint) : undefined;
}
+ async getGenerationRun(
+ namespace: string,
+ schemaVersion: number,
+ runId: string | null,
+ ): Promise<FtsSearchReindexRunState | undefined> {
+ if (!runId) return this.getTargetRun(namespace, schemaVersion);
+ const rebuilt = await this.getTargetRun(namespace, schemaVersion, runId);
+ if (rebuilt) return rebuilt;
+ const canonical = await this.getTargetRun(namespace, schemaVersion);
+ return canonical?.run.id === runId ? canonical : undefined;
+ }
+
+ async listRuns(namespace?: string): Promise<FtsSearchReindexRunState[]> {
+ const files = await readdir(this.stateDirectory).catch((error) => {
+ if (isMissingFileError(error)) return [];
+ throw error;
+ });
+ const runs: FtsSearchReindexRunState[] = [];
+ for (const file of files.filter(
+ (item) => item.startsWith(CHECKPOINT_FILE_PREFIX) && item.endsWith('.json'),
+ )) {
+ const checkpointPath = path.join(this.stateDirectory, file);
+ const checkpoint = await this.readCheckpoint(checkpointPath);
+ if (namespace && checkpoint.run.namespace !== namespace) continue;
+ runs.push(this.stateOf(checkpointPath, checkpoint));
+ }
+ return runs.sort((left, right) => left.run.createdAt.localeCompare(right.run.createdAt));
+ }
+
async getRun(runId: string): Promise<FtsSearchReindexRunState | undefined> {
const checkpointPath = await this.findCheckpointPath(runId);
if (!checkpointPath) return;
return this.stateOf(checkpointPath, await this.readCheckpoint(checkpointPath));
}
+ async assertRunCaptureFingerprint(runId: string): Promise<void> {
+ const checkpointPath = await this.findCheckpointPath(runId);
+ if (!checkpointPath) throw new Error(`Missing reindex run ${runId}`);
+ this.assertCaptureFingerprint(
+ await this.readCheckpoint(checkpointPath),
+ await this.readCaptureFingerprint(),
+ );
+ }
+
async listUnresolvedFailures(runId: string, entity?: FtsSearchDocumentEntity) {
const checkpointPath = await this.findCheckpointPath(runId);
if (!checkpointPath) throw new Error(`Missing reindex run ${runId}`);
diff --git a/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
index b8549d102d0..5a60834ce73 100644
--- a/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
+++ b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
@@ -3,6 +3,7 @@ import { isDeepStrictEqual } from 'node:util';
import { z } from 'zod';
import { resolveElasticsearchTransport } from '../../../packages/database/src/repositories/ftsSearch/elasticsearch/url';
+import { parseFtsSearchPhysicalIndexName } from '../../../packages/database/src/repositories/ftsSearchDocument';
import type {
FtsSearchReindexAliasOutcome,
FtsSearchReindexBulkItemResult,
@@ -74,6 +75,20 @@ const mappingResponseSchema = z.record(
}),
);
+const indexMetaResponseSchema = z.record(
+ z.string(),
+ z.object({
+ mappings: z.object({
+ _meta: z.object({
+ reindex_run_id: z.string(),
+ schema_fingerprint: z.string().optional(),
+ schema_version: z.number().int().positive(),
+ superseded_by_reindex_run_id: z.string().optional(),
+ }),
+ }),
+ }),
+);
+
const catIndicesResponseSchema = z.array(z.object({ index: z.string(), status: z.string() }));
const generationDetailSchema = z.record(
@@ -85,6 +100,7 @@ const generationDetailSchema = z.record(
reindex_run_id: z.string().optional(),
schema_fingerprint: z.string().optional(),
schema_version: z.number().int().positive().optional(),
+ superseded_by_reindex_run_id: z.string().optional(),
})
.passthrough()
.optional(),
@@ -107,6 +123,7 @@ export interface FtsSearchReindexGenerationDescription {
reindex_run_id?: string;
schema_fingerprint?: string;
schema_version?: number;
+ superseded_by_reindex_run_id?: string;
} | null;
/** Closed generations are mid-retirement: sync no longer targets them, deletion comes next. */
state: 'closed' | 'open';
@@ -122,16 +139,14 @@ export interface FtsSearchReindexGenerationDescription {
* 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);
+ const built = parseFtsSearchPhysicalIndexName(alias, index)?.builtSchemaVersion;
if (built === undefined) return null;
return stampedVersion ?? built;
};
-/** Generation number of `index` if it is named `<alias>-v<n>`. */
+/** Generation number of a canonical or same-schema rebuild physical index. */
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;
+ return parseFtsSearchPhysicalIndexName(alias, index)?.builtSchemaVersion;
};
const settingsResponseSchema = z.record(
@@ -384,7 +399,7 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
return 'kept_other_generation';
}
throw new FtsSearchReindexRequestError(
- `Elasticsearch alias ${alias} points to ${targets.map(([index]) => index).join(', ') || 'no index'} instead of a single writable ${alias}-v<n> generation`,
+ `Elasticsearch alias ${alias} points to ${targets.map(([index]) => index).join(', ') || 'no index'} instead of a single writable ${alias}-v<n>[-r<run-id>] generation`,
);
}
if (response.status !== 404) {
@@ -545,6 +560,48 @@ export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearch
await this.assertAcknowledged(response, `alias promotion for ${alias}`);
}
+ async markGenerationSuperseded(index: string, supersededByReindexRunId: string): Promise<void> {
+ const metaResponse = await this.request(
+ `/${encodeURIComponent(index)}/_mapping?filter_path=*.mappings._meta`,
+ { method: 'GET' },
+ );
+ if (!metaResponse.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch generation metadata lookup failed for ${index} (${metaResponse.status})`,
+ metaResponse.status,
+ );
+ }
+ const parsed = indexMetaResponseSchema.safeParse(await metaResponse.json());
+ const meta = parsed.success ? parsed.data[index]?.mappings._meta : undefined;
+ if (!parsed.success || !meta) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch generation metadata response has an invalid shape for ${index}`,
+ metaResponse.status,
+ parsed.success ? undefined : parsed.error,
+ );
+ }
+ if (meta.superseded_by_reindex_run_id === supersededByReindexRunId) return;
+
+ await this.beforeMutation();
+ const response = await this.request(`/${encodeURIComponent(index)}/_mapping`, {
+ body: JSON.stringify({
+ _meta: {
+ ...meta,
+ superseded_by_reindex_run_id: supersededByReindexRunId,
+ },
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PUT',
+ });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch generation supersession failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ await this.assertAcknowledged(response, `generation supersession for ${index}`);
+ }
+
async closeIndex(index: string): Promise<void> {
await this.beforeMutation();
const response = await this.request(`/${encodeURIComponent(index)}/_close`, { method: 'POST' });
diff --git a/scripts/elasticsearchReindex/runtime/generationService.ts b/scripts/elasticsearchReindex/runtime/generationService.ts
index 3bb45535c79..93ed05fa5f2 100644
--- a/scripts/elasticsearchReindex/runtime/generationService.ts
+++ b/scripts/elasticsearchReindex/runtime/generationService.ts
@@ -7,6 +7,7 @@ import {
getFtsSearchIndexSchemaFingerprint,
getFtsSearchIndexSchemaVersion,
getFtsSearchPhysicalIndexName,
+ parseFtsSearchPhysicalIndexName,
} 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';
@@ -21,6 +22,7 @@ export interface FtsSearchGenerationElasticsearchClient {
deleteIndex: (index: string) => Promise<void>;
describeGenerations: (alias: string) => Promise<FtsSearchReindexGenerationDescription[]>;
ensureRetiredIndexProtection: (index: string) => Promise<void>;
+ markGenerationSuperseded: (index: string, supersededByReindexRunId: string) => Promise<void>;
promoteAlias: (alias: string, from: readonly string[], to: string) => Promise<void>;
}
@@ -28,6 +30,7 @@ export interface FtsSearchGenerationElasticsearchClient {
export type FtsSearchGenerationCheckpointReader = (
namespace: string,
schemaVersion: number,
+ reindexRunId: string | null,
) => Promise<FtsSearchReindexRunState | undefined>;
/**
@@ -62,6 +65,7 @@ export interface FtsSearchGenerationSummary {
matchesDeclared: boolean;
reindexRunId: string | null;
state: 'closed' | 'open';
+ supersededByReindexRunId: string | null;
version: number | null;
}
@@ -135,6 +139,7 @@ const summarize = (
(fingerprint === null || fingerprint === getFtsSearchIndexSchemaFingerprint(entity)),
reindexRunId: generation.meta?.reindex_run_id ?? null,
state: generation.state,
+ supersededByReindexRunId: generation.meta?.superseded_by_reindex_run_id ?? null,
version: generation.meta?.schema_version ?? generation.version,
};
};
@@ -159,23 +164,34 @@ export const describeEntityGeneration = async ({
};
const generations = await client.describeGenerations(alias);
- const checkpoints = new Map<number, FtsSearchReindexRunState | undefined>();
- const checkpointFor = async (version: number | null) => {
+ const checkpoints = new Map<string, FtsSearchReindexRunState | undefined>();
+ const checkpointFor = async (version: number | null, reindexRunId: string | null) => {
if (version === null) return;
- if (!checkpoints.has(version)) {
- checkpoints.set(version, await readCheckpoint(namespace, version));
+ const key = `${version}:${reindexRunId ?? 'canonical'}`;
+ if (!checkpoints.has(key)) {
+ checkpoints.set(key, await readCheckpoint(namespace, version, reindexRunId));
}
- return checkpoints.get(version);
+ return checkpoints.get(key);
};
const liveGeneration = generations.find((generation) => generation.isWriteIndex);
const live = liveGeneration
- ? summarize(entity, liveGeneration, await checkpointFor(liveGeneration.version))
+ ? summarize(
+ entity,
+ liveGeneration,
+ await checkpointFor(liveGeneration.version, liveGeneration.meta?.reindex_run_id ?? null),
+ )
: null;
const candidates: FtsSearchGenerationSummary[] = [];
for (const generation of generations) {
if (generation === liveGeneration) continue;
- candidates.push(summarize(entity, generation, await checkpointFor(generation.version)));
+ candidates.push(
+ summarize(
+ entity,
+ generation,
+ await checkpointFor(generation.version, generation.meta?.reindex_run_id ?? null),
+ ),
+ );
}
const mappingDiff =
liveGeneration?.mappings && liveGeneration.state === 'open'
@@ -243,9 +259,12 @@ export const describeEntityGeneration = async ({
export interface FtsSearchPromoteGenerationOptions {
client: FtsSearchGenerationElasticsearchClient;
entity: FtsSearchDocumentEntity;
+ /** Exact target required when more than one physical generation implements the same version. */
+ generation?: string;
namespace: string;
outboxStats: FtsSearchSyncOutboxStats;
readCheckpoint: FtsSearchGenerationCheckpointReader;
+ validateCheckpointCapture?: (runId: string) => Promise<void>;
/** Target generation; defaults to the declared version. Any other existing version is a rollback. */
version?: number;
}
@@ -266,19 +285,40 @@ export interface FtsSearchPromoteGenerationResult {
export const promoteGeneration = async ({
client,
entity,
+ generation,
namespace,
outboxStats,
readCheckpoint,
- version = getFtsSearchIndexSchemaVersion(entity),
+ validateCheckpointCapture = async () => {},
+ version: requestedVersion,
}: 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,
- );
+ const available = [...status.candidates, ...(status.live ? [status.live] : [])];
+ const version = requestedVersion ?? getFtsSearchIndexSchemaVersion(entity);
+ const versionTargets = available.filter((candidate) => candidate.version === version);
+ const target = generation
+ ? available.find((candidate) => candidate.index === generation)
+ : versionTargets.length === 1
+ ? versionTargets[0]
+ : undefined;
if (!target) {
+ if (!generation && versionTargets.length > 1) {
+ throw new Error(
+ `Multiple v${version} generations exist for ${alias}; choose one with --generation=<exact-index>`,
+ );
+ }
throw new Error(`No v${version} generation exists for ${alias}; run --apply first`);
}
+ const targetVersion = generation && requestedVersion === undefined ? target.version : version;
+ if (targetVersion === null) {
+ throw new Error(`${target.index} carries no managed schema version and cannot be promoted`);
+ }
+ if (target.version !== targetVersion) {
+ throw new Error(
+ `${target.index} implements v${target.version ?? 'unknown'}, not the requested v${targetVersion}`,
+ );
+ }
if (target.state !== 'open') {
throw new Error(`${target.index} is closed (being retired) and cannot be promoted`);
}
@@ -298,14 +338,14 @@ export const promoteGeneration = async ({
`${target.index} requires source fields the current projection cannot preserve: ${details}; retain compatible source bridge fields before promoting`,
);
}
- if (version === getFtsSearchIndexSchemaVersion(entity) && !target.matchesDeclared) {
+ if (targetVersion === getFtsSearchIndexSchemaVersion(entity) && !target.matchesDeclared) {
throw new Error(
- `${target.index} was not built from the declared v${version} mapping; rebuild it before promoting`,
+ `${target.index} was not built from the declared v${targetVersion} mapping; rebuild it before promoting`,
);
}
if (
status.live?.index === target.index &&
- version === getFtsSearchIndexSchemaVersion(entity) &&
+ targetVersion === getFtsSearchIndexSchemaVersion(entity) &&
status.mappingChange !== 'identical'
) {
throw new Error(
@@ -315,6 +355,9 @@ export const promoteGeneration = async ({
if (target.backfill === 'backfilling') {
throw new Error(`${target.index} backfill is incomplete; finish --apply --entity=${entity}`);
}
+ if (target.backfill !== 'unknown' && target.reindexRunId) {
+ await validateCheckpointCapture(target.reindexRunId);
+ }
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`);
@@ -326,7 +369,7 @@ export const promoteGeneration = async ({
`${target.index} has no checkpoint and no reindex _meta, so its contents cannot be trusted`,
);
}
- if (target.backfill === 'unknown' && version > (status.live?.version ?? 0)) {
+ if (target.backfill === 'unknown' && (targetVersion ?? 0) > (status.live?.version ?? 0)) {
throw new Error(
`No checkpoint proves ${target.index} finished its backfill; keep ES_REINDEX_STATE_DIR from the --apply run`,
);
@@ -341,6 +384,12 @@ export const promoteGeneration = async ({
}
const from = status.live ? [status.live.index] : [];
+ if (!target.reindexRunId) {
+ throw new Error(`${target.index} carries no managed reindex identity and cannot be promoted`);
+ }
+ for (const previous of from) {
+ await client.markGenerationSuperseded(previous, target.reindexRunId);
+ }
await client.promoteAlias(alias, from, target.index);
return { alias, from, outcome: 'promoted', to: target.index };
};
@@ -372,10 +421,8 @@ const isKnownManagedGeneration = (
alias: string,
generation: FtsSearchGenerationSummary,
): boolean => {
- const suffix = generation.index.slice(`${alias}-v`.length);
return (
- generation.index.startsWith(`${alias}-v`) &&
- /^\d+$/.test(suffix) &&
+ parseFtsSearchPhysicalIndexName(alias, generation.index) !== undefined &&
generation.reindexRunId !== null &&
generation.version !== null
);
@@ -394,7 +441,10 @@ const isRetirementCandidate = (
liveVersion !== null &&
liveVersion !== undefined &&
candidate.version !== null &&
- candidate.version < liveVersion
+ (candidate.version < liveVersion ||
+ (candidate.version === liveVersion &&
+ status.live?.reindexRunId !== null &&
+ candidate.supersededByReindexRunId === status.live?.reindexRunId))
);
};
@@ -420,7 +470,9 @@ export const planRetiredGenerations = (
continue;
}
if (!isRetirementCandidate(status, candidate)) {
- blockedBy.push(`${candidate.index} is not older than the live generation`);
+ blockedBy.push(
+ `${candidate.index} is neither older than the live generation nor marked as superseded by it`,
+ );
continue;
}
if (candidate.backfill === 'backfilling') {
diff --git a/scripts/elasticsearchReindex/runtime/reindexService.ts b/scripts/elasticsearchReindex/runtime/reindexService.ts
index f52631be7a4..3abec816e71 100644
--- a/scripts/elasticsearchReindex/runtime/reindexService.ts
+++ b/scripts/elasticsearchReindex/runtime/reindexService.ts
@@ -3,8 +3,8 @@ import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import type {
+ FtsSearchBuiltIndexMeta,
FtsSearchDocumentBuilder,
- FtsSearchIndexMeta,
} from '../../../packages/database/src/repositories/ftsSearchDocument';
import {
buildFtsSearchIndexMeta,
@@ -13,6 +13,7 @@ import {
getFtsSearchIndexAlias,
getFtsSearchIndexSchemaVersion,
getFtsSearchPhysicalIndexName,
+ parseFtsSearchPhysicalIndexName,
} from '../../../packages/database/src/repositories/ftsSearchDocument';
import { pruneFtsSearchDocumentForMapping } from '../../../packages/database/src/repositories/ftsSearchDocument/projectionCompatibility';
import type {
@@ -51,7 +52,7 @@ export interface FtsSearchReindexElasticsearchClient {
/** Additive mapping upgrade applied to a live index: the full declared field set plus new `_meta`. */
export interface FtsSearchReindexMappingUpgrade {
- _meta: Required<FtsSearchIndexMeta>;
+ _meta: FtsSearchBuiltIndexMeta;
properties: (typeof FTS_SEARCH_INDEX_DEFINITIONS)[FtsSearchDocumentEntity]['mappings']['properties'];
}
@@ -61,7 +62,7 @@ export interface FtsSearchReindexIndexOptions {
export interface FtsSearchReindexIndexBody {
mappings: (typeof FTS_SEARCH_INDEX_DEFINITIONS)[FtsSearchDocumentEntity]['mappings'] & {
- _meta: Required<FtsSearchIndexMeta>;
+ _meta: FtsSearchBuiltIndexMeta;
};
settings: { analysis: typeof FTS_SEARCH_INDEX_ANALYSIS };
}
@@ -416,7 +417,15 @@ export class FtsSearchReindexService {
entity,
state.run.schemaVersion,
);
- if (physicalIndex !== rebuildIndex && status !== 'completed') {
+ const physicalIdentity = parseFtsSearchPhysicalIndexName(
+ getFtsSearchIndexAlias(state.run.namespace, entity),
+ physicalIndex,
+ );
+ const createsNewIndex =
+ physicalIndex === rebuildIndex ||
+ (physicalIdentity?.builtSchemaVersion === state.run.schemaVersion &&
+ physicalIdentity.reindexRunId === state.run.id);
+ if (!createsNewIndex && status !== 'completed') {
await this.upgradeIndexInPlace(state.run.namespace, entity, physicalIndex, meta);
}
await this.client.ensureIndex(
@@ -425,7 +434,7 @@ export class FtsSearchReindexService {
mappings: { ...FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings, _meta: meta },
settings: { analysis: FTS_SEARCH_INDEX_ANALYSIS },
},
- { createIfMissing: physicalIndex === rebuildIndex && status !== 'completed' },
+ { createIfMissing: createsNewIndex && status !== 'completed' },
);
} catch (error) {
throw new FtsSearchReindexEntityError(entity, error);
@@ -1017,12 +1026,20 @@ export class FtsSearchReindexService {
namespace: string,
schemaVersion: number,
runEntities: readonly FtsSearchDocumentEntity[] = FTS_SEARCH_DOCUMENT_ENTITIES,
+ runId?: string,
): Promise<FtsSearchReindexResult> {
- const initialState = await this.repository.createOrResume(
- namespace,
- schemaVersion,
- runEntities,
- );
+ const initialState = runId
+ ? await this.repository.getRun(runId)
+ : await this.repository.createOrResume(namespace, schemaVersion, runEntities);
+ if (!initialState) throw new Error(`Missing reindex run ${runId}`);
+ if (
+ initialState.run.namespace !== namespace ||
+ initialState.run.schemaVersion !== schemaVersion
+ ) {
+ throw new Error(
+ `Reindex run ${initialState.run.id} belongs to ${initialState.run.namespace} v${initialState.run.schemaVersion}, not ${namespace} v${schemaVersion}`,
+ );
+ }
if (initialState.run.status === 'ready_for_incremental_sync') {
return {
runId: initialState.run.id,