Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ export const validateSpans = {
expectedSpan: 'undefined-attr-op',
},
{ test: 'setAttributes', expectedSpan: 'set-attributes-op' },
{
test: 'setAttributesConversion',
expectedSpan: 'set-attributes-conversion-op',
},
{ test: 'setStatus', expectedSpan: 'status-error-op' },
{ test: 'updateName', expectedSpan: 'update-name-original' },
{ test: 'publicImportTracing', expectedSpan: 'public-import-op' },
Expand All @@ -66,6 +70,15 @@ export const validateSpans = {
},
{ test: 'helperStartActiveSpan', expectedSpan: 'helper-detached-op' },
{ test: 'startActiveSpanSyncThrow', expectedSpan: 'manual-throw-op' },
{ test: 'arrayAttributes', expectedSpan: 'array-attrs-op' },
{
test: 'arrayAttributeByteLimit',
expectedSpan: 'array-limit-strings-op',
},
{
test: 'arrayAttributeByteLimit',
expectedSpan: 'array-limit-nullish-op',
},
];

for (const { test, expectedSpan } of testValidations) {
Expand Down Expand Up @@ -234,6 +247,160 @@ export const validateSpans = {
);
}

{
const span = (spansByTest.get('setAttributesConversion') || []).find(
(s) => s.name === 'set-attributes-conversion-op'
);
assert(span, 'setAttributesConversion: span present');
assert.strictEqual(span['ordered.scalar'], 'before');
assert.deepStrictEqual(span['ordered.array'], ['before']);
assert.strictEqual(span['ordered.later'], 'after');
assert(
!Object.keys(span).some((key) => key.startsWith('failed.')),
'setAttributes should not record any part of a failed batch'
);
}

// Array attributes on a user-created span: arrays arrive as arrays with scalar-vs-array
// identity preserved, nullish positions retained, and invalid arrays omitted.
{
const span = (spansByTest.get('arrayAttributes') || []).find(
(s) => s.name === 'array-attrs-op'
);
assert(span, 'arrayAttributes: span present');

assert.deepStrictEqual(span.strings, ['a', 'b', 'c']);
assert.deepStrictEqual(span.numbers, [1, 2.5, -3, 0]);
assert.deepStrictEqual(span.booleans, [true, false, true]);

assert.deepStrictEqual(span['single.string'], ['stop']);
assert.deepStrictEqual(span['single.number'], [42]);
assert.deepStrictEqual(span['single.boolean'], [false]);

assert.deepStrictEqual(span.empty, []);

assert.deepStrictEqual(span['nullish.strings'], [
null,
'a',
null,
'b',
null,
]);
assert.deepStrictEqual(span['nullish.numbers'], [null, 1, null, 2]);
assert.deepStrictEqual(span['nullish.booleans'], [null, true]);
assert.deepStrictEqual(span['nullish.only'], [null, null]);

for (const key of [
'invalid.mixed',
'invalid.mixedBoolNumber',
'invalid.mixedAfterNull',
'invalid.nested',
'invalid.objects',
'invalid.bigint',
'invalid.tooLong',
'invalid.sparse',
'set.invalid',
'set.skipped',
]) {
assert(
!(key in span),
`arrayAttributes: '${key}' should not be recorded`
);
}

assert.deepStrictEqual(span['set.strings'], ['x', 'y']);
assert.deepStrictEqual(span['set.numbers'], [7]);
assert.deepStrictEqual(span['set.booleans'], [true, null, false]);
assert.deepStrictEqual(span['set.empty'], []);

assert.deepStrictEqual(span['overwrite.toArray'], ['a', 'b']);
assert.strictEqual(span['overwrite.toScalar'], 'scalar');
assert.deepStrictEqual(span['overwrite.arrayType'], ['one', 'two']);

// Every array attribute above stayed within the span data limit.
assert(
!('cloudflare.warning.type' in span),
'arrayAttributes: no span data limit warning expected'
);
}

// Array attributes on the invocation span are delivered as attribute events on the root span.
{
const invocation = invocations.find((invocation) =>
invocation.attributes.some(
({ name, value }) =>
name === 'invocation.test' &&
value === 'invocationSpanArrayAttributes'
)
);
assert(invocation, 'invocationSpanArrayAttributes: invocation present');
const attributes = new Map(
invocation.attributes.map(({ name, value }) => [name, value])
);
assert.deepStrictEqual(attributes.get('invocation.strings'), ['a', 'b']);
assert.deepStrictEqual(attributes.get('invocation.numbers'), [1.5, 2]);
assert.deepStrictEqual(attributes.get('invocation.booleans'), [false]);
assert.deepStrictEqual(attributes.get('invocation.single'), ['stop']);
assert.deepStrictEqual(attributes.get('invocation.empty'), []);
assert.deepStrictEqual(attributes.get('invocation.nullish'), [
null,
'a',
null,
]);
assert.deepStrictEqual(attributes.get('invocation.set.numbers'), [
3,
null,
4,
]);
assert(
!attributes.has('invocation.invalid'),
'invocationSpanArrayAttributes: heterogeneous array should be omitted'
);
assert(
!attributes.has('invocation.set.invalid'),
'invocationSpanArrayAttributes: nested array should be omitted'
);
}

