Skip to content

Commit

Permalink
[Lens] Enable previous time shift when using a date histogram (#149126)
Browse files Browse the repository at this point in the history
## Summary

Fixes #104259 

This PR expands the support of the `previous` time shift for
visualisations with a date histogram defined.
On the implementation side, an absolute time shift in the shape of
`endAt( startRange )` is leveraged to make it work the `previous` shift:
anchoring the shift to the beginning of the current range will make sure
to compute the right shift in terms of buckets in order to avoid
misaligned shifts and the main reason why this feature has been disabled
initially.

I've tried to condense an explanation here with this diagram of the
misalignment problem:


![previous_before](https://user-images.githubusercontent.com/924948/213234848-40e3382a-843d-43fa-83d1-769a5f2e7953.png)

With the current approach, there's a small time range overlap between
the two requested interval, but that's the result of the rounding logic
to get both shifts aligned.


![previous_2](https://user-images.githubusercontent.com/924948/213235429-1c99aefb-e18b-450a-b2d7-45b7d74c9e71.png)

The only alternative to avoid the overlap is to get a gap between the
two, but the former seems a better result to me.

### 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
- [ ] 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)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

Co-authored-by: Stratoula Kalafateli <[email protected]>
  • Loading branch information
dej611 and stratoula authored Jan 24, 2023
1 parent d692d40 commit 06cec01
Show file tree
Hide file tree
Showing 19 changed files with 74 additions and 191 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,7 @@ export function TimeShift({
options={timeShiftOptions.filter(({ value }) => {
const parsedValue = parseTimeShift(value);
return (
parsedValue &&
!isValueTooSmall(parsedValue) &&
!isValueNotMultiple(parsedValue) &&
!(parsedValue === 'previous' && dateHistogramInterval.interval)
parsedValue && !isValueTooSmall(parsedValue) && !isValueNotMultiple(parsedValue) // &&
);
})}
selectedOptions={getSelectedOption()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ import {
} from './utils';
import { DEFAULT_TIME_SCALE } from '../../time_scale_utils';
import { OperationDefinition } from '..';
import { getFormatFromPreviousColumn, getFilter, combineErrorMessages } from '../helpers';
import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils';
import { getFormatFromPreviousColumn, getFilter } from '../helpers';

const ofName = buildLabelFunction((name?: string) => {
return i18n.translate('xpack.lens.indexPattern.CounterRateOf', {
Expand Down Expand Up @@ -107,16 +106,13 @@ export const counterRateOperation: OperationDefinition<
return hasDateField(newIndexPattern);
},
getErrorMessage: (layer: FormBasedLayer, columnId: string) => {
return combineErrorMessages([
getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.counterRate', {
defaultMessage: 'Counter rate',
})
),
getDisallowedPreviousShiftMessage(layer, columnId),
]);
return getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.counterRate', {
defaultMessage: 'Counter rate',
})
);
},
getDisabledStatus(indexPattern, layer, layerType) {
const opName = i18n.translate('xpack.lens.indexPattern.counterRate', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ import {
checkForDataLayerType,
} from './utils';
import { OperationDefinition } from '..';
import { getFormatFromPreviousColumn, getFilter, combineErrorMessages } from '../helpers';
import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils';
import { getFormatFromPreviousColumn, getFilter } from '../helpers';
import { DOCUMENT_FIELD_NAME } from '../../../../../../common';

const ofName = buildLabelFunction((name?: string) => {
Expand Down Expand Up @@ -107,16 +106,13 @@ export const cumulativeSumOperation: OperationDefinition<
return true;
},
getErrorMessage: (layer: FormBasedLayer, columnId: string) => {
return combineErrorMessages([
getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.cumulativeSum', {
defaultMessage: 'Cumulative sum',
})
),
getDisallowedPreviousShiftMessage(layer, columnId),
]);
return getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.cumulativeSum', {
defaultMessage: 'Cumulative sum',
})
);
},
getDisabledStatus(indexPattern, layer, layerType) {
const opName = i18n.translate('xpack.lens.indexPattern.cumulativeSum', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ import {
checkForDataLayerType,
} from './utils';
import { OperationDefinition } from '..';
import { getFormatFromPreviousColumn, getFilter, combineErrorMessages } from '../helpers';
import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils';
import { getFormatFromPreviousColumn, getFilter } from '../helpers';

const OPERATION_NAME = 'differences';

Expand Down Expand Up @@ -93,16 +92,13 @@ export const derivativeOperation: OperationDefinition<
return hasDateField(newIndexPattern);
},
getErrorMessage: (layer: FormBasedLayer, columnId: string) => {
return combineErrorMessages([
getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.derivative', {
defaultMessage: 'Differences',
})
),
getDisallowedPreviousShiftMessage(layer, columnId),
]);
return getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.derivative', {
defaultMessage: 'Differences',
})
);
},
getDisabledStatus(indexPattern, layer, layerType) {
const opName = i18n.translate('xpack.lens.indexPattern.derivative', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,8 @@ import {
checkForDataLayerType,
} from './utils';
import { updateColumnParam } from '../../layer_helpers';
import {
getFormatFromPreviousColumn,
isValidNumber,
getFilter,
combineErrorMessages,
} from '../helpers';
import { getFormatFromPreviousColumn, isValidNumber, getFilter } from '../helpers';
import type { OperationDefinition, ParamEditorProps } from '..';
import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils';

const ofName = buildLabelFunction((name?: string) => {
return i18n.translate('xpack.lens.indexPattern.movingAverageOf', {
Expand Down Expand Up @@ -115,16 +109,13 @@ export const movingAverageOperation: OperationDefinition<
return hasDateField(newIndexPattern);
},
getErrorMessage: (layer: FormBasedLayer, columnId: string) => {
return combineErrorMessages([
getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.movingAverage', {
defaultMessage: 'Moving average',
})
),
getDisallowedPreviousShiftMessage(layer, columnId),
]);
return getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.movingAverage', {
defaultMessage: 'Moving average',
})
);
},
helpComponent: () => <MovingAveragePopup />,
helpComponentTitle: i18n.translate('xpack.lens.indexPattern.movingAverage.titleHelp', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { getErrorsForDateReference } from './utils';
import type { OperationDefinition } from '..';
import { combineErrorMessages, getFormatFromPreviousColumn } from '../helpers';
import { FormBasedLayer } from '../../../types';
import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils';

type OverallMetricIndexPatternColumn<T extends string> = FormattedIndexPatternColumn &
ReferenceBasedIndexPatternColumn & {
Expand Down Expand Up @@ -110,7 +109,6 @@ export const timeScaleOperation: OperationDefinition<TimeScaleIndexPatternColumn
defaultMessage: 'Normalize by unit',
})
),
getDisallowedPreviousShiftMessage(layer, columnId),
!(layer.columns[columnId] as TimeScaleIndexPatternColumn).params.unit
? [
i18n.translate('xpack.lens.indexPattern.timeScale.missingUnit', {
Expand All @@ -123,7 +121,7 @@ export const timeScaleOperation: OperationDefinition<TimeScaleIndexPatternColumn
) === -1
? [
i18n.translate('xpack.lens.indexPattern.timeScale.wrongUnit', {
defaultMessage: 'Unknown unit specified, use s,m,h or d.',
defaultMessage: 'Unknown unit specified: use s, m, h or d.',
}),
]
: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import {
isColumnOfType,
} from './helpers';
import { adjustTimeScaleLabelSuffix } from '../time_scale_utils';
import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils';
import { updateColumnParam } from '../layer_helpers';
import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils';
import { getGroupByKey } from './get_group_by_key';
Expand Down Expand Up @@ -93,7 +92,6 @@ export const cardinalityOperation: OperationDefinition<
getErrorMessage: (layer, columnId, indexPattern) =>
combineErrorMessages([
getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern),
getDisallowedPreviousShiftMessage(layer, columnId),
getColumnReducedTimeRangeError(layer, columnId, indexPattern),
]),
isTransferable: (column, newIndexPattern) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import {
isColumnOfType,
} from './helpers';
import { adjustTimeScaleLabelSuffix } from '../time_scale_utils';
import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils';
import { updateColumnParam } from '../layer_helpers';
import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils';
import { getGroupByKey } from './get_group_by_key';
Expand Down Expand Up @@ -92,7 +91,6 @@ export const countOperation: OperationDefinition<CountIndexPatternColumn, 'field
getErrorMessage: (layer, columnId, indexPattern) =>
combineErrorMessages([
getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern),
getDisallowedPreviousShiftMessage(layer, columnId),
getColumnReducedTimeRangeError(layer, columnId, indexPattern),
]),
allowAsReference: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,9 +395,9 @@ export async function getNamedArgumentSuggestions({
if (dateHistogramInterval == null) return true;
const parsedValue = parseTimeShift(value);
return (
parsedValue !== 'previous' &&
(parsedValue === 'invalid' ||
Number.isInteger(parsedValue.asMilliseconds() / dateHistogramInterval))
parsedValue === 'previous' ||
parsedValue === 'invalid' ||
Number.isInteger(parsedValue.asMilliseconds() / dateHistogramInterval)
);
})
.map(({ value }) => value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import {
getFilter,
} from './helpers';
import { adjustTimeScaleLabelSuffix } from '../time_scale_utils';
import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils';
import { isRuntimeField, isScriptedField } from './terms/helpers';
import { FormRow } from './shared_components/form_row';
import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils';
Expand Down Expand Up @@ -214,7 +213,6 @@ export const lastValueOperation: OperationDefinition<
if (invalidSortFieldMessage) {
errorMessages = [invalidSortFieldMessage];
}
errorMessages.push(...(getDisallowedPreviousShiftMessage(layer, columnId) || []));
errorMessages.push(...(getColumnReducedTimeRangeError(layer, columnId, indexPattern) || []));
return errorMessages.length ? errorMessages : undefined;
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
ValueFormatConfig,
} from './column_types';
import { adjustTimeScaleLabelSuffix } from '../time_scale_utils';
import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils';
import { updateColumnParam } from '../layer_helpers';
import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils';
import { getGroupByKey } from './get_group_by_key';
Expand Down Expand Up @@ -215,7 +214,6 @@ function buildMetricOperation<T extends MetricColumn<string>>({
layer.columns[columnId] as FieldBasedIndexPatternColumn,
indexPattern
),
getDisallowedPreviousShiftMessage(layer, columnId),
getColumnReducedTimeRangeError(layer, columnId, indexPattern),
]),
filterable: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {
import { FieldBasedIndexPatternColumn } from './column_types';
import { adjustTimeScaleLabelSuffix } from '../time_scale_utils';
import { useDebouncedValue } from '../../../../shared_components';
import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils';
import { FormRow } from './shared_components';
import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils';
import { getGroupByKey, groupByKey } from './get_group_by_key';
Expand Down Expand Up @@ -290,7 +289,6 @@ export const percentileOperation: OperationDefinition<
getErrorMessage: (layer, columnId, indexPattern) =>
combineErrorMessages([
getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern),
getDisallowedPreviousShiftMessage(layer, columnId),
getColumnReducedTimeRangeError(layer, columnId, indexPattern),
]),
paramEditor: function PercentileParamEditor({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import {
import { FieldBasedIndexPatternColumn } from './column_types';
import { adjustTimeScaleLabelSuffix } from '../time_scale_utils';
import { useDebouncedValue } from '../../../../shared_components';
import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils';
import { FormRow } from './shared_components';
import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils';

Expand Down Expand Up @@ -168,7 +167,6 @@ export const percentileRanksOperation: OperationDefinition<
getErrorMessage: (layer, columnId, indexPattern) =>
combineErrorMessages([
getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern),
getDisallowedPreviousShiftMessage(layer, columnId),
getColumnReducedTimeRangeError(layer, columnId, indexPattern),
]),
paramEditor: function PercentileParamEditor({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,80 +6,9 @@
*/

import moment from 'moment';
import { getDisallowedPreviousShiftMessage, resolveTimeShift } from './time_shift_utils';
import { FormBasedLayer } from './types';
import { resolveTimeShift } from './time_shift_utils';

describe('time_shift_utils', () => {
describe('getDisallowedPreviousShiftMessage', () => {
const layer: FormBasedLayer = {
indexPatternId: '',
columnOrder: [],
columns: {
a: {
operationType: 'date_histogram',
dataType: 'date',
isBucketed: true,
label: '',
references: [],
sourceField: 'timestamp',
},
b: {
operationType: 'count',
dataType: 'number',
isBucketed: false,
label: 'non shifted',
references: [],
sourceField: 'records',
},
c: {
operationType: 'count',
dataType: 'number',
isBucketed: false,
label: 'shifted',
timeShift: '1d',
references: [],
sourceField: 'records',
},
},
};

it('shoud not produce an error for no shift', () => {
expect(getDisallowedPreviousShiftMessage(layer, 'b')).toBeUndefined();
});

it('shoud not produce an error for non-previous shift', () => {
expect(getDisallowedPreviousShiftMessage(layer, 'c')).toBeUndefined();
});

it('shoud produce an error for previous shift with date histogram', () => {
expect(
getDisallowedPreviousShiftMessage(
{
...layer,
columns: { ...layer.columns, c: { ...layer.columns.c, timeShift: 'previous' } },
},
'c'
)
).toHaveLength(1);
});

it('shoud not produce an error for previous shift without date histogram', () => {
expect(
getDisallowedPreviousShiftMessage(
{
...layer,
columns: {
...layer.columns,
a: { ...layer.columns.a, operationType: 'terms' },
c: { ...layer.columns.c, timeShift: 'previous' },
},
},
'c'
)
).toBeUndefined();
});
});

describe('resolveTimeShift', () => {
const dateString = '2022-11-02T00:00:00.000Z';
// shift by 2 days + 2500 s (to get a shift which is not a multiple of the given interval)
Expand Down Expand Up @@ -113,6 +42,10 @@ describe('time_shift_utils', () => {
.toBe('261000s');
});

it('should convert previous relative time shift to seconds (rounded) when a date histogram is present', () => {
expect(resolveTimeShift(`previous`, getDateRange(), 100, true)).toBe('171000s');
});

it('should always include the passed date in the computed interval', () => {
const dateRange = getDateRange();
for (const anchor of ['startAt', 'endAt']) {
Expand Down
Loading

0 comments on commit 06cec01

Please sign in to comment.