qpanda3_runtime.toolbox.tracker#

Tracker toolbox module for quantum program execution tracking and analysis.

This module provides a comprehensive tracking system for monitoring quantum program execution, including context management, data recording, and trace analysis.

Classes#

TrackerSystem : Global tracking process manager Tracker : User interface class for tracking operations TrackerRef : Tracking reference for decorator scenarios TrackerTrace : Memory/historical data object for tracking traces TraceAnalyzer : Trace data analyzer with rule-based analysis TrackingRule : Base class for tracking analysis rules TrackingRules : Manager for tracking rules TraceDebugger : Debugging tool for trace analysis

Functions#

tracker : Decorator for automatic function tracking

Notes

  • The tracker system supports both synchronous and asynchronous operations

  • Traces can be saved to files for later analysis

  • Multiple analysis rules can be registered for different use cases

Submodules#

Classes#

TrackerSystem

Global tracking process manager combining RuntimeService and GlobalTracker responsibilities.

Tracker

User interface for tracking operations with three usage patterns.

TrackerRef

Reference wrapper for tracker instances in decorator scenarios.

TrackerTrace

Memory/historical data object for tracking traces.

TraceAnalyzer

Trace data analyzer for rule-based analysis of tracking traces.

TrackingRule

Abstract base class for tracking analysis rules.

TrackingRules

Manager for tracking analysis rules.

DefaultTrackingRule

Default tracking rule - passes data through unchanged.

DefaultTrackingRule

Default tracking rule - passes data through unchanged.

QTaskFailureRule

Quantum task failure tracking rule - records task failure information.

TraceDebugger

Debugging tool for analyzing tracker records and reconstructing hierarchy trees.

Functions#

tracker(service[, ref, data])

Decorator for automatic function tracking.

Package Contents#

class qpanda3_runtime.toolbox.tracker.TrackerSystem(name: str = 'TrackerSystem', trace_record_file: str | None = None, load_history_records: bool = True, save_to_file: bool = True)#

Global tracking process manager combining RuntimeService and GlobalTracker responsibilities.

This class provides a unified interface for tracking quantum program execution, managing trace data, and handling tracking rules. It serves as the central coordinator between user-facing tracking operations and internal trace storage.

Variables:
  • save_to_file (bool) – Whether to save tracking records to file

  • name (str) – Name identifier for this tracker system

  • _trace (TrackerTrace) – Internal trace data storage and management

  • _rules (TrackingRules) – Manager for tracking analysis rules

Examples

>>> tracker = TrackerSystem("my_tracker", "trace.jsonl")
>>> tracker.enter("quantum_circuit", ["qiskit", "simulation"])
>>> tracker.record({"qubits": 5, "depth": 10})
>>> tracker.exit({"result": "success"})
>>> tracker.close()
save_to_file = True#
name = 'TrackerSystem'#
enter(context_name: str, tracking_labels: List[str] = [], context_data: Dict[str, Any] = None) → None#

Enter a new tracking context.

Parameters:
  • context_name (str) – Name of the context to enter

  • tracking_labels (List[str], optional) – Labels for categorizing the context

  • context_data (Dict[str, Any], optional) – Additional data associated with the context

Notes

  • Contexts can be nested to represent hierarchical operations

  • Each context must be matched with a corresponding exit() call

  • Labels can be used for filtering and analysis

exit(result_data: Dict[str, Any] = None, labels: List[str] = []) → None#

Exit the current tracking context.

Parameters:
  • result_data (Dict[str, Any], optional) – Result data to associate with the completed context

  • labels (List[str], optional) – Additional labels for the exit operation

Raises:

RuntimeError – If there is no active context to exit

Notes

  • Must be called to match each enter() call

  • Result data is recorded as part of the context completion

record(record: Dict[str, Any], labels: List[str] = []) → None#

Record data within the current tracking context.

Parameters:
  • record (Dict[str, Any]) – Data to record, typically key-value pairs

  • labels (List[str], optional) – Labels for categorizing the recorded data

