Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(search): alias all OpenSearch indices for zero-downtime reindex (#3101)

gbirman5f141484558b
diff --git a/infra/stacks/opensearch/helpers/README.md b/infra/stacks/opensearch/helpers/README.md
index b6c473e375..6df9765096 100644
--- a/infra/stacks/opensearch/helpers/README.md
+++ b/infra/stacks/opensearch/helpers/README.md
@@ -1,10 +1,10 @@
# Opensearch Helpers
-This is a directory of simple helper files to interact with Opensearch and setup all necessary indices etc.
+Helper scripts to manage OpenSearch indices.
## Setup
-1. Create a `.env` file in this directory with the following variables:
+Create a `.env` file in this directory with:
```
OPENSEARCH_URL=
@@ -12,4 +12,250 @@ OPENSEARCH_USERNAME=
OPENSEARCH_PASSWORD=
```
-2. Run `bun scripts/${OPERATION}` to perform the desired operation.
+Then run `bun scripts/${OPERATION}.ts` to perform an operation.
+
+## Index aliasing
+
+Application code (Rust) reads/writes via stable alias names defined in
+`SearchIndex` / `OpenSearchEntityType::index_name()`:
+
+| Alias | Underlying index (current) |
+| -------------- | -------------------------- |
+| `channels` | `channels_v1` |
+| `chats` | `chats_v1` |
+| `documents` | `documents_v1` |
+| `emails` | `emails_v1` |
+| `call_records` | `call_records_v1` |
+
+The alias is the contract; the physical index is an implementation detail
+that can be swapped without a code deploy.
+
+### Helpers
+
+| Script | Purpose |
+| ---------------------------- | ---------------------------------------------------------------------- |
+| `verify_aliases.ts` | Pre/post-flight check: alias exists and points at the expected index. |
+| `add_alias.ts` | Idempotent additive alias (no reindex). Use to dual-alias an index. |
+| `reindex_with_alias_swap.ts` | Reindex + atomic swap (handles `remove_index` for bare physical case). |
+| `create_indices.ts` | Idempotent first-time creation of every versioned index + alias. |
+
+All three migration scripts default to `DRY_RUN=true`; pass `DRY_RUN=false` to apply.
+
+## Deploy ordering for this PR (read me first)
+
+The Rust SearchIndex enum starts using alias names for every index when
+this PR ships. Of the five aliases the new code references, four happen
+to coincide with the existing physical index name in dev/prod
+(`channels`, `chats`, `documents`, `call_records`), so OpenSearch
+resolves the write correctly even before any alias is added — those
+require **no** pre-merge action. The fifth, `emails`, does not exist
+yet (the index lives at `emails_v2` under the legacy `emails_alias`),
+so post-deploy email writes/reads would 404.
+
+Required pre-merge step in each environment:
+
+```sh
+DRY_RUN=false bun scripts/add_alias.ts emails emails_v2
+bun scripts/verify_aliases.ts # emails entry should now show -> emails_v2
+```
+
+This is purely additive — old code keeps writing through `emails_alias`,
+new code writes through `emails`, both resolve to `emails_v2`. Drop
+`emails_alias` after the new code is fully rolled out.
+
+The bare-physical → versioned migrations (`channels` → `channels_v1`,
+etc.) and the `emails_v2` → `emails_v1` standardisation are independent
+follow-up operations that can be scheduled per index using the playbook
+below; they are not deploy-blocking for this PR.
+
+## Migration playbook: bringing an existing environment to alias-based access
+
+Each environment starts in a different state. Before deploying code that
+relies on the new alias names, run the playbook for whichever index is
+not yet behind the expected alias. The order minimises the write window
+where new code could land before its alias is in place.
+
+Pre-flight: see what's missing.
+
+```sh
+bun scripts/verify_aliases.ts
+```
+
+The output flags each alias that's missing, points at the wrong index,
+or is currently a physical index (which needs a reindex). Three states
+show up in practice:
+
+1. **Bare physical index** (`channels`, `chats`, `documents`,
+ `call_records` in pre-migration envs). The name is a physical index
+ with no alias of the same name. Resolution: reindex + swap.
+2. **Already aliased under a legacy name** (`emails_v2` aliased as
+ `emails_alias`). The new code wants alias `emails`. Resolution: add
+ the new alias name additively, then drop the legacy alias once the
+ deploy is in.
+3. **Mismatched physical index** (`emails` alias pointing at `emails_v2`
+ when the canonical name is `emails_v1`). Resolution: reindex + swap.
+
+### State 1: bare physical index → versioned index behind alias
+
+```sh
+# 1. Create the new empty versioned physical index. Idempotent.
+# create_indices.ts detects that the alias name (e.g. "channels") is
+# currently a bare physical index and creates the new versioned index
+# *without* attempting to add the alias — the alias has to be added
+# atomically with the deletion of the conflicting physical index, and
+# that's the swap script's job.
+bun scripts/create_indices.ts
+
+# 2. Dry run the swap. Confirm the actions list looks correct.
+bun scripts/reindex_with_alias_swap.ts channels channels_v1
+
+# 3. Apply. The script reindexes channels -> channels_v1, validates doc
+# counts, then issues an atomic _aliases call:
+# [{ remove_index: { index: "channels" } },
+# { add: { index: "channels_v1", alias: "channels" } }]
+DRY_RUN=false bun scripts/reindex_with_alias_swap.ts channels channels_v1
+
+# 4. Replay writes that landed during the reindex window via the
+# search_processing_service backfill endpoints. Bound the window with
+# `since` set to just before step 3 started.
+
+# 5. Re-run verify.
+bun scripts/verify_aliases.ts
+```
+
+### State 2: legacy alias → add canonical alias additively, then drop legacy
+
+For `emails_v2` aliased as `emails_alias`, the new code uses alias
+`emails`. The safe order is:
+
+```sh
+# 1. Add the canonical alias on top of the existing physical index.
+# This is purely additive — emails_alias keeps working.
+DRY_RUN=false bun scripts/add_alias.ts emails emails_v2
+
+# 2. Verify both aliases now point at emails_v2.
+bun scripts/verify_aliases.ts
+
+# 3. Deploy the new application code. Old code still writes via
+# emails_alias; new code writes via emails. Both resolve to emails_v2.
+
+# 4. Once the new code is fully rolled out and stable, drop the legacy
+# alias via the OpenSearch _aliases API:
+# POST /_aliases { "actions": [{ "remove": { "index": "emails_v2", "alias": "emails_alias" }}] }
+```
+
+### State 3: standardise emails_v2 onto emails_v1 (optional cleanup)
+
+To bring the email physical index in line with the rest of the v1
+naming, run the swap script after the alias is in place:
+
+```sh
+# Prereq: the canonical `emails` alias already points at emails_v2 (state 2).
+# 1. Create emails_v1 with the same mapping. create_indices.ts notices
+# that the `emails` alias already points at emails_v2 (a different
+# index), so it creates emails_v1 *without* attempting to add the
+# alias. The swap in step 2 handles that atomically.
+bun scripts/create_indices.ts
+
+# 2. Dry run + apply.
+bun scripts/reindex_with_alias_swap.ts emails emails_v1
+DRY_RUN=false bun scripts/reindex_with_alias_swap.ts emails emails_v1
+
+# 3. Replay writes from the reindex window via backfill.
+# 4. Drop the old physical index.
+bun scripts/delete_indices.ts emails_v2
+```
+
+### Avoiding downtime — write window strategy
+
+The reindex script does `wait_for_completion=true` and then issues the
+atomic alias swap. Writes that arrive *during* the reindex land on the
+old index only and get cut off when the alias swaps. Two options:
+
+- **Replay (default)**: accept the write window, then run a backfill
+ bounded by `since=<reindex start time>` to replay anything that
+ arrived during reindex onto the new index. Idempotent on `_id`, so
+ re-running is safe.
+- **Pause writers**: stop the producers (SQS consumers in
+ search_processing_service) before the reindex, drain the queue, then
+ reindex with no live writes. Lower risk, but causes a real pause in
+ freshness rather than a backfill catch-up.
+
+The reindex script refuses the swap when the destination has fewer docs
+than the source, so it won't silently complete a half-finished migration.
+
+## Runbook: reindex with new mapping (zero downtime)
+
+Use when you need to change a mapping that requires a full reindex (e.g.
+field type change, analyzer change, breaking schema migration).
+
+1. **Create the new physical index** at the next version. Either bump the
+ version in `constants.ts` and run `bun scripts/create_indices.ts`, or
+ create directly via the OpenSearch API. Example: `documents_v2`.
+
+2. **Reindex + swap (dry run first)**:
+
+ ```sh
+ bun scripts/reindex_with_alias_swap.ts documents documents_v2
+ ```
+
+ This reads the current index behind the `documents` alias, reindexes
+ into `documents_v2`, validates doc counts, and prints the `_aliases`
+ actions it would apply. Nothing is changed.
+
+3. **Pause writers** (or accept that writes during reindex go to the old
+ index and need to be replayed). Backfill jobs are the most common
+ replay path — see `search_processing_service` backfill endpoints.
+
+4. **Apply the swap**:
+
+ ```sh
+ DRY_RUN=false bun scripts/reindex_with_alias_swap.ts documents documents_v2
+ ```
+
+ The script issues a single `_aliases` request that atomically removes
+ the alias from the old index and adds it to the new one (or
+ `remove_index` + `add` when the alias name was previously a physical
+ index).
+
+5. **Verify**: writes through the alias now land in `documents_v2`. Check
+ doc counts continue to grow on the new index. Use the search API to
+ confirm reads return expected results.
+
+6. **Replay** any writes that landed during the reindex window via the
+ backfill endpoints (filter by `since` to bound work).
+
+7. **Drop the old index** once you're confident:
+
+ ```sh
+ bun scripts/delete_indices.ts "documents_v1"
+ ```
+
+### Promoting an existing physical index to live behind an alias
+
+If an environment still has a raw physical index sharing the alias name
+(e.g. an older `channels` index), the swap script handles this — it
+detects the conflict and emits `remove_index` + `add` in the same atomic
+actions list. Run the migration to a versioned name:
+
+```sh
+# 1. Create the new versioned index with the desired mapping (use create_indices.ts after bumping versions, or call the API directly).
+# 2. Reindex + swap. The script will detect that "channels" is currently a physical index and handle removal atomically with the alias add.
+DRY_RUN=false bun scripts/reindex_with_alias_swap.ts channels channels_v1
+```
+
+### Dry-run verification
+
+Always run the script with `DRY_RUN=true` (the default) first. The output
+shows the exact `_aliases` actions list that would be POSTed — eyeball
+this before applying. Example output:
+
+```
+[DRY-RUN] Would run _aliases with actions:
+{
+ "actions": [
+ { "remove_index": { "index": "documents" } },
+ { "add": { "index": "documents_v1", "alias": "documents" } }
+ ]
+}
+```
diff --git a/infra/stacks/opensearch/helpers/constants.ts b/infra/stacks/opensearch/helpers/constants.ts
index c315aac183..88bab9e623 100644
--- a/infra/stacks/opensearch/helpers/constants.ts
+++ b/infra/stacks/opensearch/helpers/constants.ts
@@ -1,19 +1,36 @@
-const CHAT_INDEX = 'chats';
-const DOCUMENT_INDEX = 'documents';
-const EMAIL_INDEX = 'emails_v2';
-const CHANNEL_INDEX = 'channels';
-const CALL_RECORDS_INDEX = 'call_records';
-const CALL_RECORDS_ALIAS = 'call_records_alias';
+// Aliases — what application code references via SearchIndex/OpenSearchEntityType.
+// Aliases are stable; underlying physical indices behind them can be swapped
+// during a reindex via the OpenSearch _aliases API.
+export const CHANNELS_ALIAS = 'channels';
+export const CHATS_ALIAS = 'chats';
+export const DOCUMENTS_ALIAS = 'documents';
+export const EMAILS_ALIAS = 'emails';
+export const CALL_RECORDS_ALIAS = 'call_records';
-export {
- CHAT_INDEX,
- DOCUMENT_INDEX,
- EMAIL_INDEX,
- CHANNEL_INDEX,
- CALL_RECORDS_INDEX,
- CALL_RECORDS_ALIAS,
+// Underlying physical indices (versioned). Bump the suffix to roll a new
+// version, then swap the alias atomically.
+export const CHANNELS_INDEX = 'channels_v1';
+export const CHATS_INDEX = 'chats_v1';
+export const DOCUMENTS_INDEX = 'documents_v1';
+export const EMAILS_INDEX = 'emails_v1';
+export const CALL_RECORDS_INDEX = 'call_records_v1';
+
+export const ALIAS_TO_INDEX: Record<string, string> = {
+ [CHANNELS_ALIAS]: CHANNELS_INDEX,
+ [CHATS_ALIAS]: CHATS_INDEX,
+ [DOCUMENTS_ALIAS]: DOCUMENTS_INDEX,
+ [EMAILS_ALIAS]: EMAILS_INDEX,
+ [CALL_RECORDS_ALIAS]: CALL_RECORDS_INDEX,
};
+// Backward-compat shorthands used by older migration scripts. They now point
+// at the alias rather than the physical index, so reads/writes go through the
+// alias and survive future index swaps.
+export const CHANNEL_INDEX = CHANNELS_ALIAS;
+export const CHAT_INDEX = CHATS_ALIAS;
+export const DOCUMENT_INDEX = DOCUMENTS_ALIAS;
+export const EMAIL_INDEX = EMAILS_ALIAS;
+
export const SHARD_SETTINGS =
process.env.ENVIRONMENT === 'prod'
? {
diff --git a/infra/stacks/opensearch/helpers/package.json b/infra/stacks/opensearch/helpers/package.json
index 9807b2bde9..86180d07f4 100644
--- a/infra/stacks/opensearch/helpers/package.json
+++ b/infra/stacks/opensearch/helpers/package.json
@@ -9,6 +9,9 @@
"health": "bun run health.ts",
"create_indices": "bun run create_indices.ts",
"delete_indices": "bun run delete_indices.ts",
+ "add_alias": "bun run scripts/add_alias.ts",
+ "reindex_with_alias_swap": "bun run scripts/reindex_with_alias_swap.ts",
+ "verify_aliases": "bun run scripts/verify_aliases.ts",
"set_refresh_interval": "bun run set_refresh_interval.ts"
},
"author": "Will Hutchinson",
diff --git a/infra/stacks/opensearch/helpers/scripts/add_alias.test.ts b/infra/stacks/opensearch/helpers/scripts/add_alias.test.ts
new file mode 100644
index 0000000000..14eb17bc81
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/add_alias.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from 'bun:test';
+import { decideAddAlias } from './add_alias';
+
+describe('decideAddAlias', () => {
+ test('alias is currently a physical index — error (use swap script)', () => {
+ const out = decideAddAlias({
+ alias: 'channels',
+ targetIndex: 'channels_v1',
+ aliasAlreadyOnTarget: false,
+ aliasIsPhysicalIndex: true,
+ });
+ expect(out.kind).toBe('error');
+ });
+
+ test('alias already on target — no-op', () => {
+ const out = decideAddAlias({
+ alias: 'emails',
+ targetIndex: 'emails_v2',
+ aliasAlreadyOnTarget: true,
+ aliasIsPhysicalIndex: false,
+ });
+ expect(out.kind).toBe('noop');
+ });
+
+ test('alias does not exist anywhere — apply add', () => {
+ const out = decideAddAlias({
+ alias: 'emails',
+ targetIndex: 'emails_v2',
+ aliasAlreadyOnTarget: false,
+ aliasIsPhysicalIndex: false,
+ });
+ expect(out.kind).toBe('apply');
+ if (out.kind === 'apply') {
+ expect(out.action).toEqual({
+ add: { index: 'emails_v2', alias: 'emails' },
+ });
+ }
+ });
+});
diff --git a/infra/stacks/opensearch/helpers/scripts/add_alias.ts b/infra/stacks/opensearch/helpers/scripts/add_alias.ts
new file mode 100644
index 0000000000..7f939bf8b0
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/add_alias.ts
@@ -0,0 +1,139 @@
+/**
+ * Idempotent additive alias creation: adds an alias name on top of an
+ * existing physical index without disrupting any other alias already
+ * pointing at it.
+ *
+ * Use during the deploy-prep phase to introduce the new alias name (e.g.
+ * `emails`) alongside a legacy alias (`emails_alias`) on the same physical
+ * index, so the new code can deploy safely before the legacy alias is
+ * dropped.
+ *
+ * Usage:
+ * bun scripts/add_alias.ts <alias> <index>
+ *
+ * The script defaults to DRY-RUN. Set DRY_RUN=false to apply.
+ */
+import type { Client } from '@opensearch-project/opensearch';
+
+export type AddAliasState = {
+ alias: string;
+ targetIndex: string;
+ aliasAlreadyOnTarget: boolean;
+ aliasIsPhysicalIndex: boolean;
+};
+
+export type AddAliasOutcome =
+ | { kind: 'noop'; reason: string }
+ | { kind: 'apply'; action: Record<string, unknown> }
+ | { kind: 'error'; reason: string };
+
+/**
+ * Pure-function decision: given the observed state, what should we do?
+ *
+ * - Alias already exists on the target index → no-op.
+ * - Alias name is currently a physical index (not an alias) → error; this
+ * tool is for additive aliases only. Use reindex_with_alias_swap.ts to
+ * convert a physical index into an alias.
+ * - Otherwise → add the alias.
+ */
+export function decideAddAlias(state: AddAliasState): AddAliasOutcome {
+ const { alias, targetIndex, aliasAlreadyOnTarget, aliasIsPhysicalIndex } =
+ state;
+
+ if (aliasIsPhysicalIndex) {
+ return {
+ kind: 'error',
+ reason: `"${alias}" is a physical index, not an alias. Use reindex_with_alias_swap.ts to convert it.`,
+ };
+ }
+
+ if (aliasAlreadyOnTarget) {
+ return {
+ kind: 'noop',
+ reason: `alias "${alias}" already points at "${targetIndex}"`,
+ };
+ }
+
+ return {
+ kind: 'apply',
+ action: { add: { index: targetIndex, alias } },
+ };
+}
+
+async function main() {
+ await import('dotenv').then((m) => m.config());
+ const { client } = await import('../client');
+ const { IS_DRY_RUN } = await import('../constants');
+
+ const [aliasArg, targetIndexArg] = process.argv.slice(2);
+ if (!aliasArg || !targetIndexArg) {
+ console.error('Usage: bun scripts/add_alias.ts <alias> <index>');
+ process.exit(1);
+ }
+
+ const opensearchClient: Client = client();
+
+ const targetIndexExists = (
+ await opensearchClient.indices.exists({ index: targetIndexArg })
+ ).body;
+ if (!targetIndexExists) {
+ console.error(`Target index "${targetIndexArg}" does not exist.`);
+ process.exit(1);
+ }
+
+ const aliasIsPhysicalIndex = await (async () => {
+ const a = await opensearchClient.indices.existsAlias({ name: aliasArg });
+ if (a.body) return false;
+ const i = await opensearchClient.indices.exists({ index: aliasArg });
+ return i.body;
+ })();
+
+ const aliasAlreadyOnTarget = (
+ await opensearchClient.indices.existsAlias({
+ name: aliasArg,
+ index: targetIndexArg,
+ })
+ ).body;
+
+ const outcome = decideAddAlias({
+ alias: aliasArg,
+ targetIndex: targetIndexArg,
+ aliasAlreadyOnTarget,
+ aliasIsPhysicalIndex,
+ });
+
+ console.log(
+ `Add-alias ${IS_DRY_RUN ? '(DRY-RUN MODE)' : '(LIVE MODE)'}: alias=${aliasArg} target=${targetIndexArg}`
+ );
+
+ if (outcome.kind === 'error') {
+ console.error(outcome.reason);
+ process.exit(1);
+ }
+
+ if (outcome.kind === 'noop') {
+ console.log(`No-op: ${outcome.reason}`);
+ return;
+ }
+
+ const actions = [outcome.action];
+ if (IS_DRY_RUN) {
+ console.log('[DRY-RUN] Would run _aliases with actions:');
+ console.log(JSON.stringify({ actions }, null, 2));
+ console.log('\nTo apply, set DRY_RUN=false');
+ return;
+ }
+
+ console.log('Applying alias add...');
+ const resp = await opensearchClient.indices.updateAliases({
+ body: { actions },
+ });
+ console.log('response:', JSON.stringify(resp.body));
+}
+
+if (import.meta.main) {
+ main().catch((err) => {
+ console.error('Error', err);
+ process.exit(1);
+ });
+}
diff --git a/infra/stacks/opensearch/helpers/scripts/create_indices.test.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.test.ts
new file mode 100644
index 0000000000..df300e1822
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'bun:test';
+import { planCreateIndex } from './create_indices';
+
+describe('planCreateIndex', () => {
+ test('fresh env — index missing, alias free → create with alias', () => {
+ const plan = planCreateIndex({
+ indexExists: false,
+ aliasExistsOnIndex: false,
+ aliasNameIsPhysicalIndex: false,
+ aliasTargets: [],
+ });
+ expect(plan.kind).toBe('create_with_alias');
+ });
+
+ test('index already in place with alias → noop', () => {
+ const plan = planCreateIndex({
+ indexExists: true,
+ aliasExistsOnIndex: true,
+ aliasNameIsPhysicalIndex: false,
+ aliasTargets: ['__SELF__'],
+ });
+ expect(plan.kind).toBe('noop');
+ });
+
+ test('index exists, alias missing, alias free → add alias', () => {
+ const plan = planCreateIndex({
+ indexExists: true,
+ aliasExistsOnIndex: false,
+ aliasNameIsPhysicalIndex: false,
+ aliasTargets: [],
+ });
+ expect(plan.kind).toBe('add_alias');
+ });
+
+ test('mid-migration: alias name is a bare physical index, new index missing → create without alias and defer', () => {
+ const plan = planCreateIndex({
+ indexExists: false,
+ aliasExistsOnIndex: false,
+ aliasNameIsPhysicalIndex: true,
+ aliasTargets: [],
+ });
+ expect(plan.kind).toBe('create_without_alias');
+ if (plan.kind === 'create_without_alias') {
+ expect(plan.nextStep).toContain('reindex_with_alias_swap.ts');
+ }
+ });
+
+ test('mid-migration: alias name is a bare physical index, new index already created → defer alias only', () => {
+ const plan = planCreateIndex({
+ indexExists: true,
+ aliasExistsOnIndex: false,
+ aliasNameIsPhysicalIndex: true,
+ aliasTargets: [],
+ });
+ expect(plan.kind).toBe('defer_alias');
+ if (plan.kind === 'defer_alias') {
+ expect(plan.nextStep).toContain('reindex_with_alias_swap.ts');
+ }
+ });
+
+ test('mid-migration: alias points at a different index (e.g. emails -> emails_v2), new index missing → create without alias', () => {
+ const plan = planCreateIndex({
+ indexExists: false,
+ aliasExistsOnIndex: false,
+ aliasNameIsPhysicalIndex: false,
+ aliasTargets: ['emails_v2'],
+ });
+ expect(plan.kind).toBe('create_without_alias');
+ });
+
+ test('mid-migration: alias points at different index, new index already created → defer alias', () => {
+ const plan = planCreateIndex({
+ indexExists: true,
+ aliasExistsOnIndex: false,
+ aliasNameIsPhysicalIndex: false,
+ aliasTargets: ['emails_v2'],
+ });
+ expect(plan.kind).toBe('defer_alias');
+ });
+});
diff --git a/infra/stacks/opensearch/helpers/scripts/create_indices.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.ts
index 5908903055..7e2edb1a76 100644
--- a/infra/stacks/opensearch/helpers/scripts/create_indices.ts
+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.ts
@@ -3,458 +3,544 @@ import { client } from '../client';
import {
CALL_RECORDS_ALIAS,
CALL_RECORDS_INDEX,
- CHANNEL_INDEX,
- CHAT_INDEX,
- DOCUMENT_INDEX,
- EMAIL_INDEX,
+ CHANNELS_ALIAS,
+ CHANNELS_INDEX,
+ CHATS_ALIAS,
+ CHATS_INDEX,
+ DOCUMENTS_ALIAS,
+ DOCUMENTS_INDEX,
+ EMAILS_ALIAS,
+ EMAILS_INDEX,
SHARD_SETTINGS,
} from '../constants';
-async function createChannelIndex(opensearchClient: Client) {
- const channelIndexExists = (
- await opensearchClient.indices.exists({
- index: CHANNEL_INDEX,
- })
- ).body;
- if (!channelIndexExists) {
- console.log(`${CHANNEL_INDEX} index does not exist, creating...`);
+type CreateIndexArgs = {
+ indexName: string;
+ aliasName: string;
+ body: Record<string, unknown>;
+};
- await opensearchClient.indices.create({
- index: CHANNEL_INDEX,
- body: {
- settings: {
- ...SHARD_SETTINGS,
- refresh_interval: '1s',
- },
- mappings: {
- dynamic: 'false',
- properties: {
- // channel id
- entity_id: {
- type: 'keyword',
- },
- channel_type: {
- type: 'keyword',
- index: true,
- },
- org_id: {
- type: 'integer',
- index: true,
- },
- // channel message id
- message_id: {
- type: 'keyword',
- },
- thread_id: {
- type: 'keyword',
- index: true,
- },
- sender_id: {
- type: 'keyword',
- index: true,
- },
- mentions: {
- type: 'keyword',
- index: true,
- },
- content: {
- type: 'text',
- analyzer: 'standard',
- },
- created_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- updated_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- },
- },
- },
- });
- } else {
- console.log(`${CHANNEL_INDEX} index already exists`);
+export type CreateIndexState = {
+ indexExists: boolean;
+ aliasExistsOnIndex: boolean;
+ aliasNameIsPhysicalIndex: boolean;
+ aliasTargets: string[];
+};
+
+export type CreatePlan =
+ | { kind: 'noop'; reason: string }
+ | { kind: 'create_with_alias' }
+ | { kind: 'create_without_alias'; nextStep: string }
+ | { kind: 'add_alias' }
+ | { kind: 'defer_alias'; nextStep: string };
+
+/**
+ * Pure decision: given the observed cluster state for one (indexName,
+ * aliasName) pair, what should this script do?
+ *
+ * The interesting cases are mid-migration ones. If the alias name is
+ * currently a bare physical index (e.g. `channels` is a physical index
+ * and we want to create `channels_v1` aliased as `channels`), we can't
+ * add the alias yet — that has to happen atomically alongside the
+ * removal of the conflicting physical index, which is the swap script's
+ * job. So we create the new versioned index without an alias and tell
+ * the operator to run `reindex_with_alias_swap.ts` next. Same logic
+ * when the alias already points at a different index.
+ */
+export function planCreateIndex(state: CreateIndexState): CreatePlan {
+ const {
+ indexExists,
+ aliasExistsOnIndex,
+ aliasNameIsPhysicalIndex,
+ aliasTargets,
+ } = state;
+ const aliasOnDifferentIndex =
+ aliasTargets.length > 0 && !aliasTargets.includes('__SELF__');
+ // Caller passes '__SELF__' in aliasTargets when the alias already includes
+ // indexName, so we can keep this function pure of indexName.
+
+ const aliasIsBlocked = aliasNameIsPhysicalIndex || aliasOnDifferentIndex;
+ const aliasBlockReason = aliasNameIsPhysicalIndex
+ ? `alias name is currently a bare physical index`
+ : `alias points at ${aliasTargets.join(', ')}`;
+
+ if (indexExists) {
+ if (aliasExistsOnIndex) {
+ return { kind: 'noop', reason: 'index and alias already in place' };
+ }
+ if (aliasIsBlocked) {
+ return {
+ kind: 'defer_alias',
+ nextStep:
+ `index exists but alias "${aliasBlockReason}". Run ` +
+ `reindex_with_alias_swap.ts to complete the migration.`,
+ };
+ }
+ return { kind: 'add_alias' };
}
+
+ if (aliasIsBlocked) {
+ return {
+ kind: 'create_without_alias',
+ nextStep:
+ `creating index now; alias deferred (${aliasBlockReason}). ` +
+ `Run reindex_with_alias_swap.ts next to swap the alias atomically.`,
+ };
+ }
+
+ return { kind: 'create_with_alias' };
}
-async function createDocumentIndex(opensearchClient: Client) {
- const documentIndexExists = (
- await opensearchClient.indices.exists({
- index: DOCUMENT_INDEX,
+async function createIndexWithAlias(
+ opensearchClient: Client,
+ { indexName, aliasName, body }: CreateIndexArgs
+) {
+ const indexExists = (
+ await opensearchClient.indices.exists({ index: indexName })
+ ).body;
+
+ const aliasExistsOnIndex = (
+ await opensearchClient.indices.existsAlias({
+ name: aliasName,
+ index: indexName,
})
).body;
- if (!documentIndexExists) {
- console.log(`${DOCUMENT_INDEX} index does not exist, creating...`);
- await opensearchClient.indices.create({
- index: DOCUMENT_INDEX,
- body: {
- settings: {
- ...SHARD_SETTINGS,
- refresh_interval: '1s',
- },
- mappings: {
- dynamic: 'false',
- properties: {
- // The id of the document
- entity_id: {
- type: 'keyword',
- },
- // The node id of the document
- // For markdown, this is the parent node of a given text section
- // For pdf/docx, this is just a uuid that is not used
- node_id: {
- type: 'keyword',
- index: false,
- doc_values: true,
- },
- file_type: {
- type: 'keyword',
- index: false,
- doc_values: true,
- },
- owner_id: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- document_name: {
- type: 'text',
- fields: {
- keyword: {
- type: 'keyword',
- ignore_above: 128,
- },
- },
- },
- raw_content: {
- type: 'text',
- },
- content: {
- type: 'text',
- analyzer: 'standard',
- },
- updated_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- sub_type: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- },
- },
- },
- });
- } else {
- console.log(`${DOCUMENT_INDEX} index already exists`);
+ const aliasNameIsPhysicalIndex = await (async () => {
+ const a = await opensearchClient.indices.existsAlias({ name: aliasName });
+ if (a.body) return false;
+ const i = await opensearchClient.indices.exists({ index: aliasName });
+ return i.body;
+ })();
+
+ const rawAliasTargets = await (async () => {
+ try {
+ const r = await opensearchClient.indices.getAlias({ name: aliasName });
+ return Object.keys(r.body ?? {});
+ } catch {
+ return [] as string[];
+ }
+ })();
+ // Normalize: if the alias already includes our target index, we want
+ // planCreateIndex to ignore those targets. We collapse "alias touches
+ // indexName" to a sentinel so the pure function doesn't need indexName.
+ const aliasTargets = rawAliasTargets.includes(indexName)
+ ? ['__SELF__']
+ : rawAliasTargets;
+
+ const plan = planCreateIndex({
+ indexExists,
+ aliasExistsOnIndex,
+ aliasNameIsPhysicalIndex,
+ aliasTargets,
+ });
+
+ switch (plan.kind) {
+ case 'noop':
+ console.log(`${indexName}: ${plan.reason}`);
+ return;
+ case 'add_alias':
+ console.log(`Adding alias ${aliasName} -> ${indexName}`);
+ await opensearchClient.indices.putAlias({
+ index: indexName,
+ name: aliasName,
+ });
+ return;
+ case 'create_with_alias':
+ console.log(
+ `${indexName} does not exist, creating with alias ${aliasName}`
+ );
+ await opensearchClient.indices.create({
+ index: indexName,
+ body: { ...body, aliases: { [aliasName]: {} } },
+ });
+ return;
+ case 'create_without_alias':
+ console.log(`${indexName}: ${plan.nextStep}`);
+ await opensearchClient.indices.create({
+ index: indexName,
+ body,
+ });
+ return;
+ case 'defer_alias':
+ console.log(`${indexName}: ${plan.nextStep}`);
+ return;
}
}
-async function createChatIndex(opensearchClient: Client) {
- const chatIndexExists = (
- await opensearchClient.indices.exists({
- index: CHAT_INDEX,
- })
- ).body;
- if (!chatIndexExists) {
- console.log(`${CHAT_INDEX} index does not exist, creating...`);
+const CHANNEL_BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ refresh_interval: '1s',
+ },
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ // channel id
+ entity_id: {
+ type: 'keyword',
+ },
+ channel_type: {
+ type: 'keyword',
+ index: true,
+ },
+ org_id: {
+ type: 'integer',
+ index: true,
+ },
+ // channel message id
+ message_id: {
+ type: 'keyword',
+ },
+ thread_id: {
+ type: 'keyword',
+ index: true,
+ },
+ sender_id: {
+ type: 'keyword',
+ index: true,
+ },
+ mentions: {
+ type: 'keyword',
+ index: true,
+ },
+ content: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ created_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ updated_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ },
+ },
+};
- await opensearchClient.indices.create({
- index: CHAT_INDEX,
- body: {
- settings: {
- ...SHARD_SETTINGS,
- refresh_interval: '1s',
- },
- mappings: {
- dynamic: 'false',
- properties: {
- /* All chat messages are put into OpenSearch under a chat index and are associated by their chat_id, chat_message_id, user_id, role, updated_at, title and content. */
- // The id of the chat
- entity_id: {
- type: 'keyword',
- },
- // The chat message id
- chat_message_id: {
- type: 'keyword',
- index: false,
- doc_values: true,
- },
- user_id: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- role: {
- type: 'keyword',
- index: false,
- doc_values: true,
- },
- updated_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- title: {
- type: 'text',
- fields: {
- keyword: {
- type: 'keyword',
- ignore_above: 50,
- },
- },
- },
- content: {
- type: 'text',
- analyzer: 'standard',
- },
+const DOCUMENT_BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ refresh_interval: '1s',
+ },
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ entity_id: {
+ type: 'keyword',
+ },
+ node_id: {
+ type: 'keyword',
+ index: false,
+ doc_values: true,
+ },
+ file_type: {
+ type: 'keyword',
+ index: false,
+ doc_values: true,
+ },
+ owner_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ document_name: {
+ type: 'text',
+ fields: {
+ keyword: {
+ type: 'keyword',
+ ignore_above: 128,
},
},
},
- });
- } else {
- console.log(`${CHAT_INDEX} index already exists`);
- }
-}
-
-async function createEmailIndex(opensearchClient: Client) {
- const emailIndexExists = (
- await opensearchClient.indices.exists({
- index: EMAIL_INDEX,
- })
- ).body;
- if (!emailIndexExists) {
- console.log(`${EMAIL_INDEX} index does not exist, creating...`);
+ raw_content: {
+ type: 'text',
+ },
+ content: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ updated_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ sub_type: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ },
+ },
+};
- await opensearchClient.indices.create({
- index: EMAIL_INDEX,
- body: {
- settings: {
- ...SHARD_SETTINGS,
- refresh_interval: '2s', // We don't need emails to refresh often
- },
- mappings: {
- dynamic: 'false',
- properties: {
- // The thread id of the email
- entity_id: {
- type: 'keyword',
- },
- message_id: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- sender: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- reply_to: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- recipients: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- cc: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- bcc: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- sender_name: {
- type: 'text',
- analyzer: 'standard',
- },
- recipient_names: {
- type: 'text',
- analyzer: 'standard',
- },
- cc_names: {
- type: 'text',
- analyzer: 'standard',
- },
- bcc_names: {
- type: 'text',
- analyzer: 'standard',
- },
- labels: {
- type: 'keyword',
- index: false, // do not index labels
- doc_values: true,
- },
- // link id
- link_id: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- // macro user id
- user_id: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- updated_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- subject: {
- type: 'text',
- fields: {
- keyword: {
- type: 'keyword',
- ignore_above: 50,
- },
- },
- },
- sent_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- content: {
- type: 'text',
- analyzer: 'standard',
- },
+const CHAT_BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ refresh_interval: '1s',
+ },
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ entity_id: {
+ type: 'keyword',
+ },
+ chat_message_id: {
+ type: 'keyword',
+ index: false,
+ doc_values: true,
+ },
+ user_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ role: {
+ type: 'keyword',
+ index: false,
+ doc_values: true,
+ },
+ updated_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ title: {
+ type: 'text',
+ fields: {
+ keyword: {
+ type: 'keyword',
+ ignore_above: 50,
},
},
},
- });
- } else {
- console.log(`${EMAIL_INDEX} index already exists`);
- }
-}
-
-async function createCallRecordsIndex(opensearchClient: Client) {
- const callRecordsIndexExists = (
- await opensearchClient.indices.exists({
- index: CALL_RECORDS_INDEX,
- })
- ).body;
- if (!callRecordsIndexExists) {
- console.log(`${CALL_RECORDS_INDEX} index does not exist, creating...`);
+ content: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ },
+ },
+};
- await opensearchClient.indices.create({
- index: CALL_RECORDS_INDEX,
- body: {
- settings: {
- ...SHARD_SETTINGS,
- refresh_interval: '2s',
- },
- aliases: {
- [CALL_RECORDS_ALIAS]: {},
+const EMAIL_BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ refresh_interval: '2s',
+ },
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ entity_id: {
+ type: 'keyword',
+ },
+ message_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ sender: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ reply_to: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ recipients: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ cc: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ bcc: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ sender_name: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ recipient_names: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ cc_names: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ bcc_names: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ labels: {
+ type: 'keyword',
+ index: false,
+ doc_values: true,
+ },
+ link_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ user_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ updated_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ subject: {
+ type: 'text',
+ fields: {
+ keyword: {
+ type: 'keyword',
+ ignore_above: 50,
+ },
},
- // One doc per transcript segment; `_id` is the `transcript_id`.
- mappings: {
- dynamic: 'false',
- properties: {
- entity_id: {
- type: 'keyword',
- },
- transcript_id: {
- type: 'keyword',
- index: false,
- doc_values: true,
- },
- channel_id: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- participant_ids: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- channel_name: {
- type: 'text',
- fields: {
- keyword: {
- type: 'keyword',
- ignore_above: 128,
- },
- },
- },
- speaker_id: {
- type: 'keyword',
- index: true,
- doc_values: true,
- },
- sequence_num: {
- type: 'integer',
- index: false,
- doc_values: true,
- },
- content: {
- type: 'text',
- analyzer: 'standard',
- },
- started_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- ended_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- // Aliases for the shared `updated_at_sort` script.
- created_at_seconds: {
- type: 'alias',
- path: 'started_at_seconds',
- },
- updated_at_seconds: {
- type: 'alias',
- path: 'started_at_seconds',
- },
+ },
+ sent_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ content: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ },
+ },
+};
+
+const CALL_RECORDS_BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ refresh_interval: '2s',
+ },
+ // One doc per transcript segment; `_id` is the `transcript_id`.
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ entity_id: {
+ type: 'keyword',
+ },
+ transcript_id: {
+ type: 'keyword',
+ index: false,
+ doc_values: true,
+ },
+ channel_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ participant_ids: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ channel_name: {
+ type: 'text',
+ fields: {
+ keyword: {
+ type: 'keyword',
+ ignore_above: 128,
},
},
},
- });
- } else {
- console.log(`${CALL_RECORDS_INDEX} index already exists`);
- }
-}
+ speaker_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ sequence_num: {
+ type: 'integer',
+ index: false,
+ doc_values: true,
+ },
+ content: {
+ type: 'text',
+ analyzer: 'standard',
+ },
+ started_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ ended_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ created_at_seconds: {
+ type: 'alias',
+ path: 'started_at_seconds',
+ },
+ updated_at_seconds: {
+ type: 'alias',
+ path: 'started_at_seconds',
+ },
+ },
+ },
+};
async function createIndices() {
const opensearchClient = client();
console.log('Creating indices...');
try {
- await createDocumentIndex(opensearchClient);
- await createChatIndex(opensearchClient);
- await createEmailIndex(opensearchClient);
- await createChannelIndex(opensearchClient);
- await createCallRecordsIndex(opensearchClient);
+ await createIndexWithAlias(opensearchClient, {
+ indexName: DOCUMENTS_INDEX,
+ aliasName: DOCUMENTS_ALIAS,
+ body: DOCUMENT_BODY,
+ });
+ await createIndexWithAlias(opensearchClient, {
+ indexName: CHATS_INDEX,
+ aliasName: CHATS_ALIAS,
+ body: CHAT_BODY,
+ });
+ await createIndexWithAlias(opensearchClient, {
+ indexName: EMAILS_INDEX,
+ aliasName: EMAILS_ALIAS,
+ body: EMAIL_BODY,
+ });
+ await createIndexWithAlias(opensearchClient, {
+ indexName: CHANNELS_INDEX,
+ aliasName: CHANNELS_ALIAS,
+ body: CHANNEL_BODY,
+ });
+ await createIndexWithAlias(opensearchClient, {
+ indexName: CALL_RECORDS_INDEX,
+ aliasName: CALL_RECORDS_ALIAS,
+ body: CALL_RECORDS_BODY,
+ });
console.log('done');
} catch (error) {
console.error('Error', error);
}
}
-createIndices();
+if (import.meta.main) {
+ createIndices();
+}
diff --git a/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.test.ts b/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.test.ts
new file mode 100644
index 0000000000..43bfb11e9f
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, test } from 'bun:test';
+import { buildSwapActions } from './reindex_with_alias_swap';
+
+describe('buildSwapActions', () => {
+ test('alias already in place — remove from old, add to new', () => {
+ const actions = buildSwapActions({
+ alias: 'documents',
+ newIndex: 'documents_v2',
+ oldIndex: 'documents_v1',
+ aliasExists: true,
+ aliasNameIsPhysicalIndex: false,
+ });
+ expect(actions).toEqual([
+ { remove: { index: 'documents_v1', alias: 'documents' } },
+ { add: { index: 'documents_v2', alias: 'documents' } },
+ ]);
+ });
+
+ test('alias name is currently a physical index — remove_index then add', () => {
+ const actions = buildSwapActions({
+ alias: 'channels',
+ newIndex: 'channels_v1',
+ oldIndex: 'channels',
+ aliasExists: false,
+ aliasNameIsPhysicalIndex: true,
+ });
+ expect(actions).toEqual([
+ { remove_index: { index: 'channels' } },
+ { add: { index: 'channels_v1', alias: 'channels' } },
+ ]);
+ });
+
+ test('first-time alias setup — just add', () => {
+ const actions = buildSwapActions({
+ alias: 'documents',
+ newIndex: 'documents_v1',
+ oldIndex: undefined,
+ aliasExists: false,
+ aliasNameIsPhysicalIndex: false,
+ });
+ expect(actions).toEqual([
+ { add: { index: 'documents_v1', alias: 'documents' } },
+ ]);
+ });
+
+ test('no-op swap (oldIndex === newIndex) skips remove', () => {
+ const actions = buildSwapActions({
+ alias: 'documents',
+ newIndex: 'documents_v1',
+ oldIndex: 'documents_v1',
+ aliasExists: true,
+ aliasNameIsPhysicalIndex: false,
+ });
+ expect(actions).toEqual([
+ { add: { index: 'documents_v1', alias: 'documents' } },
+ ]);
+ });
+});
diff --git a/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.ts b/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.ts
new file mode 100644
index 0000000000..7ff6e82319
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.ts
@@ -0,0 +1,232 @@
+/**
+ * Reindex an index behind an alias to a new versioned index, then atomically
+ * swap the alias.
+ *
+ * Usage:
+ * bun scripts/reindex_with_alias_swap.ts <alias> <new_index> [<old_index>]
+ *
+ * Examples:
+ * # Roll documents to v2; resolve old physical index from current alias
+ * bun scripts/reindex_with_alias_swap.ts documents documents_v2
+ *
+ * # Promote a physical index that was created without an alias to live
+ * # behind one (no reindex needed in that case — pass the same name twice)
+ * bun scripts/reindex_with_alias_swap.ts call_records call_records old_call_records
+ *
+ * The script defaults to DRY-RUN. Set DRY_RUN=false to apply changes.
+ *
+ * Required env: OPENSEARCH_URL, OPENSEARCH_USERNAME, OPENSEARCH_PASSWORD.
+ */
+import type { Client } from '@opensearch-project/opensearch';
+
+export type SwapState = {
+ alias: string;
+ newIndex: string;
+ oldIndex?: string;
+ aliasExists: boolean;
+ aliasNameIsPhysicalIndex: boolean;
+};
+
+/**
+ * Build the atomic `_aliases` actions list for the swap. Pure function so it
+ * can be unit-tested without an OpenSearch connection.
+ *
+ * Cases:
+ * - Alias already exists pointing at oldIndex → remove from oldIndex, add to newIndex.
+ * - Alias name is currently a physical index (no alias yet) → remove_index +
+ * add alias atomically (OpenSearch allows this in a single _aliases call).
+ * - Neither exists → just add. (First-time alias setup.)
+ */
+export function buildSwapActions(
+ state: SwapState
+): Array<Record<string, unknown>> {
+ const { alias, newIndex, oldIndex, aliasExists, aliasNameIsPhysicalIndex } =
+ state;
+ const actions: Array<Record<string, unknown>> = [];
+ if (aliasNameIsPhysicalIndex && oldIndex === alias) {
+ actions.push({ remove_index: { index: alias } });
+ } else if (aliasExists && oldIndex && oldIndex !== newIndex) {
+ actions.push({ remove: { index: oldIndex, alias } });
+ }
+ actions.push({ add: { index: newIndex, alias } });
+ return actions;
+}
+
+async function resolveCurrentIndex(
+ opensearchClient: Client,
+ alias: string
+): Promise<string | undefined> {
+ try {
+ const response = await opensearchClient.indices.getAlias({ name: alias });
+ const indices = Object.keys(response.body ?? {});
+ if (indices.length > 1) {
+ console.warn(
+ `Alias "${alias}" points at multiple indices: ${indices.join(', ')}. ` +
+ `Pass <old_index> explicitly to disambiguate.`
+ );
+ return undefined;
+ }
+ return indices[0];
+ } catch (_err) {
+ return undefined;
+ }
+}
+
+async function refreshIndex(opensearchClient: Client, index: string) {
+ await opensearchClient.indices.refresh({ index });
+}
+
+async function countDocs(
+ opensearchClient: Client,
+ index: string
+): Promise<number> {
+ const res = await opensearchClient.count({ index });
+ return Number(res.body?.count ?? 0);
+}
+
+async function reindexAndSwap(
+ opensearchClient: Client,
+ args: { alias: string; newIndex: string; oldIndex?: string },
+ dryRun: boolean
+) {
+ const aliasArg = args.alias;
+ const newIndexArg = args.newIndex;
+ const oldIndexArg = args.oldIndex;
+
+ console.log('\n' + '='.repeat(60));
+ console.log(
+ `Reindex + alias swap ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`
+ );
+ console.log('='.repeat(60));
+
+ const alias = aliasArg;
+ const newIndex = newIndexArg;
+
+ const aliasExists = (
+ await opensearchClient.indices.existsAlias({ name: alias })
+ ).body;
+ const aliasAsIndexExists = (
+ await opensearchClient.indices.exists({ index: alias })
+ ).body;
+
+ let oldIndex: string | undefined = oldIndexArg;
+ if (!oldIndex) {
+ if (aliasExists) {
+ oldIndex = await resolveCurrentIndex(opensearchClient, alias);
+ } else if (aliasAsIndexExists) {
+ // The alias name currently resolves to a physical index — we'll need to
+ // delete that physical index in the same atomic actions block as the
+ // alias add, since OpenSearch cannot have an alias and an index share
+ // a name.
+ oldIndex = alias;
+ }
+ }
+
+ console.log(
+ `alias=${alias} new_index=${newIndex} old_index=${oldIndex ?? '<none>'}`
+ );
+
+ const newIndexExists = (
+ await opensearchClient.indices.exists({ index: newIndex })
+ ).body;
+ if (!newIndexExists) {
+ console.error(
+ `New index "${newIndex}" does not exist. Create it first (with the desired mapping) before running this script.`
+ );
+ process.exit(1);
+ }
+
+ if (oldIndex && oldIndex !== newIndex) {
+ if (dryRun) {
+ console.log(
+ `[DRY-RUN] Would reindex from ${oldIndex} -> ${newIndex} (wait_for_completion=true)`
+ );
+ } else {
+ console.log(`Reindexing ${oldIndex} -> ${newIndex} (synchronous)...`);
+ const reindexResp = await opensearchClient.reindex({
+ wait_for_completion: true,
+ refresh: true,
+ body: {
+ source: { index: oldIndex },
+ dest: { index: newIndex },
+ },
+ });
+ console.log('reindex response:', JSON.stringify(reindexResp.body));
+ }
+ } else {
+ console.log('Skipping reindex (no separate source index).');
+ }
+
+ if (!dryRun && oldIndex && oldIndex !== newIndex) {
+ await refreshIndex(opensearchClient, newIndex);
+ const oldCount = await countDocs(opensearchClient, oldIndex);
+ const newCount = await countDocs(opensearchClient, newIndex);
+ console.log(`doc count: old=${oldCount} new=${newCount}`);
+ if (newCount < oldCount) {
+ console.error(
+ `Refusing to swap: destination has fewer docs (${newCount} < ${oldCount}).`
+ );
+ process.exit(2);
+ }
+ }
+
+ const actions = buildSwapActions({
+ alias,
+ newIndex,
+ oldIndex,
+ aliasExists,
+ aliasNameIsPhysicalIndex: aliasAsIndexExists,
+ });
+
+ if (dryRun) {
+ console.log('[DRY-RUN] Would run _aliases with actions:');
+ console.log(JSON.stringify({ actions }, null, 2));
+ console.log('\nTo apply, set DRY_RUN=false');
+ return;
+ }
+
+ console.log('Applying alias swap...');
+ const swapResp = await opensearchClient.indices.updateAliases({
+ body: { actions },
+ });
+ console.log('swap response:', JSON.stringify(swapResp.body));
+
+ console.log('\nNext steps:');
+ console.log(
+ ` - Verify writes through alias "${alias}" land in "${newIndex}"`
+ );
+ console.log(
+ ` - Once confident, delete the old index: bun scripts/delete_indices.ts "${oldIndex ?? '<old>'}"`
+ );
+}
+
+async function main() {
+ // Dynamic imports — keep the module side-effect-free so the unit test can
+ // import `buildSwapActions` without firing OpenSearch network calls.
+ await import('dotenv').then((m) => m.config());
+ const { client } = await import('../client');
+ const { IS_DRY_RUN } = await import('../constants');
+
+ const [aliasArg, newIndexArg, oldIndexArg] = process.argv.slice(2);
+ if (!aliasArg || !newIndexArg) {
+ console.error(
+ 'Usage: bun scripts/reindex_with_alias_swap.ts <alias> <new_index> [<old_index>]'
+ );
+ process.exit(1);
+ }
+
+ await reindexAndSwap(
+ client(),
+ { alias: aliasArg, newIndex: newIndexArg, oldIndex: oldIndexArg },
+ IS_DRY_RUN
+ );
+}
+
+// Bun executes top-level statements only when the file is run directly, but we
+// still gate to be explicit and safe under different test runners.
+if (import.meta.main) {
+ main().catch((err) => {
+ console.error('Error', err);
+ process.exit(1);
+ });
+}
diff --git a/infra/stacks/opensearch/helpers/scripts/verify_aliases.test.ts b/infra/stacks/opensearch/helpers/scripts/verify_aliases.test.ts
new file mode 100644
index 0000000000..66a66172bd
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/verify_aliases.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, test } from 'bun:test';
+import { evaluateAlias } from './verify_aliases';
+
+describe('evaluateAlias', () => {
+ test('alias missing entirely is FAIL', () => {
+ const out = evaluateAlias({
+ alias: 'documents',
+ expectedIndex: 'documents_v1',
+ actualIndices: [],
+ aliasNameIsPhysicalIndex: false,
+ });
+ expect(out.ok).toBe(false);
+ expect(out.reason).toContain('does not exist');
+ });
+
+ test('alias name is currently a physical index is FAIL', () => {
+ const out = evaluateAlias({
+ alias: 'channels',
+ expectedIndex: 'channels_v1',
+ actualIndices: [],
+ aliasNameIsPhysicalIndex: true,
+ });
+ expect(out.ok).toBe(false);
+ expect(out.reason).toContain('physical index');
+ });
+
+ test('alias points at unexpected index is FAIL', () => {
+ const out = evaluateAlias({
+ alias: 'emails',
+ expectedIndex: 'emails_v1',
+ actualIndices: ['emails_v2'],
+ aliasNameIsPhysicalIndex: false,
+ });
+ expect(out.ok).toBe(false);
+ expect(out.reason).toContain('emails_v2');
+ });
+
+ test('alias points at multiple indices is FAIL', () => {
+ const out = evaluateAlias({
+ alias: 'emails',
+ expectedIndex: 'emails_v1',
+ actualIndices: ['emails_v1', 'emails_v2'],
+ aliasNameIsPhysicalIndex: false,
+ });
+ expect(out.ok).toBe(false);
+ expect(out.reason).toContain('multiple');
+ });
+
+ test('alias points at expected index is OK', () => {
+ const out = evaluateAlias({
+ alias: 'emails',
+ expectedIndex: 'emails_v1',
+ actualIndices: ['emails_v1'],
+ aliasNameIsPhysicalIndex: false,
+ });
+ expect(out.ok).toBe(true);
+ expect(out.reason).toBeUndefined();
+ });
+});
diff --git a/infra/stacks/opensearch/helpers/scripts/verify_aliases.ts b/infra/stacks/opensearch/helpers/scripts/verify_aliases.ts
new file mode 100644
index 0000000000..7a736ca2bc
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/verify_aliases.ts
@@ -0,0 +1,139 @@
+/**
+ * Pre/post-flight check: print a table of current alias state and compare
+ * against the expected mapping defined in constants.ts. Exits non-zero if
+ * any expected alias is missing, points at the wrong physical index, or
+ * resolves to multiple physical indices (which would make swap ambiguous).
+ *
+ * Run this before deploying code that depends on the new alias names, and
+ * again after a migration to confirm the end state.
+ *
+ * Usage:
+ * bun scripts/verify_aliases.ts
+ */
+import type { Client } from '@opensearch-project/opensearch';
+
+export type AliasState = {
+ alias: string;
+ expectedIndex: string;
+ actualIndices: string[];
+ aliasNameIsPhysicalIndex: boolean;
+};
+
+export type VerifyOutcome = {
+ ok: boolean;
+ reason?: string;
+};
+
+export function evaluateAlias(state: AliasState): VerifyOutcome {
+ const { alias, expectedIndex, actualIndices, aliasNameIsPhysicalIndex } =
+ state;
+
+ if (aliasNameIsPhysicalIndex && actualIndices.length === 0) {
+ return {
+ ok: false,
+ reason: `"${alias}" is a physical index — needs reindex+swap to become an alias for "${expectedIndex}"`,
+ };
+ }
+
+ if (actualIndices.length === 0) {
+ return {
+ ok: false,
+ reason: `alias "${alias}" does not exist`,
+ };
+ }
+
+ if (actualIndices.length > 1) {
+ return {
+ ok: false,
+ reason: `alias "${alias}" points at multiple indices: ${actualIndices.join(', ')}`,
+ };
+ }
+
+ if (actualIndices[0] !== expectedIndex) {
+ return {
+ ok: false,
+ reason: `alias "${alias}" points at "${actualIndices[0]}", expected "${expectedIndex}"`,
+ };
+ }
+
+ return { ok: true };
+}
+
+async function getActualIndices(
+ opensearchClient: Client,
+ alias: string
+): Promise<string[]> {
+ try {
+ const response = await opensearchClient.indices.getAlias({ name: alias });
+ return Object.keys(response.body ?? {});
+ } catch (_err) {
+ return [];
+ }
+}
+
+async function isPhysicalIndex(
+ opensearchClient: Client,
+ name: string
+): Promise<boolean> {
+ // exists returns true for both indices and aliases; combined with the
+ // empty-indices check from getActualIndices we can tell them apart.
+ const aliasResp = await opensearchClient.indices.existsAlias({ name });
+ if (aliasResp.body) return false;
+ const indexResp = await opensearchClient.indices.exists({ index: name });
+ return indexResp.body;
+}
+
+async function main() {
+ await import('dotenv').then((m) => m.config());
+ const { client } = await import('../client');
+ const { ALIAS_TO_INDEX } = await import('../constants');
+
+ const opensearchClient = client();
+
+ let allOk = true;
+ console.log('alias -> expected_index (actual)');
+ console.log('-'.repeat(70));
+
+ for (const [alias, expectedIndex] of Object.entries(ALIAS_TO_INDEX)) {
+ const actualIndices = await getActualIndices(opensearchClient, alias);
+ const aliasNameIsPhysicalIndex =
+ actualIndices.length === 0
+ ? await isPhysicalIndex(opensearchClient, alias)
+ : false;
+
+ const outcome = evaluateAlias({
+ alias,
+ expectedIndex,
+ actualIndices,
+ aliasNameIsPhysicalIndex,
+ });
+
+ const actualLabel = aliasNameIsPhysicalIndex
+ ? `<physical index "${alias}">`
+ : actualIndices.length === 0
+ ? '<missing>'
+ : actualIndices.join(', ');
+
+ const status = outcome.ok ? 'OK' : 'FAIL';
+ console.log(
+ `${alias.padEnd(20)} -> ${expectedIndex.padEnd(24)} (${actualLabel}) [${status}]`
+ );
+ if (!outcome.ok) {
+ console.log(` reason: ${outcome.reason}`);
+ allOk = false;
+ }
+ }
+
+ if (!allOk) {
+ console.error('\nAlias verification failed.');
+ process.exit(1);
+ }
+ console.log('\nAll aliases match expected state.');
+}
+
+if (import.meta.main) {
+ main().catch((err) => {
+ console.error('Error', err);
+ process.exit(1);
+ });
+}
diff --git a/rust/cloud-storage/models_opensearch/src/lib.rs b/rust/cloud-storage/models_opensearch/src/lib.rs
index 21033eeb7b..70569505e2 100644
--- a/rust/cloud-storage/models_opensearch/src/lib.rs
+++ b/rust/cloud-storage/models_opensearch/src/lib.rs
@@ -3,21 +3,23 @@
//! This crate should never contain utoipa or any service-level models.
//! This is purely a crate containing models used for opensearch directly.
-/// Enum for all the search indices in OpenSearch
+/// Enum for all the search indices in OpenSearch.
+///
+/// Every variant resolves to a stable alias name. The underlying physical
+/// indices live behind the alias and can be swapped via the OpenSearch
+/// `_aliases` API to support zero-downtime reindexing.
#[derive(Debug, Clone, Hash, Eq, PartialEq, strum::Display, strum::EnumString, strum::AsRefStr)]
-#[strum(serialize_all = "lowercase")]
+#[strum(serialize_all = "snake_case")]
pub enum SearchIndex {
- /// The channel index
+ /// The channel alias
Channels,
- /// The chat index
+ /// The chat alias
Chats,
- /// The document index
+ /// The document alias
Documents,
- /// aliased email index
- #[strum(serialize = "emails_alias")]
+ /// The email alias
Emails,
- /// aliased call records index
- #[strum(serialize = "call_records_alias")]
+ /// The call records alias
CallRecords,
}
@@ -34,8 +36,8 @@ pub enum SearchIndex {
serde::Serialize,
serde::Deserialize,
)]
-#[strum(serialize_all = "lowercase")]
-#[serde(rename_all = "lowercase")]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum SearchEntityType {
/// The channel entity type (has OpenSearch index)
Channels,
@@ -48,8 +50,6 @@ pub enum SearchEntityType {
/// The project entity type (Postgres-only)
Projects,
/// The call records entity type (has OpenSearch index)
- #[strum(serialize = "call_records")]
- #[serde(rename = "call_records")]
CallRecords,
}
@@ -66,8 +66,8 @@ pub enum SearchEntityType {
serde::Serialize,
serde::Deserialize,
)]
-#[strum(serialize_all = "lowercase")]
-#[serde(rename_all = "lowercase")]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum OpenSearchEntityType {
/// The channel index
Channels,
@@ -78,20 +78,20 @@ pub enum OpenSearchEntityType {
/// The email index
Emails,
/// The call records index
- #[strum(serialize = "call_records")]
- #[serde(rename = "call_records")]
CallRecords,
}
impl OpenSearchEntityType {
- /// Returns the index name to use for OpenSearch queries.
+ /// Returns the alias name to use for OpenSearch queries. The alias points
+ /// at the current physical index for this entity; reindexes swap the alias
+ /// without requiring a code change here.
pub fn index_name(&self) -> &'static str {
match self {
Self::Channels => "channels",
Self::Chats => "chats",
Self::Documents => "documents",
- Self::Emails => "emails_alias",
- Self::CallRecords => "call_records_alias",
+ Self::Emails => "emails",
+ Self::CallRecords => "call_records",
}
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
index bb1a981b42..264a707a92 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs
@@ -179,7 +179,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {
]
}
},
- {"term": {"_index": "emails_alias"}},
+ {"term": {"_index": "emails"}},
{"terms": {"link_id": ["link1", "link2"]}},
{
"bool": {
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
index 2811f4ffd2..7f1100efea 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -545,7 +545,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
},
{
"term": {
- "_index": "emails_alias"
+ "_index": "emails"
}
},
{