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): async reindex with slicing + task polling (#3107)

gbirman04d54f228507
diff --git a/infra/stacks/opensearch/helpers/README.md b/infra/stacks/opensearch/helpers/README.md
index 6df9765096..8135e1727f 100644
--- a/infra/stacks/opensearch/helpers/README.md
+++ b/infra/stacks/opensearch/helpers/README.md
@@ -168,9 +168,24 @@ 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:
+The reindex script submits the reindex *async* (`wait_for_completion=false`)
+with `slices=auto` (one sub-task per primary shard) and polls the OpenSearch
+task API every `REINDEX_POLL_SECONDS` (default 10s) until it completes,
+then issues the atomic alias swap. The async submission keeps a 60+ minute
+documents reindex from being killed by the ALB / proxy idle timeout that a
+synchronous request would hit.
+
+Tunable env vars:
+
+- `REINDEX_SLICES` — `auto` (default; matches the primary shard count) or a
+ positive integer.
+- `REINDEX_POLL_SECONDS` — poll cadence in seconds (default 10).
+
+Ctrl-C during polling sends a `tasks.cancel` for the running reindex so it
+doesn't keep running orphaned in the cluster.
+
+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
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
index 43bfb11e9f..82639b9277 100644
--- a/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.test.ts
+++ b/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, test } from 'bun:test';
-import { buildSwapActions } from './reindex_with_alias_swap';
+import {
+ buildSwapActions,
+ formatTaskProgress,
+} from './reindex_with_alias_swap';
describe('buildSwapActions', () => {
test('alias already in place — remove from old, add to new', () => {
@@ -56,3 +59,38 @@ describe('buildSwapActions', () => {
]);
});
});
+
+describe('formatTaskProgress', () => {
+ test('empty status renders sensibly', () => {
+ expect(formatTaskProgress({})).toBe('[0s] 0/0 (?)');
+ });
+
+ test('mid-run progress shows percent and elapsed', () => {
+ const line = formatTaskProgress({
+ total: 1000,
+ created: 250,
+ updated: 50,
+ running_time_in_nanos: 12_000_000_000,
+ });
+ expect(line).toBe('[12s] 300/1000 (30.0%)');
+ });
+
+ test('appends conflicts only when non-zero', () => {
+ expect(
+ formatTaskProgress({
+ total: 100,
+ created: 100,
+ version_conflicts: 0,
+ running_time_in_nanos: 5_000_000_000,
+ })
+ ).toBe('[5s] 100/100 (100.0%)');
+ expect(
+ formatTaskProgress({
+ total: 100,
+ created: 90,
+ version_conflicts: 3,
+ running_time_in_nanos: 5_000_000_000,
+ })
+ ).toBe('[5s] 90/100 (90.0%) conflicts=3');
+ });
+});
diff --git a/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.ts b/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.ts
index 7ff6e82319..15130c4eb6 100644
--- a/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.ts
+++ b/infra/stacks/opensearch/helpers/scripts/reindex_with_alias_swap.ts
@@ -13,8 +13,17 @@
* # 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
*
+ * Reindex strategy: async submission with `slices=auto` (parallelises across
+ * primary shards) plus task-API polling. This keeps a 60+ minute documents
+ * reindex from being killed by the ALB / proxy idle timeout that a
+ * `wait_for_completion=true` request would hit.
+ *
* The script defaults to DRY-RUN. Set DRY_RUN=false to apply changes.
*
+ * Optional env:
+ * REINDEX_SLICES — slice count, defaults to "auto" (= shard count).
+ * REINDEX_POLL_SECONDS — poll interval in seconds, default 10.
+ *
* Required env: OPENSEARCH_URL, OPENSEARCH_USERNAME, OPENSEARCH_PASSWORD.
*/
import type { Client } from '@opensearch-project/opensearch';
@@ -84,14 +93,139 @@ async function countDocs(
return Number(res.body?.count ?? 0);
}
+export type TaskStatus = {
+ total?: number;
+ created?: number;
+ updated?: number;
+ deleted?: number;
+ batches?: number;
+ version_conflicts?: number;
+ noops?: number;
+ failures?: unknown[];
+ running_time_in_nanos?: number;
+};
+
+/**
+ * Format a single progress line from a reindex task status. Pure function
+ * so the formatting is unit-testable.
+ */
+export function formatTaskProgress(status: TaskStatus): string {
+ const total = status.total ?? 0;
+ const done = (status.created ?? 0) + (status.updated ?? 0);
+ const pct = total > 0 ? `${((done / total) * 100).toFixed(1)}%` : '?';
+ const elapsedSec = Math.floor((status.running_time_in_nanos ?? 0) / 1e9);
+ const conflicts = status.version_conflicts ?? 0;
+ const conflictsLabel = conflicts > 0 ? ` conflicts=${conflicts}` : '';
+ return `[${elapsedSec}s] ${done}/${total} (${pct})${conflictsLabel}`;
+}
+
+async function startReindexAsync(
+ opensearchClient: Client,
+ source: string,
+ dest: string,
+ slices: string | number
+): Promise<string> {
+ const resp = await opensearchClient.reindex({
+ wait_for_completion: false,
+ refresh: true,
+ slices,
+ body: {
+ source: { index: source },
+ dest: { index: dest },
+ },
+ });
+ const taskId = (resp.body as { task?: string }).task;
+ if (!taskId) {
+ throw new Error(
+ `reindex submission did not return a task id: ${JSON.stringify(resp.body)}`
+ );
+ }
+ return taskId;
+}
+
+async function getTask(
+ opensearchClient: Client,
+ taskId: string
+): Promise<{
+ completed: boolean;
+ task?: { status?: TaskStatus };
+ response?: unknown;
+ error?: unknown;
+}> {
+ // The opensearch-js client supports tasks.get(); fall back to raw transport
+ // if the API surface differs.
+ const resp = await opensearchClient.tasks.get({ task_id: taskId });
+ return resp.body as {
+ completed: boolean;
+ task?: { status?: TaskStatus };
+ response?: unknown;
+ error?: unknown;
+ };
+}
+
+async function cancelTask(opensearchClient: Client, taskId: string) {
+ try {
+ await opensearchClient.tasks.cancel({ task_id: taskId });
+ console.log(`Sent cancel for task ${taskId}.`);
+ } catch (err) {
+ console.warn('Cancel request failed:', err);
+ }
+}
+
+async function waitForTask(
+ opensearchClient: Client,
+ taskId: string,
+ pollMs: number
+): Promise<{ status: TaskStatus; failures: unknown[] }> {
+ // Allow Ctrl+C to cancel the running reindex rather than orphaning it.
+ let cancelled = false;
+ const onSigint = () => {
+ if (cancelled) return;
+ cancelled = true;
+ console.log('\nReceived SIGINT — cancelling reindex task...');
+ void cancelTask(opensearchClient, taskId);
+ };
+ process.on('SIGINT', onSigint);
+
+ try {
+ while (true) {
+ const t = await getTask(opensearchClient, taskId);
+ const status = t.task?.status ?? {};
+ console.log(`reindex progress: ${formatTaskProgress(status)}`);
+ if (t.completed) {
+ const failures =
+ (t.response as { failures?: unknown[] } | undefined)?.failures ?? [];
+ if (t.error) {
+ throw new Error(`reindex task failed: ${JSON.stringify(t.error)}`);
+ }
+ return { status, failures };
+ }
+ if (cancelled) {
+ throw new Error('reindex cancelled by operator');
+ }
+ await new Promise((r) => setTimeout(r, pollMs));
+ }
+ } finally {
+ process.off('SIGINT', onSigint);
+ }
+}
+
async function reindexAndSwap(
opensearchClient: Client,
- args: { alias: string; newIndex: string; oldIndex?: string },
+ args: {
+ alias: string;
+ newIndex: string;
+ oldIndex?: string;
+ slices: string | number;
+ pollMs: number;
+ },
dryRun: boolean
) {
const aliasArg = args.alias;
const newIndexArg = args.newIndex;
const oldIndexArg = args.oldIndex;
+ const slices = args.slices;
+ const pollMs = args.pollMs;
console.log('\n' + '='.repeat(60));
console.log(
@@ -139,19 +273,34 @@ async function reindexAndSwap(
if (oldIndex && oldIndex !== newIndex) {
if (dryRun) {
console.log(
- `[DRY-RUN] Would reindex from ${oldIndex} -> ${newIndex} (wait_for_completion=true)`
+ `[DRY-RUN] Would reindex from ${oldIndex} -> ${newIndex} (slices=${slices}, async + task polling every ${pollMs}ms)`
);
} 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));
+ console.log(
+ `Reindexing ${oldIndex} -> ${newIndex} async (slices=${slices})...`
+ );
+ const taskId = await startReindexAsync(
+ opensearchClient,
+ oldIndex,
+ newIndex,
+ slices
+ );
+ console.log(`Submitted reindex task: ${taskId}`);
+ const { status, failures } = await waitForTask(
+ opensearchClient,
+ taskId,
+ pollMs
+ );
+ if (failures.length > 0) {
+ console.error(
+ `Refusing to swap: reindex task reported ${failures.length} failures.`
+ );
+ console.error(JSON.stringify(failures.slice(0, 5), null, 2));
+ process.exit(2);
+ }
+ console.log(
+ `Reindex complete: ${status.created ?? 0} created, ${status.updated ?? 0} updated, ${status.version_conflicts ?? 0} conflicts.`
+ );
}
} else {
console.log('Skipping reindex (no separate source index).');
@@ -215,9 +364,34 @@ async function main() {
process.exit(1);
}
+ const slicesEnv = process.env.REINDEX_SLICES ?? 'auto';
+ const slices = slicesEnv === 'auto' ? 'auto' : Number.parseInt(slicesEnv, 10);
+ if (slices !== 'auto' && Number.isNaN(slices)) {
+ console.error(
+ `REINDEX_SLICES must be "auto" or a positive integer, got "${slicesEnv}"`
+ );
+ process.exit(1);
+ }
+ const pollSeconds = Number.parseInt(
+ process.env.REINDEX_POLL_SECONDS ?? '10',
+ 10
+ );
+ if (Number.isNaN(pollSeconds) || pollSeconds < 1) {
+ console.error(
+ `REINDEX_POLL_SECONDS must be a positive integer, got "${process.env.REINDEX_POLL_SECONDS}"`
+ );
+ process.exit(1);
+ }
+
await reindexAndSwap(
client(),
- { alias: aliasArg, newIndex: newIndexArg, oldIndex: oldIndexArg },
+ {
+ alias: aliasArg,
+ newIndex: newIndexArg,
+ oldIndex: oldIndexArg,
+ slices,
+ pollMs: pollSeconds * 1000,
+ },
IS_DRY_RUN
);
}