Skip to content

Commit 6434dbc

Browse files
alvarezmelissa87elasticmachinekibanamachinestratoula
authored
[ML][Discover] Add change point view in Discover (elastic#265331)
## Summary This PR adds a change point view in Discover. ~~Closes elastic#232587 - moved to dedicated PR elastic#269572 https://github.com/user-attachments/assets/140673d7-cb98-43d4-b406-82965ad53363 <img width="1470" height="888" alt="image" src="https://github.com/user-attachments/assets/813293d6-edd2-43ab-9e50-7eb753faa9ab" /> ### Dependencies ~~This PR is blocked by [this](elastic/elasticsearch#145210) work which will add the BY functionality. I tested this by checking out that branch and running ES locally.~~ PR has been merged. Changes to `kbn-lens-embeddable-utils` package have been moved to a dedicated PR in elastic#269824 -- This PR needs to go in before this one. ### Notes for testing Example ES|QL commands using sample data (Note you may need to play around with the bucket length or the function - sum, count, avg, etc). For many change points: ``` FROM kibana_sample_data_logs | STATS avg_bytes=AVG(bytes) BY geo.dest, day=BUCKET(timestamp, 1d) | CHANGE_POINT avg_bytes ON day BY geo.dest | WHERE type IS NOT NULL ``` Multiple groupings: ``` FROM kibana_sample_data_logs | STATS sum_bytes=SUM(bytes) BY host, response.keyword, day=BUCKET(timestamp, 1 d) | CHANGE_POINT sum_bytes ON day BY host, response.keyword | WHERE type IS NOT NULL ``` No groupings: ``` FROM kibana_sample_data_logs | STATS avg_bytes=AVG(bytes) BY day=BUCKET(timestamp, 1d) | CHANGE_POINT avg_bytes ON day | WHERE type IS NOT NULL ``` Using TS also: ``` TS kibana_sample_data_logstsdb | STATS avg_bytes=AVG(bytes) BY geo.dest, day=BUCKET(@timestamp, 4h) | CHANGE_POINT avg_bytes ON day BY geo.dest | WHERE type IS NOT NULL ``` ### Checklist Check the PR satisfies following conditions. Reviewers should verify this PR satisfies this list as well. - [ ] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md) - [ ] [Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html) was added for features that require explanation or tutorials - [ ] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios - [ ] If a plugin configuration key changed, check if it needs to be allowlisted in the cloud and added to the [docker list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker) - [ ] This was checked for breaking HTTP API changes, and any breaking changes have been approved by the breaking-change committee. The `release_note:breaking` label should be applied in these situations. - [ ] [Flaky Test Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was used on any tests changed - [ ] The PR description includes the appropriate Release Notes section, and the correct `release_note:*` label is applied per the [guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process) - [ ] Review the [backport guidelines](https://docs.google.com/document/d/1VyN5k91e5OVumlc0Gb9RPa3h1ewuPE705nRtioPiTvY/edit?usp=sharing) and apply applicable `backport:*` labels. ### Identify risks Does this PR introduce any risks? For example, consider risks like hard to test bugs, performance regression, potential of data loss. Describe the risk, its severity, and mitigation for each identified risk. Invite stakeholders and evaluate how to proceed before merging. - [ ] [See some risk examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) - [ ] ... --------- Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Stratou <efstratia.kalafateli@elastic.co>
1 parent 6ca9939 commit 6434dbc

46 files changed

Lines changed: 3890 additions & 1 deletion

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/CODEOWNERS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,7 @@ src/platform/packages/shared/kbn-calculate-width-from-char-count @elastic/kibana
519519
src/platform/packages/shared/kbn-cases-components @elastic/kibana-cases
520520
src/platform/packages/shared/kbn-cbor @elastic/kibana-operations
521521
src/platform/packages/shared/kbn-cell-actions @elastic/security-threat-hunting
522+
src/platform/packages/shared/kbn-change-point-chart-viewer @elastic/ml-ui
522523
src/platform/packages/shared/kbn-chart-icons @elastic/kibana-visualizations
523524
src/platform/packages/shared/kbn-charts-theme @elastic/kibana-visualizations
524525
src/platform/packages/shared/kbn-cleanup-before-exit @elastic/observability-ui
@@ -1541,6 +1542,7 @@ x-pack/platform/test/serverless/api_integration/test_suites/platform_security @e
15411542
/src/platform/plugins/shared/discover/public/context_awareness/profile_providers/common/metrics_data_source_profile @elastic/obs-exploration-team
15421543
/src/platform/plugins/shared/discover/public/context_awareness/profile_providers/common/deprecation_logs_data_source_profile @elastic/kibana-data-discovery @elastic/kibana-core
15431544
/src/platform/plugins/shared/discover/public/context_awareness/profile_providers/common/patterns_data_source_profile @elastic/ml-ui
1545+
/src/platform/plugins/shared/discover/public/context_awareness/profile_providers/common/change_point_data_source_profile @elastic/ml-ui
15441546
/src/platform/plugins/shared/discover/public/context_awareness/profile_providers/observability @elastic/kibana-data-discovery @elastic/obs-exploration-team
15451547
/src/platform/plugins/shared/discover/public/context_awareness/profile_providers/observability/observability_document_profile @elastic/obs-exploration-team
15461548
/src/platform/plugins/shared/discover/public/context_awareness/profile_providers/observability/observability_root_profile @elastic/obs-exploration-team

.i18nrc.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@
9797
"src/platform/packages/shared/kbn-management",
9898
"packages/kbn-management"
9999
],
100+
"changePointChartViewer": "src/platform/packages/shared/kbn-change-point-chart-viewer/src",
100101
"metricsExperience": "src/platform/packages/shared/kbn-unified-chart-section-viewer/src",
101102
"monaco": "src/platform/packages/shared/kbn-monaco/src",
102103
"navigation": [

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,7 @@
277277
"@kbn/cbor": "link:src/platform/packages/shared/kbn-cbor",
278278
"@kbn/cell-actions": "link:src/platform/packages/shared/kbn-cell-actions",
279279
"@kbn/change-history": "link:x-pack/platform/packages/shared/kbn-change-history",
280+
"@kbn/change-point-chart-viewer": "link:src/platform/packages/shared/kbn-change-point-chart-viewer",
280281
"@kbn/chart-expressions-common": "link:src/platform/packages/shared/chart-expressions-common",
281282
"@kbn/chart-icons": "link:src/platform/packages/shared/kbn-chart-icons",
282283
"@kbn/charts-plugin": "link:src/platform/plugins/shared/charts",
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the "Elastic License
4+
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
export { LazyChangePointExperienceGrid } from './src/lazy_change_point_experience_grid';
11+
export type { ChangePointChartSectionActions, UnifiedChangePointGridProps } from './src/types';
12+
export {
13+
getPvalueImpactLevel,
14+
PVALUE_IMPACT_COLORS,
15+
PVALUE_IMPACT_LEVELS,
16+
} from './src/utils/get_pvalue_impact';
17+
export type { PvalueImpactLevel } from './src/utils/get_pvalue_impact';
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the "Elastic License
4+
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
module.exports = {
11+
preset: '@kbn/test',
12+
rootDir: '../../../../..',
13+
roots: ['<rootDir>/src/platform/packages/shared/kbn-change-point-chart-viewer'],
14+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"type": "shared-browser",
3+
"id": "@kbn/change-point-chart-viewer",
4+
"owner": "@elastic/ml-ui",
5+
"group": "platform",
6+
"visibility": "shared"
7+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
dependsOn:
2+
- '@kbn/embeddable-plugin'
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# This file is generated by the @kbn/moon package. Any manual edits will be erased!
2+
# To extend this, write your extensions/overrides to 'moon.extend.yml'
3+
# then regenerate this file with: 'node scripts/regenerate_moon_projects.js --update --filter @kbn/change-point-chart-viewer'
4+
5+
$schema: https://moonrepo.dev/schemas/project.json
6+
id: '@kbn/change-point-chart-viewer'
7+
layer: unknown
8+
owners:
9+
defaultOwner: '@elastic/ml-ui'
10+
toolchains:
11+
default: node
12+
language: typescript
13+
project:
14+
title: '@kbn/change-point-chart-viewer'
15+
description: Moon project for @kbn/change-point-chart-viewer
16+
channel: ''
17+
owner: '@elastic/ml-ui'
18+
sourceRoot: src/platform/packages/shared/kbn-change-point-chart-viewer
19+
dependsOn:
20+
- '@kbn/data-plugin'
21+
- '@kbn/es-query'
22+
- '@kbn/esql-utils'
23+
- '@kbn/expressions-plugin'
24+
- '@kbn/i18n'
25+
- '@kbn/lens-embeddable-utils'
26+
- '@kbn/lens-plugin'
27+
- '@kbn/react-hooks'
28+
- '@kbn/shared-ux-error-boundary'
29+
- '@kbn/shared-ux-utility'
30+
- '@kbn/ui-actions-plugin'
31+
- '@kbn/unified-histogram'
32+
- '@kbn/embeddable-plugin'
33+
- '@kbn/esql-types'
34+
- '@kbn/esql-language'
35+
- '@kbn/embeddable-plugin'
36+
tags:
37+
- shared-browser
38+
- package
39+
- prod
40+
- group-platform
41+
- shared
42+
- jest-unit-tests
43+
fileGroups:
44+
src:
45+
- '**/*.ts'
46+
- '**/*.tsx'
47+
- '!target/**/*'
48+
jest-config:
49+
- jest.config.js
50+
tasks: {}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"name": "@kbn/change-point-chart-viewer",
3+
"private": true,
4+
"version": "1.0.0",
5+
"license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0"
6+
}
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the "Elastic License
4+
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
import React from 'react';
11+
import { render, screen } from '@testing-library/react';
12+
import {
13+
KibanaErrorBoundaryProvider,
14+
KibanaSectionErrorBoundary,
15+
} from '@kbn/shared-ux-error-boundary';
16+
import { ChangePointExperienceGrid } from './change_point_experience_grid';
17+
import type { UnifiedChangePointGridProps } from './types';
18+
19+
// The APM client is pulled in transitively by the error boundary package.
20+
jest.mock('@elastic/apm-rum');
21+
22+
jest.mock('@kbn/unified-histogram', () => ({
23+
// Render children directly so we can test the grid content in isolation.
24+
ChartSectionTemplate: ({ children }: { children?: React.ReactNode }) => <>{children}</>,
25+
}));
26+
27+
jest.mock('@kbn/esql-utils', () => ({
28+
getChangePointSeriesColumns: jest.fn().mockReturnValue(undefined),
29+
}));
30+
31+
jest.mock('./utils/derive_change_point_cards', () => ({
32+
buildChangePointCards: jest.fn().mockReturnValue([]),
33+
}));
34+
35+
jest.mock('./utils/get_esql_query', () => ({
36+
getEsqlQuery: jest.fn().mockReturnValue('FROM logs-* | CHANGE_POINT count ON @timestamp'),
37+
}));
38+
39+
// Stub out ChangePointExperienceGridContent so happy-path tests don't need Lens.
40+
jest.mock('./change_point_experience_grid_content', () => ({
41+
ChangePointExperienceGridContent: () => (
42+
<div data-test-subj="changePointExperienceGridContent">grid content stub</div>
43+
),
44+
}));
45+
46+
// Render EuiDelayRender children immediately to avoid timer flakiness in loading tests.
47+
jest.mock('@elastic/eui', () => {
48+
const actual = jest.requireActual('@elastic/eui');
49+
return {
50+
...actual,
51+
EuiDelayRender: ({ children }: { children?: React.ReactNode }) => <>{children}</>,
52+
};
53+
});
54+
55+
// Minimal fetchParams with only the fields the grid reads directly.
56+
const fetchParams = {
57+
query: { esql: 'FROM logs-* | CHANGE_POINT count ON @timestamp' },
58+
table: { columns: [], rows: [] },
59+
timeRange: { from: 'now-15m', to: 'now' },
60+
relativeTimeRange: { from: 'now-15m', to: 'now' },
61+
filters: [],
62+
esqlVariables: [],
63+
} as unknown as UnifiedChangePointGridProps['fetchParams'];
64+
65+
const fetchParamsWithRows = {
66+
...fetchParams,
67+
table: {
68+
columns: [{ id: '@timestamp' }, { id: 'count' }, { id: 'type' }, { id: 'pvalue' }],
69+
rows: [
70+
{ '@timestamp': '2024-01-15T00:00:00.000Z', count: 5, type: 'mean_shift', pvalue: 0.001 },
71+
],
72+
},
73+
} as unknown as UnifiedChangePointGridProps['fetchParams'];
74+
75+
const minimalProps = {
76+
services: {} as never,
77+
fetchParams,
78+
fetch$: {} as never,
79+
isComponentVisible: true,
80+
isTabSelected: true,
81+
renderToggleActions: () => undefined,
82+
};
83+
84+
/**
85+
* Mirrors the error boundary structure used in LazyChangePointExperienceGrid:
86+
*
87+
* <KibanaErrorBoundaryProvider analytics={undefined}>
88+
* <KibanaSectionErrorBoundary sectionName="Change point charts">
89+
* <ChangePointExperienceGrid .../>
90+
* </KibanaSectionErrorBoundary>
91+
* </KibanaErrorBoundaryProvider>
92+
*/
93+
const renderWithBoundary = (props = minimalProps) =>
94+
render(
95+
<KibanaErrorBoundaryProvider analytics={undefined}>
96+
<KibanaSectionErrorBoundary sectionName="Change point charts">
97+
<ChangePointExperienceGrid {...props} />
98+
</KibanaSectionErrorBoundary>
99+
</KibanaErrorBoundaryProvider>
100+
);
101+
102+
describe('ChangePointExperienceGrid error boundary integration', () => {
103+
beforeEach(() => {
104+
// Suppress the expected React error-boundary console output so test output stays clean.
105+
jest.spyOn(console, 'error').mockImplementation(() => {});
106+
});
107+
108+
afterEach(() => {
109+
jest.restoreAllMocks();
110+
jest.requireMock('./utils/derive_change_point_cards').buildChangePointCards.mockReturnValue([]);
111+
});
112+
113+
it('renders the grid without errors under normal conditions', () => {
114+
// buildChangePointCards returns [] by default → "No change points" empty-prompt branch.
115+
const { container } = renderWithBoundary();
116+
// The section error boundary UI must NOT be present.
117+
expect(screen.queryByTestId('sectionErrorBoundaryPromptHeader')).not.toBeInTheDocument();
118+
// Some DOM output must exist (the grid renders at minimum an empty container).
119+
expect(container.firstChild).not.toBeNull();
120+
});
121+
122+
it('shows the section error boundary UI instead of crashing when buildChangePointCards throws', () => {
123+
// Simulate the kind of synchronous render-time crash the error boundary is there to catch
124+
// (e.g. malformed data, unexpected null reference inside a memoised helper).
125+
jest
126+
.requireMock('./utils/derive_change_point_cards')
127+
.buildChangePointCards.mockImplementation(() => {
128+
throw new Error('Simulated crash in buildChangePointCards');
129+
});
130+
131+
renderWithBoundary();
132+
133+
// The error boundary should have caught the throw and rendered its fallback heading.
134+
expect(screen.getByTestId('sectionErrorBoundaryPromptHeader')).toBeInTheDocument();
135+
// The normal grid output should not be present.
136+
expect(screen.queryByText('No change points detected.')).not.toBeInTheDocument();
137+
});
138+
});
139+
140+
describe('ChangePointExperienceGrid UI states', () => {
141+
const { buildChangePointCards, getChangePointSeriesColumns } = {
142+
buildChangePointCards: () =>
143+
jest.requireMock('./utils/derive_change_point_cards').buildChangePointCards,
144+
getChangePointSeriesColumns: () =>
145+
jest.requireMock('@kbn/esql-utils').getChangePointSeriesColumns,
146+
};
147+
148+
afterEach(() => {
149+
buildChangePointCards().mockReturnValue([]);
150+
getChangePointSeriesColumns().mockReturnValue(undefined);
151+
});
152+
153+
it('shows "No results yet" when not loading and table has no rows', () => {
154+
render(
155+
<ChangePointExperienceGrid
156+
{...minimalProps}
157+
fetchParams={fetchParams}
158+
isChartLoading={false}
159+
/>
160+
);
161+
expect(screen.getByText('No results yet')).toBeInTheDocument();
162+
});
163+
164+
it('shows "No change point series to chart" when table has rows but no cards', () => {
165+
buildChangePointCards().mockReturnValue([]);
166+
getChangePointSeriesColumns().mockReturnValue(undefined);
167+
render(
168+
<ChangePointExperienceGrid
169+
{...minimalProps}
170+
fetchParams={fetchParamsWithRows}
171+
isChartLoading={false}
172+
/>
173+
);
174+
expect(screen.getByText('No change point series to chart')).toBeInTheDocument();
175+
});
176+
177+
it('shows a skeleton when loading and table has no rows', () => {
178+
render(
179+
<ChangePointExperienceGrid
180+
{...minimalProps}
181+
fetchParams={fetchParams}
182+
isChartLoading={true}
183+
/>
184+
);
185+
// EuiSkeletonText renders multiple lines; at least one should be present.
186+
const skeleton = document.querySelector('.euiSkeletonText');
187+
expect(skeleton).not.toBeNull();
188+
});
189+
190+
it('renders grid content when table has rows and cards are available', () => {
191+
buildChangePointCards().mockReturnValue([{ id: 'card-1', title: 'Series 1' }]);
192+
getChangePointSeriesColumns().mockReturnValue({
193+
valueColumn: 'count',
194+
timeColumn: '@timestamp',
195+
});
196+
render(
197+
<ChangePointExperienceGrid
198+
{...minimalProps}
199+
fetchParams={fetchParamsWithRows}
200+
isChartLoading={false}
201+
/>
202+
);
203+
expect(screen.getByTestId('changePointExperienceGridContent')).toBeInTheDocument();
204+
});
205+
});

0 commit comments

Comments
 (0)