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.

🐛 fix(search): harden Elasticsearch reindex operations (#19772)

YuTengjing0bc3f57cd382
diff --git a/.agents/skills/full-text-search/references/mapping-migrations.md b/.agents/skills/full-text-search/references/mapping-migrations.md
index d69d4ebedb5..48a860248e3 100644
--- a/.agents/skills/full-text-search/references/mapping-migrations.md
+++ b/.agents/skills/full-text-search/references/mapping-migrations.md
@@ -77,10 +77,10 @@ same-version generation eligible for ordinary `--retire` and later `--purge`.
- Rollback is an optional recovery branch: select a retained, open older generation first, then
redeploy matching older code. Older sync code rejects a live generation newer than it declares.
Unlike forward promotion, rollback may accept an older stamped generation without its checkpoint.
-- Retire only while the declared generation is serving and rollback is no longer needed. `--retire`
- only closes eligible old indexes. Explicit `--purge` installs and verifies an exact-index template
- with `allow_auto_create: false` before deletion, requiring `manage_index_templates`. Keep these
- protection templates; conflicts fail closed. An empty Outbox is not a fence against paused workers.
+- Retire or purge only while the declared generation is serving and rollback is no longer needed.
+ `--purge` protects each eligible open or closed index with an exact `allow_auto_create: false`
+ template before direct deletion. `--retire` is optional and only works where `_close` is supported;
+ skip it on Elastic Cloud Serverless. Keep protection templates; conflicts fail closed.
- Mutating commands acquire a non-expiring lock in `<namespace>-fts-search-control`. Status reads
`migrationLock` without acquiring one. Failed/interrupted commands may retain the lock; stop the
old process and resolve uncertain requests before `--release-lock=<owner> --yes`. Never use timeout
@@ -120,6 +120,18 @@ does not establish production duration. Use bounded `--batch-size`, `--bulk-max-
options in `scripts/elasticsearchReindex/options.ts`. `--max-batches-per-entity` bounds a rehearsal or pause; exit
code zero alone does not mean the backfill is complete.
+- Never use production to test or tune migration parameters.
+- Exercise migration-script changes through the real workflow in both Docker and Dev PostgreSQL plus
+ Dev Elastic Cloud before production. Give every rehearsal an explicit timeout and the smallest
+ dataset or batch count that proves the behavior; never run a full large-table backfill just to test.
+- Design Elasticsearch scripts for Docker and Elastic Cloud compatibility; verify every API and
+ setting used instead of assuming the two environments support the same capabilities.
+- For large production migrations, consider Vercel Sandbox as an isolated execution environment to
+ improve throughput.
+- Minimize production impact: scope work to selected entities and their source tables. Reserve and
+ fence the base revision only when creating a checkpoint; resume it without another table lock.
+ Never lock unrelated capture tables for a single-entity migration.
+
For Docker self-hosting, startup migration is a blocking maintenance step, not an image-build step.
The application and manual migration tool must share the same durable `ES_REINDEX_STATE_DIR`.
The official Compose file mounts the existing reindex volume on both. Do not silently adopt indexes
diff --git a/docs/self-hosting/advanced/full-text-search.mdx b/docs/self-hosting/advanced/full-text-search.mdx
index d7e842a8252..eac94748908 100644
--- a/docs/self-hosting/advanced/full-text-search.mdx
+++ b/docs/self-hosting/advanced/full-text-search.mdx
@@ -246,7 +246,9 @@ docker compose run --rm fts-search-reindex \
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
+generations; do not pause application writes or the sync worker. Creating the checkpoint briefly
+fences only the PostgreSQL tables that can emit the selected entities; resuming the same checkpoint
+does not repeat that fence. After the backfill reports
`ready_for_incremental_sync` and the `messages` Outbox is idle, promote the exact physical index:
```bash
@@ -255,9 +257,11 @@ docker compose run --rm fts-search-reindex \
```
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.
+observation window so the alias can be promoted back to its exact name. Once rollback is no longer
+needed, run `--purge --entity=messages --yes`. Purge installs an exact-name auto-create guard before
+deleting each detached old index. Self-managed clusters may run `--retire --entity=messages --yes`
+first to close old indexes; Elastic Cloud Serverless does not support index close, so skip retire and
+purge directly.
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
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 654148571b9..6d66f9c220f 100644
--- a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
+++ b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx
@@ -199,14 +199,14 @@ 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 空闲后,按精确物理索引名切换:
+命令会输出 run ID,以及类似 `<namespace>-messages-v1-r<run-id>` 的索引名。若任务中断,使用相同命令并增加 `--run-id=<run-id>` 继续。持续同步会同时写入现有 generation 和重建 generation;不要暂停应用写入或同步 worker。首次创建 checkpoint 时只会短暂阻挡能够生成所选实体更新的 PostgreSQL 表;续跑同一 checkpoint 不会再次执行这一步。回填显示 `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`。
+alias 和逻辑 schema 版本保持不变。观察期内保留旧 generation,出现问题时可按其精确名称切回。确认无需回滚后,执行 `--purge --entity=messages --yes`。Purge 会先安装精确索引名的防自动创建规则,再删除每个已脱离 alias 的旧索引。自建集群可以先用 `--retire --entity=messages --yes` 关闭旧索引;Elastic Cloud Serverless 不支持关闭索引,应跳过 retire,直接 purge。
这一模式的安全边界:`ES_ALLOW_INSECURE_HTTP=true` 允许向非回环主机使用明文 HTTP,并允许省略
`ES_API_KEY`;但它永远不允许通过明文 HTTP 发送 API 密钥,因此不要把它与 `ES_API_KEY` 和 `http://`
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts
index 306333c189b..ebe36e98088 100644
--- a/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts
+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts
@@ -18,12 +18,13 @@ import {
topics,
users,
} from '../../../schemas';
-import { FtsSearchDocumentBuilder } from '../../ftsSearchDocument';
+import { FTS_SEARCH_DOCUMENT_ENTITIES, FtsSearchDocumentBuilder } from '../../ftsSearchDocument';
import { FtsSearchSyncOutboxRepository } from '..';
import captureHistory from '../captureHistory.json';
import {
FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS,
FTS_SEARCH_SYNC_MEMORY_CONTEXTS_GIN_INDEX,
+ getFtsSearchSyncCaptureSourceTables,
} from '../captureInfrastructure';
const USER_ID = 'fts-search-sync-integration-user';
@@ -71,7 +72,7 @@ const createRecordedRepository = (revisionRows: unknown[]) => {
const execute = vi.fn(async (statement: SQL) => {
const normalized = normalizeSql(statement);
statements.push(normalized);
- return normalized.includes('FROM fts_search_sync_revision_seq') ? { rows: revisionRows } : [];
+ return normalized.includes('fts_search_sync_revision_seq') ? { rows: revisionRows } : [];
});
const database = {
execute,
@@ -181,6 +182,13 @@ afterAll(async () => {
}, CAPTURE_INSTALL_TEST_TIMEOUT);
describe('FtsSearchSyncOutboxRepository', { concurrent: false }, () => {
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)(
+ 'maps %s to at least one capture source table',
+ (entity) => {
+ expect(getFtsSearchSyncCaptureSourceTables([entity])).not.toHaveLength(0);
+ },
+ );
+
it('pins immutable historical capture snapshots independently of current definitions', () => {
const digests = captureHistory.map((snapshot) => ({
digest: createHash('sha256').update(JSON.stringify(snapshot)).digest('hex'),
@@ -512,16 +520,37 @@ describe('FtsSearchSyncOutboxRepository', { concurrent: false }, () => {
);
it('reserves and fences revisions for a local full-reindex checkpoint', async () => {
- const revision = await repository.reserveRevisionWithWriteFence();
+ const revision = await repository.reserveRevisionWithWriteFence(FTS_SEARCH_DOCUMENT_ENTITIES);
expect(revision).toBeGreaterThan(0);
await expect(repository.readHighWaterRevision()).resolves.toBeGreaterThanOrEqual(revision);
});
+ it.each([
+ { entities: ['messages'] as const, tables: ['messages'] },
+ { entities: ['documents'] as const, tables: ['documents', 'knowledge_base_files'] },
+ ])('fences only capture sources for $entities', async ({ entities, tables }) => {
+ const { repository: recordedRepository, statements } = createRecordedRepository([
+ { revision: '42' },
+ ]);
+
+ await expect(recordedRepository.reserveRevisionWithWriteFence(entities)).resolves.toBe(42);
+ expect(statements).toHaveLength(3);
+ expect(statements[0]).toBe(
+ "SELECT nextval('fts_search_sync_revision_seq')::bigint AS revision",
+ );
+ expect(statements[1]).toBe("SET LOCAL lock_timeout = '3s'");
+ expect(statements[2]).toBe(
+ `LOCK TABLE ${tables.map((table) => `"public"."${table}"`).join(', ')} IN SHARE MODE`,
+ );
+ });
+
it('reads a committed revision boundary without allocating a new revision', async () => {
const before = await repository.readHighWaterRevision();
- await expect(repository.readCommittedRevisionBoundary()).resolves.toBe(before);
+ await expect(
+ repository.readCommittedRevisionBoundary(FTS_SEARCH_DOCUMENT_ENTITIES),
+ ).resolves.toBe(before);
await expect(repository.readHighWaterRevision()).resolves.toBe(before);
});
@@ -530,10 +559,10 @@ describe('FtsSearchSyncOutboxRepository', { concurrent: false }, () => {
{ revision: '42' },
]);
- await expect(recordedRepository.readCommittedRevisionBoundary()).resolves.toBe(42);
+ await expect(recordedRepository.readCommittedRevisionBoundary(['messages'])).resolves.toBe(42);
expect(statements).toHaveLength(3);
expect(statements[0]).toBe("SET LOCAL lock_timeout = '3s'");
- expect(statements[1]).toMatch(/^LOCK TABLE .* IN SHARE MODE$/);
+ expect(statements[1]).toBe('LOCK TABLE "public"."messages" IN SHARE MODE');
expect(statements[2]).toBe(
'SELECT CASE WHEN is_called THEN last_value ELSE 0 END AS revision FROM fts_search_sync_revision_seq',
);
@@ -542,7 +571,7 @@ describe('FtsSearchSyncOutboxRepository', { concurrent: false }, () => {
it('rejects an invalid committed revision boundary', async () => {
const { repository: recordedRepository } = createRecordedRepository([]);
- await expect(recordedRepository.readCommittedRevisionBoundary()).rejects.toThrow(
+ await expect(recordedRepository.readCommittedRevisionBoundary(['messages'])).rejects.toThrow(
'Failed to read a valid FTS search sync revision while reading the committed revision boundary',
);
});
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/captureInfrastructure.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/captureInfrastructure.ts
index 5bfc169ad07..c9a43900632 100644
--- a/packages/database/src/repositories/ftsSearchSyncOutbox/captureInfrastructure.ts
+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/captureInfrastructure.ts
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
import { sql } from 'drizzle-orm';
import { SEARCHABLE_TEXT_SQL_PATTERN } from '../../utils/searchableText';
+import type { FtsSearchDocumentEntity } from '../ftsSearchDocument';
interface CaptureFunctionDefinition {
body: string;
@@ -14,6 +15,8 @@ interface CaptureFunctionDefinition {
interface CaptureTriggerDefinition {
createSql: string;
+ /** Search entities whose Outbox rows this trigger can enqueue. */
+ entities: readonly FtsSearchDocumentEntity[];
name: string;
table: string;
}
@@ -229,6 +232,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'agents', 'user_id', 'visibility', 'workspace_id'
)`,
+ entities: ['agents'],
name: 'fts_search_sync_agents',
table: 'agents',
},
@@ -239,6 +243,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
'topics', 'agent_id,content,description,group_id,session_id,status,title,user_id,workspace_id',
'user_id', 'workspace_id'
)`,
+ entities: ['topics'],
name: 'fts_search_sync_topics',
table: 'topics',
},
@@ -248,6 +253,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'files', 'user_id', 'visibility', 'workspace_id'
)`,
+ entities: ['files'],
name: 'fts_search_sync_files',
table: 'files',
},
@@ -257,6 +263,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'knowledgeBases', 'is_public', 'user_id', 'visibility', 'workspace_id'
)`,
+ entities: ['knowledgeBases'],
name: 'fts_search_sync_knowledge_bases',
table: 'knowledge_bases',
},
@@ -266,6 +273,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'chatGroups', 'user_id', 'visibility', 'workspace_id'
)`,
+ entities: ['chatGroups'],
name: 'fts_search_sync_chat_groups',
table: 'chat_groups',
},
@@ -275,6 +283,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'documents', 'user_id', 'visibility', 'workspace_id'
)`,
+ entities: ['documents'],
name: 'fts_search_sync_documents',
table: 'documents',
},
@@ -285,6 +294,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
'messages', 'agent_id,content,group_id,role,session_id,summary,thread_id,topic_id,user_id,workspace_id',
'user_id', 'workspace_id'
)`,
+ entities: ['messages'],
name: 'fts_search_sync_messages',
table: 'messages',
},
@@ -294,6 +304,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'userMemories', 'user_id'
)`,
+ entities: ['userMemories'],
name: 'fts_search_sync_user_memories',
table: 'user_memories',
},
@@ -301,6 +312,13 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
createSql: `CREATE TRIGGER fts_search_sync_user_memories_fanout
AFTER INSERT OR DELETE OR UPDATE OF captured_at, details, memory_category, memory_layer, status, summary, tags, title, user_id ON public.user_memories
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_memory_fanout()`,
+ entities: [
+ 'memoryContexts',
+ 'memoryPreferences',
+ 'memoryActivities',
+ 'memoryIdentities',
+ 'memoryExperiences',
+ ],
name: 'fts_search_sync_user_memories_fanout',
table: 'user_memories',
},
@@ -310,6 +328,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'memoryContexts', 'user_id'
)`,
+ entities: ['memoryContexts'],
name: 'fts_search_sync_memory_contexts',
table: 'user_memories_contexts',
},
@@ -319,6 +338,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'memoryPreferences', 'user_id'
)`,
+ entities: ['memoryPreferences'],
name: 'fts_search_sync_memory_preferences',
table: 'user_memories_preferences',
},
@@ -328,6 +348,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'memoryActivities', 'user_id'
)`,
+ entities: ['memoryActivities'],
name: 'fts_search_sync_memory_activities',
table: 'user_memories_activities',
},
@@ -337,6 +358,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'memoryIdentities', 'user_id'
)`,
+ entities: ['memoryIdentities'],
name: 'fts_search_sync_memory_identities',
table: 'user_memories_identities',
},
@@ -346,6 +368,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'memoryExperiences', 'user_id'
)`,
+ entities: ['memoryExperiences'],
name: 'fts_search_sync_memory_experiences',
table: 'user_memories_experiences',
},
@@ -355,6 +378,7 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
'personaDocuments', 'user_id'
)`,
+ entities: ['personaDocuments'],
name: 'fts_search_sync_persona_documents',
table: 'user_memory_persona_documents',
},
@@ -362,11 +386,25 @@ const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
createSql: `CREATE TRIGGER fts_search_sync_knowledge_base_files
AFTER INSERT OR DELETE OR UPDATE OF file_id, knowledge_base_id ON public.knowledge_base_files
FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_knowledge_base_files()`,
+ entities: ['files', 'documents'],
name: 'fts_search_sync_knowledge_base_files',
table: 'knowledge_base_files',
},
];
+export const getFtsSearchSyncCaptureSourceTables = (
+ entities: readonly FtsSearchDocumentEntity[],
+) => {
+ const selected = new Set(entities);
+ return [
+ ...new Set(
+ CAPTURE_TRIGGER_DEFINITIONS.filter(({ entities: capturedEntities }) =>
+ capturedEntities.some((entity) => selected.has(entity)),
+ ).map(({ table }) => table),
+ ),
+ ];
+};
+
export const normalizeFtsSearchSyncCaptureDefinition = (definition: string) => {
const compact = definition
.trim()
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts
index edb1476816a..c5584c95a30 100644
--- a/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts
+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts
@@ -10,6 +10,7 @@ import {
FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS,
FTS_SEARCH_SYNC_CAPTURE_TRIGGER_STATEMENTS,
FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS,
+ getFtsSearchSyncCaptureSourceTables,
normalizeFtsSearchSyncCaptureDefinition,
} from './captureInfrastructure';
@@ -50,13 +51,6 @@ const ACKNOWLEDGEMENT_DEADLOCK_MAX_ATTEMPTS = 3;
const ACKNOWLEDGEMENT_DEADLOCK_RETRY_BASE_DELAY_MS = 10;
const POSTGRES_DEADLOCK_DETECTED = '40P01';
-const FTS_SEARCH_SYNC_CAPTURE_SOURCE_TABLE_IDENTIFIERS = sql.join(
- [...new Set(FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS.map(({ table }) => table))].map(
- (table) => sql`${sql.identifier('public')}.${sql.identifier(table)}`,
- ),
- sql`, `,
-);
-
type FtsSearchSyncExecutor = Pick<LobeChatDatabase, 'execute'>;
type FtsSearchSyncDatabase = Pick<LobeChatDatabase, 'execute' | 'transaction'>;
@@ -312,11 +306,18 @@ const revisionNumber = (value: number | string | undefined, operation: string, m
return revision;
};
-const lockCaptureSourceWrites = async (transaction: FtsSearchSyncExecutor): Promise<void> => {
- await transaction.execute(sql`SET LOCAL lock_timeout = '3s'`);
- await transaction.execute(
- sql`LOCK TABLE ${FTS_SEARCH_SYNC_CAPTURE_SOURCE_TABLE_IDENTIFIERS} IN SHARE MODE`,
+const lockCaptureSourceWrites = async (
+ transaction: FtsSearchSyncExecutor,
+ entities: readonly FtsSearchDocumentEntity[],
+): Promise<void> => {
+ const sourceTables = getFtsSearchSyncCaptureSourceTables(entities);
+ if (sourceTables.length === 0) throw new Error('Cannot fence writes for an empty entity set');
+ const sourceTableIdentifiers = sql.join(
+ sourceTables.map((table) => sql`${sql.identifier('public')}.${sql.identifier(table)}`),
+ sql`, `,
);
+ await transaction.execute(sql`SET LOCAL lock_timeout = '3s'`);
+ await transaction.execute(sql`LOCK TABLE ${sourceTableIdentifiers} IN SHARE MODE`);
};
/** Durable claim and settlement operations for the PostgreSQL-triggered search outbox. */
@@ -457,9 +458,11 @@ export class FtsSearchSyncOutboxRepository {
* locks could include a revision whose Outbox row is still invisible and later commits after the
* validation snapshot. The locks close that race without allocating a revision or mutating rows.
*/
- async readCommittedRevisionBoundary(): Promise<number> {
+ async readCommittedRevisionBoundary(
+ entities: readonly FtsSearchDocumentEntity[] = FTS_SEARCH_DOCUMENT_ENTITIES,
+ ): Promise<number> {
return this.db.transaction(async (transaction) => {
- await lockCaptureSourceWrites(transaction);
+ await lockCaptureSourceWrites(transaction, entities);
const result = await transaction.execute(sql`
SELECT CASE WHEN is_called THEN last_value ELSE 0 END AS revision
FROM fts_search_sync_revision_seq
@@ -476,7 +479,9 @@ export class FtsSearchSyncOutboxRepository {
* Without this fence, a long transaction could commit an older Outbox revision after the
* backfill has already written stale data at the newer base revision.
*/
- async reserveRevisionWithWriteFence(): Promise<number> {
+ async reserveRevisionWithWriteFence(
+ entities: readonly FtsSearchDocumentEntity[],
+ ): Promise<number> {
return this.db.transaction(async (transaction) => {
const result = await transaction.execute(sql`
SELECT nextval('fts_search_sync_revision_seq')::bigint AS revision
@@ -486,18 +491,11 @@ export class FtsSearchSyncOutboxRepository {
'reserving a reindex version',
1,
);
- await lockCaptureSourceWrites(transaction);
+ await lockCaptureSourceWrites(transaction, entities);
return revision;
});
}
- /** Re-establishes the write fence before resuming a checkpoint created by an older process. */
- async fenceSourceWrites(): Promise<void> {
- await this.db.transaction(async (transaction) => {
- await lockCaptureSourceWrites(transaction);
- });
- }
-
async acknowledgeMany(works: FtsSearchSyncWork[]): Promise<FtsSearchSyncWork[]> {
if (works.length === 0) return [];
diff --git a/scripts/elasticsearchReindex/index.ts b/scripts/elasticsearchReindex/index.ts
index a0f8436afdf..11acbbb0589 100644
--- a/scripts/elasticsearchReindex/index.ts
+++ b/scripts/elasticsearchReindex/index.ts
@@ -265,7 +265,7 @@ const outbox = new FtsSearchSyncOutboxRepository(db);
const repository = new FtsSearchReindexFileRepository({
readCaptureFingerprint: () => outbox.readCaptureFingerprint(),
readHighWaterRevision: () => outbox.readHighWaterRevision(),
- reserveRevisionWithWriteFence: () => outbox.reserveRevisionWithWriteFence(),
+ reserveRevisionWithWriteFence: (entities) => outbox.reserveRevisionWithWriteFence(entities),
stateDirectory,
});
@@ -839,9 +839,6 @@ const applyGeneration = async ({
);
},
});
- if (existing && existing.run.status !== 'ready_for_incremental_sync') {
- await outbox.fenceSourceWrites();
- }
auditLogger = new FtsSearchReindexFileLogger({
runId: prepared.run.id,
sessionId: randomUUID(),
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
index 1d8e07d298b..7977d6e1d82 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/checkpointRepository.test.ts
@@ -59,6 +59,22 @@ describe('FtsSearchReindexFileRepository', () => {
});
});
+ it('fences only selected entities once when creating a checkpoint, not when resuming it', async () => {
+ const reserveRevisionWithWriteFence = vi.fn(async () => ++revision);
+ const scopedRepository = new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: vi.fn(async () => captureFingerprint),
+ readHighWaterRevision: vi.fn(async () => revision),
+ reserveRevisionWithWriteFence,
+ stateDirectory,
+ });
+
+ const created = await scopedRepository.createOrResume('scoped-search', 1, ['messages']);
+ const resumed = await scopedRepository.createOrResume('scoped-search', 1, ['messages']);
+
+ expect(resumed.run.id).toBe(created.run.id);
+ expect(reserveRevisionWithWriteFence).toHaveBeenCalledExactlyOnceWith(['messages']);
+ });
+
it('refuses to resume a checkpoint when capture definitions changed', async () => {
const state = await repository.createOrResume('changed-capture-search', 1);
await repository.completeEntity(state.run.id, 'agents');
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
index a3c46b7064a..315ad3f1946 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/elasticsearchClient.test.ts
@@ -891,6 +891,43 @@ describe('FtsSearchReindexHttpClient', () => {
expect(beforeMutation).not.toHaveBeenCalled();
});
+ it('accepts unsafe-integer priorities on unrelated Elastic Cloud templates', async () => {
+ const index = 'lobehub-messages-v1';
+ const templateName = getRetiredIndexProtectionTemplateName(index);
+ const fetchMock = vi.fn().mockResolvedValue(
+ response({
+ index_templates: [
+ {
+ index_template: {
+ _meta: { index, owner: 'lobehub-fts-search-retirement' },
+ allow_auto_create: false,
+ index_patterns: [index],
+ priority: 1_000_000,
+ template: {},
+ },
+ name: templateName,
+ },
+ {
+ index_template: {
+ index_patterns: ['.elastic-cloud-*'],
+ priority: Number.MAX_SAFE_INTEGER + 1,
+ template: {},
+ },
+ name: 'elastic-cloud-defaults',
+ },
+ ],
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureRetiredIndexProtection(index)).resolves.toBeUndefined();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
it('refuses to shadow an external template matching the retired index', async () => {
const fetchMock = vi.fn().mockResolvedValue(
response({
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
index d11f5b612f3..d0c69b2fb9a 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/generationService.test.ts
@@ -856,7 +856,7 @@ describe('retireGenerations', () => {
});
describe('purgeRetiredGenerations', () => {
- it('deletes only closed, detached, managed generations after installing deletion protection', async () => {
+ it('deletes open and closed detached managed generations after installing deletion protection', async () => {
setDeclaredVersion(ENTITY, 3);
const unmanaged = buildGeneration(physicalIndex(0), { aliased: false, state: 'closed' });
const client = createClient([
@@ -873,15 +873,22 @@ describe('purgeRetiredGenerations', () => {
namespace: NAMESPACE,
readCheckpoint: createCheckpointReader({ 3: createRunState(3, 'completed') }),
}),
- ).resolves.toEqual({ alias: ALIAS, deleted: [physicalIndex(2)], kept: physicalIndex(3) });
- expect(client.ensureRetiredIndexProtection).toHaveBeenCalledExactlyOnceWith(physicalIndex(2));
- expect(client.deleteIndex).toHaveBeenCalledExactlyOnceWith(physicalIndex(2));
+ ).resolves.toEqual({
+ alias: ALIAS,
+ deleted: [physicalIndex(1), physicalIndex(2)],
+ kept: physicalIndex(3),
+ });
+ expect(client.ensureRetiredIndexProtection.mock.calls).toEqual([
+ [physicalIndex(1)],
+ [physicalIndex(2)],
+ ]);
+ expect(client.deleteIndex.mock.calls).toEqual([[physicalIndex(1)], [physicalIndex(2)]]);
});
it('rejects deletion while the retired generation checkpoint is still backfilling', async () => {
setDeclaredVersion(ENTITY, 2);
const client = createClient([
- buildManagedGeneration(1, { aliased: false, state: 'closed' }),
+ buildManagedGeneration(1, { aliased: false, state: 'open' }),
buildManagedGeneration(2, { isWriteIndex: true }),
]);
@@ -926,7 +933,7 @@ describe('planRetiredGenerations', () => {
`${physicalIndex(4)} is neither older than the live generation nor marked as superseded by it`,
],
close: [physicalIndex(1)],
- purgeCandidates: [physicalIndex(2)],
+ purgeCandidates: [physicalIndex(1), physicalIndex(2)],
});
expect(client.closeIndex).not.toHaveBeenCalled();
expect(client.deleteIndex).not.toHaveBeenCalled();
diff --git a/scripts/elasticsearchReindex/runtime/checkpointRepository.ts b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
index e6e8050e25e..589493b943f 100644
--- a/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
+++ b/scripts/elasticsearchReindex/runtime/checkpointRepository.ts
@@ -79,7 +79,7 @@ export interface FtsSearchReindexRunState {
export interface FtsSearchReindexFileRepositoryOptions {
readCaptureFingerprint: () => Promise<string>;
readHighWaterRevision: () => Promise<number>;
- reserveRevisionWithWriteFence: () => Promise<number>;
+ reserveRevisionWithWriteFence: (entities: readonly FtsSearchDocumentEntity[]) => Promise<number>;
stateDirectory: string;
}
@@ -550,7 +550,7 @@ export class FtsSearchReindexFileRepository {
}
/** Reserve outside the file lock so a slow database connection cannot stale the local lock. */
- const baseRevision = await this.options.reserveRevisionWithWriteFence();
+ const baseRevision = await this.options.reserveRevisionWithWriteFence(entities);
if (!Number.isSafeInteger(baseRevision) || baseRevision < 1) {
throw new Error('Failed to reserve a valid search reindex base revision');
}
diff --git a/scripts/elasticsearchReindex/runtime/generationService.ts b/scripts/elasticsearchReindex/runtime/generationService.ts
index 93ed05fa5f2..2b7542d7e7c 100644
--- a/scripts/elasticsearchReindex/runtime/generationService.ts
+++ b/scripts/elasticsearchReindex/runtime/generationService.ts
@@ -483,8 +483,8 @@ export const planRetiredGenerations = (
close.push(candidate.index);
} else {
alreadyClosed.push(candidate.index);
- purgeCandidates.push(candidate.index);
}
+ purgeCandidates.push(candidate.index);
}
return { alreadyClosed, blockedBy, close, purgeCandidates };
};
@@ -530,7 +530,7 @@ export interface FtsSearchPurgeRetiredGenerationsResult {
kept: string;
}
-/** Permanently deletes closed, detached generations after installing an exact-index write guard. */
+/** Permanently deletes detached generations after installing an exact-index write guard. */
export const purgeRetiredGenerations = async ({
client,
entity,
@@ -549,10 +549,7 @@ export const purgeRetiredGenerations = async ({
const plan = planRetiredGenerations(status);
const backfilling = status.candidates.find(
- (candidate) =>
- isRetirementCandidate(status, candidate) &&
- candidate.state === 'closed' &&
- candidate.backfill === 'backfilling',
+ (candidate) => isRetirementCandidate(status, candidate) && candidate.backfill === 'backfilling',
);
if (backfilling) {
throw new Error(`${backfilling.index} backfill is still running; it cannot be purged`);
diff --git a/scripts/elasticsearchReindex/runtime/retiredIndexProtection.ts b/scripts/elasticsearchReindex/runtime/retiredIndexProtection.ts
index c73eb6ec8fc..2cde3586c2c 100644
--- a/scripts/elasticsearchReindex/runtime/retiredIndexProtection.ts
+++ b/scripts/elasticsearchReindex/runtime/retiredIndexProtection.ts
@@ -13,7 +13,7 @@ const indexTemplateSchema = z.object({
composed_of: z.array(z.string()).optional(),
data_stream: z.unknown().optional(),
index_patterns: z.array(z.string()),
- priority: z.number().int().optional(),
+ priority: z.number().optional(),
template: z.record(z.string(), z.unknown()).optional(),
})
.passthrough(),