Raises:

RuntimeError – If there is no active context for recording

Notes

  • Data is recorded under the current active context

  • Multiple records can be added within a single context

  • Labels help organize and filter recorded data

close() → None#

Close the tracker system and release resources.

Notes

  • Flushes any buffered data to file

  • Closes file handles and cleans up internal resources

  • Should be called when tracking is complete

exit_broken_context()#

Exit a broken context (e.g., due to exception).

Notes

  • Used when a context cannot be properly exited via normal flow

  • Marks the context as broken for later analysis

  • Helps maintain trace integrity during error conditions

class qpanda3_runtime.toolbox.tracker.Tracker(service: qpanda3_runtime.toolbox.tracker.tracker_system.TrackerSystem, name: str = None, data: Dict[str, Any] = None)#

User interface for tracking operations with three usage patterns.

This class provides a unified interface for tracking operations with support for manual tracking, context manager usage, and decorator-based tracking.

Variables:

is_active (bool) – Indicates whether the tracker is currently active.

Examples

>>> # Manual tracking
>>> tracker = Tracker(service)
>>> tracker.start("operation_name")
>>> tracker.record({"key": "value"})
>>> tracker.end()
>>> # Context manager usage
>>> with Tracker(service, name="operation") as t:
...     t.record({"data": 123})
>>> # Decorator usage
>>> @tracker(service)
... def my_function():
...     pass
start(context_name: str, labels: List[str] = None, data: Dict[str, Any] = None) → Tracker#

Start tracking an operation.

Parameters:
  • context_name (str) – Name of the operation or context being tracked.

  • labels (List[str], optional) – List of labels to categorize the tracking session.

  • data (Dict[str, Any], optional) – Initial data to record for this tracking session.

Returns:

Self reference for method chaining.

Return type:

Tracker

Raises:

RuntimeError – If the tracker is already active or service is not available.

end(result_data: Dict[str, Any] = None, labels: List[str] = None) → Tracker#

End the current tracking session.

Parameters:
  • result_data (Dict[str, Any], optional) – Result data to record at the end of the operation.

  • labels (List[str], optional) – Additional labels to apply to the end record.

Returns:

Self reference for method chaining.

Return type:

Tracker

Notes

If the tracker is not active, this method does nothing and returns the tracker instance unchanged.

record(data: Dict[str, Any], labels: List[str] = None) → Tracker#

Record data during an active tracking session.

Parameters:
  • data (Dict[str, Any]) – Data to record in the current tracking session.

  • labels (List[str], optional) – Labels to associate with this data record.

Returns:

Self reference for method chaining.

Return type:

Tracker

Raises:

RuntimeError – If the tracker is not active when attempting to record data.

exit_broken_context() → None#

Exit a broken context when used as a context manager.

This method is called internally when a context manager exits due to an exception. It ensures proper cleanup of tracking state.

property is_active: bool#

Check if the tracker is currently active.

Returns:

True if the tracker is actively tracking, False otherwise.

Return type:

bool

get_current_record() → qpanda3_runtime.toolbox.tracker.tracker_trace.TrackerTrace#

Get the current tracking record.

Returns:

The current trace record if tracking is active.

Return type:

TrackerTrace

Notes

Returns None if no tracking session is active or if the service does not have a current trace.

class qpanda3_runtime.toolbox.tracker.TrackerRef(name: str = '')#

Reference wrapper for tracker instances in decorator scenarios.

This class provides a way to reference a tracker instance from within a decorated function without direct access to the tracker object.

Variables:
  • name (str) – Reference name for identification.

  • is_active (bool) – Indicates whether the referenced tracker is currently active.

Examples

>>> ref = TrackerRef("my_tracker")
>>> @tracker(service, ref=ref)
... def my_function():
...     ref.record({"data": "value"})
name = ''#
tracker = None#
record(data: Dict[str, Any], labels: List[str] = None) → None#

Record data through the referenced tracker.

