qpanda3_runtime.toolbox.tracker.tools.trace_debugger#
Classes#
Debugging tool for analyzing tracker records and reconstructing hierarchy trees. |
Module Contents#
- class qpanda3_runtime.toolbox.tracker.tools.trace_debugger.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#
Loads records from .jsonl files
Reconstructs hierarchy trees based on parent_id relationships
Provides various display formats for hierarchy visualization
Detects and reports issues in trace data
Supports filtering and searching records
Exports hierarchy trees to text files
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, default0) – Root record ID to start display from. Use 0 to display all root trees (records with parent_id = 0).max_depth (
Optional[int], defaultNone) – Maximum depth to display. If None, displays the entire tree.show_data (
bool, defaultFalse) – Whether to show record data summaries. When True, includes key information from the data field.indent_size (
int, default2) – 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, defaultTrue) – Whether to highlight incomplete contexts (CONTEXT_START without matching CONTEXT_END). Incomplete contexts are marked with a warning symbol.show_data (
bool, defaultTrue) – 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], defaultNone) – Record type to filter by (e.g., ‘CONTEXT_START’, ‘METRIC’, ‘EVENT’). If None, all record types are included.search_text (
Optional[str], defaultNone) – 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], defaultNone) – 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, default0) – Root record ID to start from. Use 0 to export all root trees.max_depth (
Optional[int], defaultNone) – Maximum depth to export. If None, exports the entire tree.show_data (
bool, defaultTrue) – 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']}")