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.

⚡ perf: accelerate and harden Elasticsearch reindex recovery (#18902)

YuTengjing321bfe86233f
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index 69c87a56945..68f260a8f2b 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -28,8 +28,9 @@ router/service -> createFtsSearchRepo -> FtsSearchRepo -> selected backend -> ex
- `packages/database/src/schemas/ftsSearchSyncOutbox.ts` and
`packages/database/src/repositories/ftsSearchSyncOutbox/` own durable change capture, claims,
retries, dead letters, leases, revision fences, and capture-definition validation.
-- `packages/database/src/repositories/ftsSearchReindex/` and `scripts/elasticsearchReindex/` own the
- resumable full backfill. `apps/server/src/services/ftsSearchSync/` and
+- `scripts/elasticsearchReindex/` owns the resumable full-backfill command and its operational
+ runtime. Shared database source queries and document construction remain in
+ `packages/database/src/repositories/ftsSearchDocument/`. `apps/server/src/services/ftsSearchSync/` and
`scripts/elasticsearchSync/` own continuous incremental draining.
- `packages/env/src/ftsSearch.ts` owns generic Elasticsearch environment variables.
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.test.ts b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
index 8bf6a61ae02..06300a5becf 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.test.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
@@ -240,18 +240,12 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
Response.json({
'lobehub-agents-v2': {
mappings: {
- fts_search_sync_deleted: {
- full_name: 'fts_search_sync_deleted',
- mapping: { fts_search_sync_deleted: { type: 'boolean' } },
- },
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
},
},
'lobehub-topics-v2': {
mappings: {
- fts_search_sync_deleted: {
- full_name: 'fts_search_sync_deleted',
- mapping: { fts_search_sync_deleted: { type: 'boolean' } },
- },
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
},
},
}),
@@ -267,7 +261,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
).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-v2,lobehub-topics-v2/_mapping/field/fts_search_sync_deleted',
+ 'https://search.example.com/lobehub-agents-v2,lobehub-topics-v2?filter_path=*.mappings.properties.fts_search_sync_deleted',
]);
});
@@ -286,16 +280,12 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
Response.json({
'lobehub-agents-v2': {
mappings: {
- fts_search_sync_deleted: {
- mapping: { fts_search_sync_deleted: { type: 'boolean' } },
- },
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
},
},
'lobehub-topics-v2': {
mappings: {
- fts_search_sync_deleted: {
- mapping: { fts_search_sync_deleted: { type: 'boolean' } },
- },
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
},
},
}),
@@ -505,9 +495,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {
Response.json({
'lobehub-agents-v2': {
mappings: {
- fts_search_sync_deleted: {
- mapping: { fts_search_sync_deleted: { type: 'boolean' } },
- },
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
},
},
}),
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.ts b/apps/server/src/services/ftsSearch/elasticsearch.ts
index b5d8033d66e..e61c47c983e 100644
--- a/apps/server/src/services/ftsSearch/elasticsearch.ts
+++ b/apps/server/src/services/ftsSearch/elasticsearch.ts
@@ -46,15 +46,12 @@ const aliasResponseSchema = z.record(
}),
);
-const fieldMappingResponseSchema = z.record(
+const syncMappingResponseSchema = z.record(
z.string(),
z.object({
- mappings: z.record(
- z.string(),
- z.object({
- mapping: z.record(z.string(), z.object({ type: z.string() }).passthrough()),
- }),
- ),
+ mappings: z.object({
+ properties: z.record(z.string(), z.object({ type: z.string() }).passthrough()).default({}),
+ }),
}),
);
@@ -223,7 +220,10 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
const physicalPath = [...new Set(writeTargets.values())].map(encodeURIComponent).join(',');
const mappingResponse = await fetch(
- new URL(`/${physicalPath}/_mapping/field/fts_search_sync_deleted`, this.url),
+ new URL(
+ `/${physicalPath}?filter_path=*.mappings.properties.fts_search_sync_deleted`,
+ this.url,
+ ),
{
headers: { Authorization: `ApiKey ${this.apiKey}` },
method: 'GET',
@@ -237,7 +237,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
);
}
- const mappingPayload = fieldMappingResponseSchema.safeParse(await mappingResponse.json());
+ const mappingPayload = syncMappingResponseSchema.safeParse(await mappingResponse.json());
if (!mappingPayload.success) {
throw new ElasticsearchFtsSearchRequestError(
'Elasticsearch full-text search sync mapping response has an invalid shape',
@@ -247,8 +247,9 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC
}
for (const [alias, physicalIndex] of writeTargets) {
- const mapping = mappingPayload.data[physicalIndex]?.mappings.fts_search_sync_deleted;
- if (mapping?.mapping.fts_search_sync_deleted?.type !== 'boolean') {
+ const mapping =
+ mappingPayload.data[physicalIndex]?.mappings.properties.fts_search_sync_deleted;
+ if (mapping?.type !== 'boolean') {
throw new ElasticsearchFtsSearchRequestError(
`Elasticsearch full-text search sync alias lacks a boolean fts_search_sync_deleted mapping: ${alias}`,
);
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.mdx b/docs/self-hosting/advanced/elasticsearch-migration.mdx
index f0141315362..2b876044d82 100644
--- a/docs/self-hosting/advanced/elasticsearch-migration.mdx
+++ b/docs/self-hosting/advanced/elasticsearch-migration.mdx
@@ -101,6 +101,10 @@ 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:
```bash
@@ -149,7 +153,7 @@ 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 --bulk-max-bytes=10485760 \
+ --batch-size=5000 --entity-batch-size=documents:1000 --bulk-max-bytes=10485760 \
--max-batches-per-entity=1
```
@@ -164,7 +168,24 @@ continue until every entity completes.
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.
+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
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
index 6507fb657cd..4b9710a5c08 100644
--- a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
+++ b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
@@ -74,6 +74,8 @@ tags:
## 在源码中运行
+包命令会先打包,再用 Node.js 运行回填任务。请使用这里记录的包命令,不要直接执行 TypeScript 入口,以确保运行前准备和临时文件清理方式一致。
+
只查看状态,不写 Elasticsearch:
```bash
@@ -106,13 +108,18 @@ 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 --bulk-max-bytes=10485760 \
+ --batch-size=5000 --entity-batch-size=documents:1000 --bulk-max-bytes=10485760 \
--max-batches-per-entity=1
```
这条命令会创建 14 类索引,并向其中有源数据的索引写入真实数据。只要至少一类数据超过批次上限,任务就会保持在 `backfilling` 状态且不会创建别名;如果某个小型部署的 14 类数据都能在上限内读完,本次演练仍会正常完成并创建别名,因此必须使用隔离的空 Elasticsearch 目标。使用同一命令再次执行可以验证断点续跑;移除 `--max-batches-per-entity` 后会从当前断点继续,直到所有数据类型完成。
-`--entity-concurrency` 控制同时读取多少类 PostgreSQL 数据,`--bulk-concurrency` 控制每个数据类型的单批数据可同时发出多少个按字节拆分的 Elasticsearch 请求。应从较小数值开始,仅在 PostgreSQL 和 Elasticsearch 运行稳定时逐步增加。`--batch-size` 限制每次按主键翻页读取的 PostgreSQL 行数;`--bulk-max-bytes` 按编码后的字节数限制单次 `_bulk` 请求。单个文档超过限制时会被明确记为失败,不会静默跳过。
+`--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` 调整。
diff --git a/package.json b/package.json
index 609aa7976c8..5827e46a667 100644
--- a/package.json
+++ b/package.json
@@ -89,7 +89,7 @@
"e2e": "cd e2e && npm run test",
"e2e:install": "playwright install",
"e2e:ui": "playwright test --ui",
- "fts-search:reindex": "bun run scripts/elasticsearchReindex/index.ts",
+ "fts-search:reindex": "node scripts/elasticsearchReindex/runner.mjs",
"fts-search:sync": "cross-env MIGRATION_DB=1 bun run scripts/elasticsearchSync/cli.ts",
"hotfix:branch": "tsx ./scripts/hotfixWorkflow/index.ts",
"i18n": "npm run workflow:i18n && lobe-i18n && prettier -c --write \"locales/**\"",
diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
index e5ca3311d83..b4f4218097f 100644
--- a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
@@ -286,6 +286,22 @@ describe('FtsSearchDocumentBuilder', () => {
expect(second.map(({ id }) => id)).toEqual(['agent-2']);
});
+ it('uses inclusive lower and exclusive upper bounds for parallel range batches', async () => {
+ await expect(
+ builder.buildRangeBatch('messages', {
+ beforeId: 'message-2',
+ fromId: 'message-1',
+ limit: 10,
+ }),
+ ).resolves.toMatchObject([{ id: 'message-1' }]);
+ await expect(
+ builder.buildRangeBatch('messages', { afterId: 'message-1', limit: 10 }),
+ ).resolves.toEqual([]);
+ await expect(
+ builder.buildRangeBatch('messages', { beforeId: 'message-1', limit: 10 }),
+ ).resolves.toEqual([]);
+ });
+
it('normalizes duplicate IDs and omits missing source records', async () => {
const result = await builder.buildByIds('agents', ['missing', 'agent-1', 'agent-1']);
@@ -296,6 +312,13 @@ describe('FtsSearchDocumentBuilder', () => {
await expect(builder.buildBatch('agents', { limit: 0 })).rejects.toThrow(
'FTS search document batch limit must be a positive integer',
);
+ await expect(
+ builder.buildRangeBatch('messages', {
+ afterId: 'message-1',
+ fromId: 'message-1',
+ limit: 1,
+ }),
+ ).rejects.toThrow('cannot use afterId and fromId together');
});
it('lists file and file-backed document keys affected by KB relation changes', async () => {
diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.ts b/packages/database/src/repositories/ftsSearchDocument/builder.ts
index ece1a21bb3b..6e854c9ce8b 100644
--- a/packages/database/src/repositories/ftsSearchDocument/builder.ts
+++ b/packages/database/src/repositories/ftsSearchDocument/builder.ts
@@ -1,4 +1,4 @@
-import { and, asc, eq, gt, inArray, or, sql } from 'drizzle-orm';
+import { and, asc, eq, gt, gte, inArray, lt, or, sql } from 'drizzle-orm';
import {
agents,
@@ -28,6 +28,8 @@ import { FTS_SEARCH_DOCUMENT_ENTITIES, parseFtsSearchDocumentSource } from './sc
interface FtsSearchDocumentSelection {
afterId?: string;
+ beforeId?: string;
+ fromId?: string;
ids?: string[];
limit: number;
}
@@ -37,6 +39,13 @@ export interface FtsSearchDocumentBatchOptions {
limit: number;
}
+export interface FtsSearchDocumentRangeBatchOptions {
+ afterId?: string;
+ beforeId?: string;
+ fromId?: string;
+ limit: number;
+}
+
export type FtsSearchDocumentRelationChange =
| { fileIds: readonly string[]; relation: 'knowledgeBaseFiles' }
| { memoryIds: readonly string[]; relation: 'userMemoryReferences' };
@@ -104,6 +113,27 @@ export class FtsSearchDocumentBuilder {
return this.build(entity, { afterId, limit });
}
+ /**
+ * Build one bounded keyset page for the two high-volume entities supported by parallel backfill.
+ * `fromId` is inclusive for the first page of a range; later pages continue with `afterId`.
+ */
+ async buildRangeBatch(
+ entity: 'documents' | 'messages',
+ { afterId, beforeId, fromId, limit }: FtsSearchDocumentRangeBatchOptions,
+ ): Promise<FtsSearchBuiltDocument[]> {
+ if (!Number.isInteger(limit) || limit < 1) {
+ throw new Error('FTS search document batch limit must be a positive integer');
+ }
+ if (afterId && fromId) {
+ throw new Error('FTS search document range cannot use afterId and fromId together');
+ }
+ if (beforeId && (afterId ?? fromId) && beforeId <= (afterId ?? fromId)!) {
+ throw new Error('FTS search document range must have ascending ID boundaries');
+ }
+
+ return this.build(entity, { afterId, beforeId, fromId, limit });
+ }
+
async buildByIds(
entity: FtsSearchDocumentEntity,
sourceIds: readonly string[],
@@ -900,9 +930,14 @@ export class FtsSearchDocumentBuilder {
.where(
selection.ids
? inArray(documents.id, selection.ids)
- : selection.afterId
- ? gt(documents.id, selection.afterId)
- : undefined,
+ : and(
+ selection.afterId
+ ? gt(documents.id, selection.afterId)
+ : selection.fromId
+ ? gte(documents.id, selection.fromId)
+ : undefined,
+ selection.beforeId ? lt(documents.id, selection.beforeId) : undefined,
+ ),
)
.orderBy(asc(documents.id))
.limit(selection.limit);
@@ -972,9 +1007,14 @@ export class FtsSearchDocumentBuilder {
.where(
selection.ids
? inArray(messages.id, selection.ids)
- : selection.afterId
- ? gt(messages.id, selection.afterId)
- : undefined,
+ : and(
+ selection.afterId
+ ? gt(messages.id, selection.afterId)
+ : selection.fromId
+ ? gte(messages.id, selection.fromId)
+ : undefined,
+ selection.beforeId ? lt(messages.id, selection.beforeId) : undefined,
+ ),
)
.orderBy(asc(messages.id))
.limit(selection.limit);
diff --git a/scripts/elasticsearchReindex/__tests__/options.test.ts b/scripts/elasticsearchReindex/__tests__/options.test.ts
index 744b4b8dc2d..0ee6b5eedf6 100644
--- a/scripts/elasticsearchReindex/__tests__/options.test.ts
+++ b/scripts/elasticsearchReindex/__tests__/options.test.ts
@@ -2,11 +2,94 @@ import { describe, expect, it } from 'vitest';
import {
assertFtsSearchReindexElasticsearchHostname,
+ assertFtsSearchReindexRangeCollation,
assertFtsSearchReindexTelemetryExportConfigured,
+ resolveFtsSearchReindexBatchSizeByEntity,
resolveFtsSearchReindexElasticsearchEnvironment,
+ resolveFtsSearchReindexEntities,
+ resolveFtsSearchReindexRangeConcurrencyByEntity,
resolveFtsSearchReindexTelemetryEnvironment,
} from '../options';
+describe('resolveFtsSearchReindexRangeConcurrencyByEntity', () => {
+ it('accepts repeatable high-volume entity concurrency', () => {
+ expect(
+ resolveFtsSearchReindexRangeConcurrencyByEntity([
+ '--entity-range-concurrency=documents:4',
+ '--entity-range-concurrency=messages:9',
+ ]),
+ ).toEqual({ documents: 4, messages: 9 });
+ });
+
+ it('rejects unsupported entities, invalid concurrency, and duplicates', () => {
+ expect(() =>
+ resolveFtsSearchReindexRangeConcurrencyByEntity(['--entity-range-concurrency=agents:2']),
+ ).toThrow('supports only documents and messages');
+ expect(() =>
+ resolveFtsSearchReindexRangeConcurrencyByEntity(['--entity-range-concurrency=messages:0']),
+ ).toThrow('<entity>:<positive-integer>');
+ expect(() =>
+ resolveFtsSearchReindexRangeConcurrencyByEntity([
+ '--entity-range-concurrency=messages:2',
+ '--entity-range-concurrency=messages:4',
+ ]),
+ ).toThrow('provided more than once');
+ });
+
+ it('requires bytewise PostgreSQL collation only when parallel ranges are enabled', () => {
+ expect(() => assertFtsSearchReindexRangeCollation('C.UTF-8', { messages: 9 })).not.toThrow();
+ expect(() => assertFtsSearchReindexRangeCollation('en_US.UTF-8', {})).not.toThrow();
+ expect(() => assertFtsSearchReindexRangeCollation('en_US.UTF-8', { messages: 9 })).toThrow(
+ 'require a bytewise database collation',
+ );
+ });
+});
+
+describe('resolveFtsSearchReindexEntities', () => {
+ it('accepts a repeatable subset while leaving the default unspecified', () => {
+ expect(resolveFtsSearchReindexEntities([])).toBeUndefined();
+ expect(resolveFtsSearchReindexEntities(['--entity=documents', '--entity=messages'])).toEqual([
+ 'documents',
+ 'messages',
+ ]);
+ });
+
+ it('rejects unknown and duplicate entities', () => {
+ expect(() => resolveFtsSearchReindexEntities(['--entity=unknown'])).toThrow(
+ 'unknown search entity',
+ );
+ expect(() =>
+ resolveFtsSearchReindexEntities(['--entity=messages', '--entity=messages']),
+ ).toThrow('provided more than once');
+ });
+});
+
+describe('resolveFtsSearchReindexBatchSizeByEntity', () => {
+ it('accepts repeatable per-entity page-size overrides', () => {
+ expect(
+ resolveFtsSearchReindexBatchSizeByEntity([
+ '--entity-batch-size=documents:1000',
+ '--entity-batch-size=messages:5000',
+ ]),
+ ).toEqual({ documents: 1000, messages: 5000 });
+ });
+
+ it('rejects unknown entities, invalid sizes, and duplicate overrides', () => {
+ expect(() =>
+ resolveFtsSearchReindexBatchSizeByEntity(['--entity-batch-size=unknown:1']),
+ ).toThrow('unknown search entity');
+ expect(() =>
+ resolveFtsSearchReindexBatchSizeByEntity(['--entity-batch-size=documents:0']),
+ ).toThrow('<entity>:<positive-integer>');
+ expect(() =>
+ resolveFtsSearchReindexBatchSizeByEntity([
+ '--entity-batch-size=documents:1000',
+ '--entity-batch-size=documents:500',
+ ]),
+ ).toThrow('provided more than once');
+ });
+});
+
describe('resolveFtsSearchReindexElasticsearchEnvironment', () => {
it('uses the canonical pair by default', () => {
expect(resolveFtsSearchReindexElasticsearchEnvironment([])).toEqual({
diff --git a/scripts/elasticsearchReindex/index.ts b/scripts/elasticsearchReindex/index.ts
index fcc085d3240..720bae18f65 100644
--- a/scripts/elasticsearchReindex/index.ts
+++ b/scripts/elasticsearchReindex/index.ts
@@ -10,15 +10,6 @@ import {
FTS_SEARCH_INDEX_SCHEMA_VERSION,
FtsSearchDocumentBuilder,
} from '../../packages/database/src/repositories/ftsSearchDocument';
-import {
- type FtsSearchReindexAuditValue,
- FtsSearchReindexEntityError,
- FtsSearchReindexFileLogger,
- FtsSearchReindexFileRepository,
- FtsSearchReindexHttpClient,
- FtsSearchReindexService,
- summarizeFtsSearchReindexError,
-} from '../../packages/database/src/repositories/ftsSearchReindex';
import { FtsSearchSyncOutboxRepository } from '../../packages/database/src/repositories/ftsSearchSyncOutbox';
import * as schema from '../../packages/database/src/schemas';
import {
@@ -32,11 +23,24 @@ import { DiagLogLevel, register, shutdownSafely } from '../../packages/observabi
import { runWithLockRetry } from '../migrateServerDB/retry';
import {
assertFtsSearchReindexElasticsearchHostname,
+ assertFtsSearchReindexRangeCollation,
assertFtsSearchReindexTelemetryExportConfigured,
+ resolveFtsSearchReindexBatchSizeByEntity,
resolveFtsSearchReindexElasticsearchEnvironment,
+ resolveFtsSearchReindexEntities,
+ resolveFtsSearchReindexRangeConcurrencyByEntity,
resolveFtsSearchReindexTelemetryEnvironment,
} from './options';
import { runFtsSearchReindexCommand } from './preparation';
+import {
+ type FtsSearchReindexAuditValue,
+ FtsSearchReindexEntityError,
+ FtsSearchReindexFileLogger,
+ FtsSearchReindexFileRepository,
+ FtsSearchReindexHttpClient,
+ FtsSearchReindexService,
+ summarizeFtsSearchReindexError,
+} from './runtime';
const { Pool } = pg;
@@ -75,6 +79,11 @@ const yes = args.has('--yes');
const batchSize = readPositiveIntegerArgument('--batch-size');
const bulkConcurrency = readPositiveIntegerArgument('--bulk-concurrency');
const bulkMaxBytes = readPositiveIntegerArgument('--bulk-max-bytes');
+const batchSizeByEntity = resolveFtsSearchReindexBatchSizeByEntity(process.argv.slice(2));
+const entities = resolveFtsSearchReindexEntities(process.argv.slice(2));
+const rangeConcurrencyByEntity = resolveFtsSearchReindexRangeConcurrencyByEntity(
+ process.argv.slice(2),
+);
const entityConcurrency = readPositiveIntegerArgument('--entity-concurrency');
const maxBatchesPerEntity = readPositiveIntegerArgument('--max-batches-per-entity');
const maxRequestRetries = readNonNegativeIntegerArgument('--max-request-retries');
@@ -92,7 +101,10 @@ const unknownArgument = process.argv
!item.startsWith('--batch-size=') &&
!item.startsWith('--bulk-concurrency=') &&
!item.startsWith('--bulk-max-bytes=') &&
+ !item.startsWith('--entity-batch-size=') &&
+ !item.startsWith('--entity=') &&
!item.startsWith('--entity-concurrency=') &&
+ !item.startsWith('--entity-range-concurrency=') &&
!item.startsWith('--elasticsearch-api-key-env=') &&
!item.startsWith('--elasticsearch-url-env=') &&
!item.startsWith('--expected-elasticsearch-host-prefix=') &&
@@ -297,6 +309,15 @@ const run = async () => {
return;
}
+ if (Object.values(rangeConcurrencyByEntity).some((concurrency) => concurrency > 1)) {
+ const collationResult = await pool.query<{ datcollate: string }>(
+ 'SELECT datcollate FROM pg_database WHERE datname = current_database()',
+ );
+ const databaseCollation = collationResult.rows[0]?.datcollate;
+ if (!databaseCollation) throw new Error('Failed to read the PostgreSQL database collation');
+ assertFtsSearchReindexRangeCollation(databaseCollation, rangeConcurrencyByEntity);
+ }
+
const endpointHostname = new URL(elasticsearchUrl!).hostname;
assertFtsSearchReindexElasticsearchHostname(endpointHostname, expectedHostPrefix);
const existing = await repository.getTargetRun(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
@@ -340,7 +361,10 @@ const run = async () => {
endpointHostname,
endpointEnvName: urlEnvironmentName,
expectedHostPrefix: expectedHostPrefix ?? null,
+ batchSizeByEntity,
+ entities: entities ?? [...FTS_SEARCH_DOCUMENT_ENTITIES],
entityConcurrency: entityConcurrency ?? 1,
+ rangeConcurrencyByEntity,
maxBatchesPerEntity: maxBatchesPerEntity ?? null,
maxRequestRetries: maxRequestRetries ?? 4,
mode: existing ? 'resume' : 'fresh',
@@ -373,7 +397,10 @@ const run = async () => {
batchSize,
bulkConcurrency,
bulkMaxBytes,
+ batchSizeByEntity,
+ entities,
entityConcurrency,
+ rangeConcurrencyByEntity,
maxBatchesPerEntity,
maxRequestRetries,
onProgress: async (event) => {
diff --git a/scripts/elasticsearchReindex/options.ts b/scripts/elasticsearchReindex/options.ts
index 0136890c8aa..8ce7e1b872a 100644
--- a/scripts/elasticsearchReindex/options.ts
+++ b/scripts/elasticsearchReindex/options.ts
@@ -1,3 +1,6 @@
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
+
export interface FtsSearchReindexElasticsearchEnvironment {
apiKeyEnvironmentName: string;
expectedHostPrefix?: string;
@@ -5,6 +8,103 @@ export interface FtsSearchReindexElasticsearchEnvironment {
}
export type FtsSearchReindexTelemetryEnvironment = 'development' | 'preview' | 'production';
+export type FtsSearchReindexRangeEntity = 'documents' | 'messages';
+
+const RANGE_ENTITIES = [
+ 'documents',
+ 'messages',
+] as const satisfies readonly FtsSearchReindexRangeEntity[];
+const BYTEWISE_DATABASE_COLLATIONS = new Set(['C', 'C.UTF-8', 'C.utf8']);
+
+export const resolveFtsSearchReindexBatchSizeByEntity = (
+ args: readonly string[],
+): Partial<Record<FtsSearchDocumentEntity, number>> => {
+ const name = '--entity-batch-size';
+ const result: Partial<Record<FtsSearchDocumentEntity, number>> = {};
+ for (const argument of args.filter((item) => item.startsWith(`${name}=`))) {
+ const value = argument.slice(name.length + 1);
+ const parts = value.split(':');
+ if (parts.length !== 2) throw new Error(`${name} must use <entity>:<positive-integer>`);
+ const [entityName, sizeText] = parts;
+ const entity = FTS_SEARCH_DOCUMENT_ENTITIES.find((item) => item === entityName);
+ if (!entity) throw new Error(`${name} names an unknown search entity: ${entityName}`);
+ if (!/^[1-9]\d*$/.test(sizeText)) {
+ throw new Error(`${name} must use <entity>:<positive-integer>`);
+ }
+ const size = Number(sizeText);
+ if (!Number.isSafeInteger(size)) {
+ throw new Error(`${name} must use <entity>:<positive-integer>`);
+ }
+ if (result[entity] !== undefined) {
+ throw new Error(`${name} was provided more than once for ${entity}`);
+ }
+ result[entity] = size;
+ }
+ return result;
+};
+
+export const resolveFtsSearchReindexRangeConcurrencyByEntity = (
+ args: readonly string[],
+): Partial<Record<FtsSearchReindexRangeEntity, number>> => {
+ const name = '--entity-range-concurrency';
+ const result: Partial<Record<FtsSearchReindexRangeEntity, number>> = {};
+ for (const argument of args.filter((item) => item.startsWith(`${name}=`))) {
+ const value = argument.slice(name.length + 1);
+ const parts = value.split(':');
+ if (parts.length !== 2) throw new Error(`${name} must use <entity>:<positive-integer>`);
+ const [entityName, concurrencyText] = parts;
+ const entity = RANGE_ENTITIES.find((item) => item === entityName);
+ if (!entity) {
+ throw new Error(`${name} supports only documents and messages: ${entityName}`);
+ }
+ if (!/^[1-9]\d*$/.test(concurrencyText)) {
+ throw new Error(`${name} must use <entity>:<positive-integer>`);
+ }
+ const concurrency = Number(concurrencyText);
+ if (!Number.isSafeInteger(concurrency)) {
+ throw new Error(`${name} must use <entity>:<positive-integer>`);
+ }
+ if (result[entity] !== undefined) {
+ throw new Error(`${name} was provided more than once for ${entity}`);
+ }
+ result[entity] = concurrency;
+ }
+ return result;
+};
+
+export const resolveFtsSearchReindexEntities = (
+ args: readonly string[],
+): FtsSearchDocumentEntity[] | undefined => {
+ const name = '--entity';
+ const requested = args
+ .filter((item) => item.startsWith(`${name}=`))
+ .map((argument) => argument.slice(name.length + 1));
+ if (requested.length === 0) return;
+
+ const entities = requested.map((entityName) => {
+ const entity = FTS_SEARCH_DOCUMENT_ENTITIES.find((item) => item === entityName);
+ if (!entity) throw new Error(`${name} names an unknown search entity: ${entityName}`);
+ return entity;
+ });
+ if (new Set(entities).size !== entities.length) {
+ throw new Error(`${name} was provided more than once for the same entity`);
+ }
+ return entities;
+};
+
+export const assertFtsSearchReindexRangeCollation = (
+ databaseCollation: string,
+ concurrencyByEntity: Partial<Record<FtsSearchReindexRangeEntity, number>>,
+) => {
+ if (
+ Object.values(concurrencyByEntity).some((concurrency) => concurrency > 1) &&
+ !BYTEWISE_DATABASE_COLLATIONS.has(databaseCollation)
+ ) {
+ throw new Error(
+ `Parallel FTS reindex ID ranges require a bytewise database collation; received ${databaseCollation}`,
+ );
+ }
+};
const readEnvironmentVariableNameArgument = (args: readonly string[], name: string) => {
const argument = args.find((item) => item.startsWith(`${name}=`));
diff --git a/scripts/elasticsearchReindex/runner.mjs b/scripts/elasticsearchReindex/runner.mjs
new file mode 100644
index 00000000000..3720dc6ccaf
--- /dev/null
+++ b/scripts/elasticsearchReindex/runner.mjs
@@ -0,0 +1,67 @@
+import { spawn } from 'node:child_process';
+import { mkdtemp, rm } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build } from 'esbuild';
+
+const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
+const projectDirectory = path.resolve(scriptDirectory, '../..');
+const dependencyPath = path.join(projectDirectory, 'node_modules');
+const runtimeDirectory = await mkdtemp(path.join(os.tmpdir(), 'lobehub-fts-reindex-'));
+const outputFile = path.join(runtimeDirectory, 'fts-search-elasticsearch-reindex.cjs');
+
+let exitCode;
+try {
+ await build({
+ absWorkingDir: projectDirectory,
+ bundle: true,
+ entryPoints: [path.join(scriptDirectory, 'index.ts')],
+ external: ['pg', 'drizzle-orm', 'drizzle-orm/*'],
+ format: 'cjs',
+ logLevel: 'warning',
+ outfile: outputFile,
+ platform: 'node',
+ sourcemap: 'linked',
+ });
+
+ const child = spawn(
+ process.execPath,
+ ['--enable-source-maps', outputFile, ...process.argv.slice(2)],
+ {
+ env: {
+ ...process.env,
+ NODE_PATH: [dependencyPath, process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
+ },
+ stdio: 'inherit',
+ },
+ );
+
+ const forwardSignal = (signal) => () => {
+ if (!child.killed) child.kill(signal);
+ };
+
+ const forwardInterrupt = forwardSignal('SIGINT');
+ const forwardTermination = forwardSignal('SIGTERM');
+ process.once('SIGINT', forwardInterrupt);
+ process.once('SIGTERM', forwardTermination);
+
+ exitCode = await new Promise((resolve) => {
+ child.once('error', (error) => {
+ console.error('Failed to launch the Elasticsearch reindex command:', error.message);
+ resolve(1);
+ });
+ child.once('exit', (code, signal) => {
+ resolve(typeof code === 'number' ? code : signal ? 1 : 0);
+ });
+ });
+
+ process.off('SIGINT', forwardInterrupt);
+ process.off('SIGTERM', forwardTermination);
+} finally {
+ await rm(runtimeDirectory, { force: true, recursive: true }).catch((error) => {
+ console.error('Failed to remove the temporary Elasticsearch reindex bundle:', error.message);
+ });
+}
+process.exitCode = exitCode;
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/logger.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/auditLogger.test.ts
similarity index 98%
rename from packages/database/src/repositories/ftsSearchReindex/__tests__/logger.test.ts
rename to scripts/elasticsearchReindex/runtime/__tests__/auditLogger.test.ts
index a0eb25eccb3..d53c83eea4b 100644
--- a/packages/database/src/repositories/ftsSearchReindex/__tests__/logger.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/auditLogger.test.ts
@@ -5,7 +5,7 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { FtsSearchReindexFileLogger, summarizeFtsSearchReindexError } from '../logger';
+import { FtsSearchReindexFileLogger, summarizeFtsSearchReindexError } from '../auditLogger';
let stateDirectory: string;
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/index.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
similarity index 99%
rename from packages/database/src/repositories/ftsSearchReindex/__tests__/index.test.ts
rename to scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
index b63c48dc681..4246a14a7a4 100644
--- a/packages/database/src/repositories/ftsSearchReindex/__tests__/index.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
@@ -6,7 +6,7 @@ import path from 'node:path';
import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { FtsSearchReindexFileRepository } from '..';
+import { FtsSearchReindexFileRepository } from '../checkpointRepository';
let stateDirectory: string;
let repository: FtsSearchReindexFileRepository;
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/elasticsearch.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
similarity index 96%
rename from packages/database/src/repositories/ftsSearchReindex/__tests__/elasticsearch.test.ts
rename to scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
index 051e54006d9..02418df423f 100644
--- a/packages/database/src/repositories/ftsSearchReindex/__tests__/elasticsearch.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
@@ -1,8 +1,12 @@
+// @vitest-environment node
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { FTS_SEARCH_INDEX_ANALYSIS, FTS_SEARCH_INDEX_DEFINITIONS } from '../../ftsSearchDocument';
-import { FtsSearchReindexHttpClient } from '../elasticsearch';
-import type { FtsSearchReindexIndexBody } from '../service';
+import {
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_INDEX_DEFINITIONS,
+} from '../../../../packages/database/src/repositories/ftsSearchDocument';
+import { FtsSearchReindexHttpClient } from '../elasticsearchClient';
+import type { FtsSearchReindexIndexBody } from '../reindexService';
const response = (body: unknown, status = 200) =>
new Response(body === undefined ? undefined : JSON.stringify(body), {
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/service.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
similarity index 71%
rename from packages/database/src/repositories/ftsSearchReindex/__tests__/service.test.ts
rename to scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
index 3e98435c550..2ff650ab273 100644
--- a/packages/database/src/repositories/ftsSearchReindex/__tests__/service.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/reindexService.test.ts
@@ -1,14 +1,15 @@
+// @vitest-environment node
import type { FtsSearchDocumentEntity } from '@lobechat/types';
import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { FtsSearchReindexRunState } from '..';
+import type { FtsSearchReindexFailure, FtsSearchReindexRunState } from '../checkpointRepository';
import type {
FtsSearchReindexElasticsearchClient,
FtsSearchReindexProgressEvent,
FtsSearchReindexStateRepository,
-} from '../service';
-import { FtsSearchReindexService } from '../service';
+} from '../reindexService';
+import { FtsSearchReindexService } from '../reindexService';
const createState = (): FtsSearchReindexRunState => ({
progress: FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => ({
@@ -35,12 +36,25 @@ const createState = (): FtsSearchReindexRunState => ({
},
});
+const createFailure = (
+ entity: FtsSearchDocumentEntity,
+ documentId: string,
+): FtsSearchReindexFailure => ({
+ attempts: 1,
+ documentId,
+ entity,
+ error: 'retryable failure',
+ resolvedAt: null,
+ retryable: true,
+});
+
const createDependencies = () => {
const state = createState();
const failures = new Map<FtsSearchDocumentEntity, { documentId: string }[]>();
const builder = {
buildBatch: vi.fn().mockResolvedValue([]),
buildByIds: vi.fn().mockResolvedValue([]),
+ buildRangeBatch: vi.fn().mockResolvedValue([]),
};
const client: FtsSearchReindexElasticsearchClient = {
bulk: vi.fn().mockResolvedValue([]),
@@ -96,6 +110,98 @@ describe('FtsSearchReindexService', () => {
});
});
+ it('uses an entity page-size override for paging and source exhaustion', async () => {
+ const { builder, client, repository } = createDependencies();
+ builder.buildBatch.mockImplementation(async (entity, { afterId }) => {
+ if (entity !== 'documents') return [];
+ if (!afterId) {
+ return [{ entity, id: 'document-1', source: { id: 'document-1' } }];
+ }
+ if (afterId === 'document-1') {
+ return [{ entity, id: 'document-2', source: { id: 'document-2' } }];
+ }
+ return [];
+ });
+ vi.mocked(client.bulk).mockResolvedValue([{ status: 201 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-documents-') ? 2 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ batchSize: 2,
+ batchSizeByEntity: { documents: 1 },
+ entityConcurrency: 1,
+ });
+
+ await service.run('test', 1);
+
+ expect(builder.buildBatch).toHaveBeenCalledWith('documents', {
+ afterId: undefined,
+ limit: 1,
+ });
+ expect(builder.buildBatch).toHaveBeenCalledWith('documents', {
+ afterId: 'document-1',
+ limit: 1,
+ });
+ expect(builder.buildBatch).toHaveBeenCalledWith('documents', {
+ afterId: 'document-2',
+ limit: 1,
+ });
+ expect(builder.buildBatch).toHaveBeenCalledWith('messages', {
+ afterId: undefined,
+ limit: 2,
+ });
+ });
+
+ it('rejects an invalid entity page-size override', () => {
+ const { builder, client, repository } = createDependencies();
+
+ expect(
+ () =>
+ new FtsSearchReindexService(builder, repository, client, {
+ batchSizeByEntity: { documents: 0 },
+ }),
+ ).toThrow('batch size for documents must be a positive integer');
+ });
+
+ it('indexes high-volume ID ranges concurrently but checkpoints them in order', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ for (const progress of state.progress) progress.status = 'completed';
+ const messageProgress = state.progress.find(({ entity }) => entity === 'messages')!;
+ messageProgress.cursor = 'msg_00AAAA';
+ messageProgress.status = 'backfilling';
+
+ builder.buildRangeBatch.mockImplementation(async (entity, { afterId, beforeId, fromId }) => {
+ if (entity !== 'messages') return [];
+ if (afterId === 'msg_00AAAA' && beforeId === 'msg_08') {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ return [{ entity, id: 'msg_01AAAA', source: { id: 'msg_01AAAA' } }];
+ }
+ if (fromId === 'msg_08' && beforeId === 'msg_0G') {
+ return [{ entity, id: 'msg_09AAAA', source: { id: 'msg_09AAAA' } }];
+ }
+ return [];
+ });
+ vi.mocked(client.bulk).mockResolvedValue([{ status: 201 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-messages-') ? 2 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ batchSize: 10,
+ entityConcurrency: 1,
+ rangeConcurrencyByEntity: { messages: 2 },
+ });
+
+ await service.run('test', 1);
+
+ const messageCheckpoints = vi
+ .mocked(repository.checkpointBatch)
+ .mock.calls.map(([checkpoint]) => checkpoint)
+ .filter(({ entity }) => entity === 'messages');
+ expect(messageCheckpoints.map(({ cursor }) => cursor)).toEqual(['msg_01AAAA', 'msg_09AAAA']);
+ expect(messageProgress).toMatchObject({ indexedCount: 2, processedCount: 2 });
+ expect(builder.buildBatch).not.toHaveBeenCalledWith('messages', expect.anything());
+ });
+
it('creates aliases only after all 14 entities complete', async () => {
const { builder, client, repository, state } = createDependencies();
const events: unknown[] = [];
@@ -144,6 +250,20 @@ describe('FtsSearchReindexService', () => {
]);
});
+ it('keeps a selected-entity run backfilling until every entity is complete', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['messages'],
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({ status: 'backfilling' });
+
+ expect(state.progress.find(({ entity }) => entity === 'messages')?.status).toBe('completed');
+ expect(state.progress.find(({ entity }) => entity === 'documents')?.status).toBe('pending');
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ expect(repository.markReadyForIncrementalSync).not.toHaveBeenCalled();
+ });
+
it('does not create aliases or mark a run ready when incremental source validation fails', async () => {
const { builder, client, repository } = createDependencies();
const validateIncrementalSyncSource = vi
@@ -469,6 +589,81 @@ describe('FtsSearchReindexService', () => {
expect(client.bulk).toHaveBeenCalledTimes(4);
});
+ it('retries large document failures in bounded projection batches', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ for (const progress of state.progress) progress.status = 'completed';
+ const documentProgress = state.progress.find(({ entity }) => entity === 'documents')!;
+ documentProgress.failedCount = 21;
+ documentProgress.status = 'backfilling';
+ const failures = Array.from({ length: 21 }, (_, index) =>
+ createFailure('documents', `document-${index}`),
+ );
+ vi.mocked(repository.listUnresolvedFailures)
+ .mockResolvedValueOnce(failures)
+ .mockResolvedValueOnce([]);
+ vi.mocked(repository.resolveFailures).mockImplementation(async (_runId, _entity, ids) => {
+ documentProgress.failedCount -= ids.length;
+ documentProgress.indexedCount += ids.length;
+ return ids.length;
+ });
+ builder.buildByIds.mockImplementation(async (entity, ids) =>
+ ids.map((id: string) => ({ entity, id, source: { id } })),
+ );
+ vi.mocked(client.bulk).mockImplementation(async (body) =>
+ Array.from({ length: body.trim().split('\n').length / 2 }, () => ({ status: 201 })),
+ );
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-documents-') ? 21 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['documents'],
+ entityConcurrency: 1,
+ });
+
+ await service.run('test', 1);
+
+ expect(builder.buildByIds).toHaveBeenCalledTimes(2);
+ expect(builder.buildByIds.mock.calls.map(([, ids]) => ids.length)).toEqual([20, 1]);
+ expect(documentProgress).toMatchObject({ failedCount: 0, indexedCount: 21 });
+ });
+
+ it('retries retryable bulk items before persisting them again', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ for (const progress of state.progress) progress.status = 'completed';
+ const documentProgress = state.progress.find(({ entity }) => entity === 'documents')!;
+ documentProgress.failedCount = 1;
+ documentProgress.status = 'backfilling';
+ vi.mocked(repository.listUnresolvedFailures)
+ .mockResolvedValueOnce([createFailure('documents', 'document-1')])
+ .mockResolvedValueOnce([]);
+ vi.mocked(repository.resolveFailures).mockImplementation(async (_runId, _entity, ids) => {
+ documentProgress.failedCount -= ids.length;
+ documentProgress.indexedCount += ids.length;
+ return ids.length;
+ });
+ builder.buildByIds.mockResolvedValue([
+ { entity: 'documents', id: 'document-1', source: { id: 'document-1' } },
+ ]);
+ vi.mocked(client.bulk)
+ .mockResolvedValueOnce([{ status: 429 }])
+ .mockResolvedValueOnce([{ status: 201 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-documents-') ? 1 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entities: ['documents'],
+ entityConcurrency: 1,
+ maxRequestRetries: 1,
+ retryBaseDelayMs: 0,
+ });
+
+ await service.run('test', 1);
+
+ expect(client.bulk).toHaveBeenCalledTimes(2);
+ expect(repository.checkpointBatch).not.toHaveBeenCalled();
+ expect(documentProgress).toMatchObject({ failedCount: 0, indexedCount: 1 });
+ });
+
it('persists an oversized item and blocks alias creation', async () => {
const { builder, client, repository } = createDependencies();
builder.buildBatch
@@ -515,7 +710,11 @@ describe('FtsSearchReindexService', () => {
index.includes('-agents-') ? 1 : 0,
);
const service = new FtsSearchReindexService(
- { buildBatch: vi.fn().mockResolvedValue([]), buildByIds: vi.fn().mockResolvedValue([]) },
+ {
+ buildBatch: vi.fn().mockResolvedValue([]),
+ buildByIds: vi.fn().mockResolvedValue([]),
+ buildRangeBatch: vi.fn().mockResolvedValue([]),
+ },
repository,
client,
{
diff --git a/packages/database/src/repositories/ftsSearchReindex/logger.ts b/scripts/elasticsearchReindex/runtime/auditLogger.ts
similarity index 98%
rename from packages/database/src/repositories/ftsSearchReindex/logger.ts
rename to scripts/elasticsearchReindex/runtime/auditLogger.ts
index a48ba200d7c..73f79312fe4 100644
--- a/packages/database/src/repositories/ftsSearchReindex/logger.ts
+++ b/scripts/elasticsearchReindex/runtime/auditLogger.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { isRecord } from '@lobechat/utils/object';
-import type { FtsSearchReindexProgressEvent } from './service';
+import type { FtsSearchReindexProgressEvent } from './reindexService';
type JsonPrimitive = boolean | null | number | string;
export type FtsSearchReindexAuditValue =
diff --git a/packages/database/src/repositories/ftsSearchReindex/index.ts b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
similarity index 96%
rename from packages/database/src/repositories/ftsSearchReindex/index.ts
rename to scripts/elasticsearchReindex/runtime/checkpointRepository.ts
index 22e74e3fd7f..4b5df5700f9 100644
--- a/packages/database/src/repositories/ftsSearchReindex/index.ts
+++ b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
@@ -11,7 +11,7 @@ import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import { z } from 'zod';
-import { getFtsSearchPhysicalIndexName } from '../ftsSearchDocument';
+import { getFtsSearchPhysicalIndexName } from '../../../packages/database/src/repositories/ftsSearchDocument';
export interface FtsSearchReindexBatchFailure {
documentId: string;
@@ -567,21 +567,3 @@ export class FtsSearchReindexFileRepository {
});
}
}
-
-export type { FtsSearchReindexHttpClientOptions } from './elasticsearch';
-export { FtsSearchReindexHttpClient, FtsSearchReindexRequestError } from './elasticsearch';
-export type {
- FtsSearchReindexAuditEvent,
- FtsSearchReindexAuditValue,
- FtsSearchReindexFileLoggerOptions,
-} from './logger';
-export { FtsSearchReindexFileLogger, summarizeFtsSearchReindexError } from './logger';
-export type {
- FtsSearchReindexElasticsearchClient,
- FtsSearchReindexIndexBody,
- FtsSearchReindexProgressEvent,
- FtsSearchReindexResult,
- FtsSearchReindexServiceOptions,
- FtsSearchReindexStateRepository,
-} from './service';
-export { FtsSearchReindexEntityError, FtsSearchReindexService } from './service';
diff --git a/packages/database/src/repositories/ftsSearchReindex/elasticsearch.ts b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
similarity index 98%
rename from packages/database/src/repositories/ftsSearchReindex/elasticsearch.ts
rename to scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
index b22d5adb751..ed3fe6ec2d3 100644
--- a/packages/database/src/repositories/ftsSearchReindex/elasticsearch.ts
+++ b/scripts/elasticsearchReindex/runtime/elasticsearchClient.ts
@@ -2,13 +2,13 @@ import { isDeepStrictEqual } from 'node:util';
import { z } from 'zod';
-import { parseElasticsearchUrl } from '../ftsSearch/elasticsearch/url';
+import { parseElasticsearchUrl } from '../../../packages/database/src/repositories/ftsSearch/elasticsearch/url';
import type {
FtsSearchReindexBulkItemResult,
FtsSearchReindexElasticsearchClient,
FtsSearchReindexIndexBody,
FtsSearchReindexIndexOptions,
-} from './service';
+} from './reindexService';
const bulkResponseSchema = z.object({
items: z.array(
diff --git a/scripts/elasticsearchReindex/runtime/index.ts b/scripts/elasticsearchReindex/runtime/index.ts
new file mode 100644
index 00000000000..7885c05511b
--- /dev/null
+++ b/scripts/elasticsearchReindex/runtime/index.ts
@@ -0,0 +1,4 @@
+export * from './auditLogger';
+export * from './checkpointRepository';
+export * from './elasticsearchClient';
+export * from './reindexService';
diff --git a/packages/database/src/repositories/ftsSearchReindex/service.ts b/scripts/elasticsearchReindex/runtime/reindexService.ts
similarity index 61%
rename from packages/database/src/repositories/ftsSearchReindex/service.ts
rename to scripts/elasticsearchReindex/runtime/reindexService.ts
index ba14ac36fd9..7192d839e0e 100644
--- a/packages/database/src/repositories/ftsSearchReindex/service.ts
+++ b/scripts/elasticsearchReindex/runtime/reindexService.ts
@@ -2,17 +2,17 @@ import type { FtsSearchDocumentEntity } from '@lobechat/types';
import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
-import type { FtsSearchDocumentBuilder } from '../ftsSearchDocument';
+import type { FtsSearchDocumentBuilder } from '../../../packages/database/src/repositories/ftsSearchDocument';
import {
FTS_SEARCH_INDEX_ANALYSIS,
FTS_SEARCH_INDEX_DEFINITIONS,
getFtsSearchIndexAlias,
-} from '../ftsSearchDocument';
+} from '../../../packages/database/src/repositories/ftsSearchDocument';
import type {
FtsSearchReindexBatchFailure,
FtsSearchReindexFileRepository,
FtsSearchReindexRunState,
-} from '.';
+} from './checkpointRepository';
export interface FtsSearchReindexBulkItemResult {
error?: unknown;
@@ -44,16 +44,24 @@ export interface FtsSearchReindexIndexBody {
export interface FtsSearchReindexServiceOptions {
batchSize: number;
+ /** Overrides the PostgreSQL page size for entities whose source rows differ materially in size. */
+ batchSizeByEntity: Partial<Record<FtsSearchDocumentEntity, number>>;
bulkConcurrency: number;
bulkMaxBytes: number;
+ /** Restricts one invocation to selected entities without allowing aliases to be created early. */
+ entities: FtsSearchDocumentEntity[];
entityConcurrency: number;
maxBatchesPerEntity?: number;
maxRequestRetries: number;
onProgress: (event: FtsSearchReindexProgressEvent) => Promise<void> | void;
+ /** Parallel key-range workers for high-volume entities. */
+ rangeConcurrencyByEntity: Partial<Record<FtsSearchRangeEntity, number>>;
retryBaseDelayMs: number;
validateIncrementalSyncSource: () => Promise<void> | void;
}
+export type FtsSearchRangeEntity = 'documents' | 'messages';
+
export type FtsSearchReindexStateRepository = Pick<
FtsSearchReindexFileRepository,
| 'checkpointBatch'
@@ -135,14 +143,66 @@ interface BulkOperation {
documentId: string;
}
+interface FtsSearchReindexIdRange {
+ afterId?: string;
+ beforeId?: string;
+ fromId?: string;
+}
+
+interface FtsSearchReindexRangeResult {
+ bulkRequests: number;
+ bytes: number;
+ durationMs: number;
+ failures: FtsSearchReindexBatchFailure[];
+ indexedCount: number;
+ lastId?: string;
+ processedCount: number;
+}
+
const DEFAULT_BATCH_SIZE = 500;
const DEFAULT_BULK_CONCURRENCY = 1;
const DEFAULT_BULK_MAX_BYTES = 50 * 1024 * 1024;
const DEFAULT_ENTITY_CONCURRENCY = 1;
const DEFAULT_MAX_REQUEST_RETRIES = 4;
const DEFAULT_RETRY_BASE_DELAY_MS = 500;
+const DEFAULT_FAILURE_RETRY_BATCH_SIZE = 1000;
+const DOCUMENT_FAILURE_RETRY_BATCH_SIZE = 20;
+const FTS_SEARCH_ID_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+const FTS_SEARCH_RANGE_PREFIXES = {
+ documents: 'docs_',
+ messages: 'msg_',
+} as const satisfies Record<FtsSearchRangeEntity, string>;
+const FTS_SEARCH_RANGE_SECOND_CHARACTER_STRIDE = 8;
const textEncoder = new TextEncoder();
+const buildIdRanges = (entity: FtsSearchRangeEntity, cursor: string | null) => {
+ const prefix = FTS_SEARCH_RANGE_PREFIXES[entity];
+ const secondCharacters = [...FTS_SEARCH_ID_ALPHABET].filter(
+ (_, index) => index % FTS_SEARCH_RANGE_SECOND_CHARACTER_STRIDE === 0,
+ );
+ const boundaries = [...FTS_SEARCH_ID_ALPHABET]
+ .flatMap((first) => secondCharacters.map((second) => `${prefix}${first}${second}`))
+ .filter((boundary) => cursor === null || boundary > cursor);
+ const ranges: FtsSearchReindexIdRange[] = [];
+ let previousBoundary: string | undefined;
+ for (const boundary of boundaries) {
+ ranges.push({
+ afterId: previousBoundary === undefined ? (cursor ?? undefined) : undefined,
+ beforeId: boundary,
+ fromId: previousBoundary,
+ });
+ previousBoundary = boundary;
+ }
+ ranges.push({
+ afterId: previousBoundary === undefined ? (cursor ?? undefined) : undefined,
+ fromId: previousBoundary,
+ });
+ return ranges;
+};
+
+const isRangeEntity = (entity: FtsSearchDocumentEntity): entity is FtsSearchRangeEntity =>
+ entity === 'documents' || entity === 'messages';
+
const errorStatus = (error: unknown) =>
isRecord(error) && typeof error.status === 'number' ? error.status : undefined;
@@ -218,7 +278,10 @@ export class FtsSearchReindexService {
private preparedRunId?: string;
constructor(
- private readonly builder: Pick<FtsSearchDocumentBuilder, 'buildBatch' | 'buildByIds'>,
+ private readonly builder: Pick<
+ FtsSearchDocumentBuilder,
+ 'buildBatch' | 'buildByIds' | 'buildRangeBatch'
+ >,
private readonly repository: FtsSearchReindexStateRepository,
private readonly client: FtsSearchReindexElasticsearchClient,
options: Partial<FtsSearchReindexServiceOptions> = {},
@@ -227,7 +290,10 @@ export class FtsSearchReindexService {
batchSize: options.batchSize ?? DEFAULT_BATCH_SIZE,
bulkConcurrency: options.bulkConcurrency ?? DEFAULT_BULK_CONCURRENCY,
bulkMaxBytes: options.bulkMaxBytes ?? DEFAULT_BULK_MAX_BYTES,
+ batchSizeByEntity: { ...options.batchSizeByEntity },
+ entities: options.entities ? [...options.entities] : [...FTS_SEARCH_DOCUMENT_ENTITIES],
entityConcurrency: options.entityConcurrency ?? DEFAULT_ENTITY_CONCURRENCY,
+ rangeConcurrencyByEntity: { ...options.rangeConcurrencyByEntity },
maxBatchesPerEntity: options.maxBatchesPerEntity,
maxRequestRetries: options.maxRequestRetries ?? DEFAULT_MAX_REQUEST_RETRIES,
onProgress: options.onProgress ?? (() => {}),
@@ -237,21 +303,52 @@ export class FtsSearchReindexService {
if (!Number.isInteger(this.options.batchSize) || this.options.batchSize < 1) {
throw new Error('FTS reindex batch size must be a positive integer');
}
+ for (const [entity, size] of Object.entries(this.options.batchSizeByEntity)) {
+ if (
+ !FTS_SEARCH_DOCUMENT_ENTITIES.includes(entity as FtsSearchDocumentEntity) ||
+ !Number.isInteger(size) ||
+ size < 1
+ ) {
+ throw new Error(`FTS reindex batch size for ${entity} must be a positive integer`);
+ }
+ }
if (!Number.isInteger(this.options.bulkMaxBytes) || this.options.bulkMaxBytes < 1) {
throw new Error('FTS reindex bulk byte limit must be a positive integer');
}
if (!Number.isInteger(this.options.bulkConcurrency) || this.options.bulkConcurrency < 1) {
throw new Error('FTS reindex bulk concurrency must be a positive integer');
}
+ if (
+ this.options.entities.length === 0 ||
+ new Set(this.options.entities).size !== this.options.entities.length ||
+ this.options.entities.some((entity) => !FTS_SEARCH_DOCUMENT_ENTITIES.includes(entity))
+ ) {
+ throw new Error('FTS reindex entities must be a non-empty unique list of search entities');
+ }
if (!Number.isInteger(this.options.entityConcurrency) || this.options.entityConcurrency < 1) {
throw new Error('FTS reindex entity concurrency must be a positive integer');
}
+ for (const [entity, concurrency] of Object.entries(this.options.rangeConcurrencyByEntity)) {
+ if (
+ !(entity in FTS_SEARCH_RANGE_PREFIXES) ||
+ !Number.isInteger(concurrency) ||
+ concurrency < 1
+ ) {
+ throw new Error(`FTS reindex range concurrency for ${entity} must be a positive integer`);
+ }
+ }
if (
this.options.maxBatchesPerEntity !== undefined &&
(!Number.isInteger(this.options.maxBatchesPerEntity) || this.options.maxBatchesPerEntity < 1)
) {
throw new Error('FTS reindex maximum batches per entity must be a positive integer');
}
+ if (
+ this.options.maxBatchesPerEntity !== undefined &&
+ Object.values(this.options.rangeConcurrencyByEntity).some((value) => value > 1)
+ ) {
+ throw new Error('FTS reindex range concurrency cannot be combined with a batch limit');
+ }
if (!Number.isInteger(this.options.maxRequestRetries) || this.options.maxRequestRetries < 0) {
throw new Error('FTS reindex request retries must be a non-negative integer');
}
@@ -462,53 +559,262 @@ export class FtsSearchReindexService {
private async retryFailures(state: FtsSearchReindexRunState, entity: FtsSearchDocumentEntity) {
const failures = await this.repository.listUnresolvedFailures(state.run.id, entity);
if (failures.length === 0) return;
-
- const documents = await this.builder.buildByIds(
- entity,
- failures.map(({ documentId }) => documentId),
- );
- const sources = new Map(
- documents.map((document) => [document.id, document.source as Record<string, unknown>]),
- );
const progress = state.progress.find((item) => item.entity === entity);
if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
- const retryDocuments = failures.map(({ documentId }) => ({
- id: documentId,
- /** A source row deleted during backfill remains versioned until the outbox applies its deletion. */
- source:
- sources.get(documentId) ??
- ({ id: documentId, fts_search_sync_deleted: true } as Record<string, unknown>),
- }));
- const result = await this.indexDocuments(
- retryDocuments,
- entity,
- progress.physicalIndex,
- state.run.baseRevision,
- );
- await this.repository.resolveFailures(state.run.id, entity, result.indexedDocumentIds);
- if (result.failures.length > 0) {
- const checkpointed = await this.repository.checkpointBatch({
- cursor: progress.cursor ?? '',
+ /** Document projections can be very large, so replay failures without retaining every source. */
+ const retryBatchSize =
+ entity === 'documents' ? DOCUMENT_FAILURE_RETRY_BATCH_SIZE : DEFAULT_FAILURE_RETRY_BATCH_SIZE;
+ for (let offset = 0; offset < failures.length; offset += retryBatchSize) {
+ const failureBatch = failures.slice(offset, offset + retryBatchSize);
+ const documents = await this.builder.buildByIds(
entity,
- failures: result.failures,
- indexedCount: 0,
- previousCursor: progress.cursor,
- processedCount: 0,
- runId: state.run.id,
- });
- if (!checkpointed) {
- const refreshed = await this.repository.getRun(state.run.id);
+ failureBatch.map(({ documentId }) => documentId),
+ );
+ const sources = new Map(
+ documents.map((document) => [document.id, document.source as Record<string, unknown>]),
+ );
+ const retryDocuments = failureBatch.map(({ documentId }) => ({
+ id: documentId,
+ /** A source row deleted during backfill remains versioned until the outbox applies its deletion. */
+ source:
+ sources.get(documentId) ??
+ ({ id: documentId, fts_search_sync_deleted: true } as Record<string, unknown>),
+ }));
+ let pendingDocuments = retryDocuments;
+ const unresolvedFailures: FtsSearchReindexBatchFailure[] = [];
+ for (let attempt = 0; pendingDocuments.length > 0; attempt += 1) {
+ const result = await this.indexDocuments(
+ pendingDocuments,
+ entity,
+ progress.physicalIndex,
+ state.run.baseRevision,
+ );
+ await this.repository.resolveFailures(state.run.id, entity, result.indexedDocumentIds);
+ unresolvedFailures.push(...result.failures.filter(({ retryable }) => !retryable));
+ const retryableDocumentIds = new Set(
+ result.failures.filter(({ retryable }) => retryable).map(({ documentId }) => documentId),
+ );
+ if (retryableDocumentIds.size === 0) break;
+ if (attempt >= this.options.maxRequestRetries) {
+ unresolvedFailures.push(...result.failures.filter(({ retryable }) => retryable));
+ break;
+ }
+
+ const exponentialDelay = this.options.retryBaseDelayMs * 2 ** attempt;
+ const delayMs = Math.floor(Math.random() * exponentialDelay);
await this.emitProgress({
- actualCursor: refreshed?.progress.find((item) => item.entity === entity)?.cursor ?? null,
+ attempt: attempt + 1,
+ delayMs,
entity,
- expectedCursor: progress.cursor,
- type: 'checkpoint_conflict',
+ errorType: 'ElasticsearchBulkItemError',
+ type: 'bulk_retry',
});
+ await sleep(delayMs);
+ pendingDocuments = pendingDocuments.filter(({ id }) => retryableDocumentIds.has(id));
}
+ if (unresolvedFailures.length > 0) {
+ const checkpointed = await this.repository.checkpointBatch({
+ cursor: progress.cursor ?? '',
+ entity,
+ failures: unresolvedFailures,
+ indexedCount: 0,
+ previousCursor: progress.cursor,
+ processedCount: 0,
+ runId: state.run.id,
+ });
+ if (!checkpointed) {
+ const refreshed = await this.repository.getRun(state.run.id);
+ await this.emitProgress({
+ actualCursor:
+ refreshed?.progress.find((item) => item.entity === entity)?.cursor ?? null,
+ entity,
+ expectedCursor: progress.cursor,
+ type: 'checkpoint_conflict',
+ });
+ }
+ }
+ }
+ }
+
+ private async runIdRange(
+ state: FtsSearchReindexRunState,
+ entity: FtsSearchRangeEntity,
+ range: FtsSearchReindexIdRange,
+ batchSize: number,
+ ): Promise<FtsSearchReindexRangeResult> {
+ const progress = state.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+
+ const startedAt = Date.now();
+ const failures: FtsSearchReindexBatchFailure[] = [];
+ let afterId = range.afterId;
+ let fromId = range.fromId;
+ let bulkRequests = 0;
+ let bytes = 0;
+ let indexedCount = 0;
+ let lastId: string | undefined;
+ let processedCount = 0;
+ while (true) {
+ const documents = await this.builder.buildRangeBatch(entity, {
+ afterId,
+ beforeId: range.beforeId,
+ fromId,
+ limit: batchSize,
+ });
+ if (documents.length === 0) break;
+
+ const result = await this.indexDocuments(
+ documents.map((document) => ({
+ id: document.id,
+ source: document.source as Record<string, unknown>,
+ })),
+ entity,
+ progress.physicalIndex,
+ state.run.baseRevision,
+ );
+ bulkRequests += result.bulkRequests;
+ bytes += result.bytes;
+ failures.push(...result.failures);
+ indexedCount += result.indexedDocumentIds.length;
+ processedCount += documents.length;
+ lastId = documents.at(-1)!.id;
+ afterId = lastId;
+ fromId = undefined;
+ if (documents.length < batchSize) break;
+ }
+
+ return {
+ bulkRequests,
+ bytes,
+ durationMs: Date.now() - startedAt,
+ failures,
+ indexedCount,
+ lastId,
+ processedCount,
+ };
+ }
+
+ /**
+ * Commit completed ranges strictly in ID order. Later ranges may finish first, but their ES
+ * writes remain safe to replay until every earlier range has advanced the durable entity cursor.
+ */
+ private async runEntityByIdRanges(
+ state: FtsSearchReindexRunState,
+ entity: FtsSearchRangeEntity,
+ concurrency: number,
+ batchSize: number,
+ ) {
+ let progress = state.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+
+ const ranges = buildIdRanges(entity, progress.cursor);
+ const completedRanges = new Map<number, FtsSearchReindexRangeResult>();
+ let checkpointFailure: unknown;
+ let checkpointQueue = Promise.resolve();
+ let nextCheckpointIndex = 0;
+
+ const queueCheckpoint = (index: number, result: FtsSearchReindexRangeResult) => {
+ completedRanges.set(index, result);
+ const operation = checkpointQueue.then(async () => {
+ if (checkpointFailure) throw checkpointFailure;
+ while (completedRanges.has(nextCheckpointIndex)) {
+ const completed = completedRanges.get(nextCheckpointIndex)!;
+ completedRanges.delete(nextCheckpointIndex);
+ nextCheckpointIndex += 1;
+ if (completed.processedCount === 0) continue;
+ if (!completed.lastId) throw new Error(`Missing completed ${entity} range cursor`);
+
+ const previousCursor = progress!.cursor;
+ const checkpointed = await this.repository.checkpointBatch({
+ cursor: completed.lastId,
+ entity,
+ failures: completed.failures,
+ indexedCount: completed.indexedCount,
+ previousCursor,
+ processedCount: completed.processedCount,
+ runId: state.run.id,
+ });
+ const refreshed = await this.repository.getRun(state.run.id);
+ const checkpointProgress = refreshed?.progress.find((item) => item.entity === entity);
+ if (!checkpointed || !checkpointProgress) {
+ await this.emitProgress({
+ actualCursor: checkpointProgress?.cursor ?? null,
+ entity,
+ expectedCursor: previousCursor,
+ type: 'checkpoint_conflict',
+ });
+ throw new Error(`Concurrent checkpoint update detected for ${entity}`);
+ }
+ progress = checkpointProgress;
+ await this.emitProgress({
+ bulkRequests: completed.bulkRequests,
+ bytes: completed.bytes,
+ checkpoint: {
+ failed: progress.failedCount,
+ indexed: progress.indexedCount,
+ scanned: progress.processedCount,
+ },
+ cursor: completed.lastId,
+ durationMs: completed.durationMs,
+ entity,
+ failed: completed.failures.length,
+ indexed: completed.indexedCount,
+ processed: completed.processedCount,
+ type: 'batch',
+ });
+ }
+ });
+ checkpointQueue = operation.catch((error) => {
+ checkpointFailure ??= error;
+ });
+ return operation;
+ };
+
+ await mapWithConcurrency(ranges, concurrency, async (range, index) => {
+ const result = await this.runIdRange(state, entity, range, batchSize);
+ await queueCheckpoint(index, result);
+ });
+ await checkpointQueue;
+ if (checkpointFailure) throw checkpointFailure;
+ if (nextCheckpointIndex !== ranges.length) {
+ throw new Error(
+ `FTS reindex committed ${nextCheckpointIndex} of ${ranges.length} ${entity} ID ranges`,
+ );
}
}
+ private async completeEntity(state: FtsSearchReindexRunState, entity: FtsSearchDocumentEntity) {
+ const refreshedState = await this.repository.getRun(state.run.id);
+ if (!refreshedState) throw new Error(`Missing reindex run ${state.run.id}`);
+ await this.retryFailures(refreshedState, entity);
+ const unresolved = await this.repository.listUnresolvedFailures(state.run.id, entity);
+ if (unresolved.length > 0) {
+ throw new Error(`Reindex paused with ${unresolved.length} unresolved ${entity} failures`);
+ }
+
+ const finalState = await this.repository.getRun(state.run.id);
+ const finalProgress = finalState?.progress.find((item) => item.entity === entity);
+ if (!finalProgress) throw new Error(`Missing final reindex progress for ${entity}`);
+ await this.client.refresh(finalProgress.physicalIndex);
+ const indexedCount = await this.client.count(finalProgress.physicalIndex);
+ await this.emitProgress({
+ checkpointCount: finalProgress.indexedCount,
+ drift: indexedCount - finalProgress.indexedCount,
+ elasticsearchCount: indexedCount,
+ entity,
+ type: 'reconciliation',
+ });
+ if (indexedCount !== finalProgress.indexedCount) {
+ throw new Error(
+ `Reindex count mismatch for ${entity}: checkpoint=${finalProgress.indexedCount}, Elasticsearch=${indexedCount}`,
+ );
+ }
+ await this.repository.completeEntity(state.run.id, entity);
+ await this.emitProgress({ count: indexedCount, entity, type: 'entity_completed' });
+ return true;
+ }
+
private async runEntity(state: FtsSearchReindexRunState, entity: FtsSearchDocumentEntity) {
let progress = state.progress.find((item) => item.entity === entity);
if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
@@ -516,13 +822,22 @@ export class FtsSearchReindexService {
await this.emitProgress({ entity, type: 'entity_started' });
+ const batchSize = this.options.batchSizeByEntity[entity] ?? this.options.batchSize;
+ const rangeConcurrency = isRangeEntity(entity)
+ ? (this.options.rangeConcurrencyByEntity[entity] ?? 1)
+ : 1;
+ if (isRangeEntity(entity) && rangeConcurrency > 1) {
+ await this.runEntityByIdRanges(state, entity, rangeConcurrency, batchSize);
+ return this.completeEntity(state, entity);
+ }
+
let processedBatches = 0;
let sourceExhausted = false;
while (true) {
const batchStartedAt = Date.now();
const documents = await this.builder.buildBatch(entity, {
afterId: progress.cursor ?? undefined,
- limit: this.options.batchSize,
+ limit: batchSize,
});
if (documents.length === 0) {
sourceExhausted = true;
@@ -579,7 +894,7 @@ export class FtsSearchReindexService {
progress = checkpointProgress;
if (!progress) throw new Error(`Missing refreshed reindex progress for ${entity}`);
processedBatches += 1;
- if (documents.length < this.options.batchSize) {
+ if (documents.length < batchSize) {
/** buildBatch applies LIMIT without post-query filtering, so a short keyset page is final. */
sourceExhausted = true;
break;
@@ -593,35 +908,7 @@ export class FtsSearchReindexService {
}
if (!sourceExhausted) return false;
-
- const refreshedState = await this.repository.getRun(state.run.id);
- if (!refreshedState) throw new Error(`Missing reindex run ${state.run.id}`);
- await this.retryFailures(refreshedState, entity);
- const unresolved = await this.repository.listUnresolvedFailures(state.run.id, entity);
- if (unresolved.length > 0) {
- throw new Error(`Reindex paused with ${unresolved.length} unresolved ${entity} failures`);
- }
-
- const finalState = await this.repository.getRun(state.run.id);
- const finalProgress = finalState?.progress.find((item) => item.entity === entity);
- if (!finalProgress) throw new Error(`Missing final reindex progress for ${entity}`);
- await this.client.refresh(finalProgress.physicalIndex);
- const indexedCount = await this.client.count(finalProgress.physicalIndex);
- await this.emitProgress({
- checkpointCount: finalProgress.indexedCount,
- drift: indexedCount - finalProgress.indexedCount,
- elasticsearchCount: indexedCount,
- entity,
- type: 'reconciliation',
- });
- if (indexedCount !== finalProgress.indexedCount) {
- throw new Error(
- `Reindex count mismatch for ${entity}: checkpoint=${finalProgress.indexedCount}, Elasticsearch=${indexedCount}`,
- );
- }
- await this.repository.completeEntity(state.run.id, entity);
- await this.emitProgress({ count: indexedCount, entity, type: 'entity_completed' });
- return true;
+ return this.completeEntity(state, entity);
}
async run(namespace: string, schemaVersion: number): Promise<FtsSearchReindexResult> {
@@ -635,8 +922,8 @@ export class FtsSearchReindexService {
await this.prepareIndices(initialState);
- const completed = await mapWithConcurrency(
- FTS_SEARCH_DOCUMENT_ENTITIES,
+ await mapWithConcurrency(
+ this.options.entities,
this.options.entityConcurrency,
async (entity) => {
const currentState = await this.repository.getRun(initialState.run.id);
@@ -649,15 +936,15 @@ export class FtsSearchReindexService {
},
);
- if (completed.some((value) => !value)) {
+ 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')) {
await this.emitProgress({ type: 'run_paused' });
return { runId: initialState.run.id, status: 'backfilling' };
}
- const completedState = await this.repository.getRun(initialState.run.id);
- if (!completedState) throw new Error(`Missing reindex run ${initialState.run.id}`);
await this.options.validateIncrementalSyncSource();
- for (const progress of completedState.progress) {
+ for (const progress of currentState.progress) {
await this.client.ensureAlias(
getFtsSearchIndexAlias(namespace, progress.entity),
progress.physicalIndex,
diff --git a/scripts/elasticsearchSync/index.ts b/scripts/elasticsearchSync/index.ts
index 0ee0b2acb15..6157d2cd932 100644
--- a/scripts/elasticsearchSync/index.ts
+++ b/scripts/elasticsearchSync/index.ts
@@ -1,5 +1,5 @@
import type { FtsSearchSyncDrainResult } from '../../apps/server/src/services/ftsSearchSync';
-import { summarizeFtsSearchReindexError } from '../../packages/database/src/repositories/ftsSearchReindex';
+import { summarizeFtsSearchReindexError } from '../elasticsearchReindex/runtime/auditLogger';
import { parseElasticsearchFtsSearchSyncCliOptions } from './options';
type FtsSearchSyncService = {
diff --git a/scripts/installFtsSearchSyncCapture/index.ts b/scripts/installFtsSearchSyncCapture/index.ts
index 76f3deb833d..fd4693f5b7e 100644
--- a/scripts/installFtsSearchSyncCapture/index.ts
+++ b/scripts/installFtsSearchSyncCapture/index.ts
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
import * as dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';
-import { summarizeFtsSearchReindexError } from '../../packages/database/src/repositories/ftsSearchReindex';
+import { summarizeFtsSearchReindexError } from '../elasticsearchReindex/runtime/auditLogger';
import { runWithLockRetry as defaultRunWithLockRetry } from '../migrateServerDB/retry';
// Load environment variables in priority order:
@@ -25,8 +25,12 @@ type LoadRepository = () => Promise<FtsSearchSyncCaptureRepository>;
type RunWithLockRetry = (operation: () => Promise<void>) => Promise<void>;
type Logger = (...arguments_: unknown[]) => void;
+interface FtsSearchSyncCaptureEnvironment {
+ DATABASE_URL?: string;
+}
+
export type InstallFtsSearchSyncCaptureOptions = {
- env?: NodeJS.ProcessEnv;
+ env?: FtsSearchSyncCaptureEnvironment;
loadRepository?: LoadRepository;
runWithLockRetry?: RunWithLockRetry;
};
@@ -45,7 +49,7 @@ const loadRepository: LoadRepository = async () => {
};
export const installFtsSearchSyncCapture = async ({
- env: environment = process.env,
+ env: environment = { DATABASE_URL: process.env.DATABASE_URL },
loadRepository: load = loadRepository,
runWithLockRetry = defaultRunWithLockRetry,
}: InstallFtsSearchSyncCaptureOptions = {}) => {
diff --git a/tsconfig.json b/tsconfig.json
index b90190ce12a..23a90c43b3d 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -43,7 +43,6 @@
"apps/mobile/**",
"apps/share/**",
"apps/workbench/**",
- "scripts/**",
"tmp",
"temp",
".temp",
@@ -62,6 +61,9 @@
"tests/**/*.tsx",
"apps/server/**/*.ts",
"apps/server/**/*.tsx",
+ "scripts/elasticsearchReindex/**/*.ts",
+ "scripts/elasticsearchSync/**/*.ts",
+ "scripts/installFtsSearchSyncCapture/**/*.ts",
"*.ts",
"*.mts",
"*.cts",