Skip to content

Jobs

Job is one Nebius job: built from its parameters, created once with create(). ns.jobs reloads a job from a saved id. JobSpec holds the same parameters as data, for YAML and reuse. Import the package as ns.

job = ns.Job(
    command=["nvidia-smi"],
    image="nvidia/cuda:13.1.1-runtime-ubuntu24.04",
    gpu="h100",
    timeout="10m",
)
job.dry_run()  # the request as data; nothing is created
job.create()   # once; sets job.id
job.wait()

How a job moves through its states, and the calls that move it. How jobs, endpoints and tasks work explains each one.

stateDiagram-v2
    %% states: job
    state "PROVISIONING<br>IMAGE_PULLING<br>STARTING" as Starting
    state "COMPLETED<br>FAILED" as Ended
    [*] --> Starting: create()
    Starting --> RUNNING
    RUNNING --> Ended: exits
    RUNNING --> CANCELLING: cancel()
    CANCELLING --> CANCELLED
    Starting --> ERROR: no capacity
    RUNNING --> ERROR: timeout, preempted

A preempted spot job ends in ERROR with the code Preempted, and nothing creates it again: see Spot preemption.

Job

One job on Nebius: built from its parameters, created once, then waited on.

ns.Job(*, command, image, timeout, **parameters)  # the parameters below
ns.Job(spec)                                      # from a JobSpec

Building a Job contacts nothing. create() sends the job once and sets id. get, wait, cancel and display need a created job, and raise before create().

command is passed by name. An unnamed first value must be a JobSpec, and anything else raises ValidationError. ns.Job(spec) takes no other argument, and checks the spec again (see Changing a spec).

ns.jobs.get(id) returns a Job for a job that already exists. Its spec is not known, so spec, dry_run, to_cli and create raise on it. Use record.

Parameters

ns.Job(...) and ns.JobSpec(...) take these parameters, all by keyword. A mistake raises ValidationError when the job is built, before any Nebius call.

What runs

Parameter Required Meaning
command yes Nonempty list of strings: the container command and its arguments. A shell string is rejected. Details
image yes name:tag or registry/path@sha256:<64 hex>, sent unchanged: a tag is not resolved to a digest.
name no The label shown in the console. When omitted, each create() makes a new job-<12 hex> name. Details
working_dir no Container working directory, at most 128 characters. Defaults to the image WORKDIR.
env no dict[str, str]. Values never appear in dry runs or errors. Use secrets for tokens.
secrets no dict[str, str] of variable name to MysteryBox id (mbsec-… or mbsecver-…). Details
registry_secret no MysteryBox version id (mbsecver-…) for a private image registry. Details
volumes no Mount strings, such as s3://<bucket name>:/data:ro. Mode ro or rw (default). Details
inject_files no local_path:container_path strings. Each file is read on create, at most 64 KiB. Details

Machine

Parameter Required Meaning
gpu no GPU selector MODEL[:COUNT], such as "h100" or "h100:8": Nebius picks the platform and preset. See Machine selection.
cpu no CPU selector FAMILY:VCPUS, such as "amd:16". Excludes gpu. Omit gpu, cpu and platform for the smallest CPU machine.
platform no Explicit platform id. Excludes gpu and cpu.
preset no Explicit preset id. Defaults to the platform's smallest preset. An unknown platform needs it.
disk no Boot disk size, such as "500Gi". Defaults to 250Gi.
shm no /dev/shm size, such as "64Gi", or 0; an integer is bytes. Defaults to 16Gi on a GPU machine and none on CPU, as in the CLI.

Limits and cost

Parameter Required Meaning
timeout yes The longest the job may run: "30m", "24h", seconds or a timedelta, between 5 minutes and 168 hours. Required, so every job has a cost limit. Details
pricing no "spot" or "on-demand"; anything else raises ValidationError. Defaults to spot on a GPU machine and on-demand on CPU, where spot raises UnsupportedFeature. See On-demand or spot.
spot_policy no Pricing policy id that caps the spot price: the machine is preempted above the cap. Requires spot pricing.

Retries

Parameter Required Meaning
restart_attempts no Restarts of the container on the same machine after the command fails. 0 (default) runs it once, -1 has no limit. Details

