|
| 1 | +# Copyright 2016-2026. Couchbase, Inc. |
| 2 | +# All Rights Reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License") |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +import asyncio |
| 17 | +import threading |
| 18 | +from time import time_ns |
| 19 | + |
| 20 | +import pytest |
| 21 | + |
| 22 | +from couchbase.logic.observability.observability_types import (DispatchAttributeName, |
| 23 | + OpAttributeName, |
| 24 | + ServiceType) |
| 25 | +from couchbase.logic.observability.threshold_logging import ThresholdLoggingTracer |
| 26 | + |
| 27 | + |
| 28 | +class FakeReporter: |
| 29 | + """Lightweight fake reporter for testing without thread delays.""" |
| 30 | + |
| 31 | + def __init__(self) -> None: |
| 32 | + self.lock = threading.Lock() |
| 33 | + self.records = [] |
| 34 | + |
| 35 | + def add_log_record(self, service_type, record, total_duration): |
| 36 | + with self.lock: |
| 37 | + self.records.append((service_type, record, total_duration)) |
| 38 | + |
| 39 | + def stop(self): |
| 40 | + pass |
| 41 | + |
| 42 | + def start(self): |
| 43 | + pass |
| 44 | + |
| 45 | + |
| 46 | +class AsyncThresholdLoggingTestSuite: |
| 47 | + TEST_MANIFEST = [ |
| 48 | + 'test_async_threshold_span_accumulation', |
| 49 | + 'test_async_callback_lifecycle', |
| 50 | + 'test_concurrent_async_operations', |
| 51 | + 'test_async_threshold_reporter_receives_records', |
| 52 | + ] |
| 53 | + |
| 54 | + @pytest.mark.asyncio |
| 55 | + async def test_async_threshold_span_accumulation(self): |
| 56 | + """Async variant of test_span_conversion_with_all_attributes. |
| 57 | +
|
| 58 | + Verifies that the full span hierarchy (root → encoding → dispatch) produces |
| 59 | + a correct log record with all expected fields and values. |
| 60 | + """ |
| 61 | + config = { |
| 62 | + 'key_value_threshold': 0.5, |
| 63 | + 'threshold_sample_size': 10, |
| 64 | + 'threshold_emit_interval': 100_000, |
| 65 | + } |
| 66 | + |
| 67 | + tracer = ThresholdLoggingTracer(config) |
| 68 | + tracer._reporter.stop() |
| 69 | + |
| 70 | + now = time_ns() |
| 71 | + op_start_ns = now - 1_000_000 |
| 72 | + op_end_ns = op_start_ns + 1_000_000 # 1ms total |
| 73 | + encode_start_ns = op_start_ns + 100_000 |
| 74 | + encode_end_ns = encode_start_ns + 100_000 # 100us encode |
| 75 | + dispatch_start_ns = encode_end_ns + 200_000 |
| 76 | + dispatch_end_ns = dispatch_start_ns + 400_000 # 400us dispatch |
| 77 | + |
| 78 | + op_span = tracer.request_span('get', start_time=op_start_ns) |
| 79 | + op_span.set_attribute(OpAttributeName.Service.value, ServiceType.KeyValue.value) |
| 80 | + |
| 81 | + encoding_span = tracer.request_span( |
| 82 | + OpAttributeName.EncodingSpanName.value, |
| 83 | + parent_span=op_span, |
| 84 | + start_time=encode_start_ns |
| 85 | + ) |
| 86 | + encoding_span.end(end_time=encode_end_ns) |
| 87 | + |
| 88 | + dispatch_span = tracer.request_span( |
| 89 | + OpAttributeName.DispatchSpanName.value, |
| 90 | + parent_span=op_span, |
| 91 | + start_time=dispatch_start_ns |
| 92 | + ) |
| 93 | + dispatch_span.set_attribute(DispatchAttributeName.LocalId.value, 'local1') |
| 94 | + dispatch_span.set_attribute(DispatchAttributeName.OperationId.value, 'op1') |
| 95 | + dispatch_span.set_attribute(DispatchAttributeName.PeerAddress.value, '127.0.0.1') |
| 96 | + dispatch_span.set_attribute(DispatchAttributeName.PeerPort.value, 11210) |
| 97 | + dispatch_span.set_attribute(DispatchAttributeName.ServerDuration.value, 200_000) |
| 98 | + dispatch_span.end(end_time=dispatch_end_ns) |
| 99 | + |
| 100 | + op_span.end(end_time=op_end_ns) |
| 101 | + |
| 102 | + kv_items, _ = tracer._reporter._queues[ServiceType.KeyValue].drain() |
| 103 | + |
| 104 | + assert len(kv_items) == 1 |
| 105 | + record = kv_items[0] |
| 106 | + |
| 107 | + assert record['operation_name'] == 'get' |
| 108 | + assert record['total_duration_us'] == 1000.0 |
| 109 | + assert record['encode_duration_us'] == 100.0 |
| 110 | + assert record['last_dispatch_duration_us'] == 400.0 |
| 111 | + assert record['total_dispatch_duration_us'] == 400.0 |
| 112 | + assert record['last_server_duration_us'] == 200.0 |
| 113 | + assert record['total_server_duration_us'] == 200.0 |
| 114 | + assert record['last_local_id'] == 'local1' |
| 115 | + assert record['operation_id'] == 'op1' |
| 116 | + assert record['last_local_socket'] == '127.0.0.1:11210' |
| 117 | + |
| 118 | + tracer.close() |
| 119 | + |
| 120 | + @pytest.mark.asyncio |
| 121 | + async def test_async_callback_lifecycle(self): |
| 122 | + """Async variant of the callback lifecycle test. |
| 123 | +
|
| 124 | + Uses asyncio + run_in_executor to model the actual AsyncClientAdapter pattern: |
| 125 | + the C++ I/O callback runs on a thread-pool thread, sets span attributes, then |
| 126 | + calls call_soon_threadsafe to hand back to the event loop, which then ends the span. |
| 127 | + """ |
| 128 | + config = { |
| 129 | + 'key_value_threshold': 0.5, |
| 130 | + 'threshold_sample_size': 10, |
| 131 | + } |
| 132 | + |
| 133 | + tracer = ThresholdLoggingTracer(config) |
| 134 | + fake_reporter = FakeReporter() |
| 135 | + tracer._reporter.stop() |
| 136 | + tracer._reporter = fake_reporter |
| 137 | + |
| 138 | + loop = asyncio.get_event_loop() |
| 139 | + N = 20 |
| 140 | + |
| 141 | + for _ in range(N): |
| 142 | + now = time_ns() |
| 143 | + root = tracer.request_span('upsert', start_time=now - 2_000_000) |
| 144 | + root.set_attribute(OpAttributeName.Service.value, ServiceType.KeyValue.value) |
| 145 | + |
| 146 | + callback_done = asyncio.Event() |
| 147 | + |
| 148 | + def io_callback(root=root): |
| 149 | + # Runs in thread-pool executor, simulating C++ I/O thread |
| 150 | + dispatch = tracer.request_span( |
| 151 | + OpAttributeName.DispatchSpanName.value, |
| 152 | + parent_span=root, |
| 153 | + start_time=time_ns() - 500_000 |
| 154 | + ) |
| 155 | + dispatch.set_attribute(DispatchAttributeName.ServerDuration.value, 500) |
| 156 | + dispatch.set_attribute(DispatchAttributeName.PeerAddress.value, '127.0.0.1') |
| 157 | + dispatch.end(end_time=time_ns()) |
| 158 | + loop.call_soon_threadsafe(callback_done.set) |
| 159 | + |
| 160 | + fut = loop.run_in_executor(None, io_callback) |
| 161 | + await callback_done.wait() |
| 162 | + await fut |
| 163 | + |
| 164 | + root.end(end_time=time_ns()) |
| 165 | + |
| 166 | + assert root._total_server_duration_ns == 500 |
| 167 | + assert root._span_snapshot is not None |
| 168 | + |
| 169 | + assert len(fake_reporter.records) == N |
| 170 | + |
| 171 | + tracer.close() |
| 172 | + |
| 173 | + @pytest.mark.asyncio |
| 174 | + async def test_concurrent_async_operations(self): |
| 175 | + """N concurrent coroutines each owning independent span hierarchies. |
| 176 | +
|
| 177 | + Each coroutine runs the full lifecycle (root → dispatch → end) with its own spans. |
| 178 | + Verifies that independent concurrent operations don't corrupt each other's state |
| 179 | + and that exactly N log records are produced. |
| 180 | + """ |
| 181 | + config = { |
| 182 | + 'key_value_threshold': 0.5, |
| 183 | + 'threshold_sample_size': 100, |
| 184 | + } |
| 185 | + |
| 186 | + tracer = ThresholdLoggingTracer(config) |
| 187 | + fake_reporter = FakeReporter() |
| 188 | + tracer._reporter.stop() |
| 189 | + tracer._reporter = fake_reporter |
| 190 | + |
| 191 | + loop = asyncio.get_event_loop() |
| 192 | + N = 50 |
| 193 | + |
| 194 | + async def run_op(op_id: int) -> None: |
| 195 | + now = time_ns() |
| 196 | + root = tracer.request_span(f'upsert_{op_id}', start_time=now - 2_000_000) |
| 197 | + root.set_attribute(OpAttributeName.Service.value, ServiceType.KeyValue.value) |
| 198 | + |
| 199 | + callback_done = asyncio.Event() |
| 200 | + |
| 201 | + def io_callback(root=root): |
| 202 | + dispatch = tracer.request_span( |
| 203 | + OpAttributeName.DispatchSpanName.value, |
| 204 | + parent_span=root, |
| 205 | + start_time=time_ns() - 400_000 |
| 206 | + ) |
| 207 | + dispatch.set_attribute(DispatchAttributeName.ServerDuration.value, 200) |
| 208 | + dispatch.end(end_time=time_ns()) |
| 209 | + loop.call_soon_threadsafe(callback_done.set) |
| 210 | + |
| 211 | + fut = loop.run_in_executor(None, io_callback) |
| 212 | + await callback_done.wait() |
| 213 | + await fut |
| 214 | + |
| 215 | + root.end(end_time=time_ns()) |
| 216 | + |
| 217 | + await asyncio.gather(*[run_op(i) for i in range(N)]) |
| 218 | + |
| 219 | + assert len(fake_reporter.records) == N |
| 220 | + for _, record, duration in fake_reporter.records: |
| 221 | + assert duration > 0 |
| 222 | + assert record['total_duration_us'] > 0 |
| 223 | + assert record['total_dispatch_duration_us'] > 0 |
| 224 | + |
| 225 | + tracer.close() |
| 226 | + |
| 227 | + def test_async_threshold_reporter_receives_records(self): |
| 228 | + """Async counterpart of test_exceeding_sample_size. |
| 229 | +
|
| 230 | + Verifies that the reporter's priority queue correctly retains only the top N |
| 231 | + records when more than N operations exceed the threshold. |
| 232 | + """ |
| 233 | + config = { |
| 234 | + 'key_value_threshold': 0.5, |
| 235 | + 'threshold_sample_size': 3, |
| 236 | + 'threshold_emit_interval': 100_000, |
| 237 | + } |
| 238 | + |
| 239 | + tracer = ThresholdLoggingTracer(config) |
| 240 | + tracer._reporter.stop() |
| 241 | + |
| 242 | + operations = [ |
| 243 | + ('get', 1_000_000), # 1ms → 1000us |
| 244 | + ('insert', 1_100_000), # 1.1ms → 1100us |
| 245 | + ('upsert', 1_050_000), # 1.05ms → 1050us |
| 246 | + ('remove', 1_200_000), # 1.2ms → 1200us |
| 247 | + ('replace', 1_150_000), # 1.15ms → 1150us |
| 248 | + ] |
| 249 | + |
| 250 | + now = time_ns() |
| 251 | + for op_name, duration_us in operations: |
| 252 | + start_ns = now - duration_us * 1000 |
| 253 | + end_ns = start_ns + duration_us * 1000 |
| 254 | + |
| 255 | + span = tracer.request_span(op_name, start_time=start_ns) |
| 256 | + span.set_attribute(OpAttributeName.Service.value, ServiceType.KeyValue.value) |
| 257 | + span.end(end_time=end_ns) |
| 258 | + |
| 259 | + kv_items, dropped_count = tracer._reporter._queues[ServiceType.KeyValue].drain() |
| 260 | + |
| 261 | + assert len(kv_items) == 3 |
| 262 | + assert dropped_count == 2 |
| 263 | + |
| 264 | + op_names = [item['operation_name'] for item in kv_items] |
| 265 | + assert 'remove' in op_names # 1200us — highest |
| 266 | + assert 'replace' in op_names # 1150us — second |
| 267 | + assert 'insert' in op_names # 1100us — third |
| 268 | + assert 'get' not in op_names |
| 269 | + assert 'upsert' not in op_names |
| 270 | + |
| 271 | + tracer.close() |
| 272 | + |
| 273 | + |
| 274 | +class ClassicAsyncThresholdLoggingTests(AsyncThresholdLoggingTestSuite): |
| 275 | + |
| 276 | + @pytest.fixture(scope='class', autouse=True) |
| 277 | + def manifest_validated(self): |
| 278 | + def valid_test_method(meth): |
| 279 | + attr = getattr(ClassicAsyncThresholdLoggingTests, meth) |
| 280 | + return callable(attr) and not meth.startswith('__') and meth.startswith('test') |
| 281 | + method_list = [meth for meth in dir(ClassicAsyncThresholdLoggingTests) if valid_test_method(meth)] |
| 282 | + test_list = set(AsyncThresholdLoggingTestSuite.TEST_MANIFEST).symmetric_difference(method_list) |
| 283 | + if test_list: |
| 284 | + pytest.fail(f'Test manifest not validated. Missing/extra tests: {test_list}.') |
0 commit comments