Skip to main content

Real-Time Job Data Over WebSocket

The job real-time channel is responsible for two things at the same time: the server sends simulation results to the client, and the client sends control messages to the running jobs. The connection path is /ws/<job_id> , where job_id is the platform job UUID, not the kernel run ID, model UUID, or job display name.

Before starting to access, read Authentication and Token Refresh and Resource Identifiers. See Job, Control, and Result APIs for job creation, status and result availability; this page only describes the real-time channel and does not repeat the complete fields of each type of result data.

Generate the Correct Connection Address​

WebSocket uses the same host as the platform:

  • When the platform root address is http://..., use ws://...;
  • When the platform root address is https://..., use wss://...;
  • The path is fixed to /ws/<job_id>, and / is not added at the end of the current path;
  • The query parameter offset indicates the position of the next message to be read.
wss://<platform-host>/ws/<job_uuid>?offset=0

The optional batch controls the number of messages read by the server at a time. The default is 200 and the valid range is 50~500. When exceeding the range, it will be limited to the boundary, and illegal values will return to the default value. batch There is no guarantee on the number of messages in each WebSocket frame: the server can send smaller batches when there are insufficient messages or when the frames are large.

When the browser uses a one-time ticket, the address looks like:

wss://<platform-host>/ws/<job_uuid>?offset=0&batch=200&ticket=<one_time_ticket>

Don't put long-lived access tokens into URLs. Query parameters may enter browser history, proxy access logs, and monitoring records.

Prepare Connection Permissions​

Before accepting the connection, the server will check the authentication identity, whether the job exists, whether the current account can access the job, and whether the result flow running information still exists.

Accounts that can currently access the real-time channel of jobs include:

  • job creator;
  • super administrator;
  • The organization administrator of the organization to which the creator of the administrative job belongs.

Making the model public, visible to the organization, or accessible to the workspace does not automatically extend the same permissions to a job. Ticket issuance and WebSocket handshakes perform separate job access checks.

Choose an Authentication Method​

Live channels support Bearer handshakes and one-time tickets. Choose one of the two; if the handshake carries both the Bearer request header and ticket, the server will process the request header first and will not fall back to the ticket after the request header is invalid.

Non-Browser Clients: Bearer Handshake​

Clients that are able to set the WebSocket handshake request header can send it directly:

Authorization: Bearer <access_token>

The connection address no longer carries ticket:

wss://<platform-host>/ws/<job_uuid>?offset=<next_offset>&batch=200

Currently the NexusFlow Python SDK uses this approach. It selects ws or wss based on the platform root address and adds the access token to the handshake; when 401 or 403 appears in the handshake and the client has refresh conditions, the SDK refreshes and retries at most. When it continues to fail, you should check the account and job permissions and do not refresh in a loop.

Browser Client: One-Time Ticket​

The browser's native WebSocket interface cannot set the Authorization request header, so first use an authenticated HTTP request to apply for a ticket:

POST /api/jobs/<job_id>/websocket-ticket/
Authorization: Bearer <access_token>

The request does not require a JSON request body. Minimal call example:

export NEXUSFLOW_BASE_URL="https://nexusflow.example.com"
export NEXUSFLOW_TOKEN="<access_token>"
export JOB_ID="<job_uuid>"

curl -sS -X POST \
-H "Authorization: Bearer ${NEXUSFLOW_TOKEN}" \
-H "Accept: application/json" \
"${NEXUSFLOW_BASE_URL%/}/api/jobs/${JOB_ID}/websocket-ticket/"

Successful response uses general business encapsulation:

{
"message": "创建任务连接票据成功",
"code": 0,
"data": {
"ticket": "<one_time_ticket>",
"expires_in": 60
}
}

expires_in should be used per response, the example number is not a client constant. The response also declares Cache-Control: no-store .

Notes have strict boundaries:

  • Bind the user and job UUIDs that issued it;
  • It is consumed atomically during authentication and cannot be reused after a handshake;
  • Valid only for a short period of time indicated by expires_in;
  • Cannot be used for another job, HTTP API, or next reconnection;
  • You must reapply every time before reconnecting;
  • It should be connected immediately after requesting and should not be written to persistent storage or logs.

If the client cancels the handshake before the connection is completed, it should consider this ticket as used and reapply before connecting again.

Correct Understanding Of offset​

Result messages are numbered consecutively starting from id: 0 within a single job. offset is not "the last read ID", but "the next position to be read".

已完成消息 0~18
下一次连接 offset=19

The client should persist the following combination:

(job_id, next_offset)

Saving only offset cannot locate the result because different jobs will start from 0. Only after business processing and local persistence are successful, next_offset can be updated to the current message id + 1.

The server will use the same location to first read the saved result fragment, and then read the result stream currently retained in Redis. After the historical message catching up is completed, the connection continues to wait for new messages; the client does not need to send subscribe or other subscription messages. Switching between storage tiers does not change message IDs.

offset cannot provide exactly-once

WebSocket does not have "Business Processing Complete" confirmation. The client may be disconnected after completing business processing and before saving the new offset, and will receive the same message again after reconnecting. Use (job_id, message.id) to remove duplicates, and design business writing and consumption location saving into the same recoverable step.