Parameters:
  • data (Dict[str, Any]) – Data to record in the current tracking session.

  • labels (List[str], optional) – Labels to associate with this data record.

Raises:

RuntimeError – If the tracker reference is not properly initialized or if no tracker is currently active.

property is_active: bool#

Check if the referenced tracker is active.

Returns:

True if the referenced tracker exists and is active.

Return type:

bool

qpanda3_runtime.toolbox.tracker.tracker(service: qpanda3_runtime.toolbox.tracker.tracker_system.TrackerSystem, ref: TrackerRef | None = None, data: Any = None)#

Decorator for automatic function tracking.

This decorator automatically tracks function execution including start time, end time, and any exceptions that occur.

Parameters:
  • service (TrackerSystem) – The tracking system service to use.

  • ref (TrackerRef, optional) – Tracker reference for accessing the tracker from within the decorated function.

  • data (Any, optional) – Additional data to associate with the tracking session.

Returns:

Decorator function that wraps the original function.

Return type:

function

Examples

>>> @tracker(service)
... def process_data(data):
...     return data * 2
>>> ref = TrackerRef()
>>> @tracker(service, ref=ref)
... def complex_operation():
...     ref.record({"step": "started"})
...     # operation logic
class qpanda3_runtime.toolbox.tracker.TrackerTrace(record_file_path: str, load_history_records: bool = True)#

Memory/historical data object for tracking traces.

Main class for managing tracking trace data in memory, supporting hierarchical context management, data recording, and file persistence.

Variables:
  • _trace_row_id_manager (TraceRowIdManager) – Manager for generating unique row IDs

  • _records (TraceTreeContextNode) – Root node of the trace tree

  • _context_stack (deque[TraceTreeContextNode]) – Stack for managing nested contexts

  • _record_file_path (str) – Path to trace record file for persistence

  • _recorder (TraceRecorder) – Recorder for writing trace data to file

  • _broken_contexts (List[TraceTreeContextNode]) – List of contexts that were exited abnormally

Examples

>>> trace = TrackerTrace("trace.jsonl")
>>> trace.begin_context("quantum_circuit", ["simulation"])
>>> trace.add_record({"qubits": 5})
>>> trace.end_context({"result": "success"})
get_current_context() → TraceTreeContextNode#

Get the current active context.

Returns:

Current context node from top of stack, or None if stack is empty

Return type:

TraceTreeContextNode

Notes

  • Returns the most recently entered context

  • Used for adding records to the correct context

  • Root context is always available as fallback

add_record(record: Dict[str, Any], save_to_file: bool = False, labels: List[str] = []) → None#

Add a data record to the current context.

Parameters:
  • record (Dict[str, Any]) – Data to record as key-value pairs

  • save_to_file (bool, optional) – Whether to save the record to file, default is False

  • labels (List[str], optional) – Categorization labels for the record

Raises:

RuntimeError – If there is no current context (should not happen with root)

Notes

  • Records are added to the current active context

  • File saving can be deferred for performance

  • Labels help with filtering and analysis

begin_context(context_name: str, context_labels: List[str] = [], context_data: Dict[str, Any] = None, save_to_file: bool = False) → None#

Begin a new nested context.

Parameters:
  • context_name (str) – Name identifier for the new context

  • context_labels (List[str], optional) – Categorization labels for the context

  • context_data (Dict[str, Any], optional) – Initial data associated with context start

  • save_to_file (bool, optional) – Whether to save context start to file, default is False

Notes

  • Creates a new context as child of current context

  • Pushes new context onto the context stack

  • Contexts can be nested arbitrarily deep

  • Each begin_context should have matching end_context

end_context(result_data: Dict[str, Any] = None, save_to_file: bool = False, labels: List[str] = []) → None#

End the current context.

Parameters:
  • result_data (Dict[str, Any], optional) – Result data to associate with context completion

  • save_to_file (bool, optional) – Whether to save context end to file, default is False

  • labels (List[str], optional) – Categorization labels for the end operation

