Skip to content

Commit

Permalink
[ML] Anomaly Detection: adds ability to delete forecasts from job (el…
Browse files Browse the repository at this point in the history
…astic#194896)

## Summary

Related issues:
-  elastic#18511
-  elastic#192301

In this PR, in Job management > expanded row > Forecasts tab - a delete
action has been added to each row in the forecasts table. A confirmation
modal allows the user to confirm the delete action.

In the SMV view, the forecast being currently viewed is now highlighted
in the Forecast modal to make it easier to identify.

![image](https://github.com/user-attachments/assets/87814889-d41d-4780-98ab-695c6f12a023)

<img width="881" alt="image"
src="https://github.com/user-attachments/assets/accbd7d9-1bae-4f1f-af8f-8bd36eae0572">

<img width="1099" alt="image"
src="https://github.com/user-attachments/assets/6011936d-3773-41ce-bbce-3ca4c0154cab">

Dark mode:

<img width="882" alt="image"
src="https://github.com/user-attachments/assets/cbec6fc8-0c62-4e34-9546-0124ae80a568">

### Checklist

Delete any items that are not applicable to this PR.

- [ ] 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/packages/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
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] 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 renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)

---------

Co-authored-by: Elastic Machine <[email protected]>
Co-authored-by: kibanamachine <[email protected]>
(cherry picked from commit f4a4a68)
  • Loading branch information