Where

Parameter Required Meaning
project no Project id. Overrides the profile's project.
profile no Nebius CLI profile name. Defaults to the active profile.
subnet_id no Subnet id. Needed only when the project has more than one subnet.

The CLI flag and API field of each parameter are in the CLI and API map.

Parameter details

command

The first element is the container command. The others are POSIX-quoted and joined into one args string; a one-element command sends no args. Wrap shell syntax as ["bash", "-lc", "a && b"].

timeout

Stored as whole seconds. Below 5 minutes or above 168 hours raises ValidationError: the CLI's range. Nothing is rounded or clamped. Nebius's own defaults differ by entry point (24 hours for job create and the API, 1 hour for job run), so the client asks for one. Nebius checks the deadline asynchronously after provisioning, so a job can run briefly past it. A timed-out job is returned as data, with status.state_details.code == "TimeoutExceeded".

volumes

s3://<bucket name>:/container_path[:mode], or source:/container_path[:mode] for a bucket id or a filesystem. On create() and dry_run(server=True), a bucket name is looked up in the project and sent as the bucket's id. A missing bucket raises AccessError before create. An s3:// string with a fourth :profile part raises UnsupportedFeature. See Storage and files.

inject_files

CLI --inject-file strings. Each local file is read on create(), not when the job is built, and sent as container content. A dry run lists the strings and does not read the files.

secrets

A secret id (mbsec-…) takes its latest version; a version id (mbsecver-…) pins one. The container gets the payload entry whose key matches the variable's name, or the first entry. Names follow [A-Za-z_][A-Za-z0-9_]* and must not repeat an env key. Dry runs show the ids. The values never reach the client.

registry_secret

The payload must have REGISTRY_USERNAME and REGISTRY_PASSWORD. A secret id (mbsec-…) raises ValidationError, unlike in secrets: the API pins registry credentials to one version. The CLI's --registry-secret resolves a secret name or id to a version; this client does not yet.

restart_attempts

N allows up to N restarts after the first run. -1 restarts without limit, like the CLI's --restart-policy on-failure. A successful exit is never restarted. Nebius never restarts after preemption, lack of capacity, an unexpected machine stop, a startup failure or a timeout: the job ends in ERROR. See Spot preemption. Below -1, a bool or a non-integer raises ValidationError. It is not the CLI's global --retries, which counts API request retries.

name

Sent unchanged on every create. When omitted, the job's name is the one create() generated, so a loop gives distinct names. A dry run generates one too, so it cannot predict the name a later create sends. With idempotency_key=, the name comes from the key (Job.create). The spec's name stays None. It is not a lookup key.

Properties

Property reads do not perform I/O.

Property Meaning
spec The spec this job was built from. Raises on a job from jobs.get.
id Nebius job id, or None before create(). It never changes after create().
name Display name: the name parameter, or the one create() generated.
status Raw status.state string. Before the first successful fetch, this is the state from the create response, or None when create did not include one.
record Last fetched job JSON, or None before the first successful get or wait.

Job.dry_run

job.dry_run(*, server=False, region=None, project=None) -> dict

The create request as data. Creates nothing.

Without server, the request is built here. Project and region come from project= / region= when passed, otherwise from the active SDK profile (profile= on the spec selects it). When the project id is known and the profile does not name a region, the region is spec.region from IAM v2 ProjectService.get. That read is not a job create. A missing or ambiguous project, or a project with no region, raises ValidationError.

The description includes image, command, args when present, project, region, gpu, cpu or platform and preset, timeout (seconds), pricing, subnet_id when set, volumes when set, inject_files when set, env (key names only), name, disk, shm when sent, and, when set, restart_attempts (when not 0), working_dir, secrets (env name to MysteryBox id), registry_secret, and spot_policy. Env values, secret values, and inject-file contents are not included. Without name=, a fresh name is generated, so a dry run cannot predict the name a later create sends.

server=True also sends the request to Nebius with dry_run set: Nebius validates it, volume sources included, and creates nothing. Its answer is under "server". A rejection raises what create() would raise. Bucket names in volumes are looked up first, as for a create.

Job.to_cli

job.to_cli(*, project=None) -> str

