Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
d16b98d
base test
jesuswr Aug 12, 2025
dc2a7ba
added some logic to have updates before the migrator transformations
jesuswr Aug 12, 2025
d942626
remove dynamic, not needed
jesuswr Aug 12, 2025
1a1757f
improve tests
jesuswr Aug 12, 2025
3a2801a
zdt test done
jesuswr Aug 12, 2025
b6114e7
remove describe block
jesuswr Aug 12, 2025
b77a50b
improve test so it covers zdt and v2
jesuswr Aug 12, 2025
7c02519
add logs to zdt
jesuswr Aug 12, 2025
c6345ab
add logs to v2
jesuswr Aug 12, 2025
3ed0005
add tests for new sumarizeErrorsWithSameType
jesuswr Aug 12, 2025
a372afa
update tests for the update action
jesuswr Aug 12, 2025
cd9ad4f
add test for v2 model
jesuswr Aug 12, 2025
237fc8c
new test for stages
jesuswr Aug 12, 2025
496b071
Merge branch 'main' into optimistic-conc-control-tests
jesuswr Aug 12, 2025
22c7cd8
fix snapshots in a test
jesuswr Aug 13, 2025
779de83
fix more snapshots
jesuswr Aug 13, 2025
34fe33a
Merge branch 'main' into optimistic-conc-control-tests
jesuswr Aug 13, 2025
0c59109
fix test description
jesuswr Aug 13, 2025
314757d
update createBulkIn... so we can decide if we want optimisc.. or not
jesuswr Aug 26, 2025
5857b7d
Merge branch 'main' into optimistic-conc-control-tests
jesuswr Aug 26, 2025
3dd63ef
lint
jesuswr Aug 26, 2025
8aa95f7
fix test
jesuswr Aug 26, 2025
441a0de
fix tests
jesuswr Aug 26, 2025
cbb71ab
Merge branch 'main' into optimistic-conc-control-tests
jesuswr Aug 27, 2025
9d12416
remove logs
jesuswr Aug 28, 2025
7561ae1
clean logs
jesuswr Aug 28, 2025
3f95f13
undo change
jesuswr Aug 28, 2025
3d27850
clean
jesuswr Aug 28, 2025
2dc877c
Merge branch 'main' into optimistic-conc-control-tests
jesuswr Aug 28, 2025
5e63c3a
move id !== originId logic inside createBulkIndex...
jesuswr Aug 28, 2025
7abb899
Merge branch 'main' into optimistic-conc-control-tests
jesuswr Sep 1, 2025
a930da2
Update src/core/packages/saved-objects/migration-server-internal/src/…
jesuswr Sep 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,45 @@ describe('createBulkIndexOperationTuple', () => {
]
`);
});

it('includes if_seq_no and if_primary_term when originId is not defined', () => {
const document = {
_id: 'doc1',
_seq_no: 10,
_primary_term: 20,
_source: { type: 'cases', title: 'no originId' },
};
const [operation] = createBulkIndexOperationTuple(document);
expect(operation.index).toBeDefined();
expect((operation.index as any).if_seq_no).toBe(10);
expect((operation.index as any).if_primary_term).toBe(20);
});

it('includes if_seq_no and if_primary_term when originId === _id', () => {
const document = {
_id: 'doc2',
_seq_no: 11,
_primary_term: 21,
_source: { type: 'cases', title: 'originId equals _id', originId: 'doc2' },
};
const [operation] = createBulkIndexOperationTuple(document);
expect(operation.index).toBeDefined();
expect((operation.index as any).if_seq_no).toBe(11);
expect((operation.index as any).if_primary_term).toBe(21);
});

it('does NOT include if_seq_no and if_primary_term when originId !== _id', () => {
const document = {
_id: 'doc3',
_seq_no: 12,
_primary_term: 22,
_source: { type: 'cases', title: 'originId not equal _id', originId: 'other-id' },
};
const [operation] = createBulkIndexOperationTuple(document);
expect(operation.index).toBeDefined();
expect((operation.index as any).if_seq_no).toBeUndefined();
expect((operation.index as any).if_primary_term).toBeUndefined();
});
});

describe('getMigrationType', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ export const createBulkIndexOperationTuple = (
doc: SavedObjectsRawDoc,
typeIndexMap: Record<string, string> = {}
): BulkIndexOperationTuple => {
const idChanged = doc._source.originId && doc._source.originId !== doc._id;
return [
{
index: {
Expand All @@ -292,8 +293,9 @@ export const createBulkIndexOperationTuple = (
}),
// use optimistic concurrency control to ensure that outdated
// documents are only overwritten once with the latest version
...(typeof doc._seq_no !== 'undefined' && { if_seq_no: doc._seq_no }),
...(typeof doc._primary_term !== 'undefined' && { if_primary_term: doc._primary_term }),
...(typeof doc._seq_no !== 'undefined' && !idChanged && { if_seq_no: doc._seq_no }),
...(typeof doc._primary_term !== 'undefined' &&
!idChanged && { if_primary_term: doc._primary_term }),
},
},
doc._source,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ export const nextActionMap = (
batchSize: state.batchSize,
searchAfter: state.lastHitSortValue,
maxResponseSizeBytes: state.maxReadBatchSizeBytes,
seqNoPrimaryTerm: true,
}),
OUTDATED_DOCUMENTS_SEARCH_CLOSE_PIT: (state: OutdatedDocumentsSearchClosePit) =>
Actions.closePit({ client, pitId: state.pitId }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ export const nextActionMap = (context: MigratorContext) => {
searchAfter: state.lastHitSortValue,
batchSize: context.migrationConfig.batchSize,
query: state.outdatedDocumentsQuery,
seqNoPrimaryTerm: true,
}),
OUTDATED_DOCUMENTS_SEARCH_TRANSFORM: (state: OutdatedDocumentsSearchTransformState) =>
Actions.transformDocs({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import Path from 'path';
import fs from 'fs/promises';
import { range } from 'lodash';
import { type TestElasticsearchUtils } from '@kbn/core-test-helpers-kbn-server';
import type { SavedObjectsBulkCreateObject } from '@kbn/core-saved-objects-api-server';
import '../jest_matchers';
import { getKibanaMigratorTestKit, startElasticsearch } from '../kibana_migrator_test_kit';
import { parseLogFile } from '../test_utils';
import { getBaseMigratorParams, getSampleAType } from '../fixtures/zdt_base.fixtures';
import type {
SavedObjectModelTransformationDoc,
SavedObjectModelUnsafeTransformFn,
} from '@kbn/core-saved-objects-server';

export const logFilePath = Path.join(__dirname, 'optimistic_concurrency.test.log');

interface TestSOType {
boolean: boolean;
keyword: string;
}

describe('ZDT & V2 upgrades - optimistic concurrency tests', () => {
let esServer: TestElasticsearchUtils['es'];

beforeAll(async () => {
esServer = await startElasticsearch();
});

afterAll(async () => {
await esServer?.stop();
});

beforeEach(async () => {
await fs.unlink(logFilePath).catch(() => {});
jest.clearAllMocks();
});

it.each(['v2', 'zdt'] as const)(
'doesnt overwrite changes made while migrating (%s)',
async (migrationAlgorithm) => {
const { runMigrations, savedObjectsRepository, client } = await prepareScenario(
migrationAlgorithm
);

const originalBulkImplementation = client.bulk;
const spy = jest.spyOn(client, 'bulk');
spy.mockImplementation(function (this: typeof client, ...args) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clever way to introduce the updates at just the right time in the migration algorithm

// let's run some updates before we run the bulk operations
return Promise.all(
['a-0', 'a-3', 'a-4'].map((id) =>
savedObjectsRepository.update('sample_a', id, {
keyword: 'concurrent update that shouldnt be overwritten',
})
)
).then(() => {
return originalBulkImplementation.apply(this, args);
});
});

await runMigrations();

const records = await parseLogFile(logFilePath);
expect(records).toContainLogEntry('-> DONE');

const { saved_objects: sampleADocs } = await savedObjectsRepository.find<TestSOType>({
type: 'sample_a',
});

expect(
sampleADocs
.map((doc) => ({
id: doc.id,
keyword: doc.attributes.keyword,
}))
.sort((a, b) => a.id.localeCompare(b.id))
).toMatchInlineSnapshot(`
Array [
Object {
"id": "a-0",
"keyword": "concurrent update that shouldnt be overwritten",
},
Object {
"id": "a-1",
"keyword": "updated by the migrator",
},
Object {
"id": "a-2",
"keyword": "updated by the migrator",
},
Object {
"id": "a-3",
"keyword": "concurrent update that shouldnt be overwritten",
},
Object {
"id": "a-4",
"keyword": "concurrent update that shouldnt be overwritten",
},
]
`);
}
);

const prepareScenario = async (migrationAlgorithm: 'zdt' | 'v2') => {
await createBaseline();

const typeA = getSampleAType();

const transformFunc: SavedObjectModelUnsafeTransformFn<TestSOType, TestSOType> = (
doc: SavedObjectModelTransformationDoc<TestSOType>
) => {
const attributes = {
...doc.attributes,
keyword: 'updated by the migrator',
};
return { document: { ...doc, attributes } };
};
typeA.modelVersions = {
...typeA.modelVersions,
'2': {
changes: [
{
type: 'unsafe_transform',
transformFn: (typeSafeGuard) => typeSafeGuard(transformFunc),
},
],
},
};

const { runMigrations, client, savedObjectsRepository } = await getKibanaMigratorTestKit({
...getBaseMigratorParams({ migrationAlgorithm }),
logFilePath,
types: [typeA],
});

return { runMigrations, client, savedObjectsRepository };
};

const createBaseline = async () => {
const { runMigrations, savedObjectsRepository, client } = await getKibanaMigratorTestKit({
...getBaseMigratorParams(),
types: [getSampleAType()],
});

try {
await client.indices.delete({ index: '.kibana_1' });
} catch (e) {
/* index wasn't created, that's fine */
}

await runMigrations();

const sampleAObjs = range(5).map<SavedObjectsBulkCreateObject<TestSOType>>((number) => ({
id: `a-${number}`,
type: 'sample_a',
attributes: {
keyword: `a_${number}`,
boolean: true,
},
}));
await savedObjectsRepository.bulkCreate<TestSOType>(sampleAObjs);
};
});