Raises:

RuntimeError – If there is no context to end (stack underflow)

Notes

  • Pops current context from the context stack

  • Marks context as closed with result data

  • Must match a previous begin_context call

  • Uses immediate file writing for context completion

exit_broken_context()#

Exit a broken context (e.g., due to exception).

Notes

  • Moves current context to broken_contexts list

  • Removes context from active stack

  • Used for error handling when normal end_context cannot be called

  • Broken contexts can be analyzed separately

get_records() → List[Dict[str, Any]]#

Get all trace records.

Returns:

List of all trace records (currently returns root node)

Return type:

List[Dict[str, Any]]

Notes

  • Currently returns the root trace tree node

  • Future implementation may flatten the hierarchy

get_context_stack() → List[Any]#

Get current context stack.

Returns:

Copy of current context stack as list

Return type:

List[Any]

Notes

  • Returns a copy to prevent external modification

  • Stack order: most recent context first (index 0)

rebuild_context_stack()#

Rebuild context stack from trace tree structure.

Returns:

Rebuilt context stack

Return type:

deque[TraceTreeContextNode]

Notes

  • Clears existing stack and rebuilds from trace tree

  • Only includes open (unclosed) contexts

  • Recursively processes nested contexts

  • Useful after loading trace data from file

clear(clear_record_file: bool = True) → None#

Clear all trace data.

Parameters:

clear_record_file (bool, optional) – Whether to also clear the record file, default is True

Notes

  • Resets in-memory trace data structures

  • Optionally clears the persistent record file

  • Maintains the root context node structure

close() → None#

Close the trace and release resources.

Notes

  • Closes the file recorder

  • Flushes any buffered data to disk

  • Should be called when trace operations are complete

class qpanda3_runtime.toolbox.tracker.TraceAnalyzer#

Trace data analyzer for rule-based analysis of tracking traces.

This class provides analysis capabilities for tracking trace files using registered analysis rules. It supports automatic rule selection and manual rule specification.

Variables:
  • _rules (TrackingRules) – Manager for tracking analysis rules

  • _trace (TrackerTrace) – Currently loaded trace data for analysis

Examples

>>> analyzer = TraceAnalyzer()
>>> result = analyzer.analyze_file("trace.jsonl")
>>> available_rules = analyzer.get_available_rules()
analyze_file(file_path: str, rule_id: str = None) → Any#

Analyze historical trace file using specified or automatic rule.

Parameters:
  • file_path (str) – Path to the trace file to analyze

  • rule_id (str, optional) – ID of the rule to use for analysis. If None, automatic rule selection is performed based on default rule.

Returns:

Analysis result, format depends on the rule used

Return type:

Any

Raises:
  • FileNotFoundError – If the specified trace file does not exist

  • ValueError – If the specified rule_id is not registered

Notes

  • Trace files are loaded with history records enabled

  • Analysis results are printed to console for debugging

get_available_rules() → List[str]#

Get list of available analysis rule IDs.

Returns:

List of registered rule IDs

Return type:

List[str]

Examples

>>> analyzer = TraceAnalyzer()
>>> rules = analyzer.get_available_rules()
>>> print(rules)
['default', 'qtask_failure']
register_rule(rule: qpanda3_runtime.toolbox.tracker.tracking_rule.TrackingRule) → None#

Register a new analysis rule.

Parameters:

rule (TrackingRule) – Rule instance to register

Notes

  • Registered rules become available for analyze_file()

  • Rules must have unique rule_id values

class qpanda3_runtime.toolbox.tracker.TrackingRule#

Bases: abc.ABC

Abstract base class for tracking analysis rules.

This class defines the interface for tracking analysis rules that can process tracker traces and produce analysis results. Each rule must implement a unique identifier and an analysis method.

Subclasses should implement specific analysis logic for different types of tracking data or analysis requirements.

Examples