// Oversized arrays are dropped and degrade into a span data limit warning, while arrays
// within the limit are recorded in full.
{
const testSpans = spansByTest.get('arrayAttributeByteLimit') || [];
const span = testSpans.find((s) => s.name === 'array-limit-strings-op');
assert(
span,
"arrayAttributeByteLimit: span 'array-limit-strings-op' present"
);
assert(!('big.strings' in span));
assert.strictEqual(
span['cloudflare.warning.type'],
'span_data_limit_exceeded'
);
assert.match(
span['cloudflare.warning.message'],
/attribute "big\.strings" of size 75776$/
);
assert.deepStrictEqual(span.fits, new Array(512).fill('abcd'));

const nullishSpan = testSpans.find(
(s) => s.name === 'array-limit-nullish-op'
);
assert(nullishSpan, 'arrayAttributeByteLimit: nullish span present');
assert(!('nulls.15' in nullishSpan));
assert.deepStrictEqual(
nullishSpan['nulls.14'],
new Array(512).fill(null)
);
assert.strictEqual(
nullishSpan['cloudflare.warning.type'],
'span_data_limit_exceeded'
);
assert.match(
nullishSpan['cloudflare.warning.message'],
/attribute "nulls\.15" of size 4096$/
);
}

// Nested spans: verify both outer and inner spans exist and both are closed.
// This exercises the AsyncContextFrame push path used by enterSpan for nesting.
for (const testName of ['nestedSyncSpans', 'nestedAsyncSpans']) {
Expand Down
189 changes: 189 additions & 0 deletions src/cloudflare/internal/test/tracing/tracing-helpers-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,78 @@ export const setAttributes = {
},
};

export const setAttributesConversion = {
async test(ctrl, env, ctx) {
const checkConversion = (span) => {
let value = 'before';
const array = ['before'];
const order = [];
assert.strictEqual(
span.setAttributes({
'ordered.scalar': {
toString() {
order.push('coerce-first');
return value;
},
},
'ordered.array': array,
get 'ordered.later'() {
order.push('get-later');
value = 'after';
array[0] = 'after';
return value;
},
}),
span
);
assert.deepStrictEqual(order, ['coerce-first', 'get-later']);

const failure = new Error('attribute conversion failed');
let readAfterFailure = false;
assert.throws(
() =>
span.setAttributes({
'failed.scalar': 'not recorded',
'failed.array': ['not recorded'],
'failed.coercion': {
toString() {
throw failure;
},
},
get 'failed.later'() {
readAfterFailure = true;
return true;
},
}),
(error) => error === failure
);
assert.strictEqual(readAfterFailure, false);

assert.throws(
() =>
span.setAttributes({
'failed.beforeGetter': 'not recorded',
get 'failed.getter'() {
throw failure;
},
}),
(error) => error === failure
);

for (const input of [undefined, null, false, 42, 'string', []]) {
assert.throws(() => span.setAttributes(input), TypeError);
}
assert.strictEqual(span.setAttributes(Object.create(null)), span);
};

env.tracingTest.withSpan('set-attributes-conversion-op', (span) => {
span.setAttribute('test', 'setAttributesConversion');
checkConversion(span);
});
checkConversion(spanCreatedOutsideInvocationContext);
},
};

