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): support Serverless migration locks (#19769)

YuTengjing7dec6a1039a0
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index de7d1c08cc0..6f41d32360a 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -140,6 +140,15 @@ For mapping changes, generation operations, repeat/resume behavior, or deploymen
[Mapping migration workflow](references/mapping-migrations.md). It routes to the public command guide
and adds recovery, automation, and local Docker rehearsal rules.
+- Treat managed and Serverless Elasticsearch APIs as capability-constrained. Create operational
+ metadata and control indexes with the smallest portable request, and add topology, storage, or
+ index settings only after verifying that the target service supports them; settings accepted by a
+ self-managed cluster may be rejected by a managed service.
+- Make idempotent Elasticsearch resource creation depend on the structured error type, such as
+ `resource_already_exists_exception`, not a broad HTTP status range. Preserve any other creation
+ failure and stop before follow-up reads or mutations instead of turning a rejected request into a
+ misleading verification error.
+
Elasticsearch cannot change an existing field's type or index-time analyzer in place. The code
declares the target and Elasticsearch records the live state, per entity:
diff --git a/scripts/elasticsearchReindex/runtime/__tests__/migrationLock.test.ts b/scripts/elasticsearchReindex/runtime/__tests__/migrationLock.test.ts
index 1249d9507d1..464a2276eab 100644
--- a/scripts/elasticsearchReindex/runtime/__tests__/migrationLock.test.ts
+++ b/scripts/elasticsearchReindex/runtime/__tests__/migrationLock.test.ts
@@ -26,6 +26,7 @@ class StatefulElasticsearch {
beforeNextDelete?: () => void;
createAcknowledged = true;
+ createFailure?: { body: unknown; status: number };
lockCreateError?: Error;
lockDeleteBody?: unknown;
lockReadBody?: unknown;
@@ -44,6 +45,9 @@ class StatefulElasticsearch {
const index = this.indexes.get(indexName);
if (method === 'PUT' && operation === undefined) {
+ if (this.createFailure) {
+ return jsonResponse(this.createFailure.body, this.createFailure.status);
+ }
if (index) return jsonResponse({ error: { type: 'resource_already_exists_exception' } }, 400);
const body = JSON.parse(String(init.body)) as { mappings: Record<string, unknown> };
this.indexes.set(indexName, { mappings: body.mappings });
@@ -146,7 +150,7 @@ describe('FtsSearchMigrationLockClient', () => {
expect(elasticsearch.indexes.has('preview-b-fts-search-control')).toBe(true);
});
- it('creates a strict, owned one-shard control index and releases after success', async () => {
+ it('creates a strict owned control index without unsupported serverless settings', async () => {
const elasticsearch = new StatefulElasticsearch();
vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
const client = createClient('test');
@@ -171,10 +175,26 @@ describe('FtsSearchMigrationLockClient', () => {
owner: { type: 'keyword' },
},
},
- settings: { number_of_shards: 1 },
});
});
+ it('does not misclassify an invalid create request as an existing index', async () => {
+ const elasticsearch = new StatefulElasticsearch();
+ elasticsearch.createFailure = {
+ body: { error: { type: 'illegal_argument_exception' } },
+ status: 400,
+ };
+ vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
+
+ await expect(createClient('test').acquire('--apply')).rejects.toMatchObject({
+ message: 'Elasticsearch migration control index creation failed (400)',
+ status: 400,
+ });
+ expect(elasticsearch.requests).toEqual([
+ { body: expect.any(String), method: 'PUT', pathname: '/test-fts-search-control' },
+ ]);
+ });
+
it('retains the lock when the callback fails and supports explicit recovery', async () => {
const elasticsearch = new StatefulElasticsearch();
vi.stubGlobal('fetch', vi.fn(elasticsearch.fetch));
diff --git a/scripts/elasticsearchReindex/runtime/migrationLock.ts b/scripts/elasticsearchReindex/runtime/migrationLock.ts
index 7728cdb146c..40de172af9b 100644
--- a/scripts/elasticsearchReindex/runtime/migrationLock.ts
+++ b/scripts/elasticsearchReindex/runtime/migrationLock.ts
@@ -36,6 +36,9 @@ const lockWriteResponseSchema = z.object({
const createIndexResponseSchema = z.object({ acknowledged: z.literal(true) });
const deleteLockResponseSchema = z.object({ result: z.literal('deleted') });
+const elasticsearchErrorResponseSchema = z.object({
+ error: z.object({ type: z.string() }).passthrough(),
+});
const lockReadResponseSchema = lockWriteResponseSchema.extend({
_source: lockSourceSchema,
@@ -220,7 +223,6 @@ export class FtsSearchMigrationLockClient {
const response = await this.request(`/${encodeURIComponent(this.controlIndex)}`, {
body: JSON.stringify({
mappings: controlMapping,
- settings: { number_of_shards: 1 },
}),
headers: { 'Content-Type': 'application/json' },
method: 'PUT',
@@ -245,9 +247,25 @@ export class FtsSearchMigrationLockClient {
return;
}
- // Concurrent creators and an already-present index both reach this path. Verification is
- // authoritative: authentication and transport failures must never be interpreted as existence.
+ let errorType: string | undefined;
if (response.status === 400 || response.status === 409) {
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch (cause) {
+ throw new FtsSearchMigrationLockError(
+ `Elasticsearch migration control index creation failed (${response.status})`,
+ { cause, status: response.status },
+ );
+ }
+ const parsed = elasticsearchErrorResponseSchema.safeParse(body);
+ errorType = parsed.success ? parsed.data.error.type : undefined;
+ }
+
+ // Concurrent creators and an already-present index reach this path. Verification is
+ // authoritative, but an arbitrary client error must retain its real create failure instead of
+ // being misreported as a missing pre-existing index.
+ if (errorType === 'resource_already_exists_exception') {
await this.assertControlIndexMapping();
return;
}