>>> class MyTrackingRule(TrackingRule):
...     @property
...     def rule_id(self) -> str:
...         return "my_rule"
...
...     def analyze(self, data: TrackerTrace) -> Any:
...         # Custom analysis logic
...         return {"result": "analysis_complete"}
property rule_id: str#
Abstractmethod:

Get the unique identifier for this rule.

Returns:

Unique rule identifier string.

Return type:

str

Notes

Rule IDs should be descriptive and unique within the system. They are used to register and retrieve rules from the rule manager.

abstractmethod analyze(data: qpanda3_runtime.toolbox.tracker.tracker_trace.TrackerTrace) → Any#

Analyze tracking data using this rule.

Parameters:

data (TrackerTrace) – Tracking trace data to analyze. Must be a valid TrackerTrace instance containing tracking session information.

Returns:

Analysis result. The type and structure of the result depends on the specific rule implementation.

Return type:

Any

Raises:
  • ValueError – If the input data is not a valid TrackerTrace instance.

  • RuntimeError – If analysis cannot be performed due to invalid data state.

class qpanda3_runtime.toolbox.tracker.TrackingRules(default_rule: TrackingRule)#

Manager for tracking analysis rules.

This class manages a collection of tracking rules, providing registration, retrieval, and rule selection functionality.

Variables:
  • available_rules (List[str]) – List of registered rule IDs.

  • default_rule (TrackingRule) – The default rule used when no specific rule is requested.

Examples

>>> default_rule = DefaultTrackingRule()
>>> rule_manager = TrackingRules(default_rule)
>>> rule_manager.register_rule(MyTrackingRule())
>>> rule = rule_manager.get_rule("my_rule")
>>> result = rule.analyze(trace_data)
register_rule(rule: TrackingRule) → None#

Register a new tracking rule.

Parameters:

rule (TrackingRule) – Rule instance to register.

Raises:

ValueError – If a rule with the same rule_id is already registered.

Notes

Registered rules can be retrieved later using their rule_id. If a rule with the same ID already exists, it will be replaced.

get_rule(rule_id: str) → TrackingRule#

Get a rule by its identifier.

Parameters:

rule_id (str) – Identifier of the rule to retrieve.

Returns:

The requested rule instance, or the default rule if the requested rule is not found.

Return type:

TrackingRule

Notes

This method provides a safe way to retrieve rules, falling back to the default rule when the requested rule is not available.

get_default_rule() → TrackingRule#

Get the default rule.

Returns:

The default rule instance.

Return type:

TrackingRule

get_available_rules() → List[str]#

Get list of available rule identifiers.

Returns:

List of registered rule IDs.

Return type:

List[str]

Notes

The list includes the default rule ID and all registered custom rule IDs.

decide_rule(data: Any) → TrackingRule#

Determine which rule to use for analyzing given data.

Parameters:

data (Any) – Data to be analyzed. The type and structure may influence rule selection.

Returns:

Rule instance selected for analyzing the data.

Return type:

TrackingRule

Notes

The default implementation always returns the default rule. Subclasses can override this method to implement custom rule selection logic based on data characteristics.

class qpanda3_runtime.toolbox.tracker.DefaultTrackingRule#

Bases: qpanda3_runtime.toolbox.tracker.tracking_rule.TrackingRule

Default tracking rule - passes data through unchanged.

This rule implements the simplest tracking behavior where data is returned unchanged without any processing or transformation.

Notes

Use this rule as a baseline or when no special processing is needed.

property rule_id: str#

Get the unique identifier for this tracking rule.

Returns:

Rule identifier string.

Return type:

str

analyze(data: qpanda3_runtime.toolbox.tracker.tracker_trace.TrackerTrace) → Any#

Analyze tracker trace data.

Parameters:

data (TrackerTrace) – The tracker trace data to analyze.

Returns:

The input data unchanged.

Return type:

Any

Notes

This implementation simply returns the input data without modification.

class qpanda3_runtime.toolbox.tracker.DefaultTrackingRule#

