Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ObsUX] Add Missing transaction warning if there are Transactions or Spans with a parent.id that doesn't exist in the trace #171196

153 changes: 153 additions & 0 deletions packages/kbn-apm-synthtrace/src/scenarios/trace_with_orphan_items.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* 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 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 or the Server
* Side Public License, v 1.
*/

import { apm, ApmFields, httpExitSpan, Serializable } from '@kbn/apm-synthtrace-client';
import { Readable } from 'stream';
import { Scenario } from '../cli/scenario';

import { RunOptions } from '../cli/utils/parse_run_cli_flags';
import { getSynthtraceEnvironment } from '../lib/utils/get_synthtrace_environment';
import { withClient } from '../lib/utils/with_client';

const ENVIRONMENT = getSynthtraceEnvironment(__filename);

const scenario: Scenario<ApmFields> = async (runOptions: RunOptions) => {
return {
generate: ({ range, clients: { apmEsClient } }) => {
const transactionName = 'trace with orphans';
const successfulTimestamps = range.interval('1s').rate(3);

const synthRum = apm
.service({ name: 'synth-rum', environment: ENVIRONMENT, agentName: 'rum-js' })
.instance('my-instance');
const synthNode = apm
.service({ name: 'synth-node', environment: ENVIRONMENT, agentName: 'nodejs' })
.instance('my-instance');
const synthGo = apm
.service({ name: 'synth-go', environment: ENVIRONMENT, agentName: 'go' })
.instance('my-instance');

const traces = successfulTimestamps.generator((timestamp) => {
// synth-rum
return synthGo
.transaction({ transactionName })
.duration(400)
.timestamp(timestamp)
.children(
// synth-rum -> synth-node
synthRum
.span(
httpExitSpan({
spanName: 'GET /api/products/top',
destinationUrl: 'http://synth-node:3000',
})
)
.duration(300)
.timestamp(timestamp)
.children(
synthRum
.transaction({ transactionName: 'Child Transaction' })
.timestamp(timestamp)
.duration(200)
.children(
synthGo
.span({ spanName: 'custom_operation', spanType: 'custom' })
.timestamp(timestamp)
.duration(100)
.success()
),
// synth-node
synthNode
.transaction({ transactionName: 'Initial transaction in synth-node' })
.duration(300)
.timestamp(timestamp)
.children(
synthNode
// synth-node -> synth-go
.span(
httpExitSpan({
spanName: 'GET synth-go:3000',
destinationUrl: 'http://synth-go:3000',
})
)
.timestamp(timestamp)
.duration(400)

.children(
// synth-go
synthGo
.transaction({ transactionName: 'Child Transaction' })
.timestamp(timestamp)
.duration(200)
.children(
synthGo
.span({ spanName: 'custom_operation', spanType: 'custom' })
.timestamp(timestamp)
.duration(100)
.success(),
synthGo
.span({ spanName: 'custom_new_operation', spanType: 'custom' })
.timestamp(timestamp)
.duration(100)
.success()
)
)
)
)
);
});

const successfulTraceEvents = Array.from(
successfulTimestamps.generator((timestamp) =>
synthNode
.transaction({ transactionName: 'successful trace' })
.timestamp(timestamp)
.duration(1000)
.success()
.children(
synthNode
.span({
spanName: 'GET apm-*/_search',
spanType: 'db',
spanSubtype: 'elasticsearch',
})
.duration(1000)
.success()
.destination('elasticsearch')
.timestamp(timestamp),
synthNode
.span({ spanName: 'custom_operation', spanType: 'custom' })
.duration(100)
.success()
.timestamp(timestamp)
)
)
);

const unserialized = Array.from(traces);

const serialized = unserialized
.flatMap((event) => event.serialize())
.filter((trace) => trace['transaction.name'] !== 'Child Transaction');

const unserializedChanged = serialized.map((event) => ({
fields: event,
serialize: () => {
return [event];
},
})) as Array<Serializable<ApmFields>>;

return withClient(
apmEsClient,
Readable.from([...unserializedChanged, ...successfulTraceEvents])
);
},
};
};

