diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.test.ts index 62cce21ead636..34e2eb2c90122 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.test.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.test.ts @@ -2089,6 +2089,38 @@ describe('state_helpers', () => { }); }); + it('should remove operations indirectly referencing unavailable fields', () => { + const layer: IndexPatternLayer = { + columnOrder: ['col1', 'col2'], + columns: { + col1: { + label: '', + dataType: 'number', + operationType: 'moving_average', + isBucketed: false, + scale: 'ratio', + references: ['col2'], + timeScale: undefined, + filter: undefined, + params: { + window: 7, + }, + }, + col2: { + dataType: 'number', + isBucketed: false, + label: '', + operationType: 'average', + sourceField: 'xxx', + }, + }, + indexPatternId: 'original', + }; + const updatedLayer = updateLayerIndexPattern(layer, newIndexPattern); + expect(updatedLayer.columnOrder).toEqual([]); + expect(updatedLayer.columns).toEqual({}); + }); + it('should remove operations referencing fields with insufficient capabilities', () => { const layer: IndexPatternLayer = { columnOrder: ['col1', 'col2'], diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts index 7853b7da7956e..1661e5de8248e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/layer_helpers.ts @@ -929,9 +929,17 @@ export function updateLayerIndexPattern( layer: IndexPatternLayer, newIndexPattern: IndexPattern ): IndexPatternLayer { - const keptColumns: IndexPatternLayer['columns'] = _.pickBy(layer.columns, (column) => - isColumnTransferable(column, newIndexPattern) - ); + const keptColumns: IndexPatternLayer['columns'] = _.pickBy(layer.columns, (column) => { + if ('references' in column) { + return ( + isColumnTransferable(column, newIndexPattern) && + column.references.every((columnId) => + isColumnTransferable(layer.columns[columnId], newIndexPattern) + ) + ); + } + return isColumnTransferable(column, newIndexPattern); + }); const newColumns: IndexPatternLayer['columns'] = _.mapValues(keptColumns, (column) => { const operationDefinition = operationDefinitionMap[column.operationType]; return operationDefinition.transfer