Bases: qpanda3_runtime.toolbox.tracker.tracking_rule.TrackingRule

Default tracking rule - passes data through unchanged.

This rule implements the simplest tracking behavior where data is returned unchanged without any processing or transformation.

Notes

Use this rule as a baseline or when no special processing is needed.

property rule_id: str#

Get the unique identifier for this tracking rule.

Returns:

Rule identifier string.

Return type:

str

analyze(data: qpanda3_runtime.toolbox.tracker.tracker_trace.TrackerTrace) → Any#

Analyze tracker trace data.

Parameters:

data (TrackerTrace) – The tracker trace data to analyze.

Returns:

The input data unchanged.

Return type:

Any

Notes

This implementation simply returns the input data without modification.

class qpanda3_runtime.toolbox.tracker.QTaskFailureRule#

Bases: qpanda3_runtime.toolbox.tracker.tracking_rule.TrackingRule

Quantum task failure tracking rule - records task failure information.

This rule is designed to track and analyze quantum task failures. It can be extended to provide specialized failure analysis logic.

Notes

Currently implements basic pass-through behavior. Extend this class to add custom failure analysis logic.

property rule_id: str#

Get the unique identifier for this tracking rule.

Returns:

Rule identifier string.

Return type:

str

analyze(data: qpanda3_runtime.toolbox.tracker.tracker_trace.TrackerTrace) → Any#

Analyze tracker trace data for quantum task failures.

Parameters:

data (TrackerTrace) – The tracker trace data to analyze.

Returns:

The input data unchanged.

Return type:

Any

Notes

This base implementation returns data unchanged. Override this method to implement custom failure analysis logic.

class qpanda3_runtime.toolbox.tracker.TraceDebugger(trace_file: str | None = None)#

Debugging tool for analyzing tracker records and reconstructing hierarchy trees.

This class provides comprehensive functionality for loading, analyzing, visualizing, and exporting tracker trace data stored in JSONL format.

Features#

  1. Loads records from .jsonl files

  2. Reconstructs hierarchy trees based on parent_id relationships

  3. Provides various display formats for hierarchy visualization

  4. Detects and reports issues in trace data

  5. Supports filtering and searching records

  6. Exports hierarchy trees to text files

  7. Analyzes data integrity and provides statistics

Examples

>>> debugger = TraceDebugger("trace.jsonl")
>>> debugger.print_summary()
>>> debugger.display_tree()
>>> debugger.export_to_text("hierarchy.txt")

Notes

The trace file should be in JSONL format with each line containing a JSON object with ‘id’, ‘parent_id’, ‘type’, and ‘data’ fields.

records = []#
records_by_id#
children_by_parent#
root_records = []#
load_trace_file(trace_file: str) → None#

Load tracker records from a JSONL trace file.

This method reads a trace file in JSONL format, parses each line as JSON, validates the required fields, and builds internal data structures for efficient hierarchy traversal and analysis.

Parameters:

trace_file (str) – Path to trace file in JSONL format.

Raises:
  • FileNotFoundError – If the specified trace file does not exist.

  • ValueError – If the trace file contains invalid JSON or missing required fields.

Notes

Each line in the trace file should be a JSON object with the following required fields: - id: Unique integer identifier - parent_id: Integer identifier of parent record (0 for root records) - type: Record type string - data: Dictionary containing record-specific data

After loading, the following internal structures are built: - records: List of all records - records_by_id: Dictionary mapping ID to record - children_by_parent: Dictionary mapping parent ID to list of child records - root_records: List of records with parent_id = 0

get_record(record_id: int) → Dict[str, Any] | None#

Get a record by its ID.

Parameters:

record_id (int) – Record ID to look up.

Returns:

The record if found, None otherwise.

Return type:

Optional[Dict[str, Any]]

get_children(parent_id: int) → List[Dict[str, Any]]#

Get all child records of a parent record.

Parameters:

parent_id (int) – Parent record ID.

Returns:

List of child records.

Return type:

List[Dict[str, Any]]