export default scenario;
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ import { useCriticalPathFeatureEnabledSetting } from '../../../../../hooks/use_c
import { TechnicalPreviewBadge } from '../../../../shared/technical_preview_badge';
import { Waterfall } from './waterfall';
import {
IWaterfall,
type IWaterfall,
WaterfallLegendType,
} from './waterfall/waterfall_helpers/waterfall_helpers';
import { WaterfallLegends } from './waterfall_legends';
import { MissingTransactionWarning } from './waterfall/missing_transaction_warning';

interface Props {
waterfallItemId?: string;
Expand All @@ -38,7 +39,7 @@ export function WaterfallContainer({
if (!waterfall) {
return null;
}
const { legends, items } = waterfall;
const { legends, items, hasOrphanTraceItems } = waterfall;

// Service colors are needed to color the dot in the error popover
const serviceLegends = legends.filter(
Expand Down Expand Up @@ -108,7 +109,19 @@ export function WaterfallContainer({
</EuiFlexItem>
) : null}
<EuiFlexItem>
<WaterfallLegends legends={legendsWithFallbackLabel} type={colorBy} />
<EuiFlexGroup justifyContent="spaceBetween">
<EuiFlexItem grow={false}>
<WaterfallLegends
legends={legendsWithFallbackLabel}
type={colorBy}
/>
</EuiFlexItem>
{hasOrphanTraceItems ? (
<EuiFlexItem grow={false}>
<MissingTransactionWarning />
Copy link
Member

@sorenlouv sorenlouv Nov 21, 2023

Choose a reason for hiding this comment

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

nit: I suggest naming this OrphanTraceItemsWarning to align with hasOrphanTraceItems

</EuiFlexItem>
) : null}
</EuiFlexGroup>
</EuiFlexItem>
<EuiFlexItem>
<Waterfall
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import { EuiBadge, EuiToolTip } from '@elastic/eui';
import { i18n } from '@kbn/i18n';

export function MissingTransactionWarning() {
return (
<EuiToolTip
position="left"
content={i18n.translate(
'xpack.apm.transactionDetails.agentMissingTransactionMessage',
{
defaultMessage:
'This trace contains spans from missing transactions. As a result these spans are not displayed in the timeline.',
Copy link
Member

@sorenlouv sorenlouv Nov 21, 2023

Choose a reason for hiding this comment

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

The error message is not entirely correct afaict. Example: a (parent) span could be missing, meaning that any child spans (or transactions) will not be displayed. So it is not just about missing transactions.
Also, we should suggest work-arounds for the user if possible.

Suggestion for error message:

This trace is incomplete and {{count}} items could not be displayed in the timeline. This could be a temporary problem caused by ingest delay, or a permanent problem caused by some events being dropped.

Copy link
Member Author

Choose a reason for hiding this comment

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

Thank you, I remember I took the message from the issue description, and now that you mentioned that it makes sense. One question regarding the {{count}} - we want to show the missing items in the waterfall based on the items returned and the items shown in the waterfall, right? I guess here we just calculate it, I don't see the missing items count existing somewhere (similar to the check we have here but instead of returning a boolean it should return the missing items count)
image

Copy link
Member Author

Choose a reason for hiding this comment

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

I added a draft PR for those changes so we can better discuss there

Copy link
Member

@sorenlouv sorenlouv Dec 13, 2023

Choose a reason for hiding this comment

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

One question regarding the {{count}} - we want to show the missing items in the waterfall based on the items returned and the items shown in the waterfall, right? I guess here we just calculate it, I don't see the missing items count existing somewhere (similar to the check we have here but instead of returning a boolean it should return the missing items count)

Yes, I was thinking it would be beneficial to at least show the number of (orphan) items that cannot be placed because a parent is missing.

If it's difficult to calculate this, let's just skip it for now.

}
)}
anchorClassName="eui-fullWidth"
>
<EuiBadge
iconType="warning"
color="hollow"
data-test-id="apm-missing-transaction-badge"
>
{i18n.translate(
'xpack.apm.transactionDetails.agentMissingTransactionLabel',
{
defaultMessage: 'Incomplete trace',
}
)}
</EuiBadge>
</EuiToolTip>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
IWaterfallTransaction,
IWaterfallError,
IWaterfallSpanOrTransaction,
getHasOrphanTraceItems,
} from './waterfall_helpers';
import { APMError } from '../../../../../../../../typings/es_schemas/ui/apm_error';
import {
Expand Down Expand Up @@ -717,4 +718,46 @@ describe('waterfall_helpers', () => {
expect(getClockSkew(child, parent)).toBe(0);
});
});

describe('getHasOrphanTraceItems', () => {
const myTransactionItem = {
processor: { event: 'transaction' },
trace: { id: 'myTrace' },
transaction: {
id: 'myTransactionId1',
},
} as WaterfallTransaction;

it('should return false if there are no orphan items', () => {
const traceItems: Array<WaterfallTransaction | WaterfallSpan> = [
myTransactionItem,
{
processor: { event: 'span' },
span: {
id: 'mySpanId',
},
parent: {
id: 'myTransactionId1',
},
} as WaterfallSpan,
];
expect(getHasOrphanTraceItems(traceItems)).toBe(false);
});

it('should return true if there are orphan items', () => {
const traceItems: Array<WaterfallTransaction | WaterfallSpan> = [
myTransactionItem,
{
processor: { event: 'span' },
span: {
id: 'myOrphanSpanId',
},
parent: {
id: 'myNotExistingTransactionId1',
},
} as WaterfallSpan,
];
expect(getHasOrphanTraceItems(traceItems)).toBe(true);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export interface IWaterfall {
totalErrorsCount: number;
traceDocsTotal: number;
maxTraceItems: number;
hasOrphanTraceItems: boolean;
}

interface IWaterfallItemBase<TDocument, TDoctype> {
Expand Down Expand Up @@ -191,7 +192,7 @@ export function getClockSkew(
case 'error':
case 'span':
return parentItem.skew;
// transaction is the inital entry in a service. Calculate skew for this, and it will be propogated to all child spans
// transaction is the initial entry in a service. Calculate skew for this, and it will be propagated to all child spans
case 'transaction': {
const parentStart = parentItem.doc.timestamp.us + parentItem.skew;

Expand Down Expand Up @@ -415,6 +416,22 @@ function getErrorCountByParentId(
}, {});
}

export const getHasOrphanTraceItems = (
traceDocs: Array<WaterfallTransaction | WaterfallSpan>
) => {
const waterfallItemsIds = new Set(
traceDocs.map((doc) =>
doc.processor.event === 'span'
? (doc?.span as WaterfallSpan['span']).id
: doc?.transaction?.id
)
);

return traceDocs.some(
(item) => item.parent?.id && !waterfallItemsIds.has(item.parent.id)
);
};

export function getWaterfall(apiResponse: TraceAPIResponse): IWaterfall {
const { traceItems, entryTransaction } = apiResponse;
if (isEmpty(traceItems.traceDocs) || !entryTransaction) {
Expand All @@ -429,6 +446,7 @@ export function getWaterfall(apiResponse: TraceAPIResponse): IWaterfall {
totalErrorsCount: 0,
traceDocsTotal: 0,
maxTraceItems: 0,
hasOrphanTraceItems: false,
};
}

Expand Down Expand Up @@ -464,6 +482,8 @@ export function getWaterfall(apiResponse: TraceAPIResponse): IWaterfall {
const duration = getWaterfallDuration(items);
const legends = getLegends(items);

const hasOrphanTraceItems = getHasOrphanTraceItems(traceItems.traceDocs);

return {
entryWaterfallTransaction,
rootWaterfallTransaction,
Expand All @@ -478,5 +498,6 @@ export function getWaterfall(apiResponse: TraceAPIResponse): IWaterfall {
totalErrorsCount: traceItems.errorDocs.length,
traceDocsTotal: traceItems.traceDocsTotal,
maxTraceItems: traceItems.maxTraceItems,
hasOrphanTraceItems,
};
}
Loading