Task processing method, electronic device, and program product
By creating a task context in the intelligent dialogue system and combining it with server push events and state sets, real-time push and connection maintenance are achieved, solving the connection management problem in the HTTP request-response mode and improving system stability and user experience.
Patent Information
- Application Number
- CN202611432934.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-15
- Publication Date
- 2026-11-24
AI Technical Summary
The existing HTTP request-response model cannot meet the needs of real-time data push in intelligent dialogue systems, and there are problems with connection keep-alive and concurrent state management, resulting in a poor user experience.
By creating a task context that includes a server push event communication interface and a set of task execution states, the business thread pushes intermediate results in real time, the heartbeat thread maintains connection activity, and the heartbeat periodic tasks are managed by a timed thread pool, thus achieving rapid release of access threads and efficient task processing.
It achieves real-time feedback and highly reliable task processing in high-concurrency environments, solves the problems of connection resource exhaustion and easy timeout disconnection of long-running tasks, and improves system stability and user experience.
Smart Images

Figure CN123157481A_ABST
Abstract
Description
Technical Field
[0001] This disclosure relates to the field of computer technology, and more particularly to task processing methods, electronic devices, and program products. Background Technology
[0002] In existing intelligent dialogue systems, after a user asks a question, the AI needs to perform complex operations such as reasoning, tool invocation, and content generation, which may take tens of seconds or even longer.
[0003] To provide a good user experience, the system needs to provide real-time feedback on the AI's thought process and generation progress, smoothly display the information word by word or sentence by sentence, ensure stable and reliable connections over long periods, and promptly notify users of errors. However, the existing HTTP request-response model cannot meet this real-time push requirement, and there are issues with connection keep-alive and concurrent state management. Therefore, a real-time, efficient task processing system is needed. Summary of the Invention
[0004] This disclosure provides task processing methods, electronic devices, and program products.
[0005] According to a first aspect of this disclosure, a task processing method is provided. The method includes: creating a task context in response to a task processing request sent by a client; wherein the task context includes a communication interface for server-pushed events and a state set representing the task execution state; submitting the task context to a business thread to execute a target processing operation and releasing the access thread; pushing intermediate execution results to the client and updating the state set by calling the communication interface in the task context through the business thread; periodically reading the task completion status in the state set through a heartbeat thread; if the task completion status indicates that the target processing operation is not completed, sending a heartbeat signal; if the task completion status indicates that the target processing operation is completed, stopping sending the heartbeat signal; and sending a task completion notification to the client through the communication interface.
[0006] In at least one embodiment of this disclosure, the state set includes at least one of the following state variables: task completion state variable, task failure state variable, task interruption state variable, inference in progress state variable, and inference completion state variable.
[0007] In at least one embodiment of this disclosure, the step of pushing intermediate execution results to the client and updating the state set by calling the communication interface in the task context through a business thread includes: determining the start of an inference operation in response to calling the application programming interface of the artificial intelligence model; switching the inference process state variable to an in progress state through a lock-free atomic operation and recording the inference start time; determining that the first inference result has been obtained in response to reading the first data block from the response stream of the artificial intelligence model; switching the inference completion state variable to a completed state through a lock-free atomic operation and recording the arrival time of the first result; determining the end of the inference operation in response to receiving an inference end flag returned by the artificial intelligence model; and switching the inference process state variable to an inactive state through a lock-free atomic operation and recording the inference end time.
[0008] In at least one embodiment of this disclosure, the method further includes: calculating cost measurement data based on the inference start time, the first result arrival time, and the inference end time; wherein the cost measurement data includes at least one of total inference time, first result delay time, and inference generation stage time.
[0009] In at least one embodiment of this disclosure, before periodically reading the task completion status in the status set via the heartbeat thread, the method further includes: pre-submitting the heartbeat periodic task to the timed thread pool and storing the task handle of the heartbeat periodic task in the task context; if the task completion status indicates that the target processing operation has been completed, then stopping the sending of the heartbeat signal includes: if the task completion status indicates that the target processing operation has been completed, then obtaining the task handle from the task context via the business thread; sending a cancellation request carrying the task handle to the timed thread to cancel the heartbeat periodic task submitted in the timed thread pool.
[0010] In at least one embodiment of this disclosure, the target processing operation includes a preprocessing stage and a processing stage, and further includes: when an exception occurs in the preprocessing stage, updating the task failure status variable to a failure state, updating the task completion status variable to a completed state, and sending a first error notification to the client through the communication interface; when a retryable exception occurs in the processing stage, sending a second error notification to the client through the communication interface and performing a retry operation, and keeping the task completion status variable in an incomplete state until the retry is successful.
[0011] In at least one embodiment of this disclosure, the step of creating a task context in response to a task processing request sent by a client includes: in response to a server push event connection request initiated by the client, establishing a long connection for the server push event and generating the corresponding communication interface; instantiating the task context in the memory of the server; storing the communication interface in the task context; and initializing the state set and storing it in the task context.
[0012] In at least one embodiment of this disclosure, sending a task completion notification to the client through the communication interface includes: in response to the business thread determining that the target processing operation has been completed, sending the task completion notification to the client through the business thread by calling the communication interface; after sending the task completion notification, updating the task completion status to a completed status through the business thread, so that the heartbeat thread stops sending heartbeat signals when it reads the task completion status as completed in the next detection cycle.
[0013] In at least one embodiment of this disclosure, the access thread is a thread in the server used to handle client connection requests; the step of submitting the task context to the business thread to execute the target processing operation and releasing the access thread includes: submitting an asynchronous task to the business thread through the access thread, the asynchronous task carrying a reference to the task context; the access thread returning immediately after submitting the asynchronous task to release the access thread to handle other client connection requests.
[0014] According to a second aspect of this disclosure, an electronic device is provided, comprising: a memory storing execution instructions; and a processor executing the execution instructions stored in the memory, such that the processor performs the method described in the first aspect of any embodiment of this disclosure.
[0015] According to a third aspect of this disclosure, a readable storage medium is provided, wherein executable instructions are stored therein, which, when executed by a processor, are used to implement the method described in the first aspect of any embodiment of this disclosure.
[0016] According to a fourth aspect of this disclosure, a computer program product is provided, including a computer program that, when executed by a processor, implements the method described in the first aspect of any embodiment of this disclosure. Attached Figure Description
[0017] The accompanying drawings illustrate exemplary embodiments of the present disclosure and, together with the description thereof, serve to explain the principles of the present disclosure. These drawings are included to provide a further understanding of the present disclosure and are incorporated in and constitute a part of this specification.
[0018] Figure 1 This is a flowchart illustrating the task processing method provided in an embodiment of the present disclosure.
[0019] Figure 2 This is a schematic diagram of a context-based reasoning method provided in an embodiment of the present disclosure.
[0020] Figure 3 This is a flowchart illustrating the heartbeat cycle cancellation method provided in an embodiment of the present disclosure.
[0021] Figure 4 This is a flowchart illustrating the target processing operation provided in the embodiments of this disclosure.
[0022] Figure 5 This is a flowchart illustrating the task context creation method provided in an embodiment of the present disclosure.
[0023] Figure 6 This is a flowchart illustrating the task completion notification sending method provided in an embodiment of the present disclosure.
[0024] Figure 7 This is a flowchart illustrating the access thread usage method provided in an embodiment of this disclosure.
[0025] Figure 8 This is a schematic block diagram of a task processing apparatus according to one embodiment of the present disclosure.
[0026] Figure 9 This is a schematic block diagram of an electronic device according to one embodiment of the present disclosure. Detailed Implementation
[0027] The present disclosure will now be described in further detail with reference to the accompanying drawings and examples. It should be understood that the specific examples described herein are for illustrative purposes only and are not intended to limit the scope of the disclosure. Furthermore, it should be noted that, for ease of description, only the parts relevant to the present disclosure are shown in the accompanying drawings.
[0028] It should be noted that, where there is no conflict, the embodiments and features described in this disclosure can be combined with each other. The technical solutions of this disclosure will now be described in detail with reference to the accompanying drawings and embodiments.
[0029] Figure 1 This is a flowchart illustrating the task processing method provided in an embodiment of this disclosure. Figure 1The method shown includes steps S101 to S106. This method can be applied to a server containing an access thread pool, a business thread pool, and a timed thread pool. Server-Sent Events (SSE) is a long-connection communication technology based on the HTTP protocol, allowing the server to proactively push data to the client. In this application, it is used to implement real-time data push during AI task processing.
[0030] Specifically, Figure 1 The method shown includes step S101: in response to a task processing request sent by a client, a task context is created; wherein the task context includes a communication interface for server push events and a set of states used to characterize the task execution state.
[0031] It should be noted that the task context mentioned here refers to a data structure object created in the server's memory, used to hold the data and communication resources needed for a single task processing request throughout its entire lifecycle. Specifically, it includes the communication interface for the server push event connection and a set of states representing the task's execution status. The communication interface refers to the physical channel object corresponding to the SSE long connection, such as SseEmitter. The business thread can push data to the client by calling methods of this communication interface. The state set refers to a set of state variables defined in the task context to represent the task's execution progress. In this application, the state set includes state variables in five dimensions: task completion status, task failure status, task interruption status, inference in progress status, and inference completion status.
[0032] In practical applications, after the server receives an SSE connection establishment request from the client, it establishes an SSE long-lived connection and generates the corresponding communication interface. Simultaneously, the server's access thread instantiates a task context object in the server's memory (e.g., JVM heap memory) and stores the generated communication interface within this task context object. At the same time, it initializes all state variables in the state set to their default states. For example, the task completion state is initialized to "incomplete" to indicate that the target processing operation has not yet been completed.
[0033] Typically, SSE connections are managed by the network layer, while task states are managed by the business layer. These two layers are isolated and usually require external storage such as Redis for state synchronization. This solution encapsulates the communication interface and state set within the same task context during the task creation phase, creating a symbiotic relationship between the two at the architectural level. This task context acts as a single data source, carrying all the data that needs to be shared in subsequent processes—including the communication capabilities required to push data downstream (the aforementioned communication interface) and the control information needed for the heartbeat thread to query and the execution thread to update (the aforementioned state set). This allows business threads to obtain both communication and state management capabilities simultaneously without relying on external storage when executing tasks.
[0034] Step S102: Submit the task context to the business thread to perform the target processing operation, and release the access thread.
[0035] It should be noted that the access thread mentioned earlier refers to the thread in the server used to receive and process client connection requests. It runs in the IO thread pool of the server's web container and is responsible for creating task contexts and submitting tasks to the business thread. The business thread mentioned earlier refers to the thread used to execute target processing operations, which runs in a separate business thread pool on the server. Target processing operations include at least one or more of the following: AI model inference operations, tool invocation operations, and content generation operations.
[0036] Specifically, the access thread submits an asynchronous task to the business thread pool. This asynchronous task carries a reference to the task context, which is the address of the task context in the server's memory. The access thread returns immediately after submitting the asynchronous task and is then released into the web container's IO thread pool to prepare for handling connection requests from other clients.
[0037] It should be noted that if the access thread is not released immediately, it will be occupied for a long time. Since the number of IO threads in the web container is limited, connection requests from other clients will not be processed in a timely manner, leading to a sharp drop in server throughput and even triggering connection timeouts. Therefore, this application passes the task context as a parameter to the business thread in the asynchronous task, allowing the access thread to be released immediately after the task is submitted. Long-running operations such as AI inference are executed entirely in an independent business thread pool, without consuming the limited IO thread resources of the web container.
[0038] By passing the task context as a parameter to the business thread in an asynchronous task, the access thread can be released after submitting the task. AI inference is executed in a separate business thread pool, without consuming the web container's IO thread resources, thus ensuring that the server can continuously receive and process new client requests. Furthermore, since the task context is an object created in heap memory, it remains in heap memory even after the access thread releases it. Business threads can still access this object through their held references; therefore, the task context is not destroyed by the access thread's release.
[0039] Step S103: Push intermediate execution results to the client and update the status set by calling the communication interface in the task context through the business thread.
[0040] After obtaining the task context, the business thread executes the target processing operation. During execution, the business thread calls the communication interface in the task context to push intermediate execution results to the client and updates the status set according to the execution progress.
[0041] Specifically, the business thread first obtains a communication interface instance from the task context. This communication interface instance was stored in the task context by the access thread during the task creation phase. The business thread pushes content fragments generated step by step by the AI model to the client by calling the send method of this communication interface. For example, the AI model returns generated words or sentences one by one in a streaming manner. Each time the business thread receives a content fragment, it calls the send method of the communication interface to send the fragment to the client. The client displays each fragment immediately upon receiving it, achieving a typewriter-like step-by-step presentation. At the same time, the business thread synchronously updates the state set in the task context according to the current execution progress. For example, when the AI model's API is first called, the business thread updates the inference progress status in the state set from "not in progress" to "in progress"; when the AI model's API is called and the first returned content fragment is received, the inference completion status is updated from "not completed" to "completed".
[0042] In the above process, business threads simultaneously execute data push and status update within the same task context. The update of the state set and data push are executed sequentially by the same business thread, thus eliminating thread contention between data push and status update. This ensures that the state values in the state set accurately reflect the progress of the pushed data, meaning the state set remains synchronized with the output of the communication interface.
[0043] Step S104: Periodically read the task completion status in the status set through the heartbeat thread. If the task completion status indicates that the target processing operation is not completed, then send a heartbeat signal.
[0044] While the business thread performs target processing operations, the heartbeat thread reads the task completion status from the task context at fixed intervals (e.g., every 5 seconds). The heartbeat thread is a timed scheduling thread that runs independently of the business thread and is triggered by the server's timed thread pool according to a preset period.
[0045] Each time the heartbeat is triggered, the heartbeat thread reads the current value of the task completion status variable from the task context. If the value is "incomplete," it means the target processing operation is still in progress. The heartbeat thread then calls the communication interface in the task context to send a heartbeat signal, such as sending a comment line of the SSE protocol (e.g., ":ping"). The purpose of this heartbeat signal is to ensure data transmission over the SSE long-lived connection, maintaining the active state of the TCP connection and preventing the connection from being timed out by intermediate network devices (such as firewalls, load balancers, or proxy servers) due to prolonged lack of data exchange.
[0046] Step S105: If the task completion status indicates that the target processing operation has been completed, then stop sending heartbeat signals.
[0047] If the value is "Completed", it means that the target processing operation has been completed, and the heartbeat thread will no longer send heartbeat signals. After reading "Completed", the heartbeat thread will stop sending heartbeat signals in subsequent cycles.
[0048] Because the heartbeat thread and the business thread share the same task context, the heartbeat thread can directly access the task completion status variable in the heap memory to determine whether the task has been completed, without needing to obtain status information through external storage such as Redis or inter-process communication (IPC) mechanisms. This eliminates the overhead of network I / O or IPC, reducing the latency of heartbeat decisions to the nanosecond level (i.e., the time taken for a single memory read operation). Furthermore, when the business thread updates the task completion status, it uses lock-free atomic operations (such as the `compareAndSet` method of `AtomicBoolean`), ensuring the atomicity of the status update and its visibility to the heartbeat thread. This means that the heartbeat thread will always read the latest value in the next detection cycle, and will not read an old value.
[0049] Step S106: Send a task completion notification to the client via the communication interface.
[0050] When the business thread calls the AI model's API and receives a returned end flag, it determines that the target processing operation has been completed. This end flag is a specific signal returned by the AI model API after all streaming output is complete, used to inform the caller that the output stream has ended. After receiving this end flag, the business thread calls the `send` method of the communication interface in the task context to send a task completion notification to the client. This task completion notification informs the client that the entire task processing flow has been completed, and the client can use this notification to close the SSE connection or enter the next state.
[0051] After sending the task completion notification, the business thread updates the task completion status to "Completed". The heartbeat thread reads this status at the next timed trigger and then stops sending heartbeat signals.
[0052] By having the business thread send the completion notification before updating the status, the sending of the completion notification is unaffected by the heartbeat cycle. The business thread sends the notification immediately upon confirming task completion, ensuring the client receives it instantly. Meanwhile, the heartbeat thread stops beating when it reads "completed" in the next detection cycle, by which time the completion notification has already been sent, and the two processes operate independently.
[0053] Based on the publicly available solutions described above, by creating a task context that includes an SSE communication interface and a state set, architectural decoupling is achieved among the access thread, business thread, and heartbeat thread. Furthermore, releasing the access thread solves the problem of server connection resource exhaustion under high concurrency; the business thread pushes intermediate results in real time based on SSE, resolving the issue of clients being unable to obtain real-time progress; and the heartbeat thread independently maintains connection keep-alive based on the state set, resolving the problem of connection timeouts and disconnections for long-running tasks. This solution ensures efficient execution of long-running tasks while providing a highly reliable, low-latency real-time feedback mechanism, effectively improving the overall system stability and user experience.
[0054] In one or more embodiments of this disclosure, the state set includes at least one of the following state variables: task completion state variable, task failure state variable, task interruption state variable, inference in progress state variable, and inference completion state variable.
[0055] It should be noted that in practical applications, users can adjust the types and number of states in the state set according to their actual needs. This is only an example and does not constitute a limitation on the technical solution of this application.
[0056] The task completion status variable indicates whether the entire task lifecycle has completely ended, and its value is either completed or not completed. The task failure status variable indicates whether the target processing operation was terminated due to an unrecoverable exception, and its value can be either failed or not failed. The task interruption status variable indicates whether the target processing operation was actively interrupted by an external instruction (e.g., manual cancellation by the user or client disconnection), and its value can be either interrupted or not interrupted. The inference in progress status variable indicates whether the AI model is currently outputting inference results, and its value can be either in progress or not progressing. The inference completion status variable indicates whether the AI model's output stream has ended, and its value can be either completed or not completed.
[0057] It's important to note that the "In-Process" and "Completed" state variables mentioned here only describe the state of the AI model during the inference phase, while the "Completed" state variable describes the final state of the entire task processing flow (including preprocessing, inference, and cleanup). The "In-Process" state variable indicates whether the AI model is currently outputting content, meaning it's in progress within the duration of the output stream; the "Completed" state variable indicates whether the output stream has ended, meaning whether an end marker has been received. When the "In-Process" state variable is in progress, the "Completed" state variable is not completed; when the "Completed" state variable is completed, the "In-Process" state variable is not in progress. There is a sequential relationship between the two.
[0058] Based on the above-mentioned publicly available solutions, adopting and maintaining this multi-dimensional state set enables the system to have the ability to finely manage the life cycle of complex tasks, and can effectively solve the problems of being unable to accurately judge the actual operation of tasks and being unable to reclaim abnormal task resources in a timely manner due to the single state representation.
[0059] In one or more embodiments of this disclosure, such as Figure 2 This is a schematic flowchart illustrating a context-based reasoning method provided in an embodiment of this disclosure. Figure 2As shown, the process of pushing intermediate execution results to the client and updating the state set by calling the communication interface in the task context through the business thread includes: Step S201: In response to calling the application programming interface (API) of the artificial intelligence model, the inference operation is determined to begin. Step S202: The inference process state variable is switched to the in progress state through a lock-free atomic operation, and the inference start time is recorded. Step S203: In response to reading the first data block from the response stream of the artificial intelligence model, the first inference result is determined to be obtained. Step S204: The inference completion state variable is switched to the completed state through a lock-free atomic operation, and the arrival time of the first result is recorded. Step S205: In response to receiving the inference end flag returned by the artificial intelligence model, the inference operation is determined to end. Step S206: The inference process state variable is switched to the inactive state through a lock-free atomic operation, and the inference end time is recorded.
[0060] The business thread holds a reference to the task context, allowing it to determine the start of the inference operation simultaneously with initiating the API call—that is, when the method call statement for that API is executed. Specifically, during the execution of the target processing operation, before or simultaneously with the execution of the statement calling the AI model API, the business thread obtains the current system time and records this time as the inference start time in the task context's timing field. Since this timestamp acquisition and the API call operation occur within the same execution sequence of the same thread, without thread switching or operating system scheduling delays, the recorded timestamp accurately reflects the start time of the inference operation.
[0061] If the business thread fails to call the AI model API (e.g., due to network timeout or API server error throwing an exception), the business thread will be unable to proceed to the subsequent inference result receiving stage. In this case, the business thread does not switch the inference progress status variable to the in progress state, but instead updates the task failure status variable to the failure state and the task completion status variable to the completed state. Simultaneously, it sends an error notification to the client through the communication interface, and the process terminates.
[0062] Furthermore, after determining that the inference operation has begun, the business thread switches the inference-in-progress state variable in the task context from the "not in progress" state to the "in progress" state. In one specific implementation, the inference-in-progress state variable is implemented using atomic variables (e.g., `AtomicBoolean`), and its switching is implemented using lock-free atomic operations. Lock-free atomic operations refer to synchronization operations that do not rely on the `synchronized` keyword or explicit locks (such as `ReentrantLock`), but directly utilize the compare-and-swap instructions provided by the underlying processor to complete the read, modify, and write operations of variables. During execution, they are not interrupted by the thread scheduling mechanism and possess atomicity.
[0063] AI models' application programming interfaces (APIs) typically support a streaming response model. In this model, the AI model doesn't wait for all inference to complete before returning a result; instead, it progressively returns generated content fragments to the caller via a response stream during the inference process. For the business thread, this response stream is a data stream object. The business thread retrieves data blocks one by one by repeatedly calling the data stream object's read methods (e.g., `read` or `next`). When the read method is called for the first time and a non-empty data block is successfully retrieved, the business thread can determine that it has obtained the first inference result. The moment the read method returns the first data block is the arrival time of the first result.
[0064] If the business thread fails to return any data block within the preset timeout period after calling the AI model API, the business thread determines that a timeout exception has occurred. In this case, the business thread does not switch the inference progress status variable or the inference completion status variable. Instead, it updates the task failure status variable to a failed state and the task completion status variable to a completed state. Simultaneously, it sends a timeout error notification to the client via the communication interface, and the process terminates.
[0065] Furthermore, after obtaining the first inference result, the business thread switches the inference completion state variable from the incomplete state to the completed state and records the arrival time of the first result. Similar to the state variable switching during inference mentioned above, this switching is also implemented using lock-free atomic operations.
[0066] When the reasoning completion state variable is "completed," the reasoning progress state variable should be "in progress." After reasoning ends (i.e., the end flag is received), the reasoning progress state variable switches back to "not in progress." During reasoning, the business thread needs to perform switching operations on the two atomic variables sequentially. If a locking mechanism is used, the two switching operations must be performed under the protection of the same lock to ensure the order, further increasing the lock holding time and contention probability. Lock-free atomic operations allow the two switching operations to complete independently without blocking each other, effectively solving the above problems.
[0067] Furthermore, in streaming response mode, the AI model's application programming interface (API) returns a specific formatted end marker at the end of the response stream after all inference results have been returned. This end marker is a special data frame or control signal defined in the AI model API protocol; for example, in the SSE protocol, this end marker could be an event of type [DONE]. During the loop reading of the response stream, the business thread can determine the end of the inference operation when the content of the read data block or event matches the format of the end marker.
[0068] If, during the inference process (i.e., the stage where the API call has begun but the end flag has not yet been received), the response stream is abnormally closed due to a network interruption or API server malfunction, the business thread will not be able to receive the end flag normally. In this case, the business thread will determine the captured exception as an unrecoverable exception, update the task failure status variable to failure, update the task completion status variable to completion, and send an error notification to the client through the communication interface, thus terminating the process.
[0069] Furthermore, after determining that the inference operation has ended, the business thread switches the inference progress status variable from the in-progress state to the non-progress state and records the inference end time. This switch is also implemented using a lock-free atomic operation.
[0070] Based on the above solution, by designing independent inference state variables and inference completion state variables for AI model inference scenarios, and employing lock-free atomic operations for state transitions throughout the process, the problems of low state synchronization efficiency, high lock overhead, and inaccurate monitoring of key inference nodes can be effectively solved when processing large-scale streaming inference tasks. Because lock-free atomic operations are used, conflict-free collaborative work between business threads and heartbeat threads can be achieved in high-concurrency, long-connection environments. This maximizes the server's concurrent processing capacity while ensuring thread safety, and enables precise quantitative monitoring of key indicators such as the latency of the first character in model inference.
[0071] In one or more embodiments of this disclosure, the method further includes: calculating cost measurement data based on the inference start time, the first result arrival time, and the inference end time; wherein the cost measurement data includes at least one of the total inference time, the first result delay time, and the inference generation stage time.
[0072] It should be noted that the cost measurement data mentioned here refers to numerical indicators used to quantitatively evaluate the time resources consumed and response performance of the artificial intelligence model during inference operations. The first result latency refers to the time from the start of the API call until the first data block in the response stream is successfully read; this indicator reflects the waiting time required for the model to process input data and generate initial output. The inference generation phase time is the difference between the inference end time and the first result arrival time, representing the time consumed from the business thread obtaining the first data block until the inference end flag is received.
[0073] In the existing architecture, SSE connections are managed by a network thread, while AI inference is executed by a business thread; the two are separate processes. That is, the SSE network thread is only responsible for sending data to the client, and the data it sends is a continuous byte stream. This byte stream itself does not distinguish semantic boundaries such as the start of inference, the first token, and the end of inference. Therefore, the network thread does not know which stage of inference the currently sent bytes belong to, and cannot identify when the first token arrives. While the business thread knows when inference starts and when the first token arrives, it does not hold the SSE communication interface and cannot associate boundary information with SSE push events. Therefore, existing technologies can only count the total connection open time on the network thread side, or the time from sending a request to receiving the first character on the client side. These statistics include factors such as network transmission latency and thread scheduling latency, and cannot accurately reflect the actual time consumed at each stage of server-side AI inference, let alone accurately calculate costs.
[0074] This application adopts an architecture based on the SSE communication interface and task execution state. In this architecture, the business thread holds the task context, which contains the SSE communication interface and state set. Therefore, when performing AI inference operations, the business thread is both the executor of the inference operation and the trigger of SSE push. When the business thread calls the AI model's API, reads the first data block from the response stream, and receives the inference end flag, it can simultaneously perceive the occurrence of the event and obtain the system timestamp. Because these three events all occur in the execution sequence of the business thread, the business thread can record the time point at the same moment the event occurs, without waiting for network thread notification or active polling by the business thread.
[0075] Specifically, this application achieves accurate event-driven identification of reasoning boundaries through the following mechanism: Phase 1: Identification and Time Recording of the Inference Start Event. During the execution of target processing operations, the business thread executes a statement that calls the AI model API. This API call is actively executed by the business thread. Simultaneously, the business thread acquires a system timestamp as the inference start time. Because the timestamp acquisition operation and the API call are executed consecutively within the same execution sequence of the same thread, there is no thread switching or operating system scheduling delay between them. Therefore, the recorded time point is the true start time of the inference operation.
[0076] Phase Two: Identification and Timing of the First Token Arrival Event. The AI model's API returns inference results in a streaming response mode. The business thread retrieves data blocks by repeatedly calling the read method of the response stream object. When the business thread successfully retrieves a non-empty data block on its first call to the read method, this data block becomes the first inference result fragment, i.e., the first Token. At the same moment the business thread retrieves this data block, it obtains the system timestamp, which serves as the arrival time of the first result. Since the data block retrieval and timestamp recording are executed consecutively within the same execution sequence of the same thread, there is no thread switching or scheduling delay between them.
[0077] Phase 3: Identification and Time Recording of Inference End Events. After the AI model's API finishes streaming, it returns a specific formatted end marker at the end of the response stream. During the loop of calling the response stream reading method, the business thread can identify the inference end event when the content of the read data block matches the format of the end marker. At the same moment this identification occurs, the business thread obtains the system timestamp as the inference end time.
[0078] All three stages described above are identified and recorded in real time by the business thread during the execution of AI model API calls and response stream reading. The business thread does not need to poll to check the status or wait for notifications from other threads. Event recognition is event-driven; the business thread perceives the event as soon as it occurs and records a timestamp upon perception.
[0079] Furthermore, based on the three boundary time points mentioned above, the following cost measurement data can be obtained through subtraction: Total inference time = Inference end time - Inference start time. This value represents the total time from calling the AI model API to the complete completion of inference, and is used for cost accounting.
[0080] First result latency = First result arrival time - Inference start time. This value represents the time from calling the API to receiving the first result fragment, and is used to evaluate the first packet response performance of the AI model.
[0081] The time taken for the inference generation phase = inference end time - first result arrival time. This value represents the time from the arrival of the first token to the completion of all content generation, and is used to evaluate the stable output throughput of the AI model.
[0082] After calculating the three basic cost measurement data mentioned above, if there are outliers in the original statistical data due to network jitter, retries, or anomalies, this application can also use a correction algorithm to remove or correct these outliers. The correction algorithm can be implemented by statistically analyzing the cost measurement data from multiple inferences. If the total inference time or the delay time of the first result in a certain inference exceeds a preset multiple of the historical average (e.g., 3 times the standard deviation), then that data is marked as an outlier and removed during billing or calculated according to the corrected value. Through the correction algorithm, occasional billing deviations caused by network jitter or model server anomalies can be filtered out, making the cost measurement results more stable and accurate.
[0083] Based on the publicly available solutions described above, by integrating the SSE communication interface with the task execution state into the same task context, the business thread can record boundary times immediately upon event occurrence, effectively addressing the issue of insufficient boundary recognition accuracy. The provided measurement results accurately reflect the actual computational resource consumption of the AI model, providing a reliable data foundation for pay-as-you-go billing. Especially for AI services employing streaming responses, the initial result latency and inference generation phase time correspond to different resource consumption types on the model server, thereby achieving more precise cost measurement.
[0084] In one or more embodiments of this disclosure. For example... Figure 3 This is a flowchart illustrating the heartbeat cycle cancellation method provided in an embodiment of this disclosure. Figure 3 As shown, before periodically reading the task completion status from the status set via the heartbeat thread, the process includes: Step S301: Pre-submitting the heartbeat periodic task to the timed thread pool and storing the task handle of the heartbeat periodic task in the task context. If the task completion status indicates that the target processing operation has been completed, then the heartbeat signal is stopped, including: Step S302: If the task completion status indicates that the target processing operation has been completed, then obtaining the task handle from the task context through the business thread. Step S303: Sending a cancellation request carrying the task handle to the timed thread to cancel the heartbeat periodic task submitted in the timed thread pool.
[0085] It should be noted that the heartbeat thread reads the task completion status in the task context at fixed intervals and determines whether to send a heartbeat signal based on the value of this status. In this application, the periodic execution of the heartbeat thread relies on the scheduling mechanism of a timed thread pool. The timed thread pool is a type of thread pool in the server whose core function is to trigger the execution of tasks submitted to it at preset time intervals (e.g., every 5 seconds). A business thread or access thread submits a heartbeat periodic task to the timed thread pool, specifying a fixed time interval. The timed thread pool periodically calls the task's execution method according to this interval, thereby triggering the heartbeat thread execution. When the timed thread pool receives a task submission request, it allocates a task handle for the task and returns it to the submitter. This task handle is the task identifier (e.g., a ScheduledFuture object) in the timed thread pool. Through this task handle, the submitter can send a cancellation request to the timed thread pool to cancel the subsequent execution of the task.
[0086] After creating a task context, the access thread submits a heartbeat periodic task to the timed thread pool, specifying the task's execution cycle (e.g., triggering every 5 seconds). Upon receiving the submission request, the timed thread pool allocates a unique task handle for the heartbeat periodic task and returns it to the access thread. The access thread then stores the task handle in the task context, thus completing the registration of the heartbeat periodic task.
[0087] It's important to note that the reason task handles are stored in the task context rather than in global variables or a cache is that in SSE long-connection scenarios, the same server may handle multiple client connections simultaneously, each corresponding to a different task processing request. Therefore, each request requires an independent heartbeat cycle task. If the task handle were stored in a global variable, task handles from multiple connections would be overwritten, making it impossible to accurately cancel the heartbeat task for a specific connection. Furthermore, the task context is uniquely bound to a single task processing request. Storing the task handle in the task context encapsulates the task handle and other related data for that request (such as communication interfaces and state sets) within the same data structure. Business threads only need to hold a reference to the task context to access the task handle, without needing additional lookups or passing.
[0088] After a heartbeat periodic task is submitted to the timed thread pool, the timed thread pool starts the heartbeat thread according to a preset period. The heartbeat thread begins to periodically read the task completion status from the task context. This reading operation is synchronized with the execution of the heartbeat periodic task. Each time a heartbeat periodic task is triggered, the heartbeat thread performs a read and a decision.
[0089] After the business thread completes the target processing operation and sends the task completion notification, the business thread needs to cancel the heartbeat periodic task in order to release the scheduling resources of the timed thread pool.
[0090] Specifically, after sending a task completion notification and updating the task completion status to "completed," the business thread retrieves a pre-stored task handle from the task context. Since the task handle is stored in the task context when the access thread creates it, the business thread can access the task handle through the held task context reference. After obtaining the task handle, the business thread sends a cancellation request to the timed thread pool, carrying the task handle in the request. Upon receiving the cancellation request with the task handle, the timed thread pool searches for the corresponding heartbeat periodic task in the scheduling queue based on the task handle, marks the task as cancelled, and removes it from the timed scheduling queue. Once the task is marked as cancelled, the timed thread pool no longer triggers the subsequent execution of the task, and the heartbeat thread is no longer periodically woken up.
[0091] It should be noted that the cancellation request mentioned above is sent by the business thread, not by the heartbeat thread itself. The business thread actively performs the cancellation action after determining that the target processing operation has been completed and updating the task completion status to "completed." This application chooses for the business thread to actively cancel because after sending the task completion notification and updating the task completion status, the business thread has already determined that the entire task processing flow has ended. Canceling the heartbeat cycle task is a cleanup task after the task ends; having the business thread complete this process centralizes the cleanup logic, and the business thread can immediately execute the cancellation without waiting for the next trigger cycle from the heartbeat thread, resulting in higher real-time performance.
[0092] This application stores the task handle in the task context and allows the business thread to actively send a cancellation request to the timed thread pool upon task completion. This ensures that heartbeat periodic tasks are cancelled at the same moment they are completed, preventing completed heartbeat periodic tasks from continuing to occupy timed thread pool resources. Furthermore, the cancellation operation for heartbeat periodic tasks is actively triggered by the business thread, and the cancellation time is not limited by the heartbeat cycle (e.g., 5 seconds). The cancellation action can be completed within milliseconds after task completion, ensuring timely release of timed thread pool resources.
[0093] Based on the publicly available solutions described above, this solution manages the heartbeat periodic task by hosting it in a timed thread pool and storing the task handle in a shared task context. This allows the business thread to proactively and precisely remove the heartbeat periodic task from the timed thread pool the instant the task is completed by sending a cancellation request carrying the task handle. Because of this cross-thread proactive cancellation mechanism based on task handles, subsequent heartbeat signal transmission can be blocked immediately upon task completion. This effectively solves the time window problem caused by passive polling in existing technologies, avoids system anomalies caused by sending signals to closed communication interfaces, and ensures the timely release of resources scheduled by the timed thread pool. This significantly improves the accuracy and stability of system resource management in high-concurrency scenarios.
[0094] In one or more embodiments of this disclosure, such as Figure 4 This is a flowchart illustrating the target processing operation provided in an embodiment of this disclosure. Figure 4 As shown, the target processing operation includes a preprocessing stage and a processing stage, and further includes: Step S401: When an exception occurs in the preprocessing stage, the task failure status variable is updated to a failure status, the task completion status variable is updated to a completed status, and a first error notification is sent to the client through the communication interface. Step S402: When a retryable exception occurs in the processing stage, a second error notification is sent to the client through the communication interface and a retry operation is performed, and the task completion status variable is kept in an incomplete state until the retry is successful.
[0095] It should be noted that the preprocessing stage mentioned here refers to the preparatory work performed before the core computing logic is executed, such as parameter parsing, data verification, environment initialization, or authentication. The processing stage refers to the stage of executing the core computing logic (such as calling an artificial intelligence model for inference calculations).
[0096] In practical applications, the business thread performs various validation operations during the preprocessing phase. If any validation operation fails during this phase (e.g., empty user input, failed user permission validation, insufficient system resources), the business thread determines that an exception has occurred in the preprocessing phase. This exception is an unrecoverable exception because even if the target processing operation is re-executed, the validation operation will still fail due to the same request content or the same system state.
[0097] In response to an exception occurring during the preprocessing phase, the business thread performs the following operations: First, it updates the task failure status variable in the task context to a failure status. The task failure status variable is used to indicate whether the target processing operation was terminated due to an unrecoverable exception, and its value is either failure or not failure. When an unrecoverable exception occurs during the preprocessing phase, the business thread updates this variable from a not failure status to a failure status to record that the task was terminated due to an exception.
[0098] Simultaneously, the task completion status variable in the task context is updated to "completed". The task completion status variable indicates whether the entire task's lifecycle has ended, and its value is either "completed" or "not completed". When an unrecoverable exception occurs during the preprocessing stage, the business thread determines that the target processing operation has terminated and cannot continue execution, therefore updating the variable from "not completed" to "completed". This update action causes the heartbeat thread to stop sending heartbeat signals when it reads the task completion status as "completed" in the next detection cycle.
[0099] Furthermore, a first error notification is sent to the client via the communication interface in the task context. The first error notification is a data message indicating an error occurred during the client's preprocessing phase. Its content includes at least the error type (e.g., "parameter validation failed," "insufficient permissions," or "insufficient system resources") and the stage at which the error occurred (i.e., the preprocessing phase). The business thread calls the data sending method (e.g., the `send` method) of the communication interface to push this first error notification to the client. After receiving the first error notification, the client can display the specific reason for the error on the interface, allowing the user to correct the request or contact the system administrator.
[0100] After the above operations are completed, the target processing operation will no longer enter the processing stage. That is, the business thread will not call the AI model application programming interface, nor will it execute subsequent inference operations and response stream reading operations, and the task processing flow will terminate.
[0101] If no exceptions occur during the preprocessing stage, meaning all verification operations pass, the business thread enters the processing stage and calls the AI model application programming interface to perform inference operations.
[0102] Furthermore, during the inference operations performed by the business thread in the processing phase, retryable exceptions may occur. Retryable exceptions refer to temporary exceptions caused by network fluctuations, temporary server overload, or other reasons; these exceptions may succeed after a retry. If a business thread calls the AI model API and the API call throws an exception of the above type, or if such an exception is caught during the response stream reading process, then a retryable exception has occurred in the processing phase.
[0103] It should be noted that unrecoverable exceptions may also occur during the processing phase. For unrecoverable exceptions during the processing phase, this application can adopt the same handling method as for exceptions in the preprocessing phase, that is, update the task failure status variable to the failure status, update the task completion status variable to the completed status, and send the corresponding error notification to the client through the communication interface.
[0104] In response to a retryable exception occurring during the processing phase, the business thread performs the following operations: First, a second error notification is sent to the client via the communication interface in the task context. This second error notification is a data message indicating a retryable error occurred during the client's processing phase. Its content includes at least the error type (e.g., "network connection timeout," "server busy," or "connection interrupted"), the stage at which the error occurred (i.e., the processing phase), and a message indicating that the system is performing a retry operation. The business thread calls the data sending method of the communication interface to push this second error notification to the client. Upon receiving this second error notification, the client knows that the system is automatically retrying, preventing the user from mistakenly believing the system has crashed due to a prolonged lack of response.
[0105] Then, the business thread performs retry operations. Retry operations refer to the business thread re-executing the operations of the processing phase, i.e., re-calling the AI model's application programming interface, re-reading data from the response stream, until the inference end flag is received. Retry operations can employ a backoff retry strategy, where the waiting time for each retry increases progressively. For example, the first retry waits 1 second, the second 2 seconds, and the third 4 seconds, to avoid increasing server load due to frequent retries when the server is busy. A maximum retry threshold (e.g., 3 times) can be preset for the number of retry operations. If the retry count fails after reaching this threshold, no further retries are made, and the business thread will determine that the exception has been escalated to an unrecoverable exception and handle it in the same way as exceptions in the preprocessing phase.
[0106] Before a successful retry, the business thread keeps the task completion status variable in the task context in an incomplete state. That is, the business thread does not update the task completion status variable to complete.
[0107] Even if a retryable exception occurs during the processing phase, as long as the business thread is still performing the retry operation, the heartbeat thread will still read the value "incomplete" when periodically checking the task completion status. Therefore, the heartbeat thread continues to send heartbeat signals to maintain the active state of the SSE long connection. If the business thread updates the task completion status variable to "completed" during the retry process, the heartbeat thread will stop sending heartbeat signals. However, since the retry operation has not yet succeeded, the SSE long connection may time out and disconnect due to the lack of heartbeat signals, resulting in the inability to push the result to the client after the retry is completed. By keeping the task completion status as "incomplete" until the retry is successful, the SSE long connection is ensured to remain active throughout the retry process, preserving a communication channel for pushing the result after the retry is successful.
[0108] If the retry operation succeeds (i.e., the business thread successfully receives the inference end flag during the retry process), the business thread will follow the normal procedure, sending a task completion notification to the client via the communication interface and updating the task completion status variable to the completed state. If the retry operation fails after reaching the maximum number of retries, the business thread will escalate the exception to an unrecoverable exception, update the task failure status variable to the failure state, update the task completion status variable to the completed state, and send the corresponding error notification to the client via the communication interface.
[0109] Based on the publicly available solutions, two distinct state control strategies are implemented by finely distinguishing between preprocessing stage anomalies and retryable anomalies in the processing stage. The technical feature of simultaneously setting the task failure and completion status variables when a preprocessing anomaly occurs allows for the immediate termination of ineffective resource consumption such as heartbeats in the event of an unrecoverable error, enabling rapid recovery of system resources. Simultaneously, the technical feature of maintaining the task completion status variable as incomplete and sending a second error notification when a retryable anomaly occurs in the processing stage ensures that the long-lived communication interface connection remains open during transient failures, keeping the network channel alive for background retry operations. This significantly improves the resilience and ultimate success rate of long-running tasks in complex network environments.
[0110] In one or more embodiments of this disclosure, such as Figure 5 This is a flowchart illustrating the task context creation method provided in an embodiment of this disclosure. Figure 5 As shown, in response to a task processing request sent by the client, a task context is created, including: Step S501: In response to a server push event connection request initiated by the client, a long connection for the server push event is established and a corresponding communication interface is generated. Step S502: The task context is instantiated in the server's memory. Step S503: The communication interface is stored in the task context. Step S504: The state set is initialized and then stored in the task context.
[0111] It should be noted that the server push event connection request mentioned here refers to a handshake request initiated by the client to the server, aimed at establishing a persistent network communication channel based on the server push event protocol. The server push event long connection mentioned here refers to a data transmission channel established between the client and the server that remains open on the basis of the HTTP protocol, avoiding the overhead of repeatedly establishing connections. Instantiation refers to the process of allocating storage resources in the server's memory space and creating specific objects according to a predefined data structure template. Initialization refers to the process of assigning default initial values to the various variables in the newly created data structure.
[0112] The client sends a server push event connection request to the server. This request header informs the server that the client expects to establish a server push event connection. Upon receiving this request, the server confirms that the client supports the server push event protocol and establishes a persistent server push event connection. This persistent connection is based on the Hypertext Transfer Protocol (HTTP). Unlike the traditional HTTP request-response model, this connection is not closed after a single server response but remains open, allowing the server to proactively push data to the client at any time. Simultaneously with establishing the persistent connection, the server generates a corresponding communication interface instance. This communication interface instance is the programmatic representation of the persistent server push event connection on the server side, providing methods for sending data to the client. Each communication interface instance corresponds one-to-one with the aforementioned persistent server push event connection; the server can send data to the client through this persistent connection by calling the methods of this communication interface instance.
[0113] If the server is unable to establish a persistent connection for pushing events due to insufficient resources (such as exceeding the maximum number of connections) or protocol incompatibility, the server will return a connection establishment failure response to the client, the task processing flow will terminate, and subsequent steps will not be executed.
[0114] Then, the task context is instantiated in the server's memory. Server memory refers to the heap memory of the server process, such as the Java Virtual Machine heap memory. Instantiating the task context in the server's memory specifically involves allocating memory space for the task context object in the server's heap memory and calling the task context object's constructor to complete object instantiation. After the task context object is instantiated, its internal fields have memory space allocated, but the field values have not yet been assigned specific data. It's important to note that this task context is instantiated in the server's memory, not created in external storage (such as Redis or a database). Subsequent business threads and heartbeat threads need to frequently read and write the state collection and communication interface in the task context. If the task context were stored in external storage, each read / write operation would require network input / output, resulting in significant latency, which cannot meet the performance requirements of the heartbeat thread's periodic high-frequency reading (e.g., every 5 seconds) and the business thread's real-time state updates. Instantiating the task context in the server's memory allows business threads and heartbeat threads to directly access the task context through memory addresses, reducing read / write latency to the nanosecond level.
[0115] Next, when the business thread performs subsequent target processing operations, it needs to push intermediate and final execution results to the client through this communication interface. A reference to the communication interface instance is assigned to the corresponding field in the task context object. This reference is the address of the communication interface instance in the server's memory. Through this reference, the business thread can obtain the communication interface instance from the task context and call its data sending method.
[0116] If the aforementioned steps of establishing a long connection for server push events and generating a communication interface fail, there will be no communication interface to store, the instantiated task context will not contain a valid reference to the communication interface, the business thread will be unable to push data, and the task processing flow will terminate.
[0117] As mentioned earlier, the state set includes at least one of the following: task completion state variable, task failure state variable, task interruption state variable, inference in progress state variable, and inference completed state variable. Initializing the state set means setting each state variable in the state set to its default state. For example, the task completion state variable is initialized to an incomplete state, the task failure state variable is initialized to a non-failure state, the task interruption state variable is initialized to a non-interruption state, the inference in progress state variable is initialized to an incomplete state, and the inference completed state variable is initialized to an incomplete state. After initialization, the state set is stored in the task context. Specifically, the references to each state variable in the state set are assigned to the corresponding fields in the task context object.
[0118] Before a task begins execution, all state variables in the state set are set to known default values. When the business thread subsequently performs target processing operations, it switches the state variables in the state set from their default states to the target state based on the execution progress. When the heartbeat thread periodically reads the task completion status variable, the value read during task execution is incomplete, and the value read after task completion is complete is complete. If the state set is not initialized when the task is created, the business thread and the heartbeat thread may read indeterminate values on their first read of the state variables. This could cause the heartbeat thread to incorrectly stop sending heartbeat signals before the task has started, or incorrectly continue sending heartbeat signals after the task has been completed.
[0119] Based on the publicly available solutions described above, by pre-establishing a long-lived connection for server push events and generating an abstract communication interface during the request access phase, and then instantiating a task context in memory, the communication interface and the initialized state set are centrally stored in this context. Because of this architectural design that pre-abstracts and encapsulates communication capabilities and state data and injects them into the memory context, a unified, thread-safe shared data carrier can be provided for subsequent access thread release, asynchronous execution of business threads, and independent monitoring by heartbeat threads. This effectively solves the problem of the inability to achieve safe decoupling and collaboration of multiple threads due to the coupling of network handles and business logic and the dispersion of state data.
[0120] In one or more embodiments of this disclosure, such as Figure 6 This is a flowchart illustrating the task completion notification sending method provided in an embodiment of this disclosure. Figure 6 As shown, sending a task completion notification to the client via the communication interface includes: Step S601: In response to the business thread determining that the target processing operation has been completed, the business thread calls the communication interface to send a task completion notification to the client. Step S602: After sending the task completion notification, the business thread updates the task completion status to "completed" so that the heartbeat thread stops sending heartbeat signals when it reads the task completion status as "completed" in the next detection cycle.
[0121] When the business thread calls the send method of the communication interface to send a task completion notification to the client, the send operation of the communication interface may experience some execution time due to factors such as network conditions and the state of the operating system kernel buffer. During the execution of this send operation, the business thread has not yet updated the task completion status to "completed". Therefore, if the heartbeat thread triggers a detection during this period, the task completion status it reads will still be "incomplete", and the heartbeat thread will continue to send heartbeat signals, keeping the SSE long connection active. After the business thread successfully completes the sending of the task completion notification (i.e., the send method of the communication interface returns normally, or the data has been confirmed to have been written to the operating system kernel buffer), the business thread updates the task completion status to "completed". After the heartbeat thread reads the "completed" status in the next detection cycle, it stops sending heartbeat signals.
[0122] By adopting the order of sending notifications first and then updating the state, the process of sending task completion notifications is ensured to be unaffected by changes in the heartbeat thread's behavior. During the completion notification sending process, the heartbeat thread continues to operate normally, and the SSE connection remains active; the heartbeat thread only stops working after the completion notification is sent. If the reverse order were used (updating the state first and then sending notifications), the heartbeat thread might stop heartbeating before the completion of the completion notification after the state update, posing a connection timeout risk; if the completion notification is sent by the heartbeat thread itself, there will be a heartbeat cycle delay.
[0123] Based on the publicly available solutions described above, a secure isolation zone is constructed between state changes and network communication by adopting an execution sequence that sends the task completion notification first and then updates the task completion status. Because of this timing control mechanism, it is possible to ensure that the heartbeat thread maintains a persistent connection during the final task result transmission, effectively resolving the problem of the heartbeat thread misjudging and severing the connection due to premature state changes, thus causing the task completion notification to fail to be sent.
[0124] In one or more embodiments of this disclosure, such as Figure 7 This is a flowchart illustrating the access thread usage method provided in an embodiment of this disclosure. Figure 7 As shown, step S701: The access thread is the thread in the server used to handle client connection requests. Submitting the task context to the business thread to execute the target processing operation and releasing the access thread includes: Step S702: Submitting an asynchronous task to the business thread through the access thread, the asynchronous task carrying a reference to the task context. Step S703: The access thread returns immediately after submitting the asynchronous task to release the access thread from handling other client connection requests.
[0125] First, an asynchronous task is submitted to the business thread via the access thread. This asynchronous task carries a reference to the task context. This asynchronous task refers to a task submission method that does not block the current thread. That is, after submitting the task, the access thread does not wait for the task to complete but immediately returns to continue executing subsequent logic. In this application, the business thread is used to execute target processing operations, which at least include inference operations of the artificial intelligence model.
[0126] The access thread calls the task submission method of the business thread pool, encapsulates the target processing operation into a task object, passes the task context as a parameter to the task object, and then calls the task submission method to submit the task object to the task queue of the business thread pool. The aforementioned task context reference refers to the address of the task context in the server's memory. Through this reference, the business thread can access the communication interface and state set stored in the task context.
[0127] In the business thread pool, one or more business threads continuously retrieve tasks to be executed from the task queue. When an asynchronous task submitted by an access thread is placed in the task queue, an idle business thread in the business thread pool will retrieve the task from the task queue and begin execution, thereby performing the target processing operation.
[0128] Then, the access thread returns immediately after submitting the asynchronous task, releasing the access thread to handle connection requests from other clients. Specifically, after the access thread calls the task submission method of the business thread pool, the method returns immediately without waiting for the asynchronous task to complete. The access thread ends the processing flow of the current request and returns to the input / output thread pool of the web container. At this point, the access thread becomes idle and can be assigned to connection requests from other clients.
[0129] If the operation of submitting an asynchronous task from the access thread to the business thread fails, for example, due to the task queue of the business thread pool being full, the access thread cannot submit the task context to the business thread. In this case, the access thread does not release itself, but instead returns an error notification of task submission failure to the client through the communication interface, and then closes the connection and releases the access thread.
[0130] Based on the publicly available solutions mentioned above, by limiting the access thread to only handle client connection requests and by immediately returning after submitting an asynchronous task carrying a task context reference, the network access layer and the business computing layer are decoupled, and the access thread is released quickly. This effectively solves the technical problem that the number of concurrent server connections is limited and service blocking and paralysis are likely to occur due to the access thread synchronously waiting for long-running tasks.
[0131] Based on any of the above embodiments, this disclosure also provides a task processing apparatus. Figure 8 This is a schematic block diagram of a task processing apparatus according to one embodiment of the present disclosure. Figure 8 As shown, the task processing device includes: a creation module 801, used to create a task context in response to a task processing request sent by a client; wherein the task context includes a communication interface for server push events and a set of states representing the task execution status. A submission module 802, used to submit the task context to a business thread for execution of the target processing operation and release the access thread. A push module 803, used to push intermediate execution results to the client and update the state set by calling the communication interface in the task context through the business thread. A sending module 804, used to periodically read the task completion status in the state set through a heartbeat thread; if the task completion status indicates that the target processing operation is not completed, a heartbeat signal is sent. The sending module 804 is also used to stop sending heartbeat signals if the task completion status indicates that the target processing operation is completed. The sending module 804 is also used to send a task completion notification to the client through the communication interface.
[0132] The specific implementation process of the functions and roles of each module in the above device can be found in the implementation process of the corresponding steps in the above method, and will not be repeated here.
[0133] The execution subject of the task processing method in the specific embodiments of this disclosure can be an electronic device such as a server (including a local server or a cloud computing platform).
[0134] Therefore, based on any of the above embodiments, this disclosure also provides an electronic device that can execute the task processing method of any of the embodiments described above.
[0135] Figure 9 This is a schematic block diagram of an electronic device according to one embodiment of the present disclosure.
[0136] The hardware architecture of the electronic device 1000 can be implemented using a bus architecture. The bus architecture can include any number of interconnect buses and bridges, depending on the specific application of the hardware and overall design constraints. Bus 1100 connects various circuits, including one or more processors 1200, memory 1300, and / or hardware modules. Bus 1100 can also connect various other circuits 1400, such as peripheral devices, voltage regulators, power management circuits, external antennas, etc.
[0137] Bus 1100 can be an Industry Standard Architecture (ISA) bus, a Peripheral Component Interconnect (PCI) bus, or an Extended Industry Standard Architecture (EISA) bus, etc. Buses can be categorized as address buses, data buses, control buses, etc. For ease of representation, this diagram uses only one connection line, but this does not imply that there is only one bus or one type of bus.
[0138] This disclosure also provides a readable storage medium storing a computer program that, when executed by a processor, is used to implement the methods described above. A "readable storage medium" can be any means capable of containing, storing, communicating, propagating, or transmitting a program for use by or in conjunction with an instruction execution system, apparatus, or device. More specific examples of a readable storage medium include: an electrical connection with one or more wires (electronic device), a portable computer disk drive (magnetic device), random access memory (RAM), read-only memory (ROM), erasable and programmable read-only memory (EPROM or flash memory), fiber optic devices, and portable read-only memory (CDROM), etc.
[0139] This disclosure also provides a computer program product, the methods of which can be implemented wholly or partially through software, hardware, firmware, or any combination thereof. When implemented in software, it can be implemented wholly or partially as a computer program product. The computer program product includes one or more computer programs or instructions. When the computer program or instructions are loaded and executed, all or part of the processes or functions of this disclosure are performed.
[0140] Computer programs or instructions can be stored in a readable storage medium or transferred from one readable storage medium to another. For example, the computer program or instructions can be transferred from one website, computer, server, or data center to another website, computer, server, or data center via wired or wireless means. The readable storage medium can be any available medium capable of access, or a data storage device such as a server or data center that integrates one or more available media. The available medium can be a magnetic medium, such as a floppy disk, hard disk, or magnetic tape; an optical medium, such as a digital video optical disc; or a semiconductor medium, such as a solid-state drive. The computer-readable storage medium can be a volatile or non-volatile storage medium, or it can include both volatile and non-volatile types of storage media.
[0141] Those skilled in the art will understand that embodiments of this disclosure can be provided as methods, systems, or computer program products. Therefore, this disclosure can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, this disclosure can take the form of a computer program product embodied on one or more computer-usable storage media (including, but not limited to, disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0142] This disclosure is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to this disclosure. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart illustrations. Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0143] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0144] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0145] In the description of this specification, the references to terms such as "one embodiment / mode," "some embodiments / modes," "example," "specific example," or "some examples," etc., refer to specific features, structures, or characteristics described in connection with that embodiment / mode or example, which are included in at least one embodiment / mode or example of this disclosure. In this specification, the illustrative expressions of the above terms do not necessarily refer to the same embodiment / mode or example. Moreover, the specific features, structures, or characteristics described may be combined in any suitable manner in one or more embodiments / modes or examples. Furthermore, without contradiction, those skilled in the art can combine and integrate the different embodiments / modes or examples described in this specification, as well as the features of different embodiments / modes or examples.
[0146] Furthermore, the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include at least one of that feature. In the description of this disclosure, "a plurality of" means at least two, such as two, three, etc., unless otherwise explicitly specified.
[0147] Those skilled in the art should understand that the above embodiments are merely for illustrating the present disclosure and are not intended to limit the scope of the disclosure. Those skilled in the art can make other changes or modifications based on the above disclosure, and these changes or modifications still fall within the scope of the present disclosure.
Claims
1. A task processing method, characterized in that, The method includes: In response to a task processing request sent by a client, a task context is created; wherein, the task context includes a communication interface for server push events and a set of states for characterizing the task execution status; Submit the task context to the business thread to execute the target processing operation, and release the access thread; The business thread calls the communication interface in the task context to push intermediate execution results to the client and update the state set. The task completion status in the status set is read periodically by the heartbeat thread. If the task completion status indicates that the target processing operation is not completed, a heartbeat signal is sent. If the task completion status indicates that the target processing operation has been completed, then stop sending heartbeat signals; A task completion notification is sent to the client via the communication interface.
2. The task processing method according to claim 1, characterized in that, The state set includes at least one of the following state variables: task completion state variable, task failure state variable, task interruption state variable, reasoning in progress state variable, and reasoning completion state variable.
3. The task processing method according to claim 2, characterized in that, The step of pushing intermediate execution results to the client and updating the state set by calling the communication interface in the task context through the business thread includes: In response to the API call to the artificial intelligence model, the inference operation is initiated. The inference process state variable is switched to an in-progress state using lock-free atomic operations, and the inference start time is recorded. In response to reading the first data block from the response stream of the artificial intelligence model, the first inference result is determined; The reasoning completion state variable is switched to the completed state through lock-free atomic operations, and the arrival time of the first result is recorded; Upon receiving an inference end flag returned by the artificial intelligence model, the inference operation is determined to have ended; The reasoning state variable is switched to an inactive state using lock-free atomic operations, and the reasoning end time is recorded.
4. The task processing method according to claim 3, characterized in that, Also includes: Cost measurement data is calculated based on the inference start time, the first result arrival time, and the inference end time; wherein the cost measurement data includes at least one of the total inference time, the first result delay time, and the inference generation stage time.
5. The task processing method according to claim 1, characterized in that, Before periodically reading the task completion status from the status set via the heartbeat thread, the method further includes: The heartbeat cycle task is pre-submitted to the timed thread pool, and the task handle of the heartbeat cycle task is stored in the task context; If the task completion status indicates that the target processing operation has been completed, then stopping the sending of heartbeat signals includes: If the task completion status indicates that the target processing operation has been completed, then the task handle is obtained from the task context through the business thread; Send a cancellation request carrying the task handle to the timed thread to cancel the heartbeat periodic task that has been submitted in the timed thread pool.
6. The task processing method according to claim 2, characterized in that, The target processing operation includes a preprocessing stage and a processing stage, and also includes: When an exception occurs during the preprocessing stage, the task failure status variable is updated to a failure status, the task completion status variable is updated to a completed status, and a first error notification is sent to the client through the communication interface. When a retryable exception occurs during the processing phase, a second error notification is sent to the client through the communication interface and a retry operation is performed, and the task completion status variable is kept in an incomplete state until the retry is successful.
7. The task processing method according to claim 1, characterized in that, The process of creating a task context in response to a task processing request sent by the client includes: In response to the server push event connection request initiated by the client, a long connection for the server push event is established and the corresponding communication interface is generated; Instantiate the task context in the memory of the server; Store the communication interface in the task context; The state set is initialized and then stored in the task context.
8. The task processing method according to claim 1, characterized in that, Sending a task completion notification to the client via the communication interface includes: In response to the business thread determining that the target processing operation has been completed, the business thread calls the communication interface to send the task completion notification to the client. After sending the task completion notification, the business thread updates the task completion status to "completed" so that the heartbeat thread stops sending heartbeat signals when it reads the task completion status as "completed" in the next detection cycle.
9. The task processing method according to claim 1, characterized in that, The access thread is a thread in the server used to handle client connection requests; The step of submitting the task context to the business thread to execute the target processing operation and releasing the access thread includes: An asynchronous task is submitted to the business thread through the access thread, and the asynchronous task carries a reference to the task context; The access thread returns immediately after submitting the asynchronous task to free up the access thread to handle other client connection requests.
10. An electronic device, characterized in that, include: The memory stores execution instructions; as well as, A processor that executes execution instructions stored in the memory, causing the processor to perform the method of any one of claims 1 to 9.
