qpanda3_runtime.toolbox.tracker.tracker_trace#
Classes#
Manager for generating unique IDs for trace rows. |
|
Enumeration of trace row types. |
|
Data structure for a tracking record row. |
|
Base class for trace tree nodes. |
|
Context node for trace tree structure. |
|
General hierarchical tracking recorder with numeric IDs and write buffer. |
|
Memory/historical data object for tracking traces. |
Module Contents#
- class qpanda3_runtime.toolbox.tracker.tracker_trace.TraceRowIdManager#
Manager for generating unique IDs for trace rows.
This class provides thread-safe and async-safe ID generation for tracking trace rows. It maintains a counter that increments with each ID request.
- Variables:
current_id (
int) – Current ID counter value_lock (
threading.Lock) – Thread lock for synchronous operations_async_lock (
asyncio.Lock) – Async lock for asynchronous operations
- current_id = -1#
- get_next_id() int#
Get next unique ID (thread-safe).
- Returns:
Next unique ID
- Return type:
int
Notes
Thread-safe using threading.Lock
IDs are monotonically increasing
- async get_next_id_async() int#
Get next unique ID (async-safe).
- Returns:
Next unique ID
- Return type:
int
Notes
Async-safe using asyncio.Lock
Suitable for async/await contexts
- reset_current_id(id: int)#
Reset the current ID counter.
- Parameters:
id (
int) – New value for current_id
Notes
Use with caution as it affects ID generation
Typically used for testing or special scenarios
- class qpanda3_runtime.toolbox.tracker.tracker_trace.TraceRowType#
Bases:
str,enum.EnumEnumeration of trace row types.
Defines the possible types of rows in a tracking trace.
- Variables:
CONTEXT_START (
str) – Marks the beginning of a tracking contextCONTEXT_END (
str) – Marks the end of a tracking contextDATA (
str) – Represents data recorded within a context
- CONTEXT_START = 'CONTEXT_START'#
- CONTEXT_END = 'CONTEXT_END'#
- DATA = 'DATA'#
- class qpanda3_runtime.toolbox.tracker.tracker_trace.TraceRow#
Data structure for a tracking record row.
Represents a single row in a tracking trace with metadata and payload data.
- Variables:
row_id (
int) – Numeric identifier for the rowrow_type (
TraceRowType) – Type of the row (context start, context end, or data)row_parent_id (
int) – Numeric identifier of parent row for hierarchical relationshipsdata (
Dict[str,Any]) – Payload data associated with the rowlabels (
List[str]) – Categorization labels for filtering and analysistimestamp (
str) – ISO 8601 timestamp of when the row was created
- row_id: int#
- row_type: TraceRowType#
- row_parent_id: int#
- data: Dict[str, Any]#
- labels: List[str]#
- timestamp: str#
- to_dict() Dict[str, Any]#
Convert the record to dictionary format.
- Returns:
Dictionary representation of the record.
- Return type:
Dict[str,Any]
Notes
Used for serialization and storage
Maintains all original field names and values
- to_json() str#
Convert the record to JSON string (single line).
- Returns:
JSON string representation of the record.
- Return type:
str
Notes
Uses compact JSON format without extra whitespace
Ensures ASCII characters are properly handled
Suitable for line-based storage in JSONL files
- class qpanda3_runtime.toolbox.tracker.tracker_trace.TraceTreeNodeBase(row_id: int | TraceRowIdManager, labels: List[str], closed: bool = False, is_data: bool = False)#
Base class for trace tree nodes.
Represents a node in the hierarchical trace tree structure, which can contain either data rows or child context nodes.
- Variables:
is_data (
bool) – Whether this node represents data (True) or context (False)start_row (
TraceRow) – Starting row for context nodes, None for data nodescontent (
List[Union[TraceRow,TraceTreeNodeBase]]) – Child elements (data rows or nested context nodes)end_row (
TraceRow) – Ending row for context nodes, None for open contextsclosed (
bool) – Whether the context is closed (completed)labels (
List[str]) – Categorization labels for the noderow_id_manager (
TraceRowIdManager) – Manager for generating unique row IDs
- is_data: bool = False#
- content: List[TraceRow | TraceTreeNodeBase] = []#
- closed: bool = False#
- labels: List[str]#
- id()#
Get the node’s ID.
- Returns:
ID from the start_row
- Return type:
int
Notes
Only valid for context nodes with start_row
Data nodes may not have an ID
- parent_id()#
Get the parent node’s ID.
- Returns:
Parent ID from the start_row
- Return type:
int
Notes
Represents hierarchical relationship in trace tree
Root node typically has parent_id of 0
- set_parent_id(parent_id: int) None#
Set the parent node ID.
- Parameters:
parent_id (
int) – New parent ID value
Notes
Updates the start_row’s parent_id field
Affects hierarchical relationships in trace tree
- set_node_id(node_id: int) None#
Set the node ID and update child relationships.
- Parameters:
node_id (
int) – New node ID value
Notes
Updates the node’s own ID in start_row
Updates parent_id of all child TraceRow objects
Recursively updates parent_id of child TraceTreeNodeBase objects
- set_labels(labels: List[str]) None#
Set the node’s labels.
- Parameters:
labels (
List[str]) – New label list
Notes
Overwrites existing labels
Labels are used for categorization and filtering
- set_closed(closed: bool = True) None#
Set the node’s closed status.
- Parameters:
closed (
bool, optional) – New closed status, default is True
Notes
Closed nodes represent completed contexts
Open nodes represent ongoing operations
- is_closed() bool#
Check if the node is closed.
- Returns:
True if node is closed, False otherwise
- Return type:
bool
Notes
Closed status indicates context completion
Data nodes are typically always closed
- to_trace_rows() List[TraceRow]#
Convert node and descendants to flat list of trace rows.
- Returns:
Flat list of all trace rows in this node and its descendants
- Return type:
List[TraceRow]
Notes
Recursively processes child nodes
Maintains hierarchical order (parent before children)
Includes start_row, content rows, and end_row if present
- timestamp()#
Get the node’s timestamp.
- Returns:
ISO 8601 timestamp from start_row
- Return type:
str
Notes
Represents when the context started
Used for chronological ordering
- order_by_row_id()#
Sort content by row ID.
Recursively sorts child TraceTreeNodeBase elements and then sorts the content list by row ID.
Notes
Recursively processes child TraceTreeNodeBase elements first
Uses row_id for TraceRow elements and id() for TraceTreeNodeBase
Results in chronological order based on ID assignment
- order_by_timestamp()#
Sort content by timestamp.
Recursively sorts child TraceTreeNodeBase elements and then sorts the content list by timestamp.
Notes
Recursively processes child TraceTreeNodeBase elements first
Uses timestamp for TraceRow elements and timestamp() for TraceTreeNodeBase
Results in chronological order based on actual timing
- class qpanda3_runtime.toolbox.tracker.tracker_trace.TraceTreeContextNode(row_id: int | TraceRowIdManager, parent_id: int, node_name: str, labels: List[str], closed: bool = False, start_row: TraceRow = None)#
Bases:
TraceTreeNodeBaseContext node for trace tree structure.
Specialized node type for representing tracking contexts with start and end markers, and containing data records or nested contexts.
- Variables:
TraceTreeNodeBase (Inherits all attributes from)
Examples
>>> node = TraceTreeContextNode(1, 0, "quantum_circuit", ["simulation"]) >>> data_row = node.add_data({"qubits": 5}) >>> node.start_context()
- add_data(data: TraceRow | Dict[str, Any], row_id: int | None = None, labels: List[str] = []) TraceRow#
Add data record to the context.
- Parameters:
data (
Union[TraceRow,Dict[str,Any]]) – Either an existing TraceRow or a dictionary of datarow_id (
Union[int,None], optional) – Specific row ID to use, if None generates new IDlabels (
List[str], optional) – Categorization labels for the data
- Returns:
The added or existing trace row
- Return type:
Notes
If data is already a TraceRow, appends it directly
If data is a dict, creates a new DATA TraceRow
Sets parent_id to this context’s ID for hierarchical relationship
- start_context() TraceRow#
Get the context start row.
- Returns:
The CONTEXT_START row for this context
- Return type:
Notes
Returns the row that marks the beginning of this context
Used for reference and debugging purposes
- add_child(node_name: str, labels: List[str], closed: bool = False, child_node: TraceTreeContextNode = None) TraceTreeContextNode#
Add a child context node.
- Parameters:
node_name (
str) – Name identifier for the child contextlabels (
List[str]) – Categorization labels for the child contextclosed (
bool, optional) – Whether the child context is closed, default is Falsechild_node (
TraceTreeContextNode, optional) – Pre-existing child node to add
- Returns:
The added or existing child node
- Return type:
Notes
If child_node is provided, appends it directly
Otherwise creates a new child context node
Sets parent-child relationship automatically
- end_context(data: TraceRow | Dict[str, Any], row_id: int | None = None, labels: List[str] = []) TraceRow#
End the context with result data.
- Parameters:
data (
Union[TraceRow,Dict[str,Any]]) – Either an existing TraceRow or dictionary of result datarow_id (
Union[int,None], optional) – Specific row ID to use, if None generates new IDlabels (
List[str], optional) – Categorization labels for the end operation
- Returns:
The CONTEXT_END row
- Return type:
Notes
Creates a CONTEXT_END TraceRow to mark context completion
Sets the context as closed
Result data is recorded in the end row
- class qpanda3_runtime.toolbox.tracker.tracker_trace.TraceRecorder(output_file: str | None = None, buffer_size: int = 1000)#
General hierarchical tracking recorder with numeric IDs and write buffer.
Features: 1. Uses numeric IDs (auto-increment integers), no string IDs 2. Manages parent reference ID hierarchy using a stack 3. Automatically generates numeric IDs and sets parent references 4. Supports enter/exit level operations 5. Users cannot customize ID generation 6. Uses write buffer with queue (deque) for ordered writes 7. When buffer reaches limit or immediate write is needed:
First write all buffer data to file
Then write the immediate record to file
Supports tracking any type of information, not limited to state
- output_file = None#
- buffer_size = 1000#
- write_buffer#
- record(trace_row: TraceRow, immediate: bool = False) None#
Record a trace row.
- Parameters:
trace_row (
'TraceRow') – Trace row to record.immediate (
bool, defaultFalse) – Whether to write immediately.
- get_buffer_size() int#
Get current buffer size.
- Returns:
Number of records currently in buffer.
- Return type:
int
- is_buffer_empty() bool#
Check if buffer is empty.
- Returns:
True if buffer is empty, False otherwise.
- Return type:
bool
- get_row_count() int#
Get total number of rows recorded.
- Returns:
Total number of rows recorded.
- Return type:
int
- flush() None#
Flush buffer to file and ensure data persistence.
- close() None#
Close the tracking recorder and release resources.
- clear() None#
Clear all records and reset the recorder.
Notes
This method: 1. Clears the write buffer 2. Clears the record mapping 3. Resets the ID counter 4. Resets the parent stack 5. Truncates the output file if it exists
- class qpanda3_runtime.toolbox.tracker.tracker_trace.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:
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 pairssave_to_file (
bool, optional) – Whether to save the record to file, default is Falselabels (
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 contextcontext_labels (
List[str], optional) – Categorization labels for the contextcontext_data (
Dict[str,Any], optional) – Initial data associated with context startsave_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 completionsave_to_file (
bool, optional) – Whether to save context end to file, default is Falselabels (
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