Parse Single and Batch Frames​

The current server sends a text frame, and the body is usually a JSON array. Even if there is only one message in this frame, it may be a single-element array:

[
{
"id": 18,
"key": "simulation_log",
"verb": "append",
"type": "log",
"data": {
"level": "info",
"timeStamp": 1787990400,
"message": "计算步完成"
}
}
]

In order to be compatible with existing data and the standardized behavior of the SDK, the client can process in the following order:

  1. The text frame first performs JSON parsing;
  2. When the result is an array, it is processed item by item, and when it is an object, it is packaged into a single-element array;
  3. If an item only has the outer layer id and the string data, and data itself is a JSON object, then parse another layer and retain the outer layer id;
  4. Ordinary result messages must have integers id and key, verb, type, data;
  5. id < next_offset is regarded as a duplicate message and will be skipped after deduplication;
  6. id > next_offset means there is a gap. Stop advancing the position first and continue reading from the current next_offset. Do not jump directly to a larger ID.

For the complete data structures of log, plot, inspect, table and container, see Return Status, Logs, and Results. A WebSocket frame may be split into multiple batches; the "end of frame" cannot be regarded as the end of a set of business results.

Status Text Is Not a Normal Result Message​

The status text in the simulation running link looks like:

status:running;0.42

The platform will recognize this text and update the job's status and progress. The current server usually consumes the state text before the result enters the persistent stream, does not assign it the normal result id, and does not count it as msg_num. Therefore direct clients should confirm the status through the job details interface, do not wait for a status frame, and do not treat the status text as a log result.

The current SDK's message normalizer still recognizes the received status text and represents it as a key: "__status__" compatible message. This is a compatibility process and does not require new kernels or new clients to mix status text into the normal result stream.

Play Back First, Then Continue Reading​

After establishing the connection, the server presses offset to read the result:

There is no separate "playback complete" event for this process. Catching up history and receiving real-time results use the exact same message format, and the client simply processes them in the id sequence.

Whether the result can be read also depends on the result_status of the job:

result_statusMeaningClient Processing
availableThere is currently still result flow run informationCan be connected; it does not mean that the job has ended or that there must be news
unavailableThere is currently no readable result stream, but it cannot be determined to be expired based on the end time.Check job status and logs; do not reconnect without boundaries
expiredThe job record is still there, but the results have exceeded the retention rangeStop the connection attempt; the ticket interface returns 410

The presence or absence of a persistent result fragment is not an interface that clients can directly detect or rely on. As long as the result stream run information has been cleaned, WebSocket will not bypass the job result retention policy and directly read the residual file.

Empty Messages After Final State​

The final state of the job is success, fault or stopped. When the final state occurs, the last batch of ordinary results may still be written to the persistent result fragment, so the connection cannot be closed immediately when the final state is first seen.

The job field msg_num is the total number of ordinary result messages. The complete emptying conditions are:

任务处于终态,并且 next_offset >= msg_num

For example, if the final job's msg_num is 19, the result ID should cover 0~18. After processing id: 18, next_offset is 19, and it is considered finished reading at this time. msg_num: 0 means there can be no ordinary result message.

Recommended process:

  1. Continue to process WebSocket messages and save next_offset;
  2. When the reception times out or the connection is closed, read status, msg_num and result_status in the job details;
  3. When the job is not over, reconnect from the current next_offset;
  4. When the job has ended but next_offset < msg_num, continue to wait or reconnect to complete the job;
  5. Only when the emptying conditions are met, the connection is actively closed and consumption ends.

The server will also wait for messages that have not yet completed persistence after the final state, but the waiting is bounded. The client cannot only rely on the server to proactively close the connection; if the connection remains open, closed, or times out, it should be returned to the job details and msg_num to re-judge.

The current SDK's stream_results() adopts the same rule: refresh the job after a single reception timeout, and limited reconnection from the current offset when the connection is accidentally disconnected; when the job is in the final state and msg_num is known, it will exit after reading offset >= msg_num. timeout of the SDK is the connection establishment and single reception timeout, not the total period of the entire consumption process.

Continue Reading from the Confirmed Position After Disconnection​

A reliable reconnection should be performed:

  1. Stop using old connections;
  2. Read the local persistently confirmed next_offset;
  3. The browser client re-applies for the one-time ticket; the Bearer client confirms that the access token is still valid;
  4. Read from offset=next_offset using a new connection;
  5. Perform idempotent processing on (job_id, id) that may arrive repeatedly;
  6. Set the number of reconnections, backoff, and deadline for the entire consumption process.

Do not rebuild the large result from offset=0 every time, and do not delete the saved consumption location just because of WebSocket network exception. If gaps are continuously received and the result status becomes unavailable, or the final state is reached but cannot be reached msg_num for a long time, the job UUID, last confirmation ID, job status and time point should be retained for investigation.

Handle Authentication and Result Errors​

The ticket interface can provide a clearer HTTP status than WebSocket upgrade failure:

