tracebook-sim 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. tracebook/__init__.py +38 -0
  2. tracebook/_version.py +3 -0
  3. tracebook/benchmarks/__init__.py +1 -0
  4. tracebook/benchmarks/runner.py +234 -0
  5. tracebook/core/__init__.py +0 -0
  6. tracebook/core/matching_engine.py +497 -0
  7. tracebook/core/order.py +436 -0
  8. tracebook/core/orderbook.py +1038 -0
  9. tracebook/core/price_level.py +309 -0
  10. tracebook/core/replay.py +173 -0
  11. tracebook/events/__init__.py +21 -0
  12. tracebook/events/cli.py +83 -0
  13. tracebook/events/market_replay.py +587 -0
  14. tracebook/profiling/__init__.py +0 -0
  15. tracebook/profiling/magic_trace_wrapper.py +595 -0
  16. tracebook/profiling/performance_monitor.py +615 -0
  17. tracebook/profiling/trace_analyzer.py +534 -0
  18. tracebook/profiling/trace_visualizer.py +475 -0
  19. tracebook/py.typed +1 -0
  20. tracebook/simulation/__init__.py +0 -0
  21. tracebook/simulation/order_generator.py +960 -0
  22. tracebook/simulation/simulation_engine.py +701 -0
  23. tracebook/utils/__init__.py +0 -0
  24. tracebook/visualization/__init__.py +0 -0
  25. tracebook/visualization/dashboard.py +698 -0
  26. tracebook/visualization/web/__init__.py +1 -0
  27. tracebook/visualization/web/app.js +146 -0
  28. tracebook/visualization/web/index.html +66 -0
  29. tracebook/visualization/web/styles.css +312 -0
  30. tracebook/visualization/web_server.py +258 -0
  31. tracebook_sim-0.2.0.dist-info/METADATA +627 -0
  32. tracebook_sim-0.2.0.dist-info/RECORD +36 -0
  33. tracebook_sim-0.2.0.dist-info/WHEEL +5 -0
  34. tracebook_sim-0.2.0.dist-info/entry_points.txt +6 -0
  35. tracebook_sim-0.2.0.dist-info/licenses/LICENSE +21 -0
  36. tracebook_sim-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,595 @@