get_ancestors(record_id: int) → List[Dict[str, Any]]#

Get all ancestors of a record (from root to parent).

Parameters:

record_id (int) – Record ID to find ancestors for.

Returns:

List of ancestor records, starting from root.

Return type:

List[Dict[str, Any]]

get_descendants(record_id: int) → List[Dict[str, Any]]#

Get all descendants of a record (breadth-first).

Parameters:

record_id (int) – Record ID to find descendants for.

Returns:

List of descendant records in breadth-first order.

Return type:

List[Dict[str, Any]]

display_tree(root_id: int = 0, max_depth: int | None = None, show_data: bool = False, indent_size: int = 2) → None#

Display hierarchy tree with indentation.

This method prints a visual representation of the record hierarchy using ASCII art for tree structure visualization.

Parameters:
  • root_id (int, default 0) – Root record ID to start display from. Use 0 to display all root trees (records with parent_id = 0).

  • max_depth (Optional[int], default None) – Maximum depth to display. If None, displays the entire tree.

  • show_data (bool, default False) – Whether to show record data summaries. When True, includes key information from the data field.

  • indent_size (int, default 2) – Number of spaces per indentation level for tree visualization.

Notes

The tree display uses the following symbols: - ├─ : Branch connector (has siblings below) - └─ : Last child connector - [id] : Record ID in brackets - type : Record type

When show_data=True, a summary of the data field is shown after the record type, truncated for readability.

Examples

>>> # Display all root trees
>>> debugger.display_tree()
>>>
>>> # Display specific tree with data
>>> debugger.display_tree(root_id=123, show_data=True)
>>>
>>> # Display with depth limit
>>> debugger.display_tree(max_depth=3)
display_context_tree(show_incomplete: bool = True, show_data: bool = True) → None#

Display context hierarchy with special formatting for contexts.

This method provides a specialized view focused on context records (CONTEXT_START and CONTEXT_END), showing their relationships and completeness status.

Parameters:
  • show_incomplete (bool, default True) – Whether to highlight incomplete contexts (CONTEXT_START without matching CONTEXT_END). Incomplete contexts are marked with a warning symbol.

  • show_data (bool, default True) – Whether to show record data summaries for context records.

Notes

Contexts are displayed with status indicators: - ✓ : Complete context (has both START and END) - ✗ : Incomplete context (missing END) - ⚠ : Incomplete context when show_incomplete=True

For each context, the method shows: 1. Context name (from data[‘context_name’] or generated) 2. Context ID 3. Start data summary (if show_data=True) 4. End data summary (if complete and show_data=True) 5. Context contents (direct children)

Examples

>>> # Display all contexts
>>> debugger.display_context_tree()
>>>
>>> # Display contexts without highlighting incomplete ones
>>> debugger.display_context_tree(show_incomplete=False)
>>>
>>> # Display contexts without data
>>> debugger.display_context_tree(show_data=False)
find_records(record_type: str | None = None, search_text: str | None = None, parent_id: int | None = None) → List[Dict[str, Any]]#

Find records matching specified criteria.

This method provides flexible filtering capabilities to search for records based on type, text content, and parent-child relationships.

Parameters:
  • record_type (Optional[str], default None) – Record type to filter by (e.g., ‘CONTEXT_START’, ‘METRIC’, ‘EVENT’). If None, all record types are included.

  • search_text (Optional[str], default None) – Text to search for in record data. The search is case-insensitive and looks in both the record type and data fields.

  • parent_id (Optional[int], default None) – Parent record ID to filter by. If None, records with any parent are included. Use 0 to find root records.

Returns:

List of matching records in the order they appear in the trace.

Return type:

List[Dict[str, Any]]

Notes

When multiple filters are provided, records must match all criteria to be included in the results.

The text search looks for matches in: - Record type (case-insensitive) - String values in the data dictionary (case-insensitive) - Numeric values converted to string (exact match)

Examples

