Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /pydantic_logfire /tests /test_tail_sampling.py
| from __future__ import annotations | |
| import logging | |
| from typing import Any | |
| import inline_snapshot.extra | |
| import pytest | |
| from inline_snapshot import snapshot | |
| from opentelemetry.context import Context | |
| from opentelemetry.sdk._logs.export import SimpleLogRecordProcessor | |
| from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor, TracerProvider | |
| from opentelemetry.sdk.trace.export import SimpleSpanProcessor | |
| from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON, Sampler, SamplingResult | |
| import logfire | |
| from logfire._internal.constants import LEVEL_NUMBERS | |
| from logfire._internal.exporters.test import TestLogExporter | |
| from logfire.sampling import SpanLevel, TailSamplingSpanInfo | |
| from logfire.sampling._tail_sampling import TailSamplingProcessor | |
| from logfire.testing import SeededRandomIdGenerator, TestExporter, TimeGenerator | |
| def test_level_threshold(config_kwargs: dict[str, Any], exporter: TestExporter): | |
| # Use the default TailSamplingOptions.level of 'notice'. | |
| # Set duration to None to not include spans with a long duration. | |
| logfire.configure(**config_kwargs, sampling=logfire.SamplingOptions.level_or_duration(duration_threshold=None)) | |
| with logfire.span('ignored span'): | |
| logfire.debug('ignored debug') | |
| logfire.notice('notice') | |
| with logfire.span('ignored span'): | |
| logfire.info('ignored info') | |
| logfire.warn('warn') | |
| # Include this whole tree because of the inner error | |
| with logfire.span('span'): | |
| with logfire.span('span2'): | |
| logfire.error('error') | |
| # Include this whole tree because of the outer fatal | |
| with logfire.span('span3', _level='fatal'): | |
| logfire.trace('trace') | |
| assert exporter.exported_spans_as_dict(_include_pending_spans=True) == snapshot( | |
| [ | |
| { | |
| 'name': 'notice', | |
| 'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False}, | |
| 'parent': None, | |
| 'start_time': 4000000000, | |
| 'end_time': 4000000000, | |
| 'attributes': { | |
| 'logfire.span_type': 'log', | |
| 'logfire.level_num': 10, | |
| 'logfire.msg_template': 'notice', | |
| 'logfire.msg': 'notice', | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| }, | |
| }, | |
| { | |
| 'name': 'warn', | |
| 'context': {'trace_id': 4, 'span_id': 6, 'is_remote': False}, | |
| 'parent': None, | |
| 'start_time': 8000000000, | |
| 'end_time': 8000000000, | |
| 'attributes': { | |
| 'logfire.span_type': 'log', | |
| 'logfire.level_num': 13, | |
| 'logfire.msg_template': 'warn', | |
| 'logfire.msg': 'warn', | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| }, | |
| }, | |
| { | |
| 'name': 'span', | |
| 'context': {'trace_id': 5, 'span_id': 10, 'is_remote': False}, | |
| 'parent': {'trace_id': 5, 'span_id': 7, 'is_remote': False}, | |
| 'start_time': 9000000000, | |
| 'end_time': 9000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span', | |
| 'logfire.msg': 'span', | |
| 'logfire.span_type': 'pending_span', | |
| 'logfire.pending_parent_id': '0000000000000000', | |
| }, | |
| }, | |
| { | |
| 'name': 'span2', | |
| 'context': {'trace_id': 5, 'span_id': 11, 'is_remote': False}, | |
| 'parent': {'trace_id': 5, 'span_id': 8, 'is_remote': False}, | |
| 'start_time': 10000000000, | |
| 'end_time': 10000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span2', | |
| 'logfire.msg': 'span2', | |
| 'logfire.span_type': 'pending_span', | |
| 'logfire.pending_parent_id': '0000000000000007', | |
| }, | |
| }, | |
| { | |
| 'name': 'error', | |
| 'context': {'trace_id': 5, 'span_id': 9, 'is_remote': False}, | |
| 'parent': {'trace_id': 5, 'span_id': 8, 'is_remote': False}, | |
| 'start_time': 11000000000, | |
| 'end_time': 11000000000, | |
| 'attributes': { | |
| 'logfire.span_type': 'log', | |
| 'logfire.level_num': 17, | |
| 'logfire.msg_template': 'error', | |
| 'logfire.msg': 'error', | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| }, | |
| }, | |
| { | |
| 'name': 'span2', | |
| 'context': {'trace_id': 5, 'span_id': 8, 'is_remote': False}, | |
| 'parent': {'trace_id': 5, 'span_id': 7, 'is_remote': False}, | |
| 'start_time': 10000000000, | |
| 'end_time': 12000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span2', | |
| 'logfire.msg': 'span2', | |
| 'logfire.span_type': 'span', | |
| }, | |
| }, | |
| { | |
| 'name': 'span', | |
| 'context': {'trace_id': 5, 'span_id': 7, 'is_remote': False}, | |
| 'parent': None, | |
| 'start_time': 9000000000, | |
| 'end_time': 13000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span', | |
| 'logfire.msg': 'span', | |
| 'logfire.span_type': 'span', | |
| }, | |
| }, | |
| { | |
| 'name': 'span3', | |
| 'context': {'trace_id': 6, 'span_id': 13, 'is_remote': False}, | |
| 'parent': {'trace_id': 6, 'span_id': 12, 'is_remote': False}, | |
| 'start_time': 14000000000, | |
| 'end_time': 14000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span3', | |
| 'logfire.msg': 'span3', | |
| 'logfire.level_num': 21, | |
| 'logfire.span_type': 'pending_span', | |
| 'logfire.pending_parent_id': '0000000000000000', | |
| }, | |
| }, | |
| { | |
| 'name': 'trace', | |
| 'context': {'trace_id': 6, 'span_id': 14, 'is_remote': False}, | |
| 'parent': {'trace_id': 6, 'span_id': 12, 'is_remote': False}, | |
| 'start_time': 15000000000, | |
| 'end_time': 15000000000, | |
| 'attributes': { | |
| 'logfire.span_type': 'log', | |
| 'logfire.level_num': 1, | |
| 'logfire.msg_template': 'trace', | |
| 'logfire.msg': 'trace', | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| }, | |
| }, | |
| { | |
| 'name': 'span3', | |
| 'context': {'trace_id': 6, 'span_id': 12, 'is_remote': False}, | |
| 'parent': None, | |
| 'start_time': 14000000000, | |
| 'end_time': 16000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_level_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span3', | |
| 'logfire.msg': 'span3', | |
| 'logfire.level_num': 21, | |
| 'logfire.span_type': 'span', | |
| }, | |
| }, | |
| ] | |
| ) | |
| def test_duration_threshold( | |
| config_kwargs: dict[str, Any], | |
| exporter: TestExporter, | |
| time_generator: TimeGenerator, | |
| ): | |
| # Set level to None to not include spans merely based on a high level. | |
| logfire.configure( | |
| **config_kwargs, sampling=logfire.SamplingOptions.level_or_duration(level_threshold=None, duration_threshold=3) | |
| ) | |
| logfire.error('short1') | |
| with logfire.span('span'): | |
| logfire.error('short2') | |
| # This has a total fake duration of 3s, which doesn't get included because we use >, not >=. | |
| with logfire.span('span2'): | |
| with logfire.span('span3', _level='error'): | |
| pass | |
| # This has a total fake duration of 4s, which does get included. | |
| with logfire.span('span4'): | |
| with logfire.span('span5'): | |
| logfire.info('long1') | |
| # This reaches the duration threshold when span7 ends but before span6 ends. | |
| # This means that a pending span is created for span6 but not for span7, | |
| # because PendingSpanProcessor doesn't create pending spans for spans that have finished. | |
| with logfire.span('span6'): | |
| time_generator() | |
| with logfire.span('span7'): | |
| time_generator() | |
| assert exporter.exported_spans_as_dict(_include_pending_spans=True) == snapshot( | |
| [ | |
| { | |
| 'name': 'long1', | |
| 'context': {'trace_id': 4, 'span_id': 8, 'is_remote': False}, | |
| 'parent': {'trace_id': 4, 'span_id': 7, 'is_remote': False}, | |
| 'start_time': 11000000000, | |
| 'end_time': 11000000000, | |
| 'attributes': { | |
| 'logfire.span_type': 'log', | |
| 'logfire.level_num': 9, | |
| 'logfire.msg_template': 'long1', | |
| 'logfire.msg': 'long1', | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_duration_threshold', | |
| 'code.lineno': 123, | |
| }, | |
| }, | |
| { | |
| 'name': 'span5', | |
| 'context': {'trace_id': 4, 'span_id': 7, 'is_remote': False}, | |
| 'parent': {'trace_id': 4, 'span_id': 6, 'is_remote': False}, | |
| 'start_time': 10000000000, | |
| 'end_time': 12000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_duration_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span5', | |
| 'logfire.msg': 'span5', | |
| 'logfire.span_type': 'span', | |
| }, | |
| }, | |
| { | |
| 'name': 'span4', | |
| 'context': {'trace_id': 4, 'span_id': 6, 'is_remote': False}, | |
| 'parent': None, | |
| 'start_time': 9000000000, | |
| 'end_time': 13000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_duration_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span4', | |
| 'logfire.msg': 'span4', | |
| 'logfire.span_type': 'span', | |
| }, | |
| }, | |
| { | |
| 'name': 'span6', | |
| 'context': {'trace_id': 5, 'span_id': 11, 'is_remote': False}, | |
| 'parent': {'trace_id': 5, 'span_id': 9, 'is_remote': False}, | |
| 'start_time': 14000000000, | |
| 'end_time': 14000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_duration_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span6', | |
| 'logfire.msg': 'span6', | |
| 'logfire.span_type': 'pending_span', | |
| 'logfire.pending_parent_id': '0000000000000000', | |
| }, | |
| }, | |
| { | |
| 'name': 'span7', | |
| 'context': {'trace_id': 5, 'span_id': 10, 'is_remote': False}, | |
| 'parent': {'trace_id': 5, 'span_id': 9, 'is_remote': False}, | |
| 'start_time': 16000000000, | |
| 'end_time': 18000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_duration_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span7', | |
| 'logfire.msg': 'span7', | |
| 'logfire.span_type': 'span', | |
| }, | |
| }, | |
| { | |
| 'name': 'span6', | |
| 'context': {'trace_id': 5, 'span_id': 9, 'is_remote': False}, | |
| 'parent': None, | |
| 'start_time': 14000000000, | |
| 'end_time': 19000000000, | |
| 'attributes': { | |
| 'code.filepath': 'test_tail_sampling.py', | |
| 'code.function': 'test_duration_threshold', | |
| 'code.lineno': 123, | |
| 'logfire.msg_template': 'span6', | |
| 'logfire.msg': 'span6', | |
| 'logfire.span_type': 'span', | |
| }, | |
| }, | |
| ] | |
| ) | |
| def test_background_rate(config_kwargs: dict[str, Any], exporter: TestExporter): | |
| config_kwargs.update( | |
| sampling=logfire.SamplingOptions.level_or_duration(background_rate=0.3), | |
| ) | |
| config_kwargs['advanced'].id_generator = SeededRandomIdGenerator(seed=1) | |
| logfire.configure(**config_kwargs) | |
| # These spans should all be included because the level is above the default. | |
| for _ in range(100): | |
| logfire.error('error') | |
| assert len(exporter.exported_spans) == 100 | |
| # About 30% these spans (i.e. an extra ~300) should be included because of the background_rate. | |
| # None of them meet the tail sampling criteria. | |
| for _ in range(1000): | |
| logfire.info('info') | |
| assert len(exporter.exported_spans) - 100 == snapshot(299) | |
| class TestSampler(Sampler): | |
| def should_sample( | |
| self, | |
| parent_context: Context | None, | |
| trace_id: int, | |
| name: str, | |
| *args: Any, | |
| **kwargs: Any, | |
| ) -> SamplingResult: | |
| if name == 'exclude': | |
| sampler = ALWAYS_OFF | |
| else: | |
| sampler = ALWAYS_ON | |
| return sampler.should_sample(parent_context, trace_id, name, *args, **kwargs) | |
| def get_description(self) -> str: # pragma: no cover | |
| return 'MySampler' | |
| def test_raw_head_sampler_without_tail_sampling(config_kwargs: dict[str, Any], exporter: TestExporter): | |
| logfire.configure( | |
| **config_kwargs, | |
| sampling=logfire.SamplingOptions(head=TestSampler()), | |
| ) | |
| # These spans should all be excluded by the head sampler | |
| for _ in range(100): | |
| logfire.error('exclude') | |
| assert len(exporter.exported_spans) == 0 | |
| for _ in range(100): | |
| logfire.error('error') | |
| assert len(exporter.exported_spans) == 100 | |
| def test_raw_head_sampler_with_tail_sampling(config_kwargs: dict[str, Any], exporter: TestExporter): | |
| config_kwargs.update( | |
| sampling=logfire.SamplingOptions.level_or_duration(head=TestSampler(), background_rate=0.3), | |
| ) | |
| config_kwargs['advanced'].id_generator = SeededRandomIdGenerator(seed=1) | |
| logfire.configure(**config_kwargs) | |
| # These spans should all be excluded by the head sampler, | |
| # so it doesn't matter that they have a high level. | |
| for _ in range(100): | |
| logfire.error('exclude') | |
| assert len(exporter.exported_spans) == 0 | |
| # These spans should all be included because the level is above the default, | |
| # and the head sampler doesn't exclude them. | |
| for _ in range(100): | |
| logfire.error('error') | |
| assert len(exporter.exported_spans) == 100 | |
| # About 30% these spans (i.e. an extra ~300) should be included because of the background_rate. | |
| # None of them meet the tail sampling criteria. | |
| for _ in range(1000): | |
| logfire.info('info') | |
| assert len(exporter.exported_spans) - 100 == snapshot(293) | |
| def test_custom_head_and_tail(config_kwargs: dict[str, Any], exporter: TestExporter): | |
| span_counts = {'start': 0, 'end': 0} | |
| def get_tail_sample_rate(span_info: TailSamplingSpanInfo) -> float: | |
| span_counts[span_info.event] += 1 | |
| if span_info.duration >= 1: | |
| return 0.5 | |
| if span_info.level > 'warn': | |
| return 0.3 | |
| return 0.1 | |
| config_kwargs.update( | |
| sampling=logfire.SamplingOptions( | |
| head=0.7, | |
| tail=get_tail_sample_rate, | |
| ), | |
| ) | |
| config_kwargs['advanced'].id_generator = SeededRandomIdGenerator(seed=3) | |
| logfire.configure(**config_kwargs) | |
| for _ in range(1000): | |
| logfire.warn('warn') | |
| assert span_counts == snapshot({'start': 719, 'end': 611}) | |
| assert len(exporter.exported_spans) == snapshot(108) | |
| assert span_counts['end'] + len(exporter.exported_spans) == span_counts['start'] | |
| exporter.clear() | |
| for _ in range(1000): | |
| with logfire.span('span'): | |
| pass | |
| assert len(exporter.exported_spans_as_dict()) == snapshot(511) | |
| exporter.clear() | |
| for _ in range(1000): | |
| logfire.error('error') | |
| assert len(exporter.exported_spans) == snapshot(298) | |
| def test_span_levels(): | |
| warn = SpanLevel(LEVEL_NUMBERS['warn']) | |
| assert 'warn' <= warn <= 'warn' | |
| assert 'debug' <= warn <= 'error' | |
| assert 'info' < warn < 'fatal' | |
| assert not (warn < 'warn') | |
| assert not (warn > 'warn') | |
| assert not (warn > 'fatal') | |
| assert not (warn >= 'fatal') | |
| assert not (warn < 'debug') | |
| assert not (warn <= 'debug') | |
| assert warn == 'warn' | |
| assert warn != 'error' | |
| assert not (warn != 'warn') | |
| assert not (warn == 'error') | |
| assert warn == warn.number | |
| assert warn != 123 | |
| assert warn == warn | |
| assert not (warn != warn) | |
| assert warn != SpanLevel(LEVEL_NUMBERS['error']) | |
| assert not (warn == SpanLevel(LEVEL_NUMBERS['error'])) | |
| assert warn == SpanLevel(LEVEL_NUMBERS['warn']) | |
| assert not (warn != SpanLevel(LEVEL_NUMBERS['warn'])) | |
| assert warn.number == LEVEL_NUMBERS['warn'] == 13 | |
| assert warn.name == 'warn' | |
| assert warn != 'foo' | |
| assert warn != [1, 2, 3] | |
| assert not (warn == [1, 2, 3]) | |
| assert not ([1, 2, 3] == warn) | |
| assert {warn, SpanLevel(LEVEL_NUMBERS['warn'])} == {warn} | |
| def test_invalid_rates(): | |
| with inline_snapshot.extra.raises( | |
| snapshot('ValueError: Invalid sampling rates, must be 0.0 <= background_rate <= head <= 1.0') | |
| ): | |
| logfire.SamplingOptions.level_or_duration(background_rate=-1) | |
| with pytest.raises(ValueError): | |
| logfire.SamplingOptions.level_or_duration(background_rate=0.5, head=0.3) | |
| with pytest.raises(ValueError): | |
| logfire.SamplingOptions.level_or_duration(head=2) | |
| def test_tail_sampling_no_warning_on_ended_span( | |
| exporter: TestExporter, | |
| id_generator: Any, | |
| time_generator: TimeGenerator, | |
| caplog: pytest.LogCaptureFixture, | |
| ): | |
| """Test that tail sampling with baggage doesn't trigger 'Setting attribute on ended span' warnings. | |
| With the redesigned TailSamplingProcessor, on_start is called immediately on the main processor | |
| (including DirectBaggageAttributesSpanProcessor), so attributes are set before the span ends. | |
| """ | |
| config_kwargs = dict( | |
| send_to_logfire=False, | |
| console=False, | |
| advanced=logfire.AdvancedOptions( | |
| id_generator=id_generator, | |
| ns_timestamp_generator=time_generator, | |
| log_record_processors=[SimpleLogRecordProcessor(TestLogExporter(time_generator))], | |
| ), | |
| additional_span_processors=[SimpleSpanProcessor(exporter)], | |
| add_baggage_to_attributes=True, | |
| ) | |
| logfire.configure( | |
| **config_kwargs, # type: ignore | |
| sampling=logfire.SamplingOptions(tail=lambda info: 1.0 if info.level >= 'error' else 0.0), | |
| ) | |
| caplog.set_level(logging.WARNING, logger='opentelemetry.sdk.trace') | |
| with logfire.span('root'): | |
| with logfire.span('child_1'): | |
| pass | |
| with logfire.span('child_2'): | |
| pass | |
| logfire.error('Trigger sampling') | |
| warnings = [r for r in caplog.records if 'Setting attribute on ended span' in r.message] | |
| assert warnings == [], f'Unexpected warnings: {[r.message for r in warnings]}' | |
| # Exercise force_flush with deferred_processor present (via PendingSpanProcessor) | |
| logfire.force_flush() | |
| def test_on_start_attribute_set_by_processor( | |
| exporter: TestExporter, | |
| id_generator: Any, | |
| time_generator: TimeGenerator, | |
| ): | |
| """Test that a custom processor's on_start attribute-setting works during tail sampling. | |
| The attribute should be set immediately (before the span ends) and appear on exported spans. | |
| """ | |
| class AttributeSettingProcessor(SpanProcessor): | |
| def on_start(self, span: Span, parent_context: Any = None) -> None: | |
| span.set_attribute('custom.from_on_start', 'hello') | |
| config_kwargs = dict( | |
| send_to_logfire=False, | |
| console=False, | |
| advanced=logfire.AdvancedOptions( | |
| id_generator=id_generator, | |
| ns_timestamp_generator=time_generator, | |
| ), | |
| additional_span_processors=[ | |
| SimpleSpanProcessor(exporter), | |
| AttributeSettingProcessor(), | |
| ], | |
| ) | |
| logfire.configure( | |
| **config_kwargs, # type: ignore | |
| sampling=logfire.SamplingOptions(tail=lambda info: 1.0 if info.level >= 'error' else 0.0), | |
| ) | |
| with logfire.span('root'): | |
| logfire.error('trigger') | |
| spans = exporter.exported_spans_as_dict() | |
| for span in spans: | |
| assert span['attributes'].get('custom.from_on_start') == 'hello', ( | |
| f"Expected 'custom.from_on_start' attribute on span {span['name']}" | |
| ) | |
| def test_deferred_processor_marker( | |
| exporter: TestExporter, | |
| id_generator: Any, | |
| time_generator: TimeGenerator, | |
| ): | |
| """Test that a processor with tail_sampling_defer_on_start=True has on_start deferred.""" | |
| on_start_order: list[str] = [] | |
| class DeferredProcessor(SpanProcessor): | |
| tail_sampling_defer_on_start = True | |
| def on_start(self, span: Span, parent_context: Any = None) -> None: | |
| on_start_order.append(f'deferred:{span.name}') | |
| def on_end(self, span: ReadableSpan) -> None: | |
| pass | |
| class ImmediateProcessor(SpanProcessor): | |
| def on_start(self, span: Span, parent_context: Any = None) -> None: | |
| on_start_order.append(f'immediate:{span.name}') | |
| def on_end(self, span: ReadableSpan) -> None: | |
| pass | |
| config_kwargs = dict( | |
| send_to_logfire=False, | |
| console=False, | |
| advanced=logfire.AdvancedOptions( | |
| id_generator=id_generator, | |
| ns_timestamp_generator=time_generator, | |
| ), | |
| additional_span_processors=[ | |
| SimpleSpanProcessor(exporter), | |
| DeferredProcessor(), | |
| ImmediateProcessor(), | |
| ], | |
| ) | |
| logfire.configure( | |
| **config_kwargs, # type: ignore | |
| sampling=logfire.SamplingOptions(tail=lambda info: 1.0 if info.level >= 'error' else 0.0), | |
| ) | |
| # Create a span that doesn't trigger sampling — immediate processor gets on_start, | |
| # but deferred processor does NOT get on_start yet. | |
| on_start_order.clear() | |
| with logfire.span('buffered'): | |
| # At this point, immediate processor should have received on_start | |
| assert 'immediate:buffered' in on_start_order | |
| assert 'deferred:buffered' not in on_start_order | |
| # Now create a trace that triggers sampling | |
| on_start_order.clear() | |
| with logfire.span('root'): | |
| logfire.error('trigger') | |
| # Both processors should have received on_start for the sampled trace | |
| assert any('immediate:' in s for s in on_start_order) | |
| assert any('deferred:' in s for s in on_start_order) | |
| def test_tail_sampling_processor_without_deferred(): | |
| """Test TailSamplingProcessor directly without a deferred_processor. | |
| Covers the deferred_processor-is-None branches in on_start, on_end, | |
| push_buffer, shutdown, and force_flush. | |
| """ | |
| on_end_spans: list[str] = [] | |
| class CollectorProcessor(SpanProcessor): | |
| def on_start(self, span: Span, parent_context: Any = None) -> None: | |
| pass | |
| def on_end(self, span: ReadableSpan) -> None: | |
| on_end_spans.append(span.name) | |
| def shutdown(self) -> None: | |
| pass | |
| def force_flush(self, timeout_millis: int = 30000) -> bool: | |
| return True | |
| collector = CollectorProcessor() | |
| processor = TailSamplingProcessor( | |
| collector, | |
| get_tail_sample_rate=lambda info: 1.0, # Always sample | |
| ) | |
| assert processor.deferred_processor is None | |
| provider = TracerProvider() | |
| provider.add_span_processor(processor) | |
| tracer = provider.get_tracer('test') | |
| # The root span triggers sampling (rate=1.0), dropping the buffer. | |
| # The child span then arrives with buffer=None, covering the | |
| # deferred_processor-is-None branch in on_start and on_end. | |
| with tracer.start_as_current_span('parent'): | |
| with tracer.start_as_current_span('child'): | |
| pass | |
| assert 'parent' in on_end_spans | |
| assert 'child' in on_end_spans | |
| # Exercise shutdown and force_flush with no deferred_processor | |
| processor.force_flush() | |
| processor.shutdown() | |
| def test_tail_sampling_config_without_pending_span_processors(): | |
| """Test config.py wiring when tail sampling is active but no processors have pending spans. | |
| Covers the deferred_processors-is-empty branch in config.py (if deferred_processors: → False), | |
| which means TailSamplingProcessor is constructed with deferred_processor=None. | |
| Must NOT use SimpleSpanProcessor(TestExporter) here — that would make has_pending=True, | |
| populating processors_with_pending_spans and making deferred_processors non-empty, | |
| which would cover the wrong branch. | |
| """ | |
| on_end_spans: list[str] = [] | |
| class CollectorProcessor(SpanProcessor): | |
| def on_end(self, span: ReadableSpan) -> None: | |
| on_end_spans.append(span.name) | |
| logfire.configure( | |
| send_to_logfire=False, | |
| console=False, | |
| additional_span_processors=[CollectorProcessor()], | |
| sampling=logfire.SamplingOptions(tail=lambda info: 1.0), | |
| ) | |
| logfire.info('test') | |
| logfire.force_flush() | |
| assert 'test' in on_end_spans | |
| class _NameCollector(SpanProcessor): | |
| def __init__(self) -> None: | |
| self.names: list[str] = [] | |
| def on_start(self, span: Span, parent_context: Any = None) -> None: | |
| pass | |
| def on_end(self, span: ReadableSpan) -> None: | |
| self.names.append(span.name) | |
| def shutdown(self) -> None: | |
| pass | |
| def force_flush(self, timeout_millis: int = 30000) -> bool: | |
| return True | |
| def test_dropped_trace_does_not_export_span_ending_after_root(): | |
| """A child that outlives a dropped root must not take the pass-through export path.""" | |
| collector = _NameCollector() | |
| processor = TailSamplingProcessor(collector, get_tail_sample_rate=lambda info: 0.0) | |
| provider = TracerProvider() | |
| provider.add_span_processor(processor) | |
| tracer = provider.get_tracer('test') | |
| with tracer.start_as_current_span('root'): | |
| child = tracer.start_span('child') | |
| child.end() | |
| assert collector.names == [] | |
| def test_late_span_can_still_sample_trace_after_root_ends(): | |
| """A child ending after the root can still include the whole trace.""" | |
| collector = _NameCollector() | |
| processor = TailSamplingProcessor( | |
| collector, | |
| get_tail_sample_rate=lambda info: 1.0 if info.event == 'end' and info.span.name == 'child' else 0.0, | |
| ) | |
| provider = TracerProvider() | |
| provider.add_span_processor(processor) | |
| tracer = provider.get_tracer('test') | |
| with tracer.start_as_current_span('root'): | |
| child = tracer.start_span('child') | |
| child.end() | |
| assert collector.names == ['root', 'child'] | |
Xet Storage Details
- Size:
- 28.8 kB
- Xet hash:
- 363b07f9b94736488e4334d3c729f370a5126fba9858ff309fb96c01919f44e9
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.