Background jobs
A job is a row of the durable queue (ADR 0150). It is written in the same transaction as the data that caused it, so it exists exactly when that data does. A worker claims it later, under the principal that enqueued it, and runs it in short transactions called chunks. Each chunk commits its effects together with the job’s own progress, so a crash repeats at most one chunk.
Operators: the settings and limits are in Background jobs for operators.
Odoo developers: ir.cron owns its calendar schedule fields and synchronizes the base.cron queue kind.
The server has optional in-app runner composition; its activation is node configuration. Shared policy
comes from the tenant database through an injected native settings source.
Declare a kind
Section titled “Declare a kind”A kind is a name <addon>.<name>, a version, and a handler. The usual handler is a step: a
method of one of your models that does one chunk of work. Because it is an ordinary model method,
another addon can extend it with an override that calls super.
use erp_sdk::jobs::{StepArgs, StepOutcome};use erp_sdk::prelude::*;
erp_sdk::addon!(name = "guide_jobs");
#[model(name = "guide_jobs.recount", description = "Recount", addon = "guide_jobs")]pub struct Recount { #[field(char)] pub name: Option<Arc<str>>,}
#[methods(Recount, addon = "guide_jobs")]impl Recount { /// One chunk: count a batch, say how far it got. #[method] async fn run_step( _this: &RecordSet<Recount>, _tx: &mut Transaction, args: StepArgs, ) -> Result<StepOutcome> { let done = args.progress.as_ref().and_then(|p| p["done"].as_u64()).unwrap_or(0); let total = args.payload["total"].as_u64().unwrap_or(1); let next = done + 1; let progress = erp_sdk::serde_json::json!({ "done": next }); Ok(if next >= total { StepOutcome::done(progress, 1) } else { StepOutcome::more(progress, 1, Some(total - next)) }) }}
erp_sdk::jobs::register_job_kind!( RECOUNT_KIND, erp_sdk::jobs::JobKindDecl::new( "guide_jobs", "guide_jobs.recount", erp_sdk::jobs::HandlerRef::Step { model: "guide_jobs.recount", method: "run_step" }, ) .max_attempts(5));
fn main() {}A step returns the job’s new progress (replacing the old one), how many items it did and how many
are left. finished completes the job in the same commit. The payload and the progress are data:
bounded JSON that is never evaluated. Do not put credentials in them; store a reference.
Builder settings of a kind (all optional): version and accepts (a rolling upgrade runs jobs
written by an older version), backoff, max_attempts, priority, history, timeouts
(Maintenance for long upkeep), max_concurrency and elevated (core and base maintenance
kinds that run as an elevated principal; a runner built with exclude_elevated never claims them). The registry refuses a malformed name, a
name outside your addon’s prefix, a duplicate, and principal(System) for any addon but the core
and base.
Enqueue inside your transaction
Section titled “Enqueue inside your transaction”use erp_sdk::jobs::{EnqueueRequest, JobKey, OnDuplicate, When};use erp_sdk::prelude::*;use std::time::Duration;
async fn schedule(tx: &mut Transaction) -> Result<()> { let env = tx.env(); let request = EnqueueRequest::new("guide_jobs.recount") .payload(&erp_sdk::serde_json::json!({ "total": 3 }))? .at(When::After(Duration::from_secs(60))) .dedup(JobKey::new("recount:warehouse:3")?, OnDuplicate::Earliest); tx.enqueue(&env, request).await?; Ok(())}
fn main() {}- The job runs as the caller: the user and companies of
env, resolved again at every chunk. If that user is archived or loses the company, the job becomes a dead letter; it never falls back to another principal. dedupmakes the enqueue idempotent among live jobs of the kind (Keepleaves the old one,Earliestlowers its due time).singletonlets at most one job with the key run at a time, on any node.- A dedup key does not include the principal: a second caller with the same kind and key finds the
first caller’s job and, with
Keep, leaves it as it is, so it runs as the first caller. Put the user in the key when the work differs per user. enqueue_manywrites up to 1,024 jobs with one statement.- Running as another user needs an audited elevation; until it ships the call is refused with an error that says so. Only core code may name another user today.
Cancel a job you enqueued
Section titled “Cancel a job you enqueued”When a business record has one job (a scheduled message) and the record is cancelled or rescheduled, drop the job instead of leaving a stale one that wakes up to do nothing:
use erp_sdk::jobs::JobKey;use erp_sdk::prelude::*;
async fn drop_job(tx: &mut Transaction, id: i64) -> Result<()> { let env = tx.env(); let key = JobKey::new(&format!("{id}:1"))?; let cancelled = tx.job_cancel_by_key(&env, "guide_jobs.recount", &key).await?; // say what you expect: zero is a count, not an error, so a missing job is yours to catch if cancelled != 1 { return Err(Error::invariant(format!("job {} was not live", key.as_str()))); } Ok(())}
fn main() {}job_cancel_by_keys(&env, kind, &[keys]) does the same for many keys in two statements (at most 10 000), for example
the keys of every row of a deleted record.
job_cancel_by_key needs no administrator right. It cancels the live jobs of the kind and key that the caller’s
user enqueued and returns how many; a job of another user is left alone (it counts as missing). Server code
that must cancel whoever’s job it is (after its own access check) passes env.sudo(true); an RPC or a client
cannot. Waiting jobs leave the queue with a cancelled history row, a running job is asked to stop, dead letters
stay for the operator. ADR 0150 D17.
Zero cancelled has four meanings, and the caller tells them apart: the job already finished (a failed record), it is a
dead letter (proceed), a non-dead job with the key exists but another transaction holds it (a claim in flight: return a
serialization failure, Error::new(ErrorKind::Concurrency, ..).with_sqlstate(Some("40001".into())), and the unit of
work repeats the call), or no job exists at all (the dead letter expired or an administrator discarded it: do not fail,
log, and re-enqueue if the record still needs the job). Do not treat any of them as an invariant breach that sticks the
record. Lock order: a cancel locks your business row first and the job row after, a running chunk the other way round, so
a rare 40P01 deadlock is possible and retried.
Failures
Section titled “Failures”A handler or step returns an error to say what happens next:
| Error | Effect |
|---|---|
a database or lock failure (the default for ? on them) | retried after a capped exponential backoff with jitter; a dead letter after max_attempts |
| validation, access or programming errors | dead letter at once |
JobError::Yield { after } | run again later, the attempt is given back (a rate limit) |
JobError::item(..) inside chunk_items | that item fails alone (below) |
A chunk that commits progress restarts the attempt count: a long job is not killed by failures that came before it made progress. A serialization failure inside a chunk runs the chunk again.
Native handlers and per-item isolation
Section titled “Native handlers and per-item isolation”Core crates and native addons can implement JobHandler and drive chunks themselves, with items
that fail individually and external steps such as sending mail. In a native handler:
use erp_sdk::jobs::{ChunkResult, JobContext, JobError, RunOutcome};use erp_sdk::BoxFuture;
async fn run(ctx: &mut JobContext<'_>) -> Result<RunOutcome, JobError> { while !ctx.budget_exhausted() { let report = ctx .chunk(|_tx| { Box::pin(async move { Ok(ChunkResult::more(erp_sdk::serde_json::json!({}), 10, None)) }) }) .await?; if report.finished { return Ok(RunOutcome::Done); } } // the run's budget is used and work remains: go back behind the jobs that are due Ok(RunOutcome::Continue)}
fn main() {}chunk_itemsruns the whole batch set-based first; when an item-attributable error comes (a constraint or data error, orJobError::item), it runs the batch again with one savepoint per item. Failing items are rolled back, listed inerp_job_item_failureand counted; the others commit with the progress. A batch in which every item fails is a failure of the chunk.externalruns work outside any transaction while the runner renews the lease; poll theCancelTokenbetween items and callcheckpointevery few of them. After a crash the next run reads the stored progress and repeats at most the items after the last checkpoint, so effects must be safe to repeat.- A run stops starting chunks after both
jobs.max_chunks_per_runchunks andjobs.run_budget_secsseconds, then continues in a new run. - Chunk closures return boxed futures (
Box::pin(async move { .. })). This keeps handler futuresSend; async closures do not yet do that reliably.
Extend another addon’s kind
Section titled “Extend another addon’s kind”Override the step method of the owning model and call super; both effects commit in the same chunk. This is how Odoo addons change what a cron calls, and it works for native and WebAssembly addons alike because the step is an ordinary method.
Porting from Odoo
Section titled “Porting from Odoo”| Odoo | Here |
|---|---|
ir.cron record in XML | the same record; one job row per schedule will be kept for you (not delivered yet) |
_trigger(at, coalesce) | ir.cron trigger, or enqueue with dedup |
_commit_progress | a chunk boundary: progress commits with the chunk’s effects, never in the middle of a call |
| the server action run under the cron user | a step or handler run as the stored principal |
Data-only addons can add schedules (ir.cron records calling server actions) but cannot add
kinds, because a kind needs code.
Isolated native maintenance runners
Section titled “Isolated native maintenance runners”A trusted composition root can call JobRunnerBuilder::maintenance_kinds with exact references to
registered native System declarations using Maintenance timeouts and ReadCommitted isolation.
The empty list, a copied/unregistered declaration or an incompatible handler is refused at build.
The same selection applies to claims, next-due queries, reaping and direct execution; handing a
claim to the wrong runner returns Access before execution or settlement. run_claimed now
returns Result<()> for this admission result; handler outcomes still settle through the queue.
Use additive exclude_kinds(names) or exclude_elevated() for the ordinary runner.
Inclusion that conflicts with exclusions is refused. Addon data and job payloads must never supply
the elevated set. Share a database_slots semaphore sized to jobs.workers_per_db and the existing
process_slots semaphore sized to jobs.workers between the pair. The semaphores bound the pair;
creating separate pools would give each runner a separate allowance.
Native attachment composition supplies a minimal owner ORM and supervised generation replacement. Enable it explicitly per node; every external removal still requires current fence admission. Ordinary request credentials remain separate.
Attachment composition keeps the existing additive exclude_kinds(names) and exclude_elevated()
APIs. maintenance_kinds(declarations) adds an exact registered native System allowlist, validated
for maintenance timeout and READ COMMITTED isolation; inclusion that conflicts with exclusions is
refused. The effective set applies to claim, next-due, direct execution and reaping. database_slots
and process_slots accept the shared pools used by the ordinary/owner runner pair; configuration
must not allocate a second independent worker allowance. The server’s owner allowlist is fixed in
native code, not selected by payload or an addon’s elevated flag.
Declared shared policy
Section titled “Declared shared policy”Base publishes Shared jobs.* catalogue entries as database-global base.jobs.* declared settings.
For example, jobs.chunk.default.lock_ms maps to base.jobs.chunk.default.lock_ms. The catalogue remains
the source of defaults and bounds; its read-only Setting::is_shared() marks the scope. Group validation
reuses JobSettings::builder() so retry backoff and timeout ordering are checked against unchanged values.
workers, workers_per_db, claim_batch and run_in_app remain node configuration.
The Settings service stores and audits administrator choices. New admissions read committed database policy; an active run keeps its captured limits. Saving a new value does not rewrite a granted lease or change a running handler’s snapshot.
Admission policy snapshots
Section titled “Admission policy snapshots”JobSettingsSource is an ORM-owned native interface; base provides DatabaseJobSettingsSource over the
existing declared Settings service. Native composition gives its minimal reader a separate bounded primary
pool. The source returns a validated JobSettingsSnapshot; the ORM applies only the node’s local capacity.
Every read is bounded by the node ORM transaction timeout, including connection acquisition. Sources must
read committed revision and values consistently and must return errors for unavailable or corrupt policy.
Orm::job_settings_snapshot().await is for new admission. Orm::job_node_settings() describes local capacity
and explicitly static configuration; it is not a live Shared-policy getter. OrmBuilder::job_settings(...)
selects static policy for isolated core fixtures. With a database source attached, explicit Shared process
overrides are refused by name. Orm::rebuild retains its source; minimal owner ORMs share the authority.
A claimed job retains an immutable snapshot. Native handlers use JobContext::settings() and
settings_revision() rather than reloading policy. Budgets, timeouts, deadline, renewal, progress writes,
retry defaults and retention stay consistent for that run. Persisted attempts and validated kind overrides
retain their existing meanings. A later claim can read an older checkpoint larger than its current write
limit, but must write within its newly admitted limit. New enqueue payloads use the current policy.
job_settings_identity() describes provider/schema/catalogue compatibility in database mode; mutable
values and revisions do not enter node identity. Static mode remains value-sensitive. Node capacities,
build/addon identity, readiness, leases and epoch fencing retain their existing roles.