alvarezmelissa87 committed Oct 9, 2024
1 parent 327ce6a commit 0ff3940
Show file tree
Hide file tree
Showing 19 changed files with 283 additions and 74 deletions.
2 changes: 2 additions & 0 deletions x-pack/plugins/ml/common/types/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const adminMlCapabilities = {
canResetJob: false,
canUpdateJob: false,
canForecastJob: false,
canDeleteForecast: false,
canCreateDatafeed: false,
canDeleteDatafeed: false,
canStartStopDatafeed: false,
Expand Down Expand Up @@ -222,6 +223,7 @@ export const featureCapabilities: FeatureCapabilities = {
'canResetJob',
'canUpdateJob',
'canForecastJob',
'canDeleteForecast',
'canCreateDatafeed',
'canDeleteDatafeed',
'canStartStopDatafeed',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,10 @@ export function createPermissionFailureMessage(privilegeType: keyof MlCapabiliti
message = i18n.translate('xpack.ml.privilege.noPermission.runForecastsTooltip', {
defaultMessage: 'You do not have permission to run forecasts.',
});
} else if (privilegeType === 'canDeleteForecast') {
message = i18n.translate('xpack.ml.privilege.noPermission.deleteForecastsTooltip', {
defaultMessage: 'You do not have permission to delete forecasts.',
});
}
return i18n.translate('xpack.ml.privilege.pleaseContactAdministratorTooltip', {
defaultMessage: '{message} Please contact your administrator.',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import PropTypes from 'prop-types';
import React, { Component } from 'react';

import {
EuiButtonIcon,
EuiCallOut,
EuiConfirmModal,
EuiFlexGroup,
EuiFlexItem,
EuiInMemoryTable,
Expand All @@ -32,9 +32,43 @@ import {
isTimeSeriesViewJob,
} from '../../../../../../../common/util/job_utils';
import { ML_APP_LOCATOR, ML_PAGES } from '../../../../../../../common/constants/locator';
import { checkPermission } from '../../../../../capabilities/check_capabilities';

const MAX_FORECASTS = 500;

const DeleteForecastConfirm = ({ onCancel, onConfirm }) => (
<EuiConfirmModal
title={i18n.translate(
'xpack.ml.jobsList.jobDetails.forecastsTable.deleteForecastConfirm.title',
{
defaultMessage: 'Delete the selected forecast?',
}
)}
onCancel={onCancel}
onConfirm={onConfirm}
cancelButtonText={i18n.translate(
'xpack.ml.jobsList.jobDetails.forecastsTable.deleteForecastConfirm.cancelButton',
{
defaultMessage: 'Cancel',
}
)}
confirmButtonText={i18n.translate(
'xpack.ml.jobsList.jobDetails.forecastsTable.deleteForecastConfirm.confirmButton',
{
defaultMessage: 'Confirm',
}
)}
defaultFocusedButton="confirm"
>
<p>
<FormattedMessage
id="xpack.ml.jobsList.jobDetails.forecastsTable.deleteForecastConfirm.text"
defaultMessage="This will permanently delete the forecast from the job."
/>
</p>
</EuiConfirmModal>
);

/**
* Table component for rendering the lists of forecasts run on an ML job.
*/
Expand All @@ -44,6 +78,7 @@ export class ForecastsTable extends Component {
this.state = {
isLoading: props.job.data_counts.processed_record_count !== 0,
forecasts: [],
forecastIdToDelete: undefined,
};
this.mlForecastService = forecastServiceFactory(constructorContext.services.mlServices.mlApi);
}
Expand All @@ -54,6 +89,11 @@ export class ForecastsTable extends Component {
static contextType = context;

componentDidMount() {
this.loadForecasts();
this.canDeleteJobForecast = checkPermission('canDeleteForecast');
}

async loadForecasts() {
const dataCounts = this.props.job.data_counts;
if (dataCounts.processed_record_count > 0) {
// Get the list of all the forecasts with results at or later than the specified 'from' time.
Expand Down Expand Up @@ -163,6 +203,36 @@ export class ForecastsTable extends Component {
await navigateToUrl(singleMetricViewerForecastLink);
}

async deleteForecast(forecastId) {
const {
services: {
mlServices: { mlApi },
},
} = this.context;

this.setState({
isLoading: true,
forecastIdToDelete: undefined,
});

try {
await mlApi.deleteForecast({ jobId: this.props.job.job_id, forecastId });
} catch (error) {
this.setState({
forecastIdToDelete: undefined,
isLoading: false,
errorMessage: i18n.translate(
'xpack.ml.jobsList.jobDetails.forecastsTable.deleteForecastErrorMessage',
{
defaultMessage: 'An error occurred when deleting the forecast.',
}
),
});
}

this.loadForecasts();
}

render() {
if (this.state.isLoading === true) {
return (
Expand Down Expand Up @@ -302,48 +372,74 @@ export class ForecastsTable extends Component {
textOnly: true,
},
{
name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.viewLabel', {
defaultMessage: 'View',
width: '75px',
name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.actionsLabel', {
defaultMessage: 'Actions',
}),
width: '60px',
render: (forecast) => {
const viewForecastAriaLabel = i18n.translate(
'xpack.ml.jobsList.jobDetails.forecastsTable.viewAriaLabel',
{
defaultMessage: 'View forecast created at {createdDate}',
values: {
createdDate: timeFormatter(forecast.forecast_create_timestamp),
},
}
);

return (
<EuiButtonIcon
onClick={() => this.openSingleMetricView(forecast)}
isDisabled={
actions: [
{
description: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.viewLabel', {
defaultMessage: 'View',
}),
type: 'icon',
icon: 'eye',
enabled: (forecast) =>
!(
this.props.job.blocked !== undefined ||
forecast.forecast_status !== FORECAST_REQUEST_STATE.FINISHED
}
iconType="singleMetricViewer"
aria-label={viewForecastAriaLabel}
data-test-subj="mlJobListForecastTabOpenSingleMetricViewButton"
/>
);
},
),
onClick: (forecast) => this.openSingleMetricView(forecast),
'data-test-subj': 'mlJobListForecastTabOpenSingleMetricViewButton',
},
...(this.canDeleteJobForecast
? [
{
description: i18n.translate(
'xpack.ml.jobsList.jobDetails.forecastsTable.deleteForecastDescription',
{
defaultMessage: 'Delete forecast',
}
),
type: 'icon',
icon: 'trash',
color: 'danger',
enabled: () => this.state.isLoading === false,
onClick: (item) => {
this.setState({
forecastIdToDelete: item.forecast_id,
});
},
'data-test-subj': 'mlJobListForecastTabDeleteForecastButton',
},
]
: []),
],
},
];

return (
<EuiInMemoryTable
data-test-subj="mlJobListForecastTable"
compressed={true}
items={forecasts}
columns={columns}
pagination={{
pageSizeOptions: [5, 10, 25],
}}
sorting={true}
/>
<>
<EuiInMemoryTable
data-test-subj="mlJobListForecastTable"
compressed={true}
items={forecasts}
columns={columns}
pagination={{
pageSizeOptions: [5, 10, 25],
}}
sorting={true}
/>
{this.state.forecastIdToDelete !== undefined ? (
<DeleteForecastConfirm
onCancel={() =>
this.setState({
forecastIdToDelete: undefined,
})
}
onConfirm={() => this.deleteForecast(this.state.forecastIdToDelete)}
/>
) : null}
</>
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,16 +216,17 @@ export const TimeSeriesExplorerUrlStateManager: FC<TimeSeriesExplorerUrlStateMan
);

useEffect(() => {
if (selectedForecastIdProp !== selectedForecastId) {
setSelectedForecastIdProp(undefined);
}

if (
autoZoomDuration !== undefined &&
boundsMinMs !== undefined &&
boundsMaxMs !== undefined &&
selectedJob !== undefined &&
selectedForecastId !== undefined
) {
if (selectedForecastIdProp !== selectedForecastId) {
setSelectedForecastIdProp(undefined);
}
mlForecastService
.getForecastDateRange(selectedJob, selectedForecastId)
.then((resp) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ export interface GetModelSnapshotsResponse {
model_snapshots: ModelSnapshot[];
}

export interface DeleteForecastResponse {
acknowledged: boolean;
}

export function mlApiProvider(httpService: HttpService) {
return {
getJobs(obj?: { jobId?: string }) {
Expand Down Expand Up @@ -368,6 +372,14 @@ export function mlApiProvider(httpService: HttpService) {
});
},

deleteForecast({ jobId, forecastId }: { jobId: string; forecastId: string }) {
return httpService.http<DeleteForecastResponse>({
path: `${ML_INTERNAL_BASE_PATH}/anomaly_detectors/${jobId}/_forecast/${forecastId}`,
method: 'DELETE',
version: '1',
});
},

overallBuckets({
jobId,
topN,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,13 @@ import { forecastServiceFactory } from '../../../services/forecast_service';
import { ForecastButton } from './forecast_button';

export const FORECAST_DURATION_MAX_DAYS = 3650; // Max forecast duration allowed by analytics.

const FORECAST_JOB_MIN_VERSION = '6.1.0'; // Forecasting only allowed for jobs created >= 6.1.0.
const STATUS_FINISHED_QUERY = {
term: {
forecast_status: FORECAST_REQUEST_STATE.FINISHED,
},
};
const FORECASTS_VIEW_MAX = 5; // Display links to a maximum of 5 forecasts.
const FORECAST_JOB_MIN_VERSION = '6.1.0'; // Forecasting only allowed for jobs created >= 6.1.0.
const FORECAST_DURATION_MAX_MS = FORECAST_DURATION_MAX_DAYS * 86400000;
const WARN_NUM_PARTITIONS = 100; // Warn about running a forecast with this number of field values.
const FORECAST_STATS_POLL_FREQUENCY = 250; // Frequency in ms at which to poll for forecast request stats.
Expand Down Expand Up @@ -64,6 +68,7 @@ export class ForecastingModal extends Component {
latestRecordTimestamp: PropTypes.number,
entities: PropTypes.array,
setForecastId: PropTypes.func,
selectedForecastId: PropTypes.string,
};

constructor(props) {
Expand Down Expand Up @@ -405,13 +410,8 @@ export class ForecastingModal extends Component {
// Get the list of all the finished forecasts for this job with results at or later than the dashboard 'from' time.
const { timefilter } = this.context.services.data.query.timefilter;
const bounds = timefilter.getActiveBounds();
const statusFinishedQuery = {
term: {
forecast_status: FORECAST_REQUEST_STATE.FINISHED,
},
};
this.mlForecastService
.getForecastsSummary(job, statusFinishedQuery, bounds.min.valueOf(), FORECASTS_VIEW_MAX)
.getForecastsSummary(job, STATUS_FINISHED_QUERY, bounds.min.valueOf(), FORECASTS_VIEW_MAX)
.then((resp) => {
this.setState({
previousForecasts: resp.forecasts,
Expand Down Expand Up @@ -558,6 +558,7 @@ export class ForecastingModal extends Component {
jobOpeningState={this.state.jobOpeningState}
jobClosingState={this.state.jobClosingState}
messages={this.state.messages}
selectedForecastId={this.props.selectedForecastId}
/>
)}
</div>
Expand Down
Loading

0 comments on commit 0ff3940

Please sign in to comment.