>>> # Find all CONTEXT_START records
>>> contexts = debugger.find_records(record_type='CONTEXT_START')
>>>
>>> # Find records containing "error" in their data
>>> errors = debugger.find_records(search_text='error')
>>>
>>> # Find children of a specific parent
>>> children = debugger.find_records(parent_id=123)
analyze_integrity() → Dict[str, Any]#

Analyze trace data integrity and report potential issues.

This method performs comprehensive integrity checks on the loaded trace data, including validation of parent-child relationships, context completeness, and data consistency.

Returns:

Dictionary containing analysis results with the following keys: - total_records: Total number of loaded records - root_records: Number of root records (parent_id = 0) - statistics: Dictionary of record counts by type - issues: List of detected issues - has_issues: Boolean indicating if any issues were found

Return type:

Dict[str, Any]

Notes

The following checks are performed: 1. Missing parent records (references to non-existent parents) 2. Incomplete contexts (CONTEXT_START without CONTEXT_END) 3. Cycles in parent-child relationships 4. Duplicate record IDs

Each issue in the ‘issues’ list contains: - type: Issue category (e.g., ‘missing_parents’, ‘incomplete_contexts’) - message: Human-readable description - details: List of relevant IDs or additional information

print_summary() → None#

Print a comprehensive summary of loaded trace data.

This method displays a formatted summary including record counts, type statistics, and integrity analysis results.

Notes

The summary includes: 1. Total number of records 2. Number of root records 3. Record type statistics (sorted by count) 4. Integrity issues (if any)

If no records are loaded, a message is printed indicating this.

Examples

>>> debugger.print_summary()
=== Trace Data Summary ===
Total records: 150
Root records: 3
Record type statistics:

METRIC: 75 EVENT: 50 CONTEXT_START: 15 CONTEXT_END: 10

✓ No integrity issues found

export_to_text(output_file: str, root_id: int = 0, max_depth: int | None = None, show_data: bool = True) → None#

Export hierarchy tree to a text file.

This method saves the visual tree representation to a text file, useful for documentation, sharing, or offline analysis.

Parameters:
  • output_file (str) – Path to output text file. The file will be created or overwritten.

  • root_id (int, default 0) – Root record ID to start from. Use 0 to export all root trees.

  • max_depth (Optional[int], default None) – Maximum depth to export. If None, exports the entire tree.

  • show_data (bool, default True) – Whether to include record data summaries in the export.

Notes

The exported file contains the same visual representation as displayed by the display_tree method, including ASCII art for tree structure.

The output is UTF-8 encoded and includes a header with export information.

Examples

>>> # Export all trees to a file
>>> debugger.export_to_text("hierarchy.txt")
>>>
>>> # Export specific tree without data
>>> debugger.export_to_text("tree_123.txt", root_id=123, show_data=False)
>>>
>>> # Export with depth limit
>>> debugger.export_to_text("shallow.txt", max_depth=2)
get_hierarchy_stats() → Dict[str, Any]#

Get hierarchy statistics for the loaded trace data.

This method calculates various statistics about the hierarchy structure, useful for understanding the complexity and shape of the trace data.

Returns:

Dictionary containing the following hierarchy statistics: - max_depth: Maximum depth of the hierarchy (root = depth 0) - avg_children_per_parent: Average number of children per parent node - max_children: Maximum number of children for any parent - leaf_nodes: Number of leaf nodes (nodes with no children) - branch_nodes: Number of branch nodes (nodes with children)

Return type:

Dict[str, Any]

Notes

Root records (parent_id = 0) are not counted as leaf or branch nodes since they are not part of the parent-child hierarchy for statistics purposes.

The statistics are calculated using breadth-first traversal to ensure accurate depth calculations.

Examples

>>> stats = debugger.get_hierarchy_stats()
>>> print(f"Max depth: {stats['max_depth']}")
>>> print(f"Leaf nodes: {stats['leaf_nodes']}")
>>> print(f"Branch nodes: {stats['branch_nodes']}")