Batch Automation and Error Handling
The most difficult situation to handle in batch processing is usually not that a certain request fails explicitly, but that the request has been sent but the client has not received a complete response. At this time, try again directly, which may save the model, create jobs or issue control instructions repeatedly.
This page provides a set of processing methods suitable for long-running scripts: first identify the source of the exception, and then make a decision based on whether the operation can be safely retried; each model or job records the results independently, and saves the platform job UUID and result reading location to local breakpoints.
Please complete Install and Authenticate the Python SDK and understand Resource Identifiers before starting.
First Distinguish Which Layer the Exception Comes From
The exception hierarchy of the SDK itself is as follows:
NexusFlowError
├── AuthError
├── ValidationError
└── APIError
├── NotFoundError
└── ResultExpiredError
The network library exception and the Python built-in TimeoutError are not in this inheritance tree. Only capturing NexusFlowError will miss connection timeout, certificate error, WebSocket disconnection and job waiting timeout.
SDK Exception
| Fault | Real Field | Common Sources | Processing Points |
|---|---|---|---|
NexusFlowError | No extra fields; use str(exc) to read the message | Common base class for SDK exceptions | It is suitable as the last step to catch SDK exceptions, but not suitable for deciding whether to try again. |
AuthError | no extra fields | Lack of available credentials, login failure, refresh token and re-login failure, token interface does not return access token | Stop the current batch or reacquire credentials; do not retry indefinitely with the same invalid credentials |
ValidationError | no extra fields | The local modeling operation is illegal, or the unified verification of save(validate=True) and run(validate=True) failed | Fixed model; error message is readable, but full positioning information should be obtained from model.validate() |
APIError | status_code: int | None、payload: Any | REST interface returns error status | Classify according to status code; do not directly output the complete payload in the log |
NotFoundError | Fields inherited from APIError | SDK actually received HTTP 404 | Check the resource type, ID, environment and permissions; not all "not found" will necessarily return 404 |
ResultExpiredError | Fields inherited from APIError | HTTP 410 and result_status in the response root object or data is expired; or Job is known to have expired results | Terminate result reading; keep job records and do not reconnect repeatedly from offset=0 |
APIError.payload retains the original JSON or text returned by the server. The structure may vary depending on the interface and error stage. The current SDK does not have a unified error_code field, nor does it convert all server-side verification questions into the same dictionary. Business code should rely on the exception type and status_code first, and only read payload when the response structure of an interface is clearly known.
HTTP Network Exception
REST requests and authentication requests use requests. The current SDK does not wrap these exceptions into NexusFlowError:
| Fault | Information You Can Rely On | Description |
|---|---|---|
requests.exceptions.Timeout | str(exc); inherited from RequestException | A single connection or read exceeds the client's timeout. It cannot be used to determine whether the server has completed the write operation. |
requests.exceptions.ConnectionError | str(exc); inherited from RequestException | DNS, connection refused, connection interrupted, etc.; results may be indeterminate when write requests are interrupted |
requests.exceptions.SSLError | str(exc); Belongs to the requests abnormal system | Certificate chain, hostname, or TLS configuration is incorrect; should not be retried until configuration is fixed |
requests.exceptions.RequestException | request, response may exist, or it may be None | Catch-up type for other HTTP client errors; SDK has no additional fields |
Do not log exc.request.headers, exc.response.request.headers, or the full request body, which may contain access tokens and model parameters.
WebSocket and Wait Exception
Job results and control instructions use websocket-client:
| Fault | Fields Used by the Current Code | Common Sources |
|---|---|---|
WebSocketBadStatusException | status_code、str(exc) | WebSocket handshake rejected; SDK will attempt an authentication refresh for 401 or 403 |
WebSocketTimeoutException | str(exc) | Connection establishment or single receive timeout |
WebSocketConnectionClosedException | str(exc) | The peer closes the connection or the connection is lost |
OSError、ConnectionResetError、ConnectionAbortedError | Python standard exception information | The underlying connection is interrupted; the resulting stream will reconnect from the current offset within limits |
TimeoutError | str(exc) | job.wait() or job.wait_runtime_snapshot() exceeds the total waiting time set by the caller |
job.stream_results() will refresh the job status when a single reception times out, and perform limited reconnection for partial disconnections; after exceeding max_reconnects, the underlying exception will still be handed over to the caller. Its timeout is the timeout of a single WebSocket operation, not the total deadline of the entire result consumption process.
wait_runtime_snapshot() currently throws RuntimeError when the running snapshot becomes failed or expired. Additionally, incorrect public method parameters or unparsed platform responses may result in ValueError , TypeError , or KeyError . These exceptions also do not belong to NexusFlowError.
Determine Whether to Retry Based on Idempotence
"The number of retries is limited" does not mean "can retry". First determine whether repeated execution will change the status of the platform or external systems.
| Action | What to Do When the Response Is Uncertain | Reason |
|---|---|---|
client.get_model(), client.get_job(), list and detail reading | Can retry within total time budget | GET does not modify the resource; retries should still be stopped for 401, 403, 404 and result-expired classes 410 |
| SDK internal token refresh | Let the SDK handle it once | When a REST request receives 401 and refresh conditions are met, the SDK will only replay the original request once after refreshing; the public client does not have the top-level refresh() method |
model.validate() | It can be re-initiated, but the current flow should be limited separately. | The current interface only verifies the submitted snapshot and does not save the model; it uses POST, so do not apply the "retry all POST" rule to other interfaces |
model.save() | First re-read the model and check the name, visibility and snapshot content before deciding whether to redo it. | Saving will update the model and generate a new model snapshot; when the response is lost, the server may have successfully saved it. |
client.create_model()、model.save_as() | First check whether the target model already exists based on the unique business tag or creation time. | Repeated calls will create new model resources |
model.run() | Marked as "Unknown Creation Result", check the job record first, and then let the business party decide. | The SDK does not currently receive caller-specified platform job UUIDs; the job may have already been created and started when the response was lost |
job.request_runtime_snapshot()、job.save_runtime_snapshot() | Generate and save snapshot_id in advance; query with get_runtime_snapshot() first after failure | Resending the same request may still give the save instruction to the kernel again; resending it after the snapshot is completed will not turn into a normal query. |
job.pause()、job.resume()、job.stop() | First refresh the job status, and then decide according to the allowed status transition. | The SDK is only responsible for sending control messages and does not promise that the caller has observed that the kernel execution is completed. |
job.send_command() | No blind replay allowed | JOB_CMD may have been forwarded; the platform echo does not mean that the kernel has actually been executed, and there is no general business idempotent key. |
| Business actions such as writing to external tables, appending messages, sending notifications, etc. | Use business unique keys to deduplicate, or commit in the same transaction as the breakpoint | When the consumer crashes after successful writing and before saving offset, the same message will be seen again after restarting. |
taskID as an idempotent key when creating a jobmodel.run() will add a job running ID when the input of this job lacks global.taskID. It is not a platform job UUID, nor is it a job creation idempotent key for the current SDK. What is really used to connect client.get_job() and the result is job.id in the returned object. See Resource Identifiers for detailed differences.
Boundaries of 401, 403, 404 And 410
- When a REST request receives
401, if the client holds a refresh token or account password, the SDK will refresh the authentication and replay the original request once. If it still fails the second time, do not continue to log in again in the outer loop. - When the WebSocket handshake receives
401or403, the SDK may also refresh once. Persistent403is usually a permissions, job access scope, or result status issue; repeated logins cannot increase permissions. - Only the actual HTTP
404will be mapped toNotFoundError. Some details interfaces may use other error status to indicate that they are not queried or have no permission to access. All missing situations cannot be hard-coded as404. - Only results with
result_status: "expired"expired410will be mapped toResultExpiredError. Other410is stillAPIError, such as another type of cleaned resource does not necessarily mean that the job result flow is expired.
Add Bounded Backoff for Safe Reads
There is currently no common retry configuration exposed by the SDK. The following is the business script's own packaging, which is only used for GET class reading. It fails immediately for certificate errors, permission errors, resource non-existence, and result expiration; it only has limited backoff for some temporary HTTP states, connection errors, and single timeouts.
from __future__ import annotations
import random
import time
from collections.abc import Callable
from typing import TypeVar
import requests
from nexusflow_sdk import APIError
T = TypeVar("T")
TRANSIENT_HTTP_STATUS = {408, 429, 500, 502, 503, 504}
def read_with_backoff(
operation: Callable[[], T],
*,
deadline: float,
max_attempts: int,
base_delay: float,
) -> T:
"""只包装不改变资源的读取操作。deadline 使用 time.monotonic()。"""
if max_attempts < 1:
raise ValueError("max_attempts 必须大于 0")
if base_delay <= 0:
raise ValueError("base_delay 必须大于 0")
for attempt in range(1, max_attempts + 1):
try:
return operation()
except requests.exceptions.SSLError:
raise
except APIError as exc:
if exc.status_code not in TRANSIENT_HTTP_STATUS:
raise
last_error: Exception = exc
except (
requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
) as exc:
last_error = exc
remaining = deadline - time.monotonic()
if attempt >= max_attempts or remaining <= 0:
raise last_error
exponential = base_delay * (2 ** (attempt - 1))
jittered = exponential * random.uniform(0.8, 1.2)
time.sleep(min(jittered, remaining))
raise RuntimeError("unreachable")
The max_attempts, base_delay and deadline here are caller policies, not the construction parameters of NexusFlowClient. APIError currently does not expose the response header, so this package cannot read Retry-After; when encountering 429, it can only stop or wait according to the external current limiting policy agreed by this system, and cannot claim that the SDK has automatically followed the response header.
Do not use this function to wrap model.save() , model.run() , run snapshot requests, or JOB_CMD .
Collect Validation Issues Instead of Just Saving One Row of Errors
A local modeling method will immediately throw ValidationError when it encounters an operation that cannot continue. For example the port does not exist, the sheet name is duplicated or the model does not have a server ID. This type of exception only has a message and no problem list; the current model_id , operation phase and str(exc) should be recorded in the batch and then continue to the next item.
The complete business verification of the model is returned by model.validate() ValidationResult:
result = model.validate()
for issue in result.issues:
record = {
"severity": issue.severity,
"code": issue.code,
"message": issue.message,
"scope": issue.scope,
"path": issue.path,
"sheet_id": issue.sheet_id,
"element_id": issue.element_id,
"component_class_id": issue.component_class_id,
"parameter_key": issue.parameter_key,
}
save_validation_issue(record)
severity will only be error, warning or info. sheet_id, element_id, component_class_id and parameter_key may all be empty, and the missing positioning field cannot be regarded as a parsing error. result.counts gives three levels of quantities, result.valid is true only when the error quantity is zero.
If only model.run() or model.save(validate=True) is called, the verification failure will become a merged ValidationError. When you need to make a report or fix multiple problems at one time, you should explicitly call model.validate() first and save all issues; then call run(validate=False) or save as needed. When the verification result structure returned by the server is illegal, the parsing will throw TypeError, which should not be mistakenly recorded as a normal model verification failure.
For the complete process of model editing and verification, see Read, Edit, and Save Models with the SDK.
Design Recoverable Breakpoints
Each batch must contain at least the following:
{
"models": {
"<model_id>": {
"phase": "reading_results",
"job_id": "<platform_job_uuid>",
"next_offset": 18,
"job_status": "success"
}
}
}
model_ididentifies the model being processed in this batch.job_idisjob.id, which is the platform job UUID. As soon asmodel.run()returns successfully, it should be saved.next_offsetindicates the position of the next message to be read, not the ID of the last read message. Save message18after processing message17.phaseis used to distinguish between "not yet created", "creation result unknown", "job UUID obtained", "reading results" and "completed".- The running snapshot should also save the
snapshot_idpre-generated by the caller separately and cannot be placed in thejob_idfield.
Breakpoint files cannot contain access tokens, refresh tokens, passwords, full request headers, or full model snapshots. If multiple processes may update breakpoints at the same time, persistent storage with transactions or conditional writes should be used; the file example below only applies to single-process sequential batch processing.
By consuming the message and then advancing next_offset, you can avoid permanently skipping the message due to "recording the breakpoint first, but the business processing has not yet been completed". But this will form at least once processing semantics: the process crashes when the business write has been successful and the breakpoint has not been saved, and the message will be processed again. When it comes to database writing, event appending or notification sending, (job_id, message_id) should be used as the deduplication key, or business writing and breakpoint updates should be in the same transaction.
Runnable Sequential Batch Processing Skeleton
The script below only calls methods exposed by the SDK. It reads the model ID from the environment variable, completes reading, verification, creating jobs, waiting for the final state and consuming the results one by one; the failure of a single model will not interrupt the entire batch.
The examples are deliberately executed sequentially to facilitate verification of permissions, capacity, and breakpoint logic first. All BATCH_ environment variables are the configuration of this sample script itself, not the built-in parameters of the SDK.
NEXUSFLOW_BASE_URL=<平台根地址>
NEXUSFLOW_ACCESS_TOKEN=<由安全设施注入,可与账号密码二选一>
NEXUSFLOW_REFRESH_TOKEN=<可选>
NEXUSFLOW_USERNAME=<未使用访问令牌时提供>
NEXUSFLOW_PASSWORD=<未使用访问令牌时提供>
NEXUSFLOW_MODEL_IDS=<用英文逗号分隔的模型 UUID>
NEXUSFLOW_STATE_PATH=<断点文件路径>
from __future__ import annotations
import json
import os
import random
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any, TypeVar
import requests
from nexusflow_sdk import (
APIError,
AuthError,
NexusFlowClient,
NotFoundError,
ResultExpiredError,
ValidationError,
)
T = TypeVar("T")
TRANSIENT_HTTP_STATUS = {408, 429, 500, 502, 503, 504}
class CreateOutcomeUnknown(RuntimeError):
"""任务创建可能已被服务端接受,必须先核对,不能自动重放。"""
def require_env(name: str) -> str:
value = os.getenv(name, "").strip()
if not value:
raise RuntimeError(f"缺少环境变量:{name}")
return value
def positive_number(name: str, default: str, *, integer: bool = False):
parser = int if integer else float
value = parser(os.getenv(name, default))
if value <= 0:
raise ValueError(f"{name} 必须大于 0")
return value
def emit(event: str, **fields: Any) -> None:
# 只接收调用处明确挑选的字段,不接收请求头、凭据或完整响应负载。
entry = {"event": event, "time": time.time(), **fields}
print(json.dumps(entry, ensure_ascii=False, sort_keys=True), flush=True)
def error_fields(exc: BaseException) -> dict[str, Any]:
fields: dict[str, Any] = {
"error_type": type(exc).__name__,
"message": str(exc).replace("\r", " ").replace("\n", " ")[:500],
}
status_code = getattr(exc, "status_code", None)
if status_code is not None:
fields["status_code"] = status_code
return fields
def load_state(path: Path) -> dict[str, Any]:
if not path.exists():
return {"models": {}}
payload = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(payload, dict) or not isinstance(payload.get("models"), dict):
raise ValueError("断点文件必须包含 models 对象")
return payload
def save_state(path: Path, state: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(state, ensure_ascii=False, indent=2, sort_keys=True),
encoding="utf-8",
)
temporary.replace(path)
def read_with_backoff(operation: Callable[[], T], *, deadline: float) -> T:
max_attempts = positive_number("BATCH_READ_MAX_ATTEMPTS", "4", integer=True)
base_delay = positive_number("BATCH_BACKOFF_BASE_SECONDS", "0.5")
for attempt in range(1, max_attempts + 1):
try:
return operation()
except requests.exceptions.SSLError:
raise
except APIError as exc:
if exc.status_code not in TRANSIENT_HTTP_STATUS:
raise
last_error: Exception = exc
except (
requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
) as exc:
last_error = exc
remaining = deadline - time.monotonic()
if attempt >= max_attempts or remaining <= 0:
raise last_error
delay = base_delay * (2 ** (attempt - 1)) * random.uniform(0.8, 1.2)
time.sleep(min(delay, remaining))
raise RuntimeError("unreachable")
def validation_records(result: Any) -> list[dict[str, Any]]:
return [
{
"severity": issue.severity,
"code": issue.code,
"message": issue.message,
"scope": issue.scope,
"path": issue.path,
"sheet_id": issue.sheet_id,
"element_id": issue.element_id,
"component_class_id": issue.component_class_id,
"parameter_key": issue.parameter_key,
}
for issue in result.issues
]
def wait_for_terminal(client: NexusFlowClient, job_id: str, *, deadline: float):
poll_interval = positive_number("BATCH_POLL_INTERVAL_SECONDS", "1")
read_budget = positive_number("BATCH_READ_RETRY_BUDGET_SECONDS", "30")
while True:
job = read_with_backoff(
lambda: client.get_job(job_id),
deadline=min(deadline, time.monotonic() + read_budget),
)
if job.is_terminal:
return job
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(f"任务 {job_id} 未在批处理预算内结束")
time.sleep(min(poll_interval, remaining))
def process_model(
client: NexusFlowClient,
model_id: str,
*,
state: dict[str, Any],
state_path: Path,
) -> str:
record = state["models"].setdefault(
model_id, {"next_offset": 0, "phase": "pending"}
)
if record.get("phase") == "create_unknown" and not record.get("job_id"):
raise CreateOutcomeUnknown(
"上次任务创建结果未知;请先核对任务记录并补入 job_id"
)
job_id = record.get("job_id")
if not job_id:
read_budget = positive_number("BATCH_READ_RETRY_BUDGET_SECONDS", "30")
model = read_with_backoff(
lambda: client.get_model(model_id),
deadline=time.monotonic() + read_budget,
)
validation = model.validate()
record["validation"] = {
"valid": validation.valid,
"counts": dict(validation.counts),
"issues": validation_records(validation),
}
if not validation.valid:
record["phase"] = "validation_failed"
save_state(state_path, state)
emit("model_validation_failed", model_id=model_id, counts=validation.counts)
return "validation_failed"
record["phase"] = "creating_job"
save_state(state_path, state)
try:
# 已保存完整校验结果,这里不重复调用统一校验。
job = model.run(validate=False)
except (AuthError, ValidationError):
record["phase"] = "create_rejected"
save_state(state_path, state)
raise
except Exception as exc:
# 服务端可能已创建任务,不能自动再次调用 run()。
record["phase"] = "create_unknown"
record["last_error"] = error_fields(exc)
save_state(state_path, state)
raise CreateOutcomeUnknown(str(exc)) from exc
job_id = job.id
record.update({"phase": "job_created", "job_id": job_id})
save_state(state_path, state)
emit("job_created", model_id=model_id, job_id=job_id)
wait_budget = positive_number("BATCH_JOB_WAIT_SECONDS", "900")
job = wait_for_terminal(
client,
str(job_id),
deadline=time.monotonic() + wait_budget,
)
record.update({"job_status": job.status, "phase": "reading_results"})
save_state(state_path, state)
next_offset = int(record.get("next_offset", 0))
stream_timeout = positive_number("BATCH_STREAM_TIMEOUT_SECONDS", "5")
stream_reconnects = positive_number(
"BATCH_STREAM_MAX_RECONNECTS", "3", integer=True
)
try:
for message in job.stream_results(
offset=next_offset,
timeout=stream_timeout,
max_reconnects=stream_reconnects,
):
message_id = message.get("id")
try:
next_offset = max(next_offset, int(message_id) + 1)
except (TypeError, ValueError):
next_offset += 1
# 真实业务先按 (job.id, message_id) 去重,再推进断点。
emit(
"result_message",
model_id=model_id,
job_id=job.id,
message_id=message_id,
message_type=message.get("type"),
key=message.get("key"),
)
record["next_offset"] = next_offset
save_state(state_path, state)
except ResultExpiredError:
record["phase"] = "result_expired"
save_state(state_path, state)
raise
outcome = "complete" if job.status == "success" else f"job_{job.status}"
record["phase"] = outcome
save_state(state_path, state)
emit(
"item_finished",
model_id=model_id,
job_id=job.id,
job_status=job.status,
next_offset=next_offset,
outcome=outcome,
)
return outcome
def build_client() -> NexusFlowClient:
session = requests.Session()
ca_bundle = os.getenv("NEXUSFLOW_CA_BUNDLE", "").strip()
if ca_bundle:
session.verify = ca_bundle
common: dict[str, Any] = {
"base_url": require_env("NEXUSFLOW_BASE_URL"),
"timeout": positive_number("BATCH_HTTP_TIMEOUT_SECONDS", "20"),
"session": session,
}
token = os.getenv("NEXUSFLOW_ACCESS_TOKEN", "").strip()
if token:
return NexusFlowClient(
**common,
token=token,
refresh_token=os.getenv("NEXUSFLOW_REFRESH_TOKEN") or None,
)
return NexusFlowClient(
**common,
username=require_env("NEXUSFLOW_USERNAME"),
password=require_env("NEXUSFLOW_PASSWORD"),
)
def main() -> None:
model_ids = [
item.strip()
for item in require_env("NEXUSFLOW_MODEL_IDS").split(",")
if item.strip()
]
if not model_ids:
raise RuntimeError("NEXUSFLOW_MODEL_IDS 中没有模型 UUID")
state_path = Path(require_env("NEXUSFLOW_STATE_PATH"))
state = load_state(state_path)
summary = {"complete": [], "failed": []}
with build_client() as client:
for model_id in model_ids:
emit("item_started", model_id=model_id)
try:
outcome = process_model(
client,
model_id,
state=state,
state_path=state_path,
)
summary["complete" if outcome == "complete" else "failed"].append(
model_id
)
except ResultExpiredError as exc:
summary["failed"].append(model_id)
emit("item_result_expired", model_id=model_id, **error_fields(exc))
except NotFoundError as exc:
summary["failed"].append(model_id)
emit("item_not_found", model_id=model_id, **error_fields(exc))
except AuthError:
# 认证失败通常影响整个批次,停止后重新取得凭据。
raise
except Exception as exc:
summary["failed"].append(model_id)
record = state["models"].setdefault(model_id, {})
record["last_error"] = error_fields(exc)
save_state(state_path, state)
emit("item_failed", model_id=model_id, **error_fields(exc))
emit(
"batch_complete",
complete_count=len(summary["complete"]),
failed_count=len(summary["failed"]),
)
if __name__ == "__main__":
main()
This skeleton intentionally retains two human decision points:
create_unknownwill not automatically callmodel.run()again. You should check whether the corresponding job has appeared based on the model, creation time and audit records; after finding it, write the platform job UUID intojob_idof the model. Only after confirming that it has not been created can you clear the status and try again.- The resulting message processing only logs metadata. When accessing the database, message queue or notification service, you must first add business deduplication or transactions, and then write the
next_offsetafter successful processing to the breakpoint.
The default values of time and retry in the example are only used to demonstrate the configuration method and should be adjusted according to test results, platform capacity and business deadlines. They are not production parameters promised by the SDK or platform.
What to Do After the Results Expire
Just because the job record still exists does not mean that the result stream is still within the retention period. When encountering ResultExpiredError:
- Mark the job breakpoint as
result_expiredand retainjob_id, processednext_offsetand business processing records; - Stopping WebSocket reconnection, increasing
max_reconnectsor changingoffsetback to0cannot restore the cleaned results; - Check whether the required results have been persisted on the business side;
- Only when the business allows recalculation, the input version can still be confirmed, and the resource budget allows, a new job will be created; the new job will get a new platform job UUID, and breakpoints must be established separately.
For results reading, message aggregation and tail reading methods, see Run Jobs and Read Results with the SDK. See Model, Job, Result, and Snapshot Lifecycles for the retention boundaries of jobs and results.
Manage Timeout Budget and Concurrency
A batch contains at least four time limits:
| Time Limit | Span of Control | Common Misunderstandings |
|---|---|---|
NexusFlowClient(timeout=...) | Single authentication, REST requests, and partial live connections | Not the entire batch deadline |
| Read retry deadline | A set of safe GETs and their backoff waits | Write requests cannot be overwritten and should not be recalculated to the full budget after each failure |
| Job waiting deadline | Wait from the existing job_id to the final state | A single HTTP request may still consume up to one client timeout, so individual timeouts should be significantly smaller than the total budget |
| WebSocket single timeout | Establish a connection or receive once | stream_results(timeout=...) No hard deadline provided for the entire result stream |
When a strict total batch deadline is required, the script should be supervised by the job scheduler or a separate process. Merely checking the clock between messages does not interrupt a network call that is still blocking.
The concurrency number should not be hard-coded into a "universally recommended value". It is limited by at least the following factors:
- The job quota of the current account and workspace;
- Compute node capacity and resource consumption of a single model;
- The pressure of model verification and space definition reading on the platform server;
- Number of WebSocket connections, result volume, and business-side write throughput;
- Actual feedback for HTTP
429, job queue time and failure rate.
First use sequential batch verification, and then gradually increase the upper limit through configuration. When executing concurrently, each worker thread should independently manage client and breakpoint updates, and multiple threads cannot rewrite the same JSON file without locks. When 429 is received, the queue continues to grow, or the error rate increases, you should reduce concurrency and let existing jobs complete instead of continuing to expand retry traffic.
Record Logs That Can Be Correlated and Desensitized
Each batch log is recommended to contain:
- Event name and time;
model_id,job_id, running snapshot ID and other identifiers with resource types;- Current stage, number of attempts, job status and
next_offset; - Exception class name,
APIError.status_codeor WebSocket handshake status; - Check the
severity,code,pathand optional element positioning fields of the problem.
Do not log:
Authorization, access token, refresh token, password, cookie;- Complete
APIError.payload, complete request or response header; - Unfiltered model snapshot, component parameters, and result message text;
- Authentication object, client object, or all environment variables.
If you need to troubleshoot a server-side error, you can write the response summary filtered by the field whitelist to the controlled log. Don't keep raw responses in the normal batch log for a long time just for "troubleshooting convenience".
Pre-Launch Checklist
- Capture specific exceptions first, then
APIError,NexusFlowErrorand network exceptions; do not classify all failures as "SDK errors". - REST
401only relies on the SDK to automatically refresh once; if it continues,401will stop, and403will go to permission troubleshooting. - Only limited backoff is performed for safe reads or clear side-effect-free verification, and no write operations are handed over to the universal retryer.
- Model saving, job creation, and running snapshot requests check the platform status first when the results are uncertain.
JOB_CMDand external append-type business actions have business deduplication solutions, so there is no need to try again by sending again.- Each model or job records success, verification failure, unknown creation, job failure, result expiration and other results respectively. A single failure will not lose the entire batch progress.
- Explicit verification saves all
ValidationIssuefields; only the mergedValidationErrortext is retained. - The breakpoint saves
model_id, the platform job UUID and the next messageoffsetat the same time, without mixing the job running ID intojob_id. - Stop reconnecting after the results expire; create new job records and breakpoints when recalculation is needed.
- Single HTTP, read retry, job waiting, result flow and total batch time limit are controlled separately.
- Concurrency caps are derived from actual capacity and operational feedback, and can be reduced with
429, queuing, and error rates. - Structured logs use field whitelisting and desensitization, and do not contain credentials, full payloads, and sensitive model parameters.
- Regardless of success or failure, the client session is eventually closed.
Next Steps
- To learn about model validation, saving, and multi-player editing boundaries, please read Read, Edit, and Save Models with the SDK.
- To learn about job waiting, control instructions, running snapshots, and result aggregation, please read Run Jobs and Read Results with the SDK.
- To reconfirm the model, job, run ID and message offset, please read Resource Identifiers.