HTTP StatusMeaningProcessing Method
401No valid access tokenControlled refresh or log in again, and then reapply for the ticket
403Authenticated but does not have access to the jobCheck the job creator and organization management scope; do not refresh in a loop
404Job UUID does not existStop retrying and check identity source
410Job result has expiredStop connection; use previously saved data instead or recalculate

When WebSocket refuses a connection before accept, different clients or proxies may only report handshake failure or 403 without retaining the server-side internal shutdown reason. The order of investigation is:

  1. Use the same identity to read the job details and confirm that the job exists and is accessible;
  2. View result_status;
  3. The browser process re-applies for a ticket and does not reuse the old ticket;
  4. Check that the job UUID of the ticket is exactly the same as the connection path;
  5. The Bearer process confirms that the handshake request header is indeed sent by the used library;
  6. If it still fails, record the HTTP status, connection time, and job UUID, and contact platform maintenance personnel.

The current SDK will throw a result expiration exception before establishing a connection when result_status: expired is known; if the handshake returns 403, it will also refresh the job details and convert to the same exception after confirming the expiration. Do not interpret all 403 as network proxy interception.

Issue Job-Level Control​

Once the connection is established, the client can send UTF-8 JSON text. There are currently no additional subscription, handshake confirmation, ping, ack or command receipt messages.

Pause, resume and stop using JOB_CONTROL:

{
"type": "JOB_CONTROL",
"payload": {
"cmd": "pause"
}
}

Change cmd to resume or stop to send a resume or stop request. Successful sending only means that the WebSocket client handed over the text to the connection, but does not mean that the job status has changed. The job status and log should be read after sending: pause may first enter pausing, stop may first enter stopping, the final status depends on the kernel and platform control process.

Request a Running Snapshot​

Running snapshots also use JOB_CONTROL. The complete form currently sent by the SDK is:

{
"type": "JOB_CONTROL",
"payload": {
"cmd": "snapshot",
"snapshot_id": "3c26ff36-b107-4ebb-9a92-2ab7de3764bb",
"name": "稳态完成后的运行状态",
"payload_key": "kernel_runtime_snapshot:payload:3c26ff36-b107-4ebb-9a92-2ab7de3764bb",
"max_bytes": 536870912
}
}

snapshot_id must be a UUID created and reserved by the caller. The platform will first create a running snapshot record with the status saving, and then forward the standardized command to the kernel; completion of sending the command does not mean that the snapshot is available. Afterwards, available, failed or expired should be queried by running the snapshot interface. See Handle Control Commands for snapshot limitations and kernel acknowledgment protocols.

Issue Component Instructions​

The component operation uses JOB_CMD:

{
"type": "JOB_CMD",
"payload": {
"cmd": {
"<component_instance_id>": [
{
"cmdKey": "<command_key>",
"data": {
"target": 0.6
}
}
]
}
}
}

payload.cmd can contain multiple component instances, each value is an array of instructions. The object key must be the component instance ID in this job snapshot; cmdKey and data are defined by the component and agreed upon by the kernel. They are not an alternative to pausing, resuming, or stopping jobs.

After receiving JOB_CMD, the platform will write the command content into the result stream as the ordinary results of type: "job" and key: "job_msg" for the job view to record history. This echo can only prove that the platform has forwarded and recorded, but cannot prove that the kernel has been executed successfully. See Handle Control Commands for specific payload, checksum and kernel confirmation methods.

Control Messages Are Not Guaranteed to Be Uniformly Idempotent​

Neither JOB_CONTROL nor JOB_CMD has a common request ID or a unified acknowledgment frame. When the network is interrupted, the client may not be able to tell whether the message is lost before being sent or has been forwarded by the platform.

  • After pause, resume and stop are sent, check the job status first and then decide whether the next step is required;
  • snapshot Save snapshot_id in advance, and then query the same snapshot record. If you cannot see the timeout, change the ID and create it again;
  • JOB_CMD is prioritized for repeatable operations such as “setting target values”;
  • For component actions that must be executed only once, the business operation ID can be added to data, and the kernel can implement bounded deduplication;
  • Don't let the WebSocket library automatically replay the last control message.

The current Python SDK's pause(), resume(), stop(), request_runtime_snapshot() and send_command() only send messages, do not automatically retry, and do not return execution confirmation. The SDK will establish a connection for the send action, send it once and close it; the caller still needs to confirm the actual effect through job status, logs, business results or running snapshot resources.

Client Acceptance Checklist​

  • http / https can be correctly mapped to ws / wss, and there are no extra slashes at the end of the job path;
  • The browser applies for a new ticket every time it connects and reconnects, and non-browser Bearer does not enter the URL;
  • Save next_offset = id + 1 only after successful business processing;
  • Compatible with both JSON arrays and single objects, and verifying id continuity;
  • Continue reading after the job ends until next_offset >= msg_num;
  • Set the upper limit, backoff and total deadline for disconnection and reconnection, and do not promise exactly-once;
  • Handle 401, 403, 404, 410 and result_status respectively;
  • After the control message is sent, it is confirmed through the status, log or resource interface, and does not wait for the non-existent ack;
  • Access tokens, full ticket URLs, sensitive values in control parameters, or full business results are not logged.