1
+ """
2
+ Magic-trace integration wrapper for Jane Street's profiling tool.
3
+
4
+ This module provides a high-level interface for integrating magic-trace
5
+ profiling into the order book simulator with minimal performance overhead.
6
+ """
7
+
8
+ import os
9
+ import re
10
+ import shutil
11
+
12
+ # subprocess is limited to the optional magic-trace profiler path.
13
+ import subprocess # nosec B404
14
+ import time
15
+ import json
16
+ import threading
17
+ import signal
18
+ import numpy as np
19
+ from typing import Any, Callable, Dict, List, Optional
20
+ from contextlib import contextmanager
21
+ from pathlib import Path
22
+
23
+
24
+ def _safe_artifact_stem(value: str) -> str:
25
+ """Return a path-safe artifact stem for trace session files."""
26
+ candidate = Path(str(value or "trace_session")).name
27
+ candidate = re.sub(r"[^A-Za-z0-9._-]+", "_", candidate).strip("._")
28
+ return candidate or "trace_session"
29
+
30
+
31
+ class NumpyJSONEncoder(json.JSONEncoder):
32
+ """Custom JSON encoder to handle numpy types."""
33
+
34
+ def default(self, obj):
35
+ if isinstance(obj, np.integer):
36
+ return int(obj)
37
+ elif isinstance(obj, np.floating):
38
+ return float(obj)
39
+ elif isinstance(obj, np.ndarray):
40
+ return obj.tolist()
41
+ return super().default(obj)
42
+
43
+
44
+ class MagicTraceConfig:
45
+ """Configuration for magic-trace profiling."""
46
+
47
+ def __init__(self):
48
+ # Default configuration
49
+ self.output_dir = "traces"
50
+ self.trace_format = "fxt" # Jane Street's trace format
51
+ self.buffer_size_mb = 64
52
+ self.sample_rate_hz = 1000
53
+ self.enable_kernel_events = False
54
+ self.enable_user_events = True
55
+ self.max_trace_duration_seconds = 60
56
+ self.auto_analyze = True
57
+
58
+ # Function-level profiling
59
+ self.profile_functions = [
60
+ "add_order",
61
+ "_execute_fifo_match",
62
+ "_execute_pro_rata_matches_at_level",
63
+ "_execute_matches_at_level",
64
+ "_match_buy_order",
65
+ "_match_sell_order",
66
+ ]
67
+
68
+ # Performance thresholds for alerts
69
+ self.latency_threshold_ns = 1_000_000 # 1ms
70
+ self.throughput_threshold_ops_per_sec = 1000
71
+
72
+ def to_dict(self) -> Dict[str, Any]:
73
+ """Convert config to dictionary."""
74
+ return {
75
+ "output_dir": self.output_dir,
76
+ "trace_format": self.trace_format,
77
+ "buffer_size_mb": self.buffer_size_mb,
78
+ "sample_rate_hz": self.sample_rate_hz,
79
+ "enable_kernel_events": self.enable_kernel_events,
80
+ "enable_user_events": self.enable_user_events,
81
+ "max_trace_duration_seconds": self.max_trace_duration_seconds,
82
+ "auto_analyze": self.auto_analyze,
83
+ "profile_functions": self.profile_functions,
84
+ "latency_threshold_ns": self.latency_threshold_ns,
85
+ "throughput_threshold_ops_per_sec": self.throughput_threshold_ops_per_sec,
86
+ }
87
+
88
+
89
+ class MagicTraceSession:
90
+ """
91
+ A magic-trace profiling session.
92
+
93
+ Manages the lifecycle of a profiling session including
94
+ starting/stopping traces, collecting data, and analysis.
95
+ """
96
+
97
+ def __init__(self, config: MagicTraceConfig, session_name: Optional[str] = None):
98
+ self.config = config
99
+ self.session_name = _safe_artifact_stem(
100
+ session_name or f"orderbook_trace_{int(time.time())}"
101
+ )
102
+ self.session_id: Optional[int] = None
103
+ self.start_time: Optional[int] = None
104
+ self.end_time: Optional[int] = None
105
+ self.trace_file: Optional[Path] = None
106
+ self.is_active = False
107
+ self.process: Optional[subprocess.Popen] = None
108
+ self.magic_trace_executable: Optional[str] = None
109
+ self.used_fallback = False
110
+
111
+ # Create output directory
112
+ self.output_path = Path(config.output_dir)
113
+ self.output_path.mkdir(parents=True, exist_ok=True)
114
+
115
+ # Session-specific files
116
+ self.trace_file = self.output_path / f"{self.session_name}.{config.trace_format}"
117
+ self.metadata_file = self.output_path / f"{self.session_name}_metadata.json"
118
+ self.analysis_file = self.output_path / f"{self.session_name}_analysis.json"
119
+
120
+ def start(self) -> bool:
121
+ """Start the magic-trace profiling session."""
122
+ if self.is_active:
123
+ return False
124
+
125
+ try:
126
+ # Check if magic-trace is available
127
+ if not self._check_magic_trace_available():
128
+ print("Warning: magic-trace not found. Using fallback profiling.")
129
+ return self._start_fallback_profiling()
130
+
131
+ # Build magic-trace command
132
+ cmd = self._build_magic_trace_command()
133
+
134
+ # Start magic-trace process
135
+ # The command uses a resolved profiler path and never invokes a shell.
136
+ self.process = subprocess.Popen( # nosec B603
137
+ cmd,
138
+ stdout=subprocess.DEVNULL,
139
+ stderr=subprocess.DEVNULL,
140
+ start_new_session=True,
141
+ )
142
+
143
+ self.start_time = time.time_ns()
144
+ self.is_active = True
145
+ self.session_id = self.process.pid
146
+
147
+ # Save session metadata
148
+ self._save_metadata()
149
+
150
+ print(f"Magic-trace session started: {self.session_name} (PID: {self.session_id})")
151
+ return True
152
+
153
+ except Exception as e:
154
+ print(f"Failed to start magic-trace session: {e}")
155
+ return self._start_fallback_profiling()
156
+
157
+ def stop(self) -> bool:
158
+ """Stop the magic-trace profiling session."""
159
+ if not self.is_active:
160
+ return False
161
+
162
+ try:
163
+ self.end_time = time.time_ns()
164
+
165
+ if self.process is not None:
166
+ # magic-trace is launched with a duration cap, so it may have
167
+ # already self-exited. poll() both checks that and reaps it; only
168
+ # signal a still-running child, and tolerate it vanishing under us.
169
+ if self.process.poll() is None:
170
+ try:
171
+ os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
172
+ self.process.wait(timeout=10)
173
+ except subprocess.TimeoutExpired:
174
+ try:
175
+ os.killpg(os.getpgid(self.process.pid), signal.SIGKILL)
176
+ except ProcessLookupError:
177
+ pass
178
+ self.process.wait()
179
+ except ProcessLookupError:
180
+ # Process (or its group) exited between poll and signal.
181
+ self.process.wait()
182
+
183
+ # Handle fallback tracer
184
+ if hasattr(self, "fallback_tracer") and self.fallback_tracer:
185
+ analysis = self.fallback_tracer.stop_session(self.session_name)
186
+ if analysis:
187
+ # Save analysis to file
188
+ analysis_file = self.output_path / f"{self.session_name}_fallback_analysis.json"
189
+ with open(analysis_file, "w", encoding="utf-8") as f:
190
+ json.dump(
191
+ analysis,
192
+ f,
193
+ indent=2,
194
+ cls=NumpyJSONEncoder,
195
+ allow_nan=False,
196
+ )
197
+ print(f"Fallback trace analysis saved to: {analysis_file}")
198
+
199
+ # Update metadata
200
+ self._save_metadata()
201
+
202
+ # Auto-analyze if enabled
203
+ if self.config.auto_analyze and not self.used_fallback:
204
+ self._analyze_trace()
205
+
206
+ print(f"Magic-trace session stopped: {self.session_name}")
207
+ return True
208
+
209
+ except Exception as e:
210
+ print(f"Error stopping magic-trace session: {e}")
211
+ return False
212
+ finally:
213
+ # Always mark inactive so a failure here can't wedge the session
214
+ # (stop() would otherwise retry forever and never reap the child).
215
+ self.is_active = False
216
+
217
+ def get_session_info(self) -> Dict[str, Any]:
218
+ """Get information about the current session."""
219
+ duration_ns = 0
220
+ if self.start_time:
221
+ end_time = self.end_time or time.time_ns()
222
+ duration_ns = end_time - self.start_time
223
+
224
+ return {
225
+ "session_name": self.session_name,
226
+ "session_id": self.session_id,
227
+ "is_active": self.is_active,
228
+ "start_time": self.start_time,
229
+ "end_time": self.end_time,
230
+ "duration_ns": duration_ns,
231
+ "duration_seconds": duration_ns / 1_000_000_000,
232
+ "trace_file": str(self.trace_file) if self.trace_file else None,
233
+ "profiling_mode": "fallback" if self.used_fallback else "magic-trace",
234
+ "config": self.config.to_dict(),
235
+ }
236
+
237
+ def _check_magic_trace_available(self) -> bool:
238
+ """Check if magic-trace is available on the system."""
239
+ executable = shutil.which("magic-trace")
240
+ if executable is None:
241
+ return False
242
+
243
+ try:
244
+ # The executable path is resolved with shutil.which and no shell is used.
245
+ result = subprocess.run( # nosec B603
246
+ [executable, "--version"],
247
+ capture_output=True,
248
+ timeout=5,
249
+ )
250
+ if result.returncode == 0:
251
+ self.magic_trace_executable = executable
252
+ return True
253
+ return False
254
+ except (subprocess.TimeoutExpired, FileNotFoundError):
255
+ return False
256
+
257
+ def _build_magic_trace_command(self) -> List[str]:
258
+ """Build the magic-trace command line."""
259
+ executable = self.magic_trace_executable or shutil.which("magic-trace")
260
+ if executable is None:
261
+ raise FileNotFoundError("magic-trace executable not found")
262
+
263
+ cmd = [
264
+ executable,
265
+ "attach",
266
+ "-p",
267
+ str(os.getpid()), # Attach to current process
268
+ "-o",
269
+ str(self.trace_file),
270
+ ]
271
+
272
+ # Add buffer size
273
+ if self.config.buffer_size_mb:
274
+ cmd.extend(["-buffer-size", f"{self.config.buffer_size_mb}MB"])
275
+
276
+ # Add sampling rate
277
+ if self.config.sample_rate_hz:
278
+ cmd.extend(["-sample-rate", str(self.config.sample_rate_hz)])
279
+
280
+ # Add duration limit
281
+ if self.config.max_trace_duration_seconds:
282
+ cmd.extend(["-duration", f"{self.config.max_trace_duration_seconds}s"])
283
+
284
+ return cmd
285
+
286
+ def _start_fallback_profiling(self):
287
+ """Start fallback profiling when magic-trace is not available."""
288
+ print("Starting fallback profiling mode...")
289
+
290
+ # Import and start high-resolution tracer
291
+ try:
292
+ from .trace_analyzer import get_tracer
293
+
294
+ self.fallback_tracer = get_tracer()
295
+ success = self.fallback_tracer.start_session(
296
+ self.session_name, function_names=self.config.profile_functions
297
+ )
298
+
299
+ if success:
300
+ print(
301
+ f"High-resolution fallback profiling started for session: {self.session_name}"
302
+ )
303
+ self.is_active = True
304
+ self.used_fallback = True
305
+ self.start_time = time.time_ns()
306
+ return True
307
+ else:
308
+ print("Failed to start fallback profiling")
309
+ return False
310
+
311
+ except ImportError as e:
312
+ print(f"Failed to import trace analyzer: {e}")
313
+ return False
314
+
315
+ def _save_metadata(self):
316
+ """Save session metadata to file."""
317
+ metadata = self.get_session_info()
318
+ try:
319
+ with open(self.metadata_file, "w", encoding="utf-8") as f:
320
+ json.dump(metadata, f, indent=2, allow_nan=False)
321
+ except Exception as e:
322
+ print(f"Failed to save metadata: {e}")
323
+
324
+ def _analyze_trace(self):
325
+ """Analyze the collected trace data."""
326
+ if self.trace_file is None or not self.trace_file.exists():
327
+ print("No trace file found for analysis")
328
+ return
329
+
330
+ try:
331
+ # Basic trace analysis
332
+ analysis = {
333
+ "session_name": self.session_name,
334
+ "status": "raw_trace_collected",
335
+ "trace_file_size": self.trace_file.stat().st_size,
336
+ "analysis_timestamp": time.time_ns(),
337
+ "summary": (
338
+ "Raw magic-trace artifact collected. Open the .fxt file with "
339
+ "magic-trace-compatible tooling for timeline analysis."
340
+ ),
341
+ "trace_file": str(self.trace_file),
342
+ "recommendations": [
343
+ "Inspect the raw trace in magic-trace before publishing profiler claims.",
344
+ "Pair trace findings with benchmark JSON from tracebook-benchmark.",
345
+ ],
346
+ }
347
+
348
+ # Save analysis results
349
+ with open(self.analysis_file, "w", encoding="utf-8") as f:
350
+ json.dump(analysis, f, indent=2, allow_nan=False)
351
+
352
+ print(f"Trace analysis saved to: {self.analysis_file}")
353
+
354
+ except Exception as e:
355
+ print(f"Failed to analyze trace: {e}")
356
+
357
+
358
+ class MagicTraceProfiler:
359
+ """
360
+ High-level interface for magic-trace profiling in the order book.
361
+
362
+ Provides context managers, decorators, and utilities for
363
+ seamless integration of profiling into the trading system.
364
+ """
365
+
366
+ def __init__(self, config: Optional[MagicTraceConfig] = None):
367
+ self.config = config or MagicTraceConfig()
368
+ self.active_sessions: Dict[str, "MagicTraceSession"] = {}
369
+ self.session_counter = 0
370
+ self._lock = threading.Lock()
371
+
372
+ # Performance metrics (mixed value types: counters and nested maps)
373
+ self.metrics: Dict[str, Any] = {
374
+ "total_sessions": 0,
375
+ "active_sessions": 0,
376
+ "total_trace_time_ns": 0,
377
+ "function_call_counts": {},
378
+ "function_latencies": {},
379
+ }
380
+
381
+ @contextmanager
382
+ def profile_session(self, session_name: Optional[str] = None):
383
+ """Context manager for profiling sessions."""
384
+ session = self.create_session(session_name)
385
+
386
+ try:
387
+ if session.start():
388
+ yield session
389
+ else:
390
+ print("Failed to start profiling session")
391
+ yield None
392
+ finally:
393
+ if session.is_active:
394
+ session.stop()
395
+ self._cleanup_session(session)
396
+
397
+ def create_session(self, session_name: Optional[str] = None) -> MagicTraceSession:
398
+ """Create a new profiling session."""
399
+ with self._lock:
400
+ if session_name is None:
401
+ self.session_counter += 1
402
+ session_name = f"session_{self.session_counter}"
403
+ session_name = _safe_artifact_stem(session_name)
404
+
405
+ session = MagicTraceSession(self.config, session_name)
406
+ self.active_sessions[session_name] = session
407
+ self.metrics["total_sessions"] += 1
408
+ self.metrics["active_sessions"] += 1
409
+
410
+ return session
411
+
412
+ def get_active_sessions(self) -> List[str]:
413
+ """Get list of active session names."""
414
+ with self._lock:
415
+ return [name for name, session in self.active_sessions.items() if session.is_active]
416
+
417
+ def stop_all_sessions(self):
418
+ """Stop all active profiling sessions."""
419
+ with self._lock:
420
+ for session in self.active_sessions.values():
421
+ if session.is_active:
422
+ session.stop()
423
+
424
+ def profile_function(self, func_name: Optional[str] = None):
425
+ """Decorator for profiling individual functions."""
426
+
427
+ def decorator(func: Callable):
428
+ name = func_name or func.__name__
429
+
430
+ def wrapper(*args, **kwargs):
431
+ start_time = time.time_ns()
432
+
433
+ try:
434
+ result = func(*args, **kwargs)
435
+ return result
436
+ finally:
437
+ end_time = time.time_ns()
438
+ latency = end_time - start_time
439
+
440
+ # Update metrics
441
+ with self._lock:
442
+ if name not in self.metrics["function_call_counts"]:
443
+ self.metrics["function_call_counts"][name] = 0
444
+ self.metrics["function_latencies"][name] = []
445
+
446
+ self.metrics["function_call_counts"][name] += 1
447
+ self.metrics["function_latencies"][name].append(latency)
448
+
449
+ # Keep only recent latencies to avoid memory growth
450
+ if len(self.metrics["function_latencies"][name]) > 1000:
451
+ self.metrics["function_latencies"][name] = self.metrics[
452
+ "function_latencies"
453
+ ][name][-1000:]
454
+
455
+ # Check for performance alerts
456
+ if latency > self.config.latency_threshold_ns:
457
+ self._trigger_latency_alert(name, latency)
458
+
459
+ return wrapper
460
+
461
+ return decorator
462
+
463
+ def get_performance_summary(self) -> Dict[str, Any]:
464
+ """Get comprehensive performance summary."""
465
+ with self._lock:
466
+ summary: Dict[str, Any] = {
467
+ "session_metrics": dict(self.metrics),
468
+ "function_performance": {},
469
+ "alerts": [],
470
+ "recommendations": [],
471
+ }
472
+
473
+ # Calculate function performance statistics
474
+ for func_name, latencies in self.metrics["function_latencies"].items():
475
+ if latencies:
476
+ import numpy as np
477
+
478
+ latencies_array = np.array(latencies)
479
+
480
+ summary["function_performance"][func_name] = {
481
+ "call_count": self.metrics["function_call_counts"][func_name],
482
+ "mean_latency_ns": float(np.mean(latencies_array)),
483
+ "median_latency_ns": float(np.median(latencies_array)),
484
+ "p95_latency_ns": float(np.percentile(latencies_array, 95)),
485
+ "p99_latency_ns": float(np.percentile(latencies_array, 99)),
486
+ "max_latency_ns": float(np.max(latencies_array)),
487
+ "std_latency_ns": float(np.std(latencies_array)),
488
+ }
489
+
490
+ # Generate recommendations
491
+ summary["recommendations"] = self._generate_performance_recommendations(summary)
492
+
493
+ return summary
494
+
495
+ def export_traces(self, output_dir: str = "exported_traces") -> bool:
496
+ """Export all trace files for external analysis."""
497
+ try:
498
+ export_path = Path(output_dir)
499
+ export_path.mkdir(parents=True, exist_ok=True)
500
+
501
+ trace_dir = Path(self.config.output_dir)
502
+ if not trace_dir.exists():
503
+ return False
504
+
505
+ # Copy all trace files
506
+ import shutil
507
+
508
+ for trace_file in trace_dir.glob("*"):
509
+ if trace_file.is_file() and not trace_file.is_symlink():
510
+ shutil.copy2(trace_file, export_path / trace_file.name)
511
+
512
+ print(f"Traces exported to: {export_path}")
513
+ return True
514
+
515
+ except Exception as e:
516
+ print(f"Failed to export traces: {e}")
517
+ return False
518
+
519
+ def _cleanup_session(self, session: MagicTraceSession):
520
+ """Clean up a finished session."""
521
+ with self._lock:
522
+ if session.session_name in self.active_sessions:
523
+ del self.active_sessions[session.session_name]
524
+ self.metrics["active_sessions"] -= 1
525
+
526
+ # Update total trace time
527
+ if session.start_time and session.end_time:
528
+ duration = session.end_time - session.start_time
529
+ self.metrics["total_trace_time_ns"] += duration
530
+
531
+ def _trigger_latency_alert(self, func_name: str, latency_ns: int):
532
+ """Trigger alert for high latency function call."""
533
+ print(
534
+ f"LATENCY ALERT: {func_name} took {latency_ns/1_000_000:.2f}ms "
535
+ f"(threshold: {self.config.latency_threshold_ns/1_000_000:.2f}ms)"
536
+ )
537
+
538
+ def _generate_performance_recommendations(self, summary: Dict) -> List[str]:
539
+ """Generate performance optimization recommendations."""
540
+ recommendations = []
541
+
542
+ func_perf = summary.get("function_performance", {})
543
+
544
+ for func_name, stats in func_perf.items():
545
+ p99_latency = stats.get("p99_latency_ns", 0)
546
+ mean_latency = stats.get("mean_latency_ns", 0)
547
+
548
+ if p99_latency > 10_000_000: # > 10ms
549
+ recommendations.append(
550
+ f"Function '{func_name}' has high P99 latency "
551
+ f"({p99_latency/1_000_000:.1f}ms). "
552
+ "Consider optimization or async processing."
553
+ )
554
+
555
+ if mean_latency > 1_000_000: # > 1ms
556
+ recommendations.append(
557
+ f"Function '{func_name}' has high average latency "
558
+ f"({mean_latency/1_000_000:.1f}ms). "
559
+ "Review algorithm efficiency."
560
+ )
561
+
562
+ # Check for high variance
563
+ std_latency = stats.get("std_latency_ns", 0)
564
+ if std_latency > mean_latency:
565
+ recommendations.append(
566
+ f"Function '{func_name}' has inconsistent performance. "
567
+ "Investigate causes of latency spikes."
568
+ )
569
+
570
+ return recommendations
571
+
572
+
573
+ # Global profiler instance
574
+ _global_profiler = None
575
+
576
+
577
+ def get_profiler() -> MagicTraceProfiler:
578
+ """Get the global profiler instance."""
579
+ global _global_profiler
580
+ if _global_profiler is None:
581
+ _global_profiler = MagicTraceProfiler()
582
+ return _global_profiler
583
+
584
+
585
+ def profile_function(func_name: Optional[str] = None):
586
+ """Convenience decorator for function profiling."""
587
+ return get_profiler().profile_function(func_name)
588
+
589
+
590
+ @contextmanager
591
+ def profile_block(block_name: str = "code_block"):
592
+ """Context manager for profiling code blocks."""
593
+ profiler = get_profiler()
594
+ with profiler.profile_session(f"block_{block_name}") as session:
595
+ yield session