-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrace_simulator.py
More file actions
1712 lines (1484 loc) · 62.7 KB
/
trace_simulator.py
File metadata and controls
1712 lines (1484 loc) · 62.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Trace simulator: loads trace JSON, turns spans into start/end events,
and runs them through a pluggable bridge (OnStart/OnEnd), mirroring
OpenTelemetry SDK SpanProcessor semantics.
With multiple loaded traces, events are interleaved into one timeline by default
(sort key: time, start/end, depth, trace_id) so a shared handler sees concurrent
work; use --sequential-traces for isolated per-trace runs. S-Bridge DEE queues are
per service name across traces.
Handlers implement the same conceptual interface as in
blueprint-docc-mod/runtime/plugins/otelcol (e.g. vanilla_processor.go):
- OnStart(parent_ctx, span): span is mutable (e.g. add baggage/attributes).
Returns whether incoming baggage was found for this span (used by --bagsize).
- OnEnd(span): span is read-only for inspection; handler may strip attributes.
"""
import argparse
import copy
import json
import sys
from abc import ABC, abstractmethod
from pathlib import Path
from collections import defaultdict, deque
from typing import Any, Dict, List, Optional, Tuple
# Bloom filter for path bridge (and later CGPB)
try:
from bloom import BloomFilter, estimate_parameters
except ImportError:
BloomFilter = None # type: ignore
estimate_parameters = None # type: ignore
# -----------------------------------------------------------------------------
# Span representation and tag helpers
# -----------------------------------------------------------------------------
def _tags_list(span: dict) -> list:
"""Return the tags/attributes list (Jaeger-style or OTel-style)."""
tags = span.get("tags")
if tags is not None:
return tags
attrs = span.get("attributes")
if isinstance(attrs, dict):
return [{"key": k, "value": v} for k, v in attrs.items()]
if isinstance(attrs, list):
return attrs
return []
def _set_tags_list(span: dict, tags: list) -> None:
"""Set span tags to a list of {key, value}."""
if "tags" in span:
span["tags"] = tags
else:
span["attributes"] = {t["key"]: t["value"] for t in tags}
return
def span_get_tag(span: dict, key: str) -> Optional[Any]:
"""Get the value of a tag/attribute by key."""
for t in _tags_list(span):
k = t.get("key") or t.get("Key")
if k == key:
# Use explicit None checks so falsy values like 0 still count.
v = t.get("value")
if v is None:
v = t.get("Value")
return v
return None
def span_set_tag(span: dict, key: str, value: Any) -> None:
"""Set a tag/attribute; updates existing or appends."""
tags = _tags_list(span)
for t in tags:
k = t.get("key") or t.get("Key")
if k == key:
t["key"] = key
t["value"] = value
return
tags.append({"key": key, "value": value})
_set_tags_list(span, tags)
def span_remove_tag(span: dict, key: str) -> None:
"""Remove a tag/attribute by key."""
tags = [t for t in _tags_list(span) if (t.get("key") or t.get("Key")) != key]
_set_tags_list(span, tags)
def span_has_tag(span: dict, key: str) -> bool:
"""Return True if the span has the given tag."""
return span_get_tag(span, key) is not None
def _baggage_value_byte_len(k_stripped: str, v: Any) -> int:
"""
Byte length of a baggage value for wire-size.
For "bf", value is raw bytes (or hex string from legacy/output); use decoded bytes length.
"""
if isinstance(v, bytes):
return len(v)
s = str(v) if not isinstance(v, str) else v
if k_stripped == "bf":
try:
return len(bytes.fromhex(s))
except (ValueError, TypeError):
pass
return len(s.encode("utf-8"))
def baggage_byte_size(span: dict) -> int:
"""
Total byte size of baggage in transit.
Key length excludes __bag. prefix. Values: raw bytes length; hex-encoded bf is decoded to bytes for count.
"""
total = 0
for t in _tags_list(span):
k = t.get("key") or t.get("Key")
if not k or not k.startswith("__bag"):
continue
v = t.get("value")
if v is None:
v = t.get("Value")
if v is None:
continue
if k.startswith("__bag."):
k_stripped = k[len("__bag."):]
else:
k_stripped = k
total += len(k_stripped.encode("utf-8")) + _baggage_value_byte_len(k_stripped, v)
return total
def baggage_byte_size_breakdown(span: dict) -> dict:
"""
Per-baggage-element byte sizes (key without __bag. prefix -> bytes for that key+value).
bf value counted as raw bytes (hex decoded if string).
"""
breakdown = {}
for t in _tags_list(span):
k = t.get("key") or t.get("Key")
if not k or not k.startswith("__bag"):
continue
v = t.get("value")
if v is None:
v = t.get("Value")
if v is None:
continue
if k.startswith("__bag."):
k_stripped = k[len("__bag."):]
else:
k_stripped = k
size = len(k_stripped.encode("utf-8")) + _baggage_value_byte_len(k_stripped, v)
breakdown[k_stripped] = size
return breakdown
# -----------------------------------------------------------------------------
# Parent context (what OnStart receives about the parent)
# -----------------------------------------------------------------------------
class ParentContext:
"""Minimal context for OnStart: identifies the parent so the handler can look up state."""
__slots__ = ("trace_id", "parent_span_id", "seq_num")
def __init__(self, trace_id: str, parent_span_id: Optional[str], seq_num: int = 0):
self.trace_id = trace_id
self.parent_span_id = parent_span_id # None for root spans
self.seq_num = seq_num # 1-based index of this span among its siblings (as processed)
# -----------------------------------------------------------------------------
# Bridge handler interface (pluggable OnStart / OnEnd)
# -----------------------------------------------------------------------------
class BridgeHandler(ABC):
"""
Bridge type: custom logic on span start and end.
Mirrors go.opentelemetry.io/otel/sdk/trace.SpanProcessor:
- OnStart(parentCtx, span): span is read-write; set baggage/attributes here.
- OnEnd(span): span is read-only; optionally strip attributes before export.
"""
@abstractmethod
def on_start(self, parent_ctx: ParentContext, span: dict) -> bool:
"""
Called when a span starts. May mutate span (e.g. set tags).
Returns True when the handler found/used incoming baggage from the parent context
(used for call-recording in --bagsize mode).
"""
raise NotImplementedError
@abstractmethod
def on_end(self, span: dict) -> None:
"""Called when a span ends. May not mutate span (read-only); export uses span as-is after this."""
pass
# -----------------------------------------------------------------------------
# Vanilla handler (no-op; pass-through like vanilla_processor.go)
# -----------------------------------------------------------------------------
class VanillaHandler(BridgeHandler):
"""No-op handler: OnStart does nothing, OnEnd does nothing. For testing the scaffold."""
def on_start(self, parent_ctx: ParentContext, span: dict) -> bool:
return False
def on_end(self, span: dict) -> None:
pass
# -----------------------------------------------------------------------------
# Path bridge constants (match blueprint-docc-mod/runtime/plugins/otelcol/defs.go)
# -----------------------------------------------------------------------------
BAG_BLOOM_FILTER = "__bag.bf"
BAG_BR = "__bag._br"
AncestryKey = "ancestry"
AncestryModeKey = "ancestry_mode"
ANCESTRY_MODE_PB = "pb"
# Single-byte ancestry mode ids (match blueprint style: one byte as string)
ANCESTRY_MODE_SBRIDGE = "\x03"
# Payload-emission metric (Figure 10): emitted checkpoint payload bytes.
# This is different from baggage/tag wire-size.
EMIT_PAYLOAD_BYTES_TAG = "__emit._br_payload_bytes"
PB_BRIDGE_TYPE_ID = 1 # path bridge type id (fits in 1 byte)
SB_BRIDGE_TYPE_ID = 3 # structural (S-) bridge type id
BR_PROPERTY_NAME_OVERHEAD_BYTES = 3 # "_br" property name overhead (as discussed)
# -----------------------------------------------------------------------------
# Packed bridge baggage: _br layout(s)
# - PB: varint(depth_mod) || bloom_bytes
# - CGPB: varint(depth_mod) || bloom_bytes || hash_array_bytes
# (No explicit priority; checkpoint-ness is derived from depth_mod==0 or leaf status.)
# -----------------------------------------------------------------------------
def _varint_encode(n: int) -> bytes:
"""Encode non-negative int as protobuf-style varint (7 bits per byte, high bit = more)."""
if n < 0:
n = 0
out = []
while n > 0x7F:
out.append((n & 0x7F) | 0x80)
n >>= 7
out.append(n & 0x7F)
return bytes(out)
def _varint_decode(buf: bytes, start: int) -> tuple:
"""Decode varint from buf[start:]; return (value, new_start)."""
n = 0
shift = 0
i = start
while i < len(buf):
b = buf[i]
n |= (b & 0x7F) << shift
i += 1
if (b & 0x80) == 0:
return (n, i)
shift += 7
if shift >= 35:
break
return (0, start)
def pack_br(depth_mod: int, bloom_bytes: bytes) -> bytes:
"""Pack path-bridge payload: varint(depth_mod) || bloom_bytes."""
return _varint_encode(depth_mod) + bloom_bytes
def unpack_br(data: bytes, bloom_len: int) -> Optional[Tuple[int, bytes]]:
"""
Unpack _br payload. Returns (depth_mod, bloom_bytes) or None if invalid.
bloom_len must match (m+7)//8 so we know how many bytes to take after the depth varint.
"""
if len(data) < bloom_len:
return None
depth_mod, i = _varint_decode(data, 0)
if i + bloom_len > len(data):
return None
bloom_bytes = data[i : i + bloom_len]
return (depth_mod, bloom_bytes)
def _span_id_hex_to_8bytes(span_id: str) -> Optional[bytes]:
"""
Convert a Jaeger spanID hex string into a fixed 8-byte representation.
Jaeger spanIDs are 64-bit = 16 hex chars. Some synthetic traces may use shorter IDs;
we left-pad with zeros to 8 bytes for deterministic packing.
"""
if not span_id:
return None
s = span_id.strip().lower()
if any(c not in "0123456789abcdef" for c in s):
return None
try:
raw = bytes.fromhex(s)
except ValueError:
return None
if len(raw) > 8:
# Unexpected width; keep the last 8 bytes to avoid negative packing.
return raw[-8:]
if len(raw) < 8:
return b"\x00" * (8 - len(raw)) + raw
return raw
def pack_cgpb_br(depth_mod: int, bloom_bytes: bytes, ha_bytes: bytes) -> bytes:
"""Pack CGPB bridge baggage: varint(depth_mod) || bloom_bytes || hash_array_bytes."""
return _varint_encode(depth_mod) + bloom_bytes + ha_bytes
def unpack_cgpb_br(data: bytes, bloom_len: int) -> Optional[Tuple[int, bytes, bytes]]:
"""
Unpack CGPB _br payload. Returns (depth_mod, bloom_bytes, ha_bytes) or None.
bloom_len must match the fixed bloom byte length.
"""
if len(data) < bloom_len:
return None
depth_mod, i = _varint_decode(data, 0)
if i + bloom_len > len(data):
return None
bloom_bytes = data[i : i + bloom_len]
ha_bytes = data[i + bloom_len :]
return (depth_mod, bloom_bytes, ha_bytes)
def _trace_id_hex_to_16bytes(trace_id: str) -> bytes:
"""W3C trace id: 32 hex chars -> 16 bytes (left-pad with zeros if shorter)."""
if not trace_id:
return b"\x00" * 16
s = trace_id.strip().lower()
if any(c not in "0123456789abcdef" for c in s):
return b"\x00" * 16
try:
raw = bytes.fromhex(s)
except ValueError:
return b"\x00" * 16
if len(raw) > 16:
return raw[-16:]
if len(raw) < 16:
return b"\x00" * (16 - len(raw)) + raw
return raw
def pack_sbridge_br(
depth: int,
checkpoint_span_8: bytes,
ordinal_groups: Dict[int, List[int]],
end_events: List[int],
dee_bytes: bytes,
) -> bytes:
"""
S-Bridge packed __bag._br:
varint(depth)
8 bytes checkpoint span id (raw)
varint(num_depth_groups)
repeated: varint(depth) varint(n_seqs) n_seqs * varint(seq)
varint(n_end_events)
n_end_events * varint(start_seq) # start ordinal of each ended span; end order is list order
dee_bytes (concatenated triples: 16-byte trace_id | varint(depth) | varint(n_seqs) | n_seqs * varint)
"""
if len(checkpoint_span_8) != 8:
checkpoint_span_8 = (checkpoint_span_8 + b"\x00" * 8)[:8]
out = bytearray()
out.extend(_varint_encode(max(0, depth)))
out.extend(checkpoint_span_8)
depths_sorted = sorted(ordinal_groups.keys())
out.extend(_varint_encode(len(depths_sorted)))
for d in depths_sorted:
seqs = ordinal_groups[d]
out.extend(_varint_encode(d))
out.extend(_varint_encode(len(seqs)))
for s in seqs:
out.extend(_varint_encode(s))
out.extend(_varint_encode(len(end_events)))
for start_seq in end_events:
out.extend(_varint_encode(start_seq))
out.extend(dee_bytes)
return bytes(out)
def unpack_sbridge_br(data: bytes) -> Optional[dict]:
"""Unpack S-Bridge _br; returns dict or None."""
if not data:
return None
try:
depth, i = _varint_decode(data, 0)
if i + 8 > len(data):
return None
ckpt = data[i : i + 8]
i += 8
num_groups, i = _varint_decode(data, i)
ordinal_groups: Dict[int, List[int]] = {}
for _ in range(num_groups):
d, i = _varint_decode(data, i)
n_seqs, i = _varint_decode(data, i)
seqs: List[int] = []
for _j in range(n_seqs):
s, i = _varint_decode(data, i)
seqs.append(s)
ordinal_groups[d] = seqs
n_end, i = _varint_decode(data, i)
end_events: List[int] = []
for _ in range(n_end):
start_seq, i = _varint_decode(data, i)
end_events.append(start_seq)
dee_bytes = data[i:]
return {
"depth": depth,
"checkpoint_span_8": ckpt,
"ordinal_groups": ordinal_groups,
"end_events": end_events,
"dee_bytes": dee_bytes,
}
except (IndexError, TypeError):
return None
def _encode_dee_triple(trace_id: str, depth: int, seqs: List[int]) -> bytes:
"""
One DEE triple: 16-byte trace id | varint(depth) | varint(n) | n * varint(start_seq).
Same semantics as inline end_events in pack_sbridge_br: only start ordinals of ended
spans, in end order; no explicit end ordinals.
"""
out = bytearray()
out.extend(_trace_id_hex_to_16bytes(trace_id))
out.extend(_varint_encode(max(0, depth)))
out.extend(_varint_encode(len(seqs)))
for s in seqs:
out.extend(_varint_encode(s))
return bytes(out)
# -----------------------------------------------------------------------------
# Path bridge handler (Bloom-only propagation; packed _br baggage)
# -----------------------------------------------------------------------------
class PathBridgeHandler(BridgeHandler):
"""
Path bridge: single packed baggage field __bag._br = varint(depth_mod) || bloom_bytes.
- OnStart: read parent _br, unpack to get depth_mod and bloom; compute next depth_mod;
set __bag._br only; set ancestry/ancestry_mode and _d for export/display.
- OnEnd: unpack _br to get depth_mod (or use leaf); strip ancestry when not checkpoint.
"""
def __init__(self, checkpoint_distance: int = 1, bloom_fp_rate: float = 0.0001):
if BloomFilter is None or estimate_parameters is None:
raise RuntimeError("Path bridge requires bloom module (bloom.py)")
self._cpd = max(1, checkpoint_distance)
self._bloom_p = bloom_fp_rate
n = max(1, self._cpd)
self._bloom_m, self._bloom_k = estimate_parameters(n, self._bloom_p)
self._bloom_len = (self._bloom_m + 7) // 8
self._span_info: dict = {} # (trace_id, span_id) -> {"_br": packed_bytes}
self._has_children: set = set()
def _empty_bloom(self):
return BloomFilter(self._bloom_m, self._bloom_k)
def on_start(self, parent_ctx: ParentContext, span: dict) -> bool:
trace_id = span.get("traceID") or span.get("traceId") or ""
span_id = span.get("spanID") or span.get("spanId") or ""
parent_id = parent_ctx.parent_span_id
if parent_id is not None:
self._has_children.add((trace_id, parent_id))
parent_info = self._span_info.get((trace_id, parent_id)) if parent_id else None
baggage_found = parent_info is not None
if parent_info is not None:
packed = parent_info.get("_br")
if packed is None:
depth_mod = 0
bf = self._empty_bloom()
else:
if isinstance(packed, str):
packed = bytes.fromhex(packed)
unpacked = unpack_br(packed, self._bloom_len)
if unpacked is None:
depth_mod = 0
bf = self._empty_bloom()
else:
parent_depth_mod, parent_bloom_bytes = unpacked
depth_mod = (parent_depth_mod + 1) % self._cpd
bf = BloomFilter.deserialize(parent_bloom_bytes, self._bloom_m, self._bloom_k)
else:
depth_mod = 0
bf = self._empty_bloom()
bf.add(span_id.encode("utf-8"))
bf_bytes = bf.to_bytes()
is_checkpoint = (depth_mod == 0)
if is_checkpoint:
# Figure 10: emitted payload bytes at checkpoint spans (depth-based).
# Emit data before the reset (bf_bytes currently includes "history up to now" + this span id).
pre_reset_bf_bytes = bf_bytes
emitted_bytes = (
BR_PROPERTY_NAME_OVERHEAD_BYTES
+ PB_BRIDGE_TYPE_ID
+ len(_varint_encode(depth_mod))
+ len(pre_reset_bf_bytes)
)
span_set_tag(span, EMIT_PAYLOAD_BYTES_TAG, emitted_bytes)
bf = self._empty_bloom()
bf.add(span_id.encode("utf-8"))
bf_bytes = bf.to_bytes()
packed = pack_br(depth_mod, bf_bytes)
span_set_tag(span, BAG_BR, packed)
span_set_tag(span, AncestryModeKey, ANCESTRY_MODE_PB)
span_set_tag(span, AncestryKey, bf.serialize())
span_set_tag(span, "_d", depth_mod)
self._span_info[(trace_id, span_id)] = {"_br": packed}
return baggage_found
def on_end(self, span: dict) -> None:
trace_id = span.get("traceID") or span.get("traceId") or ""
span_id = span.get("spanID") or span.get("spanId") or ""
raw = span_get_tag(span, BAG_BR)
is_leaf = (trace_id, span_id) not in self._has_children
# Decode depth_mod + bloom_bytes from _br (for leaf-based emission) when possible.
if raw is None:
depth_mod = 0
bloom_bytes = b""
else:
if isinstance(raw, str):
raw = bytes.fromhex(raw)
unpacked = unpack_br(raw, self._bloom_len)
if unpacked is None:
depth_mod = 0
bloom_bytes = b""
else:
depth_mod, bloom_bytes = unpacked
is_checkpoint = (depth_mod == 0) or is_leaf
# Leaf-based checkpoint emission (only if we didn't already emit at depth-based checkpoint).
if is_leaf and span_get_tag(span, EMIT_PAYLOAD_BYTES_TAG) is None:
emitted_bytes = (
BR_PROPERTY_NAME_OVERHEAD_BYTES
+ PB_BRIDGE_TYPE_ID
+ len(_varint_encode(depth_mod))
+ len(bloom_bytes)
)
span_set_tag(span, EMIT_PAYLOAD_BYTES_TAG, emitted_bytes)
if not is_checkpoint:
span_remove_tag(span, AncestryKey)
span_remove_tag(span, AncestryModeKey)
# -----------------------------------------------------------------------------
# CGPB bridge handler (Bloom + call-graph hash array; packed _br baggage)
# -----------------------------------------------------------------------------
# Payload-emission metric needs to count the bytes of the checkpoint payload we "emit".
# For CGPB that includes bloom bytes plus the packed hash-array bytes.
CGP_BRIDGE_TYPE_ID = 2 # call-graph preserving bridge type id
def _ha_append_entry(ha: bytes, parent_span_id: str, depth_mod: int) -> Optional[bytes]:
"""
Append one CGPB hash-array entry:
entry := parent_span_id_bytes(8) || varint(depth_mod)
"""
pid_bytes = _span_id_hex_to_8bytes(parent_span_id)
if pid_bytes is None:
return None
return ha + pid_bytes + _varint_encode(depth_mod)
class CGPBBridgeHandler(BridgeHandler):
"""
CGPB: uses a packed baggage field __bag._br containing:
varint(depth_mod) || bloom_bytes || hash_array_bytes
- Bloom propagation matches PB: bloom accumulates span IDs, and resets on depth_mod==0.
- Hash-array propagation: on the 2nd started sibling of a given parent (seq_num == 2),
append (parent_span_id_bytes, varint(depth_mod)) to the hash-array bytes.
"""
def __init__(self, checkpoint_distance: int = 1, bloom_fp_rate: float = 0.0001):
if BloomFilter is None or estimate_parameters is None:
raise RuntimeError("CGPB bridge requires bloom module (bloom.py)")
self._cpd = max(1, checkpoint_distance)
self._bloom_p = bloom_fp_rate
n = max(1, self._cpd)
self._bloom_m, self._bloom_k = estimate_parameters(n, self._bloom_p)
self._bloom_len = (self._bloom_m + 7) // 8
self._span_info: dict = {} # (trace_id, span_id) -> {"_br": packed_bytes}
self._has_children: set = set()
def _empty_bloom(self) -> BloomFilter:
return BloomFilter(self._bloom_m, self._bloom_k)
def on_start(self, parent_ctx: ParentContext, span: dict) -> bool:
trace_id = span.get("traceID") or span.get("traceId") or ""
span_id = span.get("spanID") or span.get("spanId") or ""
parent_id = parent_ctx.parent_span_id
if parent_id is not None:
self._has_children.add((trace_id, parent_id))
parent_info = self._span_info.get((trace_id, parent_id)) if parent_id else None
baggage_found = parent_info is not None
# Unpack parent bridge state (if present)
if parent_info is not None:
packed = parent_info.get("_br")
if packed is None:
parent_depth_mod, parent_bf_bytes, parent_ha_bytes = 0, b"", b""
else:
if isinstance(packed, str):
packed = bytes.fromhex(packed)
unpacked = unpack_cgpb_br(packed, self._bloom_len)
if unpacked is None:
parent_depth_mod, parent_bf_bytes, parent_ha_bytes = 0, b"", b""
else:
parent_depth_mod, parent_bf_bytes, parent_ha_bytes = unpacked
else:
parent_depth_mod, parent_bf_bytes, parent_ha_bytes = 0, b"", b""
depth_mod = (parent_depth_mod + 1) % self._cpd
# Bloom state: deserialize parent bloom, add current span, then possibly reset at checkpoint.
if parent_info is not None and parent_bf_bytes:
bf = BloomFilter.deserialize(parent_bf_bytes, self._bloom_m, self._bloom_k)
else:
bf = self._empty_bloom()
span_id_bytes = span_id.encode("utf-8")
# Note: bloom hash inputs must match the rest of the simulator's assumptions.
# Current PB uses span_id.encode("utf-8") (ASCII hex) as the bloom insertion input.
bf.add(span_id_bytes)
# Hash-array propagation: only the 2nd sibling append happens here (seq_num comes from processed order).
ha_bytes = parent_ha_bytes
if parent_id is not None and parent_ctx.seq_num == 2:
updated = _ha_append_entry(ha_bytes, parent_id, depth_mod)
if updated is not None:
ha_bytes = updated
is_checkpoint = (depth_mod == 0)
if is_checkpoint:
# Pre-reset bloom bytes are what the checkpoint payload measures.
pre_reset_bf_bytes = bf.to_bytes()
emitted_bytes = (
BR_PROPERTY_NAME_OVERHEAD_BYTES
+ CGP_BRIDGE_TYPE_ID
+ len(_varint_encode(depth_mod))
+ len(pre_reset_bf_bytes)
+ len(ha_bytes)
)
span_set_tag(span, EMIT_PAYLOAD_BYTES_TAG, emitted_bytes)
# Reset bloom state (hash array is not cleared here; it is carried forward).
bf = self._empty_bloom()
bf.add(span_id_bytes)
bf_bytes = bf.to_bytes()
packed = pack_cgpb_br(depth_mod, bf_bytes, ha_bytes)
span_set_tag(span, BAG_BR, packed)
span_set_tag(span, AncestryModeKey, "cgpb")
span_set_tag(span, AncestryKey, bf.serialize())
span_set_tag(span, "_d", depth_mod)
self._span_info[(trace_id, span_id)] = {"_br": packed}
return baggage_found
def on_end(self, span: dict) -> None:
trace_id = span.get("traceID") or span.get("traceId") or ""
span_id = span.get("spanID") or span.get("spanId") or ""
raw = span_get_tag(span, BAG_BR)
is_leaf = (trace_id, span_id) not in self._has_children
if raw is None:
depth_mod = 0
bloom_bytes = b""
ha_bytes = b""
else:
if isinstance(raw, str):
raw = bytes.fromhex(raw)
unpacked = unpack_cgpb_br(raw, self._bloom_len)
if unpacked is None:
depth_mod, bloom_bytes, ha_bytes = 0, b"", b""
else:
depth_mod, bloom_bytes, ha_bytes = unpacked
is_checkpoint = (depth_mod == 0) or is_leaf
# Leaf-based checkpoint emission (only if we didn't already emit at depth-based checkpoint).
if is_leaf and span_get_tag(span, EMIT_PAYLOAD_BYTES_TAG) is None:
emitted_bytes = (
BR_PROPERTY_NAME_OVERHEAD_BYTES
+ CGP_BRIDGE_TYPE_ID
+ len(_varint_encode(depth_mod))
+ len(bloom_bytes)
+ len(ha_bytes)
)
span_set_tag(span, EMIT_PAYLOAD_BYTES_TAG, emitted_bytes)
if not is_checkpoint:
span_remove_tag(span, AncestryKey)
span_remove_tag(span, AncestryModeKey)
# -----------------------------------------------------------------------------
# S-Bridge (structural): ordinal + end-event pairs + delayed end events; packed _br
# -----------------------------------------------------------------------------
class DeeSizeLogger:
"""
stderr logging for S-bridge delayed end-event (DEE) byte sizes.
- pickup: a span start drains the per-service DEE queue and incoming bytes exceed threshold.
- queue_over_threshold: after an enqueue, the per-service DEE queue total exceeds threshold.
"""
__slots__ = ("threshold_bytes",)
def __init__(self, threshold_bytes: int):
self.threshold_bytes = threshold_bytes
def log_pickup(
self,
*,
service: str,
incoming_bytes: int,
trace_id: str,
source_file: str,
) -> None:
if incoming_bytes > self.threshold_bytes:
print(
"dee_log: kind=pickup "
f"service={service!r} incoming_bytes={incoming_bytes} "
f"trace_id={trace_id} source_file={source_file or '?'}",
file=sys.stderr,
)
def log_enqueue_queue_over_threshold(
self,
*,
service: str,
new_queue_bytes: int,
trace_id: str,
source_file: str,
added_bytes: int,
) -> None:
if new_queue_bytes > self.threshold_bytes:
print(
"dee_log: kind=queue_over_threshold "
f"service={service!r} queue_total_bytes={new_queue_bytes} "
f"added_bytes={added_bytes} trace_id={trace_id} source_file={source_file or '?'}",
file=sys.stderr,
)
class SBridgeBridgeHandler(BridgeHandler):
"""
Structural bridge: monotonic depth; checkpoint when depth % cpd == 0 or leaf.
Packed __bag._br via pack_sbridge_br. Per-service (service name) delayed DEE queue.
Only the first child of a parent (seq_num == 1) receives full inline baggage: upstream
end events (ee_from_parent), deferred bytes from the parent, and DEE drained at this
start. Later siblings receive only local sibling end events (acc_ends) — which siblings
ended before this child started — but not upstream EE/DEE. This preserves the full
sibling endpoint interleaving at every fanout while avoiding redundant replication of
upstream lateral state across branches.
"""
def __init__(
self,
checkpoint_distance: int = 1,
dee_size_logger: Optional[DeeSizeLogger] = None,
):
self._cpd = max(1, checkpoint_distance)
self._dee_size_logger = dee_size_logger
self._span_info: dict = {} # (trace_id, span_id) -> {"_br": bytes}
self._has_children: set = set()
self._parent_event_count: Dict[Tuple[str, str], int] = {}
self._child_seq_start: Dict[Tuple[str, str], int] = {}
# Per parent: start ordinals of children that have ended (on_end order); no explicit end ordinals.
self._parent_ee_acc: Dict[Tuple[str, str], List[int]] = defaultdict(list)
# service_name -> deque of bytes (DEE triples; cross-request / cross-trace on same service)
self._dee_queue: Dict[str, deque] = defaultdict(deque)
def _bump_event(self, tid: str, parent_span_id: str) -> int:
k = (tid, parent_span_id)
self._parent_event_count[k] = self._parent_event_count.get(k, 0) + 1
return self._parent_event_count[k]
def _dee_queue_total_bytes(self, service: str) -> int:
q = self._dee_queue.get(service)
if not q:
return 0
return sum(len(b) for b in q)
def _drain_dee_for_service(
self,
service: str,
consuming_trace_id: str,
consuming_source_file: str,
) -> bytes:
q = self._dee_queue.get(service)
if not q:
return b""
parts = []
while q:
parts.append(q.popleft())
combined = b"".join(parts)
if self._dee_size_logger is not None:
self._dee_size_logger.log_pickup(
service=service,
incoming_bytes=len(combined),
trace_id=consuming_trace_id,
source_file=consuming_source_file,
)
return combined
def _enqueue_dee(
self,
service: str,
triple_bytes: bytes,
contributing_trace_id: str,
contributing_source_file: str,
) -> None:
prev = self._dee_queue_total_bytes(service)
self._dee_queue[service].append(triple_bytes)
new = prev + len(triple_bytes)
if self._dee_size_logger is not None:
self._dee_size_logger.log_enqueue_queue_over_threshold(
service=service,
new_queue_bytes=new,
trace_id=contributing_trace_id,
source_file=contributing_source_file,
added_bytes=len(triple_bytes),
)
def on_start(self, parent_ctx: ParentContext, span: dict) -> bool:
trace_id = span.get("traceID") or span.get("traceId") or ""
span_id = span.get("spanID") or span.get("spanId") or ""
parent_id = parent_ctx.parent_span_id
service = span.get("_service_name") or "missing_service"
src_file = span.get("_trace_source_file") or ""
if parent_id is not None:
self._has_children.add((trace_id, parent_id))
dee_incoming = self._drain_dee_for_service(service, trace_id, src_file)
parent_info = self._span_info.get((trace_id, parent_id)) if parent_id else None
baggage_found = parent_info is not None
if parent_id is None:
depth = 0
ckpt_8 = b"\x00" * 8
ordinal_groups: Dict[int, List[int]] = {}
ee_from_parent: List[int] = []
dee_from_parent = b""
end_events: List[int] = []
else:
packed_parent = parent_info.get("_br") if parent_info else None
if packed_parent is None:
parent_depth = 0
ckpt_8 = b"\x00" * 8
ordinal_groups = {}
ee_from_parent = []
dee_from_parent = b""
else:
if isinstance(packed_parent, str):
packed_parent = bytes.fromhex(packed_parent)
unpacked = unpack_sbridge_br(packed_parent)
if unpacked is None:
parent_depth = 0
ckpt_8 = b"\x00" * 8
ordinal_groups = {}
ee_from_parent = []
dee_from_parent = b""
else:
parent_depth = unpacked["depth"]
ckpt_8 = unpacked["checkpoint_span_8"]
ordinal_groups = {d: list(v) for d, v in unpacked["ordinal_groups"].items()}
ee_from_parent = list(unpacked["end_events"])
dee_from_parent = unpacked["dee_bytes"]
depth = parent_depth + 1
# merge ordinal: copy groups (all siblings inherit parent's ordinal chain)
ordinal_groups = {d: list(v) for d, v in ordinal_groups.items()}
seq_start = self._bump_event(trace_id, parent_id)
self._child_seq_start[(trace_id, span_id)] = seq_start
ordinal_groups.setdefault(depth, []).append(seq_start)
acc_ends = list(self._parent_ee_acc[(trace_id, parent_id)])
if parent_ctx.seq_num == 1:
end_events = ee_from_parent + acc_ends
else:
end_events = list(acc_ends)
self._parent_ee_acc[(trace_id, parent_id)].clear()
dee_bytes = dee_from_parent + dee_incoming
if parent_id is not None and parent_ctx.seq_num != 1:
dee_bytes = b""
is_checkpoint = (depth % self._cpd == 0)
if is_checkpoint:
pre_payload = pack_sbridge_br(depth, ckpt_8, ordinal_groups, end_events, dee_bytes)
emitted_bytes = (
BR_PROPERTY_NAME_OVERHEAD_BYTES
+ SB_BRIDGE_TYPE_ID
+ len(pre_payload)
)
span_set_tag(span, EMIT_PAYLOAD_BYTES_TAG, emitted_bytes)
ckpt_8 = _span_id_hex_to_8bytes(span_id) or b"\x00" * 8
ordinal_groups = {}
end_events = []
dee_bytes = b""
self._parent_event_count[(trace_id, span_id)] = 0
self._parent_ee_acc[(trace_id, span_id)] = []
packed = pack_sbridge_br(depth, ckpt_8, ordinal_groups, end_events, dee_bytes)
span_set_tag(span, BAG_BR, packed)
span_set_tag(span, AncestryModeKey, ANCESTRY_MODE_SBRIDGE)
span_set_tag(span, AncestryKey, packed.hex())
span_set_tag(span, "_d", depth)
self._span_info[(trace_id, span_id)] = {"_br": packed}
return baggage_found
def on_end(self, span: dict) -> None:
trace_id = span.get("traceID") or span.get("traceId") or ""
span_id = span.get("spanID") or span.get("spanId") or ""
parent_id = span.get("parent_span_id")
service = span.get("_service_name") or "missing_service"
src_file = span.get("_trace_source_file") or ""
raw = span_get_tag(span, BAG_BR)
is_leaf = (trace_id, span_id) not in self._has_children
if raw is None:
depth = 0
ckpt_8 = b"\x00" * 8
ordinal_groups: Dict[int, List[int]] = {}
end_events: List[int] = []
dee_bytes = b""
else:
if isinstance(raw, str):
raw = bytes.fromhex(raw)
unpacked = unpack_sbridge_br(raw)
if unpacked is None:
depth = 0
ckpt_8 = b"\x00" * 8
ordinal_groups = {}
end_events = []
dee_bytes = b""
else:
depth = unpacked["depth"]
ckpt_8 = unpacked["checkpoint_span_8"]
ordinal_groups = unpacked["ordinal_groups"]
end_events = list(unpacked["end_events"])
dee_bytes = unpacked["dee_bytes"]
if parent_id is not None:
seq_start = self._child_seq_start.pop((trace_id, span_id), None)
if seq_start is not None:
self._parent_ee_acc[(trace_id, parent_id)].append(seq_start)
# Start ordinals still in the accumulator were never handed to a later child start → delayed.
rem = list(self._parent_ee_acc[(trace_id, span_id)])
if rem:
# Last end is implied at reconstruction; omit it from the triple. If only one
# remained, nothing is queued.
rem = rem[:-1]
if rem:
triple = _encode_dee_triple(trace_id, depth, rem)