Returns the nebius ai job create command that sends the same request as create(), one flag per line, for a shell or the Nebius docs. It does not contact Nebius. Without name=, a fresh name is generated, as create() does. project (or the spec's) becomes --parent-id; without one, the CLI uses its profile's project. With no machine argument it prints the CPU platform explicitly, because the CLI's own default is a GPU. An s3://<bucket> volume prints as given: the CLI takes the bucket name itself.

Nothing secret is printed: env values become --env KEY="$KEY" placeholders for the shell to fill, secrets appear by id, and a token never appears. restart_attempts above 0 has no CLI flag and is printed as a # note. The flags come from the same table as the CLI and API map, and a test keeps the two in step.

Job.create

job.create(
    *,
    region=None,
    project=None,
    idempotency_key=None,
    quiet=False,
) -> Job

Creates the job on Nebius, once, and returns this Job. It blocks until Nebius has accepted the job and the id is known, and does not wait for the container. It prints one submission line. quiet=True suppresses that line for this call only.

A second create() on the same Job raises ValidationError: a Job is one job. For another job, build another ns.Job(...). Without name=, each create gets a new job- name, so a loop gives distinct names.

region and project work as for dry_run. Pass region to skip the project lookup. Nebius resolves gpu/cpu in the project's region at create. project on this call overrides the project parameter.

An optional transport= keyword replaces the Nebius SDK client. Tests use it. Scripts leave it unset.

idempotency_key= makes a create safe to retry. Every create sends one x-idempotency-key: this argument, or a new UUID for the call. When the outcome is ambiguous (a non-definite gRPC code, or an accepted operation without an id), the client sends the same request again with the same key, up to 3 times, and Nebius returns the resource it already made instead of making a second one (checked live: same key and body return the same id; same key with a different body is rejected with INVALID_ARGUMENT). Only then does it raise SubmissionUncertain, whose idempotency_key and recovery say how to retry. Pass your own key, such as "lr-3e-4", to re-run a notebook cell or a script and reconnect to what it already created. Without name=, the default name is derived from the key, so a same-key retry sends an identical request; a create without a key still gets a fresh name. How long Nebius remembers a key is not documented.

Job.create_async

await job.create_async(
    *,
    region=None,
    project=None,
    idempotency_key=None,
    quiet=False,
) -> Job

Same call as create, including quiet. Cancelling the await leaves the cloud job running.

Job.get

job.get(*, quiet=False) -> dict

One nebius ai job get. Returns the job JSON: state plus the submitted params. Stores that JSON on record and status. Prints one snapshot line. quiet=True suppresses it for this call only.

FAILED, CANCELLED, ERROR, and a platform timeout are data. get does not raise because the container exited badly.

Job.wait

job.wait(timeout=None, *, quiet=False) -> dict

Polls get about every 10 seconds until status.state is terminal, then returns that JSON. Terminal states are COMPLETED, FAILED, CANCELLED, ERROR, and DELETING. The raw string is preserved. Each new state is one line, with the seconds since the wait started. The last line is the outcome. An interactive terminal also keeps a spinner on the current state. quiet=True suppresses that progress for this call only.

timeout is seconds, a duration string such as "45m", or a timedelta. wait(timeout=0) performs one fetch. When the state is not terminal it raises WaitTimeout with the job id. wait(timeout=seconds) stops the local poll at that deadline. Neither form cancels the cloud job. The job may still be running. Reload it with jobs.get(id) or call cancel.

Spot preemption

Nebius can stop a spot machine. The job then ends in ERROR with state_details.code "Preempted". wait() returns that record like any other ERROR: nothing creates the job again, and job.id never changes. Nebius does not restart a preempted machine, and restart_attempts only restarts a failed command on the same machine.

To run it again, create a new job from the same spec:

record = job.wait()
details = record["status"].get("state_details") or {}
if details.get("code") == "Preempted":
    job = ns.Job(job.spec).create()  # a new job, with a new id

The new job starts from scratch with the full timeout, so save checkpoints to a mounted volume and resume from them (Storage and files). A preempted task ends in TaskFailed: see Pricing, restarts and preemption.

Job.cancel

job.cancel(*, quiet=False) -> dict

Requests cancellation and returns when the request is accepted. It does not wait for the container to stop: the job is usually CANCELLING at that point, and stopping can take minutes. The payload does not claim the container has stopped. wait() returns once the state is CANCELLED. Progress says the request was accepted. quiet=True suppresses that line for this call only. A later get reports the cancelled state when Nebius has finished cancelling.

Job.display

job.display() -> None

Prints the last fetched record as a short summary on stdout: id, name, state, image, command, machine, disk, timings, and one line per instance. Bytes and durations are human-readable. The state word is colored on a terminal. NO_COLOR and a non-terminal stdout leave the text plain. record stays the raw JSON.

display does not fetch. Before the first successful get or wait it prints the id, the name, and no record yet.

Awaited twins

await job.get_async(*, quiet=False)
await job.wait_async(timeout=None, *, quiet=False)
await job.cancel_async(*, quiet=False)

Same calls as the synchronous methods, including quiet. Cancelling wait_async or get_async does not cancel the cloud job. A cancelled wait_async also stops its progress display and its polling, so asyncio.run can return. Sync calls work in a notebook cell, and the awaited twins keep an event loop responsive: see Async and notebooks.

jobs

Module-level collection, ns.jobs. It matches the CLI noun nebius ai job.

jobs.get

ns.jobs.get(job_id, *, profile=None, project=None, quiet=False) -> Job

One nebius ai job get, starting from an id string. Returns a Job whose record is already filled. Does not create a job. Prints one snapshot. quiet=True suppresses it for this call only.

profile and project select the SDK profile for this fetch. transport= is the same test injection as on Job.create.

jobs.get_async

await ns.jobs.get_async(
    job_id,
    *,
    profile=None,
    project=None,
    quiet=False,
) -> Job

Same fetch as jobs.get, including quiet.

JobSpec

Specs as data, for advanced use. A JobSpec holds the parameters of ns.Job as frozen data: to load and save YAML, to reuse a recipe with clone(), to compare recipes, or to give an agent tool a JSON schema. ns.Job(spec) builds a job from it, and job.spec is the spec of a job.

ns.JobSpec(*, command, image, timeout, **parameters)  # the parameters of ns.Job

Building a spec contacts nothing. Each parameter is readable as an attribute of the same name. command and volumes are tuples, env and secrets are dicts, timeout is in seconds, and pricing is None unless it was set. repr(spec) leaves out env values.

Specs are data

A spec is frozen and compares by value. Its methods make no Nebius call.

Member Meaning
spec.clone(**changes) A copy with changes, built through the constructor, so a change is checked like the original arguments. spec.clone() equals spec.
spec.to_dict(redact=True) The fields as JSON values. redact=True writes env values as "<hidden>".
spec.to_yaml(redact=True) A schema-version-1 YAML document that from_yaml reads back. profile, project and inject_files are left out.
JobSpec.from_yaml(path) A spec from a YAML document. See below.
JobSpec.model_json_schema() The JSON schema of every field, for editors and agents. A Pydantic AI tool can take a JobSpec as its argument.
JobSpec.model_validate(data) A spec from a dict. A mistake raises ValidationError, whose details lists each problem.

JobSpec is a Pydantic model, and pydantic>=2,<3 is a dependency of the package.

Changing a spec

Use spec.clone(**changes), for example ns.Job(spec.clone(timeout="2h")).create(). Pydantic's model_copy(update=...) and model_construct() skip the checks, so ns.Job(spec) checks the spec again: an invalid one raises ValidationError with the constructor's message, without env values or tokens, and a valid one is kept as it is (ns.Job(spec).spec == spec).

JobSpec.from_yaml

ns.JobSpec.from_yaml(path) -> JobSpec

Load a schema-version-1 command document. Relative strings inside the document are not expanded.

schema_version: 1
kind: job
image: nvidia/cuda:13.1.1-runtime-ubuntu24.04
command: ["nvidia-smi"]
gpu: h100
timeout: 1h

The keys are schema_version, kind, and the same keys as the parameters, except profile, project and inject_files. schema_version must be 1 and kind must be job. command is a list of strings. gpu or cpu selects the machine and may be omitted for the CPU default; gpu: cpu is rejected. What a document may not hold is in YAML and the CLI.