Skip to content

Tasks

ns.Task runs a Python function or a bash script as a Nebius job. Calling the task starts the job, waits for it, and returns the result. submit returns a TaskRun at once, and a run can be passed to another task, which then starts when the run has finished.

What one task run writes and creates, in order. How jobs, endpoints and tasks work explains each step.

%%{init: {"sequence": {"width": 90, "actorMargin": 30}}}%%
sequenceDiagram
    participant You
    participant Bucket
    participant Job
    You->>Bucket: submit(): code, payload
    You->>Job: create the job
    Job->>Bucket: result.json, files/
    You->>Bucket: result() reads it
    Note over Bucket,Job: preempted: ERROR, TaskFailed

Task

ns.Task(
    function=None,
    *,
    command=None,
    inputs=None,
    image,
    local_libs=(),
    name=None,
    **job_options,
)
Parameter Required Meaning
function one of these two A plain Python function, not async. Its arguments and return value must be JSON values.
command one of these two A bash script, run with set -e. The image needs bash 4 or newer.
inputs no A script's input names: letters, digits, and underscores. Not used with a function, whose inputs are its arguments.
image yes An ns.Image, built on the first run and reused after that, or an image reference such as python:3.12-slim-bookworm. A function task needs python3 in the image.
local_libs no Import names of local packages or modules to send with the task, such as ["mylib"] or ["mylib.training"].
name for a script The task's name. Defaults to the function's name. Lowercased, with other characters turned into hyphens, at most 40 characters. Each run's job is named <name>-<UTC time>.
**job_options no Options of the job, as on JobSpec: gpu, cpu, pricing (on-demand by default, on a GPU too), timeout (default 24h), disk, volumes, env, secrets, restart_attempts, profile, project, and the rest. They are checked here, so a mistake fails at once. inject_files is not available: use local_libs for code and volumes for data.

Constructing a Task does not contact Nebius. After construction these attributes are readable: name, function, command, inputs, image, local_libs.

Functions

A function is sent in one of two ways:

  • By name. When it comes from a package in local_libs, the package is uploaded and the job imports the function. It must be defined at module level.
  • As source. Otherwise its source is sent on its own. It must be self-contained: imports and helpers go inside its body, and it must not use names from the surrounding file, decorators, or variables of an enclosing function. Type annotations are dropped, so they may name anything.

A function defined in a notebook cell is sent as source. IPython keeps a cell's source readable, so this works in Jupyter. The same rule applies: a function that uses names from other cells is refused, with the names it uses. The source runs in the image's python3: use an image with the same Python minor version as your machine.

The function gets its arguments as JSON values and must return a JSON value.

Scripts

A script reads its inputs from the bash array inputs, and returns values by setting keys in the bash array outputs. The call returns outputs as a dict[str, str]. An input that is not a string arrives as JSON text. Pass inputs by name.

hello = ns.Task(
    name="hello",
    image="python:3.12-slim-bookworm",
    inputs=["who"],
    command='outputs[greeting]="hello ${inputs[who]}"',
)
hello(who="world")  # {"greeting": "hello world"}

The script, with its inputs, must be at most 64 KiB. Pass large data as files.

Files and the task bucket

Code, arguments, and results travel through one bucket in the project, ns-workspace-<project id without "project-">. The first run creates it with the label managed-by: nebius-serverless, which needs rights to manage Object Storage in the project, otherwise AccessError. The bucket is not configurable. Every task's job mounts it at the same path, /ns, so a path one task returns can be opened by another.

The package writes these folders:

ns-workspace-<project id>/
├── libs/<hash>.tar.gz           task code archives
├── tasks/<task>/<run>/          a task called on its own
└── flows/<flow>/<run>/<job>/    tasks inside a Prefect flow

Each run has its own folder, with its payload, its result, and files/. A task called on its own uses tasks/<task>/<UTC time>/. A job can write files to $NS_OUTPUT_DIR, the files/ folder of its run. run.output_uri is that folder as an s3:// address.

Reading results on your machine uses S3: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, or the profile in ~/.aws/credentials (AWS_PROFILE, default default).

Variables in a task job

Variable Value
NS_OUTPUT_DIR The run's files/ folder under /ns.
NS_TASK_MOUNT Where the bucket is mounted: /ns.
NS_TASK_FOLDER In a flow's driver job: the flow run's folder, where its tasks keep their runs.

Pricing, restarts and preemption

A task runs on-demand unless it sets pricing, on a GPU too. Jobs and endpoints default to spot on a GPU; a task does not. Pass pricing="spot" for a cheaper machine that can be preempted.

restart_attempts=N restarts the container on the same machine after the command fails, as for any job. For a task, that means a function that raises, or a script that exits non-zero, runs again from the start.

A preempted spot job ends in ERROR with the reason Preempted, and the task raises TaskFailed. Nothing creates the job again. Submit the task again to run it on a new machine: the new run gets a new folder. To continue work, save checkpoints to $NS_OUTPUT_DIR and pass the earlier run's output_path to the new run, which loads them at the start. Write a checkpoint locally, then copy it to the mount: the S3 mount does not support appends (Storage and files).

Task.__call__

task(*args, **kwargs) -> Any

Start a job, wait for it, and return the function's return value or the script's outputs. A failure raises TaskFailed. Ctrl-C while waiting cancels the job.

Task.submit

task.submit(*args, **kwargs) -> TaskRun

Start a job and return its run at once. The first run builds the image when it is an ns.Image, and uploads local_libs when they changed.

An argument may be a TaskRun, or a list or dict that holds runs. submit still returns at once: the job starts when those runs have finished, with their results in their place. If one of them fails, this run is not started and its result() raises TaskFailed. A run still waiting for its inputs when the script ends is never started.

data = prepare.submit(dataset="mnist")
runs = [train.submit(data=data, lr=lr) for lr in (0.1, 0.01)]  # start together, after prepare
best = pick.submit(runs=runs)  # starts when both have finished
print(best.result())

TaskRun

One run of a task, returned by submit. One call of a task is one run, with one Nebius job.

Member Meaning
result() Wait for the job and return the result. Raises TaskFailed when the function raised, the script exited non-zero, the job ended without a result, or the run was not started because an input failed. Later calls return or raise the same outcome without waiting.
cancel() Request cancellation of the run's job. A run still waiting for its inputs is dropped and never starts. Never raises.
job The run's Job: job.id, and the rest.
project The project the run's job is in.
name The UTC time the run started, such as 20261124-153922.
task The task's name.
inputs The inputs by name, with other runs replaced by their results.
output_path The run's files folder as jobs see it, under /ns.
output_uri The same folder as an s3:// address.
started Whether the run has a job. A run waiting for its inputs has none yet; job, name, inputs, output_path, and output_uri then wait for it.

After a kernel restart or a crashed script, the job keeps running until it ends. Find it with nebius ai job list or in the console. Its files stay in its run's folder in the bucket.

Errors

TaskFailed is an ns.Error. Its resource_id is the job id and state the job's final state. A job that ended without a result names the reason when Nebius gives one, such as Preempted. A function's traceback from the job is in remote_traceback. For a script, exit_code is its exit code and outputs what it had set before it stopped. Its recovery names the logs command: nebius ai job logs <id>.

See First task for a runnable example.