export const setStatus = {
async test(ctrl, env, ctx) {
const errorSpan = publicTracing.startSpan('status-error-op');
Expand Down Expand Up @@ -302,6 +374,123 @@ export const spanContext = {
},
};

// Array attribute values follow OpenTelemetry semantics: homogeneous primitive arrays are
// recorded as arrays (including one-element and empty arrays), null/undefined positions are
// retained, and heterogeneous or nested arrays are ignored. The received values are checked in
// tracing-helpers-instrumentation-test.js.
export const arrayAttributes = {
async test(ctrl, env, ctx) {
const { withSpan } = env.tracingTest;

withSpan('array-attrs-op', (span) => {
span.setAttribute('test', 'arrayAttributes');

// Attribute setters keep returning the span for chaining.
assert.strictEqual(span.setAttribute('strings', ['a', 'b', 'c']), span);
span.setAttribute('numbers', [1, 2.5, -3, 0]);
span.setAttribute('booleans', [true, false, true]);

// One-element arrays must stay arrays (e.g. gen_ai.response.finish_reasons: ["stop"]).
span.setAttribute('single.string', ['stop']);
span.setAttribute('single.number', [42]);
span.setAttribute('single.boolean', [false]);

// Empty arrays are recorded as empty arrays.
span.setAttribute('empty', []);

// null/undefined elements retain their positions and are normalized to null downstream.
span.setAttribute('nullish.strings', [null, 'a', undefined, 'b', null]);
span.setAttribute('nullish.numbers', [undefined, 1, null, 2]);
span.setAttribute('nullish.booleans', [null, true]);
span.setAttribute('nullish.only', [null, undefined]);

// Invalid arrays are ignored entirely.
span.setAttribute('invalid.mixed', ['a', 1]);
span.setAttribute('invalid.mixedBoolNumber', [true, 1]);
span.setAttribute('invalid.mixedAfterNull', [null, 'a', null, false]);
span.setAttribute('invalid.nested', [['a']]);
span.setAttribute('invalid.objects', [{ a: 1 }]);
span.setAttribute('invalid.bigint', [1n]);
span.setAttribute('invalid.tooLong', new Array(513).fill('x'));
const sparse = new Array(0xffffffff);
Object.defineProperty(sparse, 0, {
get() {
throw new Error(
'oversized arrays must be rejected before reading elements'
);
},
});
span.setAttribute('invalid.sparse', sparse);

// setAttributes() applies the same rules per key.
assert.strictEqual(
span.setAttributes({
'set.strings': ['x', 'y'],
'set.numbers': [7],
'set.booleans': [true, null, false],
'set.empty': [],
'set.skipped': undefined,
'set.invalid': [1, 'a'],
}),
span
);

// Later writes replace earlier ones, in both directions between scalars and arrays.
span.setAttribute('overwrite.toArray', 'scalar');
span.setAttribute('overwrite.toArray', ['a', 'b']);
span.setAttribute('overwrite.toScalar', ['a']);
span.setAttribute('overwrite.toScalar', 'scalar');
span.setAttribute('overwrite.arrayType', [1, 2]);
span.setAttribute('overwrite.arrayType', ['one', 'two']);
});
},
};

// Array attributes on the invocation span take the BaseTracer::addSpanAttribute() path rather
// than the SpanBuilder path used by user-created spans; verify both preserve arrays.
export const invocationSpanArrayAttributes = {
async test(ctrl, env, ctx) {
const span = publicTracing.getActiveSpan();
assert.ok(span);
assert.strictEqual(span.isTraced, true);
span.setAttribute('invocation.test', 'invocationSpanArrayAttributes');
span.setAttribute('invocation.strings', ['a', 'b']);
span.setAttribute('invocation.numbers', [1.5, 2]);
span.setAttribute('invocation.booleans', [false]);
span.setAttribute('invocation.single', ['stop']);
span.setAttribute('invocation.empty', []);
span.setAttribute('invocation.nullish', [null, 'a', undefined]);
span.setAttribute('invocation.invalid', ['a', 1]);
span.setAttributes({
'invocation.set.numbers': [3, null, 4],
'invocation.set.invalid': [[1]],
});
},
};

// Array elements count toward the per-span data limit exactly like scalar values. Each span
// gets a single oversized attribute because the first violation stops further recording.
export const arrayAttributeByteLimit = {
async test(ctrl, env, ctx) {
const { withSpan } = env.tracingTest;

withSpan('array-limit-strings-op', (span) => {
span.setAttribute('test', 'arrayAttributeByteLimit');
// 512 * 4 bytes fits comfortably under the 64 KiB limit.
span.setAttribute('fits', new Array(512).fill('abcd'));
// 512 * 140 bytes exceed the limit and must be dropped with a warning.
span.setAttribute('big.strings', new Array(512).fill('x'.repeat(140)));
});

withSpan('array-limit-nullish-op', (span) => {
span.setAttribute('test', 'arrayAttributeByteLimit');
for (let i = 0; i < 16; i++) {
span.setAttribute(`nulls.${i}`, new Array(512).fill(null));
}
});
},
};

// Verify that nested withSpan calls produce correctly nested spans. This exercises the
// AsyncContextFrame push path in enterSpan: the inner span should be parented on the
// outer span.
Expand Down
Loading
Loading