A ctf tracking data parallel resolution method and electronic equipment
By combining parallel parsing and dynamic structure function generation with multi-process processing and interrupt nested stack reconstruction, the performance and memory peak issues of CTF trace data parsing under embedded RTOS are solved, achieving efficient and automated context reconstruction and analysis querying.
Patent Information
- Application Number
- CN202611204616.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-10
- Publication Date
- 2026-11-27
AI Technical Summary
Existing CTF tracing data parsing tools suffer from insufficient parsing performance and excessively high memory peaks in scenarios with tens of millions of events. Furthermore, they lack an understanding of the semantics of embedded real-time operating systems, resulting in context reconstruction relying on manual post-processing scripts.
A parallel parsing method is adopted to obtain metadata by parsing the CTF metadata file, dynamically generate structure parsing functions, use multi-process parallel processing of CTF data stream files to generate Parquet files, maintain interrupt nesting stacks, automatically rebuild the context, and generate analysis reports.
It significantly improves the parsing efficiency and memory controllability of CTF trace data, automatically reconstructs the interrupt nesting stack and task context, and achieves efficient and lightweight end-to-end CTF data processing without the need for external scripts.
Smart Images

Figure CN123180116A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of data processing technology, and in particular to a parallel parsing method and electronic device for CTF tracking data. Background Technology
[0002] For parsing CTF (Common Trace Format) tracing data in embedded devices, existing solutions can be evaluated from three dimensions: parallel parsing capability, memory control mechanism, and RTOS semantic support. Representative tools and frameworks are as follows: (1) Eclipse Trace Compass – a state-based desktop analytics platform: Trace Compass is a Java-based trace analysis framework implemented on the Eclipse platform. Its TSDL (TraceStream Description Language) parser, generated by ANTLR, comprises lexical and syntactic analysis phases. After generating an AST, the application layer traverses the AST to populate the stream / trace definition. Its core analysis mechanism is a state system and state history tree, transforming trace events into state changes and querying attributes using SHT in logarithmic time complexity. Regarding RTOS semantics, Trace Compass includes general views such as control flow graphs, resource statistics, and latency analysis, but it does not provide native support for specific debugging semantics of embedded real-time operating systems, such as interrupt context nesting and task switching chain reconstruction.
[0003] (2) Babeltrace 2 - Reference implementation and conversion framework for CTF format: Babeltrace 2, developed and maintained by EfficiOS, is a major reference implementation for CTF formats. It employs a component architecture based on a directed acyclic graph (DAG), comprising three types of components: Source, Filter, and Sink. Components communicate with each other via messages between ports. This architecture uses a pull model, where the Sink component pulls event messages from upstream one by one through a message iterator, encapsulating each event as a message object for transmission. Babeltrace 2 focuses on format conversion and composable pipelines and does not provide a semantic analysis layer for RTOS.
[0004] (3) Perfetto — A general-purpose trace framework for Android / Linux: Perfetto employs a streaming architecture with a shared memory buffer (256KB per producer by default), periodically flushing to disk via `write_into_file` mode (`file_write_period_ms` defaults to 5 seconds), and using a sliding window for trace sorting to limit the memory required for sorting. It should be noted that Perfetto is primarily designed for Android / Linux systems, and its native trace format is protobuf rather than CTF, limiting its applicability in traditional embedded RTOS scenarios (such as FreeRTOS, Zephyr, and ThreadX).
[0005] (4) Percepio Tracealyzer — A visual trace tool for embedded RTOS: Tracealyzer is a visual trace analysis tool specifically designed for embedded RTOS, supporting mainstream kernels such as FreeRTOS, Zephyr, and SAFERTOS. It includes built-in RTOS semantic views such as task switching chains, CPU usage statistics, and interrupt response latency. However, Tracealyzer uses a proprietary trace format and a commercial licensing model. Its kernel adaptation layer requires events to be recorded via hook functions, and it is not a pure software end-to-end solution based on the CTF standard. Furthermore, its analysis focuses on metric visualization and does not provide efficient parallel and streaming memory control capabilities for batch parsing of tens of millions of events.
[0006] While the aforementioned tools support trace data parsing for embedded devices to some extent, they still have the following core limitations in scenarios where the total number of events in a single trace session reaches tens of millions (approximately GB of trace files) and is generated by high-frequency interrupts and task switching in the RTOS: (1) Lack of efficient parallel parsing architecture, resulting in insufficient parsing performance. Disadvantages: When dealing with tens of millions of events, the parsing speed of existing CTF parsing tools becomes a bottleneck. Babeltrace 2 uses pull-based per-event message passing, which is essentially single-threaded streaming processing; Trace Compass builds the SHT after loading the complete trace, and the construction phase is serial; although Perfetto uses shared memory and multiple producers at the acquisition end, its trace sorting still relies on a single-threaded sliding window. None of these three can meet the needs of rapid iteration in RTOS debugging.
[0007] Reasons: The CTF specification has cross-stream timing dependencies between events, and the global sorting requirement naturally limits the degree of parallelism; existing tools are mostly derived from Linux / desktop general scenarios, and their architecture design aims at composability and generality. They have not optimized the degree of parallelism for the monotonic clock domain of RTOS and the fixed set of event types, nor have they introduced a hybrid scheduling mechanism of pipeline and parallelism.
[0008] (2) No stream-based batch memory control, memory peak is too high Disadvantages: Babeltrace 2 encapsulates each event as a message object for transmission, and the object's lifecycle spans the entire pipeline. As the number of events grows linearly, memory spikes become uncontrollable. Trace Compass builds an SHT after loading the complete trace, and the full index resides in memory. Tracealyzer focuses on visualization, but its desktop version also struggles to handle tens of millions of events without memory overflow. In RTOS scenarios with massive event volumes, the excessive memory usage of these tools can cause the parsing process to crash. While Perfetto offers streaming and sliding window memory control at the acquisition end, it is designed for Android / Linux and is not adapted to embedded RTOS CTF trace parsing scenarios.
[0009] Reasons: The architecture of existing general-purpose trace parsing tools prioritizes composability and query flexibility over memory efficiency; they do not introduce batch callback mechanisms, and the lifecycle of event objects is deeply coupled with the pipeline, making it difficult to release intermediate results in a timely manner during the parsing process; for RTOS scenarios, they also lack memory quota scheduling based on event type or time window.
[0010] (3) Lack of built-in understanding of the semantics of embedded real-time operating systems Disadvantages: Babeltrace 2 and Perfetto are essentially format conversion or general acquisition frameworks, and do not provide a semantic analysis layer for RTOS; Trace Compass, although providing general views such as control flow graphs and resource statistics, does not provide a built-in calculation layer for critical needs in embedded RTOS debugging such as interrupt context nesting, task switching chain reconstruction, and CPU usage statistics by time block, and users still need to write complex post-processing scripts themselves; Tracealyzer, although it has an RTOS semantic view, relies on proprietary formats and kernel hooks, and does not provide end-to-end CTF parsing → context reconstruction → analysis and query integrated capabilities.
[0011] Reasons: Existing tools are mostly derived from general Linux / desktop scenarios and were not designed with consideration for the resource constraints and specific debugging semantics of embedded RTOS. The embedded field has long lacked a lightweight, pure software, end-to-end integrated solution for CTF parsing → context reconstruction → analysis and query. The toolchain is fragmented in terms of acquisition, format conversion and analysis, and users have to reinvent the wheel for the RTOS semantic computing layer. Summary of the Invention
[0012] This invention addresses three core problems in existing CTF trace data parsing technologies: insufficient parsing performance in scenarios with tens of millions of events due to serialized parsing architecture; excessively high memory peaks due to lack of batch memory control in streaming processing; and reliance on manual post-processing scripts for context reconstruction due to a lack of understanding of the execution semantics of embedded real-time operating systems. The invention aims to provide a parallel parsing method and electronic device for CTF trace data, achieving end-to-end automated processing from CTF trace data to structured, queryable analysis results (timeline, CPU usage, memory statistics). It balances parsing performance, memory stability, and the completeness of embedded semantic analysis even at the tens of millions of event scale.
[0013] To achieve the above objectives, the first objective of this invention is to provide a parallel parsing method for CTF tracking data, comprising: Parse the CTF metadata file to obtain the metadata; Dynamically generate structure parsing functions based on metadata; For the CTF data stream file, multiple worker processes are created, and the structure parsing function is called to parse the CTF data stream file to obtain the stream data Parquet file; Maintain an interrupt nested stack based on the streaming data Parquet file to update the streaming data Parquet file; While updating the Parquet file of streaming data, generate analysis reports; Write the table names and file matching patterns of the analysis reports, updated streaming data Parquet files, to the manifest file; Create a materialized view based on the manifest file.
[0014] As a further improvement of the present invention, the step of parsing the CTF metadata file to obtain the metadata includes: Extract the byte order, clock definition, all data stream definitions and their associated event list, event ID, event name, and field structure of the events from the CTF metadata file; The field structure includes: field type; Extract event header information and packet structure information from byte order, clock definition, all data stream definitions and their associated event list, event ID, event name, and the field structure contained in the event; Compile a Packet header structure parser and a Packet content structure unpacker based on event header information and Packet structure information.
[0015] As a further improvement of the present invention, the step of dynamically generating a structure parsing function based on metadata includes: Dynamically generate structure parsing functions based on field types.
[0016] As a further improvement of the present invention, the step of creating multiple working processes for the CTF data stream file and calling the structure parsing function to parse the CTF data stream file to obtain the stream data Parquet file includes: The main process uses a process pool to create several worker processes; Assign a worker process to each CTF data stream file; For CTF data stream files, starting from the buffer header, the Packet header structure parser and Packet content structure unpacker are used to locate the starting offset in the event data of the CTF data stream file. Inside Packet, starting from the initial offset, the event header information is used to read the time ID and timestamp. After performing boundary checks based on the event header information, the structure parsing function is called to extract the event fields and the parsing result is encapsulated into a four-tuple structure. When the number of event parsed reaches a set threshold, a callback function is triggered to convert the quadruple structure into a columnar format and write it to the Parquet streaming data file.
[0017] As a further improvement of the present invention, if an event field is detected to be truncated at the end of the Packet during the parsing of the CTF data stream file by the structure parsing function, the parsed events are encapsulated into a quadruple structure, converted into columnar format, written to the stream data Parquet file, and the truncation alarm information is returned.
[0018] As a further improvement of the present invention, the quadruple structure includes: timestamp, CPU core ID, event name, and event data; The step of maintaining an interrupt nested stack based on the streaming data Parquet file to update the streaming data Parquet file includes: Construct a mapping dictionary between task IDs and task names based on the Parquet streaming data file; Read all the streaming data Parquet files again, dynamically maintain the interrupt nesting stack at the CPU core ID granularity, determine the context to which each event belongs by tracking the changes of the top element of the stack, and append the context name as a new column back to the streaming data Parquet file.
[0019] As a further improvement of the present invention, the step of constructing a mapping dictionary between task IDs and task names based on the Parquet streaming data file includes: All streaming data Parquet files are sorted by timestamp; Select two types of events from all the Parquet streaming data files: task creation and task synchronization. Perform JSON reverse parsing on these two types of events to extract the task ID and task name fields, and construct a mapping dictionary between task IDs and task names.
[0020] As a further improvement of the present invention, the step of determining the context to which each event belongs by tracking changes in the top element of the stack includes: When the event name is "Entering Interrupt", push the interrupt number onto the top of the stack; When the event name is "Exit Interrupt", pop the top of the stack; When the event name is task switch, call the mapping dictionary between task ID and task name, and push the task name onto the top of the stack; Based on the current top of the stack, determine the context to which each event belongs.
[0021] As a further improvement of the present invention, the analysis reports include: timeline Parquet file, CPU usage Parquet file, and memory statistics Parquet file.
[0022] The second invention provides an electronic device, characterized in that it includes a processor, a communication interface, a memory, and a communication bus, wherein the processor, the communication interface, and the memory communicate with each other through the communication bus; the memory is used to store computer programs; and the processor is used to implement the above-mentioned parallel parsing method for CTF tracking data when executing the program stored in the memory.
[0023] Compared with existing technologies, this invention has the following advantages: Through a parallel parsing mechanism, this invention significantly improves the parsing efficiency and memory controllability of CTF trace data, effectively solving the problems of slow parsing speed and high memory peaks in traditional tools under scenarios with tens of millions of events. By dynamically generating structure parsing functions and combining them with multi-process parallel processing, high-throughput data conversion is achieved, significantly shortening trace loading time.
[0024] Furthermore, this invention can automatically reconstruct the interrupt nesting stack and task context, and synchronously generate analysis reports without relying on external scripts or proprietary formats. Finally, by unifying data organization through manifest files and materialized views, it achieves integrated parsing, semantic enhancement, and analysis querying, providing an efficient, lightweight, end-to-end CTF data processing solution for embedded system debugging. Attached Figure Description
[0025] The present invention will now be described in further detail with reference to the accompanying drawings and embodiments.
[0026] Figure 1 This is a flowchart of the parallel parsing method for CTF tracking data described in this invention; Figure 2 This is another flowchart of the parallel parsing method for CTF tracking data described in this invention. Detailed Implementation
[0027] To make the technical problems solved by the present invention, the technical solutions adopted, and the technical effects achieved clearer, the technical solutions of the embodiments of the present invention will be further described in detail below. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0028] This invention discloses a parallel parsing method for CTF tracking data, such as... Figure 1 and Figure 2 As shown, it includes: S1. Parse the CTF metadata file to obtain the metadata. The CTF metadata file is a TSDL format text specified by the CTF standard. Perform syntax parsing on the CTF metadata file to extract the following key information: byte order, clock definition, all data stream definitions and their associated event list, event ID, event name, and the field structure contained in the event. Among them, the field structure includes: field name, field type, field size, whether it is signed, whether it is an array type, etc.
[0029] Extract event header information and packet structure information from byte order, clock definition, all data stream definitions and their associated event list, event ID, event name, and the field structure contained in the event.
[0030] Specifically, it iterates through all data stream definitions, locates the structure containing the timestamp field and event ID, and automatically calculates: the total size of the event header, the offset and byte size of the timestamp field, and the offset and byte size of the event ID field. Simultaneously, it extracts the Packet header structure information: Packet header size, Packet magic number, size of the Packet context field and its contained fields (such as content_size, packet_size, cpu_id, etc.), and pre-compiles the corresponding Packet header structure unpacker and Packet content structure unpacker accordingly for subsequent fast parsing of Packet boundaries.
[0031] S2. Dynamically generate structure parsing functions based on metadata, that is, dynamically generate structure parsing functions at runtime based on field types, transforming metadata from static descriptions into executable parsing logic. Different parsing strategies are adopted for each field type: (a) For standard-sized integer types (1 / 2 / 4 / 8 bytes), a pre-compiled unpacker is used and cached to achieve O(1) parsing; (b) For non-standard-sized integer types (such as 3 / 5 / 6 / 7 bytes), the int.from_bytes method is used for general parsing; (c) For fixed-length integer arrays, a pre-compiled batch unpacker unpacks all elements at once; (d) For string arrays, a byte sequence of a specified length is read and truncated to the first null character ('\0') before UTF-8 decoding. All pre-compiled structure objects are cached using a dictionary to avoid repeated compilation, and the total field size required for each event type is recorded for out-of-bounds detection during subsequent streaming parsing. The final parsing function receives a binary buffer and an offset, and returns the parsed field dictionary and the number of bytes consumed.
[0032] Step S1 above elevates CTF metadata from passive type reference information to an active source of parsing logic generation. During the parsing initialization phase, the TSDL-formatted metadata text is parsed, extracting field definitions (field name, type, size, symbol, array length, etc.) for each event type. Step S2 dynamically generates a structure parsing function for that event type at runtime.
[0033] This mechanism enables the parser to be self-adaptive. When faced with CTF trace data generated by different RTOSs (Uniproton, FreeRTOS, Zephyr, RT-Thread, etc.) and user-defined events, the system only needs to read the corresponding metadata file to automatically generate a matching set of parsing functions without modifying any parsing code, thus achieving complete decoupling between the parser and the event type.
[0034] S3. For the CTF data stream file, create multiple worker processes and call the structure parsing function to parse the CTF data stream file, obtaining the stream data Parquet file (stream_ (.parquet file).
[0035] As one implementation method, step S3 includes: For loading multiple incoming CTF data stream files, the main process uses a process pool to create multiple worker processes (10 by default), with each worker process assigned a parsing task for one data stream file. To avoid each worker process repeatedly reading the metadata file, the main process reads the metadata file content only once and passes it as a string along with the task parameters to each worker process. After submitting all tasks, the main process asynchronously collects the return results from each worker process, collecting the results from the processes that finish first, thus achieving pipelined parallel processing. After collecting the results, the main process updates the global event count, the success / failure file count, and generates corresponding alarm logs based on the truncation information.
[0036] Each worker process independently loads a data stream file and completes full parsing within the process. Metadata is passed to each worker process in string form to avoid duplicate file I / O. The main process collects the parsing results of each process through an asynchronous Future mechanism, realizing pipelined parallel processing of multiple stream files.
[0037] After each worker process starts, it first reconstructs the trace parsing instance using the passed metadata, then reads the corresponding data stream file into memory all at once to form a binary buffer, and then calls the streaming parsing method for processing. The working mechanism of this method is as follows: (a) Packet boundary location: Starting from the buffer header, the Packet header is parsed using the pre-compiled Packet header structure unpacker and Packet content structure unpacker in step S1 to extract cpu_id, content_size and packet_size, and the starting offset of the event data is accurately located accordingly.
[0038] (b) Event-by-Event Parsing: Inside Packet, starting from the offset of the event data, the event ID and timestamp are read using the event header information extracted in step S1; the corresponding dynamic parsing function and the required field size are obtained by looking up the table according to the event ID; after performing boundary checks, the structure parsing function is called to extract the event fields; the parsing results are assembled into a unified four-tuple structure: timestamp, CPU core ID, event name, and event data, {cpu_id, timestamp, event_name, data}, where data is the JSON binary representation of all fields except cpu_id, timestamp, and event_name.
[0039] Within each worker process, the traditional approach of loading the entire data and objectifying it event by event is abandoned. Instead, the binary buffer is read in a streaming manner and parsed in batches (50,000 events by default). Once a batch is accumulated, the events are written to the Parquet columnar storage file in batches through a callback function and the intermediate objects are released. The memory can be reclaimed after the batch processing is completed. The large-scale binary CTF trace data is transformed into structured event data in columnar storage (Parquet), and the execution context identifier is appended synchronously during the parsing process.
[0040] (c) Batch Callback Write: When the cumulative number of events processed in each batch reaches a set threshold (default 50,000), a callback function will be triggered. This callback converts the event batch into a PyArrow columnar table containing four columns: cpu_id (uint32), timestamp (uint64), event_name (string), and data (binary), and appends it to the output file using ParquetWriter with Zstd compression. After the write is complete, the event batch list is immediately cleared to release memory.
[0041] (d) Fault tolerance: For the latest file, if the event field is truncated at the end of the packet, the entire parsed batch is written and the truncation alarm information is returned instead of discarding the entire file data; for truncation of other files, the error is recorded and the problematic packet is skipped.
[0042] S4. Maintain an interrupt nested stack based on the streaming data Parquet file to update the streaming data Parquet file.
[0043] In one implementation method, step S4 includes: S41. Construct a mapping dictionary between task IDs and task names based on the Parquet streaming data file.
[0044] Perform the first full scan: sort all streams by the first timestamp of the file. The process begins by reading the `.parquet` file, batch by batch, of its `event_name` and `data` columns. Using PyArrow's `compute.equal` vectorization operation, a boolean mask is generated to quickly filter out event rows with the event names "task_create" or "task_sync". Only these rows are subjected to JSON reverse parsing to extract the `task_id` and `task_name` fields, constructing a global `task_id→task_name` mapping dictionary. This strategy is employed because the "task_create" event may have occurred before the trace capture window, while the "task_sync" event periodically writes the identifier of the currently running task to the trace. Scanning both types of events simultaneously ensures the integrity of the task mapping. This vectorized filtering and on-demand parsing strategy makes this step significantly less expensive than full JSON parsing.
[0045] S42. Read all the streaming data Parquet files again, dynamically maintain the interrupt nested stack with CPU core ID as the granularity, determine the context to which each event belongs by tracking the changes of the top element of the stack, and append the context name as a new column back to the streaming data Parquet file.
[0046] During this process, all columns (timestamp, cpu_id, event_name, data) are read again file by file and batch by batch, and the following state variables are maintained independently at the CPU core (cpu_id) level: (a) Interrupt Nesting Stack: Each CPU core holds a double-ended queue as an interrupt nesting stack, with the initial top element being the "idle task". When an "enter interrupt" event is encountered, the "interrupt number" is extracted from the data, an "interrupt number" identifier is constructed, and pushed onto the top of the stack, supporting interrupt nesting (high-priority interrupts can preempt low-priority interrupts). When an "exit interrupt" event is encountered, if the stack depth is greater than 1, the top element is popped, restoring the context before the interruption. When an "event switch" event is encountered, the "switching target event ID" is extracted from the data, converted into a task name using the mapping table constructed in step 6, and pushed onto the top of the stack. The top element always represents the context currently being executed on the CPU core.
[0047] (b) Context Append: For each event, determine its context based on the current top element of the stack, append the context name as a new column to the original event data, and write it back to stream_ The .parquet file (atomic replacement after being written to a temporary file) gives the original event contextual semantics.
[0048] S5. While reconstructing the context, generate analysis reports; the analysis reports include: timeline Parquet file, CPU usage Parquet file, and memory statistics Parquet file.
[0049] (a) Timeline Calculation: The current context and its start timestamp for each CPU core are tracked in real time. When a context change is detected (the current context differs from the context of the previous event), a timeline record is created: {cpu_id, context_name, start_timestamp, end_timestamp, duration}, where start_timestamp is the context start timestamp, end_timestamp is the context end timestamp (i.e., the timestamp when the change occurred), and duration is the difference between the two. After all CPU cores have processed the last batch of events, the last unclosed context time period is also written to the timeline record. Finally, the collected complete timeline data is written to the timeline.parquet file in columnar format.
[0050] (b) CPU Usage Calculation: The runtime of each CPU core is divided into consecutive time blocks with a fixed time step (default 10,000,000 nanoseconds = 10 milliseconds). For the time interval between two adjacent events, the time block index range spanned by the time interval is calculated based on the context name and start / end timestamp of the previous event. If the time interval is within the same block, the duration of the context is directly added to that block. If it spans multiple blocks, the duration is distributed proportionally to each block (from the start of the event to the end of the block for the first block, from the start of the block to the end of the event for the last block, and the entire step length for the middle blocks). The final generated file is cpu.parquet, with each line containing: CPU ID, block start time, block end time, block duration, total usage time of all contexts within the block, and a JSON dictionary of the usage time of each context.
[0051] (c) Memory Statistics Calculation: During the event-by-event processing, when a "memory allocation" event is encountered, the `alloc_size` field is extracted, and the `alloc` count is incremented using the key combination (`cpu_id`, `context_name`). When a "memory release" event is encountered, the `free_size` field is extracted, and the `free` count is incremented using the same key combination. The final result is a `memory.parquet` file, with each line containing: `cpu_id`, `context_name`, total allocation, total release, and net remaining memory (total - total release).
[0052] The above steps address the three most critical questions in embedded RTOS debugging: "In which task context is the current code executing?", "What is the depth and order of interrupt nesting?", and "How much time does each task and interrupt occupy on each CPU core?". An automated semantic analysis calculation layer is built-in.
[0053] In terms of context reconstruction, a state machine is maintained independently at the granularity of each CPU core, and the core data structure is a double-ended queue as an interrupt nesting stack. The top element of the stack always represents the current execution context of that CPU core, naturally supporting interrupt nesting of arbitrary depth, that is, the stack automatically deepens when a high-priority interrupt preempts a low-priority interrupt.
[0054] In terms of computational strategy, a two-step traversal design is adopted to solve the problem of incomplete metadata caused by the limited trace capture window: the first scan builds a complete mapping dictionary; the second scan synchronously completes the three calculations of timeline, CPU usage, and memory statistics.
[0055] The core advantage of this mechanism lies in its versatility. `isr_enter`, `isr_exit`, and `task_switched` are common scheduling events generated by almost all RTOS kernels. The aforementioned steps, based on the semantics of these three common events, construct a context reconstruction algorithm that does not rely on the kernel event naming conventions or data structures of any specific RTOS. This achieves a single codebase across multiple RTOS platforms, providing universal coverage for various systems. Compared to Trace Compass's design, which hard-codes the Control Flow view with the Linux `sched_switch` event name, this invention offers a greater advantage in versatility.
[0056] S6. Write the table names and file matching patterns of the timeline Parquet file, CPU usage Parquet file, memory statistics Parquet file, and updated stream data Parquet file to the manifest.json file. The tables declared in the manifest.json file include: stream (all stream_ The .parquet file contains appended context columns, timeline (timeline.parquet), cpu (cpu.parquet), and memory (memory.parquet). The subsequent query engine can automatically discover all available tables and create SQL views by reading this manifest file. Users can directly query and analyze the results using standard SQL statements without needing to understand the underlying file organization.
[0057] The parallel parsing method for CTF tracking data of this invention will be explained next in conjunction with a practical application scenario, as follows: Scenario Setting: An automated production line in a smart factory has a main control PLC with its real-time operating system enabled to record CTF trace data. When an abnormal alarm occurs, the CTF trace data for the abnormal period is recorded and archived. On average, 50 events are recorded within 1ms of the real-time system control cycle, and data is archived into one CTF trace data file per minute. When the trace recording time reaches ten minutes, the total number of trace data records will reach 30 million.
[0058] Example of Trace data parsing: (1) Preparation stage: Operations / development personnel connect to embedded devices that need to analyze trace data on their personal development PCs / cloud-based parsing servers, capturing CTF metadata files and CTF trace data files from the devices.
[0059] (2) Task initialization phase: Read the CTF metadata file to obtain the event field structure definition, and dynamically construct the event structure parsing function.
[0060] (3) Parsing and execution phase: The main process receives the CTF trace data stream file and the event structure parsing function. It creates independent event parsing processes through a parallel process pool. Within a single parsing process, events are parsed in batches and streamed into a Parquet file.
[0061] After the parallel process completes event parsing, it performs its first traversal to establish a mapping from event ID to event name and updates the Parquet data.
[0062] The second iteration filters key events in the context, calculates the context timeline, CPU usage, and memory allocation data, and writes them to the corresponding Parquet data.
[0063] (4) Completion stage: Once all parsing tasks within the parallel process pool are completed, including context computation, CPU usage calculation, and memory allocation calculation, the corresponding data is compressed, recorded in the Parquet streaming data file, and metadata is updated in the local lightweight database (TinyDB). The CTF trace data parsing is then successful. Developers can filter trace data by parameters such as time range, event name, and context scope using SQL statements to view trace data information corresponding to key time points of anomaly alerts.
[0064] This invention differs from the single-threaded, event-by-event full objectification processing mode commonly used in existing CTF parsing tools. Its core lies in constructing a two-layer parallel streaming parsing architecture, namely, a multi-process parallel scheduling layer on the upper layer and a single-process streaming batch processing layer on the lower layer. The deep coupling between the two achieves dual optimization of parsing performance and memory usage.
[0065] In terms of upper-level parallel scheduling, the main process receives CTF trace data stream files, arranges them in numerical order by filename, and uses a process pool executor to create multiple worker processes. Each worker process is independently responsible for parsing one data stream file. After all tasks are submitted, the main process collects the parsing results of each process in a pipeline mode of first-come, first-served through an asynchronous mechanism, and summarizes global statistics (total number of events, number of successful / failed files, truncation alarms, etc.).
[0066] In the lower-level streaming batch processing, the traditional three-stage process of full read → event-by-event objectification → full write is completely abandoned within each worker process, replaced by a streaming batch pipeline. After reading the binary buffer once, the data is parsed according to the preset batch size, triggering a batch callback. The batch of events is then converted into a PyArrow columnar table and appended to the Parquet streaming data file using Zstd compression. The batch list is immediately cleared and intermediate Python objects are released after the write to disk is complete. Each iteration of the streaming parsing loop only maintains the event list of the current batch; the memory of the previous batch has been reclaimed. This completely decouples the peak memory usage of a single process from the total size of the trace file, depending only on the data size of a single batch.
[0067] This invention fundamentally solves two long-standing and contradictory problems in embedded device trace data parsing: insufficient parsing performance and uncontrolled memory spikes. Traditional solutions face a dilemma: prioritizing parsing speed requires storing a large number of events in memory for batch processing, leading to memory bloat and even crashes; controlling memory usage necessitates interpreting and processing events and fields one by one, resulting in a sharp drop in parsing speed. The invention's two-layer architecture, through complementary designs of inter-process parallel throughput scaling and intra-process batch streaming memory control, optimizes both metrics simultaneously rather than at odds.
[0068] Specifically: Multi-process parallel scheduling allows the parsing throughput to scale linearly with the number of CPU cores. If a machine has N idle cores, N data stream files can be parsed simultaneously, and the total time is approximately equal to the maximum file time rather than the sum of the times for all files. The batch callback mechanism reduces the memory usage of a single process from being proportional to the total number of events to being proportional to the size of a single batch (default 50,000 records × each record is approximately several hundred bytes ≈ tens of MB). Even when faced with trace data of tens of millions of events, the peak memory usage remains stable and controllable.
[0069] The present invention has the following technical effects: A significant leap in parsing performance: With a configuration of 10 worker processes, trace data of tens of millions of events can be parsed from raw binary data to columnar structured data in tens of seconds (actual single-process parsing speed can reach hundreds of thousands of events / second), meeting the stringent requirements of rapid iterative debugging for timely feedback.
[0070] Memory safety and controllability: The peak memory usage of a single process is stable at the tens of MB level, completely eliminating the production risk of parsing crashes due to memory overflow. This allows large-scale trace parsing to run stably on development machines with limited memory, without the need to configure a dedicated large memory server.
[0071] This invention integrates three major mechanisms—a streaming parsing architecture with multi-process parallelism and batch callbacks, runtime generation of metadata-driven dynamic structure parsing functions, and interrupt nested stack and two-pass RTOS context reconstruction—to bring significant overall technical advancements to CTF trace data parsing in embedded RTOS. (1) Achieving both parsing performance and memory safety: The dual-layer parallel streaming architecture breaks the dilemma of the traditional solution where speed and memory cannot be achieved simultaneously. The full-process parsing of tens of millions of event trace data (including context reconstruction and statistical calculation) can be completed in minutes, while the peak memory usage is stable at tens of MB, enabling large-scale trace analysis to run reliably on ordinary development machines.
[0072] (2) Automated semantic understanding of RTOS: From raw binary events to structured conclusions such as "which task was executed on which CPU core for how long, how many interrupt nestings occurred, and how much memory was allocated", all are automatically calculated and generated. Users do not need to write any post-processing scripts or state machine definitions, shortening the analysis workflow from parsing and manual analysis to one-click parsing to obtain the conclusion.
[0073] (3) Cross-RTOS platform universality: The dynamic structure parsing function driven by metadata generates and the context reconstruction of general event semantics can adapt to CTF trace data generated by different RTOS such as Uniproton, FreeRTOS, Zephyr, RT-Thread, and ThreadX without any modification. Only the metadata file corresponding to each RTOS needs to be provided.
[0074] (4) Ecosystem compatibility: The output adopts the Apache Parquet columnar storage format, which is natively compatible with mainstream data analysis tools such as DuckDB, Pandas, PyArrow, and Spark. Users can directly query analysis tables such as timeline, CPU, and memory through standard SQL without having to learn a dedicated query language or API, thus reducing the threshold for team collaboration and toolchain integration.
[0075] Based on the same inventive concept, the present invention also provides an electronic device, including a processor, a communication interface, a memory, and a communication bus, wherein the processor, the communication interface, and the memory communicate with each other through the communication bus; the memory is used to store computer programs; and the processor is used to implement the above-mentioned parallel parsing method for CTF tracking data when executing the program stored in the memory.
[0076] The communication bus mentioned above can be a Peripheral Component Interconnect (PCI) bus or an Extended Industry Standard Architecture (EISA) bus, etc. This communication bus can be divided into address bus, data bus, control bus, etc. The communication interface is used for communication between the aforementioned terminal and other devices.
[0077] The memory may include random access memory (RAM) or non-volatile memory, such as at least one disk storage device. Optionally, the memory may also be at least one storage device located remotely from the aforementioned processor.
[0078] The processors mentioned above can be general-purpose processors, including central processing units (CPUs), graphics processing units (GPUs), network processors (NPs), etc.; they can also be digital signal processors (DSPs), application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), or other programmable logic devices, discrete gate or transistor logic devices, or discrete hardware components.
[0079] The CPU is used for point cloud centering, 3D convex hull construction, surface aggregation, 2D convex hull calculation, and ranking decisions. The memory stores point clouds, convex hull structures, candidate support surface parameters, and intermediate steady-state decision results, as well as the input model, output rotation matrix, and steady-state surface decision logs. The GPU is used for batch preprocessing or visualization of large-scale point clouds.
[0080] Furthermore, it should be understood that although this specification describes embodiments, not every embodiment contains only one independent technical solution. This narrative style of the specification is merely for clarity. Those skilled in the art should consider the specification as a whole, and the technical solutions in each embodiment can also be appropriately combined to form other embodiments that can be understood by those skilled in the art.
[0081] The technical principles of the present invention have been described above with reference to specific embodiments. These descriptions are merely for explaining the principles of the invention and should not be construed as limiting the scope of protection of the invention in any way. Based on this explanation, those skilled in the art can readily conceive of other specific embodiments of the invention without inventive effort, and these embodiments will all fall within the scope of protection of the present invention.
Claims
1. A parallel parsing method for CTF tracking data, characterized in that, include: Parse the CTF metadata file to obtain the metadata; Dynamically generate structure parsing functions based on metadata; For the CTF data stream file, multiple worker processes are created, and the structure parsing function is called to parse the CTF data stream file to obtain the stream data Parquet file; Maintain an interrupt nested stack based on the streaming data Parquet file to update the streaming data Parquet file; While updating the Parquet file of streaming data, generate analysis reports; Write the analysis report, the table names of the updated streaming data Parquet files, and the file matching patterns to the manifest file.
2. The parallel parsing method for CTF tracking data according to claim 1, characterized in that, The steps for parsing the CTF metadata file to obtain metadata include: Extract the byte order, clock definition, all data stream definitions and their associated event list, event ID, event name, and field structure of the events from the CTF metadata file; The field structure includes: field type; Extract event header information and packet structure information from byte order, clock definition, all data stream definitions and their associated event list, event ID, event name, and the field structure contained in the event; Compile a Packet header structure parser and a Packet content structure unpacker based on event header information and Packet structure information.
3. The parallel parsing method for CTF tracking data according to claim 2, characterized in that, The step of dynamically generating a structure parsing function based on metadata includes: Dynamically generate structure parsing functions based on field types.
4. The parallel parsing method for CTF tracking data according to claim 2, characterized in that, The steps of creating multiple worker processes for the CTF data stream file and calling the structure parsing function to parse the CTF data stream file to obtain the Parquet stream data file include: The main process uses a process pool to create several worker processes; Assign a worker process to each CTF data stream file; For CTF data stream files, starting from the buffer header, the Packet header structure parser and Packet content structure unpacker are used to locate the starting offset in the event data of the CTF data stream file. Inside Packet, starting from the initial offset, the event header information is used to read the time ID and timestamp. After performing boundary checks based on the event header information, the structure parsing function is called to extract the event fields and the parsing result is encapsulated into a four-tuple structure. When the number of event parsed reaches a set threshold, a callback function is triggered to convert the quadruple structure into a columnar format and write it to the Parquet streaming data file.
5. The parallel parsing method for CTF tracking data according to claim 4, characterized in that, During the parsing of the CTF data stream file by the structure parsing function, if an event field is detected to be truncated at the end of the Packet, the parsed events will be encapsulated into a quadruple structure, converted into columnar format, written to the Parquet stream data file, and the truncation alarm information will be returned.
6. The parallel parsing method for CTF tracking data according to claim 4, characterized in that, The quadruple structure includes: timestamp, CPU core ID, event name, and event data; The step of maintaining an interrupt nested stack based on the streaming data Parquet file to update the streaming data Parquet file includes: Construct a mapping dictionary between task IDs and task names based on the Parquet streaming data file; Read all the streaming data Parquet files again, dynamically maintain the interrupt nesting stack at the CPU core ID granularity, determine the context to which each event belongs by tracking the changes of the top element of the stack, and append the context name as a new column back to the streaming data Parquet file.
7. The parallel parsing method for CTF tracking data according to claim 6, characterized in that, The step of constructing a mapping dictionary between task IDs and task names based on the Parquet streaming data file includes: All streaming data Parquet files are sorted by timestamp; Select two types of events from all the Parquet streaming data files: task creation and task synchronization. Perform JSON reverse parsing on these two types of events to extract the task ID and task name fields, and construct a mapping dictionary between task IDs and task names.
8. The parallel parsing method for CTF tracking data according to claim 6, characterized in that, The step of determining the context of each event by tracking changes in the top element of the stack includes: When the event name is "Entering Interrupt", push the interrupt number onto the top of the stack; When the event name is "Exit Interrupt", pop the top of the stack; When the event name is task switch, call the mapping dictionary between task ID and task name, and push the task name onto the top of the stack; Based on the current top of the stack, determine the context to which each event belongs.
9. The parallel parsing method for CTF tracking data according to claim 1, characterized in that, The analysis reports include: timeline Parquet file, CPU usage Parquet file, and memory statistics Parquet file.
10. An electronic device, characterized in that, The system includes a processor, a communication interface, a memory, and a communication bus, wherein the processor, the communication interface, and the memory communicate with each other via the communication bus; the memory is used to store computer programs; and the processor, when executing the program stored in the memory, implements the CTF tracking data parallel parsing method as described in any one of claims 1 to 9.
