Run Jobs and Read Results with the SDK
This page starts from a saved model and explains how to start the job, wait for the final state, read the results, send running instructions and save the running snapshot. Before starting, you should have completed the SDK certification and prepared a model that the current account has access to and can pass unified verification.
A job uses the model data and component definition submitted when creating the job. Once a job is created, continuing to edit or save the model will not change it. See Model, Job, Result, and Snapshot Lifecycles for the complete data boundary, and see Resource Identifiers for the difference between platform job UUID, model ID and underlying job ID.
Start a Job from a Saved Model
First read an existing model and then call run():
model = client.get_model(model_id)
job = model.run(timeout=300, validate=True)
print(job.id, job.status, job.progress)
The current public signature of Model.run() is:
def run(
self,
*,
timeout: int | None = None,
image: str | None = None,
validate: bool = True,
) -> "Job": ...
The meanings of the three parameters are as follows.
| Parameters | Meaning | Usage Suggestions |
|---|---|---|
validate | By default, the platform unified model verification is called first; when there is an error, ValidationError is thrown and no job is created. | Generally reserved True. Only when the caller has just checked the same data and has not modified the model since then will it be considered to be set to False. |
timeout | The running timeout for writing the input of this job, in seconds | This is the upper limit of operation on the computing side, not the waiting time limit of job.wait() |
image | Override the computing image ID used in this job | Only set when the platform maintainer explicitly provides an available identifier; do not guess the image name for normal calls |
run() will convert the data of the current Model object in memory into a job snapshot, and refresh the component definition of the current workspace before each run. It does not call model.save() first: if the parameters are modified in memory after reading the model, this job will use the modified data, but these modifications will not be written back to the model. When you need to continue using the same version in the future, you should call model.save() explicitly.
Even if validate=False is set, the job creation interface still checks the snapshot infrastructure, permissions, and security conditions required to run; this is not a replacement for unified model verification.
Continue Calculation from Running Snapshot
run() has no runtime_snapshot parameter. When starting from an existing running snapshot, write the snapshot ID to the global parameters of the model, and then start the new job:
model.set_global("started_from_runtime_snapshot", runtime_snapshot_id)
job = model.run(timeout=300)
When creating a job, the platform will check whether the snapshot exists, is available, has not expired, and the current account has the permission to use it. Running a snapshot only restores the kernel running state, and the job will still solidify the model and definition submitted this time; the caller should ensure that the model, parameters, and snapshot are from a compatible computing version.
The global parameter is retained when the same Model object is run again. When no longer booting from a snapshot, it should be cleared explicitly:
model.set_global("started_from_runtime_snapshot", "")
Automatically Save a Running Snapshot at the End of a Normal Calculation
Automatic saving is also not a parameter of run(), but is compatible with the global parameters retained by existing models:
model.set_global("save_runtime_snapshot_on_stop", True)
model.set_global("save_runtime_snapshot_on_stop_name", "基准工况结束状态")
job = model.run(timeout=300)
Although there is still on_stop in the parameter Key, the current semantics is Save when the normal calculation of the job ends, and it is not automatically saved after receiving job.stop(). When a computation fails or is actively stopped, it should not be assumed that a usable snapshot will be generated. The name can be left blank and the platform will generate a default name; when automatic saving is no longer needed, set the switch back to False.
Read Job Status
run() returns Job. Commonly used fields and attributes are as follows.
| Field or Attribute | Description |
|---|---|
id | Platform job UUID, used for querying jobs and connecting result streams |
status | Current status |
progress | Current progress, usually between 0 and 1 |
msg_num | The total number of ordinary result messages recorded by the platform; it may be None if it has not yet been determined |
finished_at | The time to enter the final state; it may be empty if it is not finished. |
result_status | Result storage status: available, unavailable or expired |
workspace_type | The workspace type to which the job belongs |
model_id | The associated model ID; may be empty if no model is associated |
task_id | The underlying running job ID is not equivalent to id |
raw | Original fields returned when creating or querying jobs |
Calling refresh() will query the latest status, progress, number of messages, end time and result storage status, and update the same object:
job.refresh()
print(job.status, job.progress, job.msg_num, job.result_status)
The status may pass through pending, running, pausing, paused, stopping, and finally enter success, fault or stopped. job.is_terminal is only True in the last three final states.
Bounded Waiting for Final State
job.wait(timeout=600, poll_interval=1)
wait() only polls the job details until the job enters the final state; it is Results channels will not be connected, nor will logs, trends, or monitoring data be read into job.result_stream . Exceeding timeout will throw the Python built-in TimeoutError .
Here timeout=600 is the total time the caller is willing to wait, and is not interchangeable with the calculation timeout of the model.run(timeout=300) write job. poll_interval A reasonable interval greater than zero should be used to avoid high-frequency queries.
A Complete Process That Can Be Run
The following example reads connection information and saved model IDs from environment variables, creates a job, waits for a bounded final state, then reads from the beginning and aggregates the results. The example does not specify a computing image and does not output the password to the log.
from __future__ import annotations
import os
from nexusflow_sdk import NexusFlowClient, ResultExpiredError
def require_env(name: str) -> str:
value = os.getenv(name, "").strip()
if not value:
raise RuntimeError(f"缺少环境变量:{name}")
return value
with NexusFlowClient(
base_url=require_env("NEXUSFLOW_BASE_URL"),
username=require_env("NEXUSFLOW_USERNAME"),
password=require_env("NEXUSFLOW_PASSWORD"),
timeout=30,
) as client:
model = client.get_model(require_env("NEXUSFLOW_MODEL_ID"))
job = model.run(timeout=300, validate=True)
print(f"任务已创建:{job.id}")
try:
job.wait(timeout=600, poll_interval=1)
except TimeoutError as exc:
job.refresh()
if not job.is_terminal:
job.stop()
raise RuntimeError(f"等待任务 {job.id} 结束超时,已请求停止") from exc
try:
results = job.get_results(timeout=5, offset=0, reset=True)
except ResultExpiredError as exc:
raise RuntimeError(f"任务 {job.id} 的结果已经过期") from exc
for log in results.logs():
print(f"[{log.level}] {log.message}")
for key, plot in results.plots().items():
print(f"趋势图 {key} 包含字段:{sorted(plot.config)}")
print(
f"任务终态={job.status},进度={job.progress},"
f"消息数={job.msg_num},结果状态={job.result_status}"
)
if job.status != "success":
raise RuntimeError(f"任务未成功结束:{job.status}")
If the wait times out, stop() will only send a stop request and will not wait synchronously for stopped. When the final status needs to be confirmed, bounded refresh() or wait() should be called again in the upper-level process that caught the exception.
Real-Time Consumption Results
When you need to process messages while calculating, use stream_results():
def on_message(message, stream):
if message.get("type") == "log":
print(f"当前已聚合 {len(stream.logs())} 条日志")
for message in job.stream_results(
offset=0,
callback=on_message,
timeout=5,
max_reconnects=3,
):
print(message.get("id"), message.get("type"), message.get("key"))
Each message will be merged into job.result_stream first, then passed to callback(message, stream), and finally generated by the iterator. stream in the callback is the current cumulative result. Callback exceptions interrupt iterations, so time-consuming processing, persistence failures, and business exceptions should be isolated in callbacks themselves.
The boundaries of each parameter are as follows.
| Parameters | Exact Meaning |
|---|---|
offset | The position of the next message to be read starts from 0 by default. id + 1 used to save the last confirmed message when continuing reading |
callback | Function called after merging each normalized message, can be omitted |
timeout | The timeout for WebSocket connection establishment and single reception is not the total deadline of the entire result stream. |
max_reconnects | In this iteration, the maximum number of reconnections after the connection is closed unexpectedly; the receive timeout itself will not consume this number |
After a single reception times out, the SDK will refresh the job status: continue to wait until the job is finished, and exit only when the job has finished and the results have been drained. When the connection is disconnected unexpectedly, the SDK will continue from the current offset instead of reading from zero again. When a deadline needs to be set for the entire real-time consumption process, the caller should also use job running timeout, supervisory thread, or process-level deadline policy; just setting stream_results(timeout=5) will not cause the iterator to end after five seconds.
Why Do We Need to Empty the Results After the Final State?
It is normal for the job to enter the final state first and the last batch of results to arrive later. When stream_results() is in the final state of the job and msg_num is known, reading will continue until the "next message position" reaches msg_num. So don't immediately close the resulting connection the first time you see success.
msg_num is the total number of ordinary result messages calculated from offset 0, not the number of logs, trend charts, or merged objects. The low-level format of the message and the rules for platform allocation id are found in Return Status, Logs, and Results.
If the msg_num of the final state job is not yet known, the SDK will refresh the job after the connection times out or is closed, and then press the final state to end reading. At this time, msg_num, the actual last message ID, and the job status should be recorded together to facilitate troubleshooting of incomplete results.
Full Read, Tail Read and Local Reset
Aggregate Results from Specified Location
get_results() will exhaust stream_results() and return ResultStream held by the current job:
results = job.get_results(
timeout=5,
offset=0,
reset=True,
)
reset=Truefirst clears the local aggregator and then reconstructs the results fromoffset;reset=Falseretains existing aggregation results, which is the default value;offsetmust be greater than or equal to0.
If the same Job has been read from 0 and is called again with the default offset=0, reset=False, the old messages will be merged again, and append logs, data points and table rows may be duplicated. When you need to reconstruct the complete result, use offset=0, reset=True; when you need to continue reading incrementally, keep the local aggregator and continue from the last confirmed next message position.
Read Only the Last Message
tail = job.get_tail_results(count=1000, timeout=5)
This method will first refresh(), calculate the starting offset as max(msg_num - count, 0), and automatically reset the local aggregator. count refers to the number of original messages, not the number of result objects.
Tail reading is suitable for viewing the most recent logs or self-contained monitoring messages at the end, but does not guarantee restoration of complete results. If there is only the append increment in the window and the original update configuration is missing, the trend, table, or container may be incomplete. When a complete curve or complete structure is required, it should be read from 0.
Only Reset Local Data
empty_stream = job.reset_results()
This will only create a new local ResultStream and will not delete the platform saved results or reset the job status. The return value is the new empty aggregator.
Use ResultStream
ResultStream.messages Saves all normalized raw messages in the order they were received. Type accessors provide a convenient view aggregated by Key:
logs = results.logs()
plots = results.plots()
inspects = results.inspects()
tables = results.tables()
containers = results.containers()
pressure_plot = results.plots("pipe_1_pressure")
latest_inspect = results.inspects("inspect")
raw_appends = results.filter(type="log", verb="append")
plots(key), inspects(key), tables(key) and containers(key) all return dictionaries; when the Key cannot be found, an empty dictionary is returned. filter(type=..., key=..., verb=...) filters the original message history, not the merged objects, so deleted messages may still appear in the filtering results.
The current aggregation rules for the SDK are as follows.
| Type | append | update | delete |
|---|---|---|---|
log | Append one or more records to the log bucket of the same Key | Empty the old bucket of the Key and save the new record | Delete the log bucket of the Key |
plot | dataset.source in dictionary form appends rows; dataset in list form appends data set objects; options already exists in the list and appends list items; other configurations are deeply merged | Replace the complete chart configuration of this Key with the new data | Delete this chart |
inspect | Append data for one or more moments | Replace the monitoring history of this Key with new data | Delete the monitoring object |
table | When the number of columns is the same, append data by column; when the number of columns is different, use the new column data. | Replace title and all columns | Delete this table |
container | Save the latest container configuration | Save the latest container configuration | Delete the container |
Common object fields include:
LogMessage:level,timestamp,message,formatandraw;PlotMessage: The complete configuration is located atconfig;InspectMessage: The history is located atentries,latest()returns the last item orNone;TableMessage:labelandcolumnsorganized by columns;ContainerMessage: The container declaration is located atcontent.
The SDK only parses and saves HTML fields and is not responsible for rendering or executing HTML. Before outputting the log or table content to the web page, it should still be filtered according to the security rules of the target system.
Differences from Simulation Workbench Results View
The SDK and Simulation Workbench consume the same kind of raw messages, but for different purposes: the SDK provides lightweight Python aggregate objects, and the Simulation Workbench also completes visualization and container routing. Therefore the merged results from both sides cannot be directly compared field by field in all cases.
| Scene | SDK Current Behavior | Simulation Workbench Results View Current Behavior |
|---|---|---|
| Logs of the same Key | Keep the history of append, reset the Key with update | The merged view retains the latest news for the Key |
Chart update | Replace complete configuration | Keep the history of existing data sets and mainly update non-data configurations |
List form chart data set append | Append new dataset object to list | Append new rows according to the data set subscript to the corresponding source |
Monitor update | Replace all entries of this Key | Preserve time series and update necessary monitoring definitions |
| container | Only save the latest container declaration | Organize sub-messages according to query conditions and support nested tab pages |
If the business requirements are completely consistent with the page display, the same display merging rules should be implemented based on ResultStream.messages, or the kernel should be constrained to only output a simple message sequence with consistent semantics for both parties. In particular, do not assume that a list-like multi-dataset chart will aggregate into the same structure at both ends.
Pause, Resume, Stop and Send Component Commands
Job control methods only send messages and do not return confirmation objects:
job.pause()
job.refresh()
job.resume()
job.refresh()
job.stop()
job.wait(timeout=60, poll_interval=1)
Whether pause and resume are supported depends on the current computing core and job phase. The return of the method does not mean that the status has been switched. You should check the subsequent status through refresh() or bounded wait().
Send instructions to the running component:
job.send_command(
component_id=valve.id,
cmd_key="开关调节",
time="2021-01-01 00:10:00",
state="0",
)
component_idis the component instance ID in this job snapshot, not the component type identifier;cmd_keyis the instruction grouping Key in the component definition;- The remaining keyword parameters constitute
dataof this instruction; - The method does not have a business confirmation return value, and the actual execution should be judged based on the job status, logs or subsequent results.
After the result stream is disconnected, the SDK will continue to read from the consumed offset, but this does not mean that the sent command also has the same replay protection. send_command() and control methods will not automatically retry; if the network is disconnected when sending, the caller may not be able to determine whether the server has received it. Do not blindly replay non-idempotent operations such as appending, incrementing, and triggering one-time actions. Priority should be given to designing instructions to be idempotent, or confirming the effect from the job status and results before deciding whether to retry.
Manually Save a Running Snapshot
The three methods related to running snapshots are responsible for "request", "waiting" and "combined execution" respectively.
Only Make Requests
snapshot_id = job.request_runtime_snapshot(
name="调试断点",
)
This method sends a save request through the job real-time channel and returns the snapshot ID immediately; the snapshot may not be available when it returns. Optional snapshot_id is used to pre-allocate the ID by the caller. max_bytes is used to limit the load of this snapshot. The default value is 512 MiB. Do not increase the upper limit arbitrarily, the platform may still enforce stricter capacity limits.
Wait for Existing Requests to Complete
snapshot = job.wait_runtime_snapshot(
snapshot_id,
timeout=60,
poll_interval=1,
)
This method polls the specified snapshot: returns the snapshot dictionary when the status is available; throws RuntimeError when the status is failed or expired; throws TimeoutError when the waiting time limit is exceeded. It does not create save requests on its own.
Request and Wait
snapshot = job.save_runtime_snapshot(
name="调试断点",
timeout=60,
poll_interval=1,
)
print(snapshot["id"], snapshot["status"], snapshot.get("expires_at"))
save_runtime_snapshot() is equivalent to calling request_runtime_snapshot() first and then calling wait_runtime_snapshot(). The retention period of the snapshot is based on the returned expires_at. When you need to stop the job and retain the current state, you should wait for the manual snapshot to change to available before calling stop(); doing the opposite does not guarantee that the kernel can still generate a snapshot.
Running snapshots and job results are two types of resources: snapshots are used to restore computing status, and ResultStream are used to analyze logs, charts, and monitoring data. Saving one of them will not automatically save the other for a long time.
Processing Results Are Unavailable and Expired
After calling refresh(), job.result_status may be:
| Value | Meaning | Suggestions |
|---|---|---|
available | The platform currently still stores the results of this job | The result stream can be connected; it does not indicate that the job has ended, nor is it guaranteed that the number of messages is greater than zero |
unavailable | The result storage cannot be found currently, but it cannot be determined to be expired based on the job end time. | Combine the job status, creation time and logs to determine whether it is not ready, failed to start or has a storage abnormality; do not directly treat it as a permanent loss. |
expired | The job record is still there, but the result has exceeded the platform retention range | No more retrying result connections, instead use previously exported data or recalculate |
When the known result of Job is expired, the SDK will throw ResultExpiredError before establishing the result connection. After the connection is rejected, the SDK will also refresh the result status; if the platform confirms that the result has expired, this exception will also be thrown. "Result expired" responses returned via HTTP are also mapped to this exception.
from nexusflow_sdk import ResultExpiredError
try:
results = job.get_results(offset=0, reset=True)
except ResultExpiredError:
print("任务记录仍存在,但结果流已经过期")
Do not reconnect indefinitely for expired results. Batch processes should separately record "job failure", "result unavailable" and "result expired" to avoid classifying all three situations as calculation failures.
Complete Inspection
When accessing job and result links, confirm at least the following:
run()retains unified model verification by default, and distinguishes between job running timeout and caller waiting timeout;- It has been clarified that this run uses the current model data in the memory, whether additional
model.save()is required; - The result is still read explicitly after
wait(), and "entering the final state" is not mistaken for "the result has been downloaded"; - The full reconstruction result uses
offset=0, reset=True, and incremental processing saves the next oneoffset; - After the final state, press
msg_numto empty the message, and the tail reading will not be mistaken for the complete result; - Business code understands the differences in result merging between the SDK and Simulation Workbench;
- Control instructions and component instructions design retry boundaries according to non-idempotent operations;
- The result expires and is captured separately
ResultExpiredError; - Running the snapshot manually has acknowledged
availablebefore stopping the job.
You can continue reading next:
- Read, Edit, and Save Models with the SDK: Assemble, verify and save the model through SDK;
- Batch Automation and Error Handling: Supplement concurrency limits, retries, cleanup and partial failure records for batch jobs;
- Return Status, Logs, and Results: Understand the complete result message convention between the kernel and the platform.