Async jobs
**********


Job priority
============

Each "WorkerAsyncJob" runs at ""high"" or ""low"" priority. Workers
take jobs from the high-priority queue first, so a participant who is
waiting for an analysis does not queue behind analyses that nobody is
waiting for. Unless you choose a priority, PsyNet picks one:

* "AsyncCodeBlock": high with "wait=True", low with "wait=False".

* "async_post_trial()": high if

  * the trial maker checks performance ("check_performance_at_end" or
    "check_performance_every_trial");

  * the trial maker is a within-participant chain trial maker
    ("chain_type="within""), because the participant's next trial in a
    chain waits for the previous trial to be finalized; or

  * the trial class overrides "show_feedback()" or "gives_feedback()"
    and keeps "wait_for_feedback = True".

  Low otherwise. Across-participant chains are low because
  participants are usually given another chain while one grows; if
  your participants often wait for chains (for example with
  "wait_for_networks=True" and few chains), set
  "async_post_trial_priority = "high"".

* "async_post_grow_network()" and "async_on_deploy()": high, because
  participants may wait for the next node.

* A "WorkerAsyncJob" you create yourself: high.

To override the choice:

   AsyncCodeBlock(save_summary, wait=False, priority="high")

   class MyTrial(StaticTrial):
       async_post_trial_priority = "low"

   WorkerAsyncJob(refit_model, priority="low").enqueue()

Priority only decides which waiting job starts next; a running job is
never interrupted. If every worker is busy with long low-priority
jobs, a high-priority job still waits for one of them to finish, and
its "timeout" does not count while it waits (see Timeouts). Priority
has no effect on a "LocalAsyncJob", which runs in a thread of the web
process. The CPU table printed after "psynet test local" (see Testing
scalability) has one row per job label, priority and place the job
runs in.


Timeouts
========

A job that runs for longer than its "timeout" fails, and so do its
trial and node. The timeout counts from when the job starts running,
so time spent waiting in the queue does not count. Jobs created
without a "timeout" get "default_timeout", one hour. Trial, network
and node jobs use the trial maker's "async_timeout_sec" (five minutes
by default). An RQ worker stops a "WorkerAsyncJob" function when it
times out; a "LocalAsyncJob" function keeps running in its thread, but
the job is already marked failed.

   WorkerAsyncJob(refit_model, timeout=4 * 3600).enqueue()

A job that has not started within an hour of being enqueued
("max_queue_wait_sec") is failed as probably lost if it can no longer
start: a "WorkerAsyncJob" that RQ no longer has, for example because
its launch failed or Redis restarted, or that RQ failed, stopped or
cancelled, or a "LocalAsyncJob", which starts as soon as it is
launched. A worker job still waiting in the RQ queue is a genuine
backlog and keeps waiting, however long that takes, and a job a worker
has finished is never failed. Lost jobs are not re-run.


Pending jobs
============

Low-priority jobs can build up a backlog that is still running after
the last participant has left. PsyNet protects that backlog on docker-
ssh deployments:

* idle hibernation does not put the app to sleep while any job is
  pending;

* "psynet export ssh" and "psynet export local" end with a warning
  that jobs are still pending, because the export does not contain
  their results; if the jobs cannot be checked, the export prints a
  warning and completes;

* "psynet destroy ssh" wakes the app if it is asleep, then refuses to
  destroy it while jobs are pending, or asks you to confirm when run
  interactively. It also refuses if the jobs cannot be checked, unless
  the app was deployed with "psynet debug ssh" (see below).

Wait for the backlog to finish, export again, and then destroy the
app. For example, "psynet destroy ssh" prints:

   WARNING: my-study: 12 async jobs are still pending (12 low priority);
   the oldest was enqueued 25 minutes ago. Destroying the app now loses their
   results. Wait for them to finish, then run `psynet export ssh` again
   before destroying the app.

Pass "--discard-pending-jobs" to destroy the app anyway, for example
when the jobs can never finish; the command still says how many jobs
it discards. The check queries the app's database from its web
container over SSH, so it works whatever the app's ingress, including
a Cloudflare tunnel that is briefly down. The app cannot be checked
if, for example, it runs an older PsyNet version, its web container is
not running, or it does not answer within 30 seconds. "psynet destroy
ssh" then says why and does not destroy the app: start its web
container and run the command again, or check in the app's logs that
its jobs have finished and pass "--discard-pending-jobs". Apps
deployed with "psynet debug ssh" or "psynet performance-test ssh" are
destroyed anyway, because debug apps' data is treated as disposable.
This includes a debug app that recruits real participants, for example
through Prolific, so deploy real studies with "psynet deploy ssh".
PsyNet recognises these apps by the "debug_ssh_app" config variable
that "psynet debug ssh" sets; apps deployed by older PsyNet versions
lack it and are refused like any other app. When "destroy ssh"
destroys several apps, it skips those it refuses and destroys the
others, then exits with status 1.

A job is pending from "enqueue()" until it finishes, fails, times out
or is cancelled, and "LocalAsyncJob" jobs count too, because
hibernation and destroying stop the web process they run in. The
experiment's clock fails timed-out and lost jobs (see Timeouts) within
about a minute, so they stop counting as pending; a backlog that is
still waiting in the RQ queue keeps counting however old it is.


API
===

Database-backed jobs that run a function outside the current request.

An "AsyncJob" stores a function and its arguments as a row in the
"async_job" table, so that slow work (e.g. "async_post_trial", asset
deposits, or "AsyncCodeBlock" functions) can run without blocking the
participant's request. "WorkerAsyncJob" runs the function on an RQ
worker and supports cancellation; "LocalAsyncJob" runs it in a thread
of the current process. Every job has a timeout,
"AsyncJob.default_timeout" unless given, counted from when it starts;
the experiment's clock fails overdue jobs, and jobs lost before they
started, with "AsyncJob.check_timeouts()".

Constructing a job does not run it. Call "AsyncJob.enqueue()", which
adds the job to the database session and launches it only once the
transaction commits, so the job never starts before the rows it
depends on are saved, and a rolled-back transaction launches nothing.
A job that is created but never enqueued is reported with a warning
when its transaction commits.

Jobs are linked to the objects they work on (participant, trial, node,
network, response, asset) through the "async_jobs" relationships on
those models. When a job fails, "AsyncJob.failure_cascade" fails its
trial and node, and the error is recorded as an "ErrorRecord" pointing
at the job.

A "WorkerAsyncJob" has a priority, ""high"" or ""low"", naming the RQ
queue it is enqueued on; workers take jobs from the "high" queue
first.

class psynet.async_job.AsyncJob(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   A function call that runs asynchronously once its transaction
   commits.

   Use a subclass, "WorkerAsyncJob" or "LocalAsyncJob", and call
   "enqueue()" to run the job.

   Parameters:
      * **function** (*callable*) -- The function to call. Instance
        methods of database objects are supported; the object is
        reloaded in the job's session.

      * **arguments** (*dict**, **optional*) -- Keyword arguments for
        "function".

      * **trial** (*optional*) -- Objects the job works on. They are
        linked to the job through their "async_jobs" relationships,
        and the participant and trial maker are inferred from them
        when not given.

      * **response** (*optional*) -- Objects the job works on. They
        are linked to the job through their "async_jobs"
        relationships, and the participant and trial maker are
        inferred from them when not given.

      * **participant** (*optional*) -- Objects the job works on. They
        are linked to the job through their "async_jobs"
        relationships, and the participant and trial maker are
        inferred from them when not given.

      * **node** (*optional*) -- Objects the job works on. They are
        linked to the job through their "async_jobs" relationships,
        and the participant and trial maker are inferred from them
        when not given.

      * **network** (*optional*) -- Objects the job works on. They are
        linked to the job through their "async_jobs" relationships,
        and the participant and trial maker are inferred from them
        when not given.

      * **asset** (*optional*) -- Objects the job works on. They are
        linked to the job through their "async_jobs" relationships,
        and the participant and trial maker are inferred from them
        when not given.

      * **label** (*str**, **optional*) -- A label for the job;
        defaults to the function's name.

      * **unique** (*bool** or **dict**, **optional*) -- If "True",
        enqueueing fails with an "IntegrityError" when a job with the
        same label, function and arguments already exists. A dict is
        used as the uniqueness key instead.

      * **priority** (*str**, **optional*) -- ""high"" or ""low""; see
        "WorkerAsyncJob". It is stored on a "LocalAsyncJob" too, but
        has no effect there.

      * **timeout** (*float**, **optional*) -- Seconds after which the
        job fails if it has not finished, counted from when it starts
        running; time spent waiting to start does not count, but see
        "max_queue_wait_sec". Defaults to "default_timeout".

   time_taken

      Wall-clock seconds the job took to run.

      Type:
         float

   queue_delay

      Seconds between enqueueing the job and the job starting.

      Type:
         float

   cpu_time

      CPU seconds used by the job's thread while its function ran,
      measured with "time.thread_time()". CPU used by other processes,
      such as the database server, is not counted. Worker and web
      processes run on gevent, so the measurement also counts other
      greenlets that ran while this job waited on I/O: other jobs in a
      worker, and page requests too for a "LocalAsyncJob" in the web
      process. It is exact for jobs that run alone and an upper bound
      otherwise.

      Type:
         float

   default_timeout

      Seconds a job created without a "timeout" may run before it
      fails (3600, i.e. 1 hour).

      Type:
         int

   max_queue_wait_sec

      Seconds after being enqueued (3600, i.e. 1 hour) after which
      "check_timeouts()" fails a job that has not started, if it is
      lost, for example because its launch failed, Redis restarted, or
      the web process running a "LocalAsyncJob" stopped. A worker job
      is lost if RQ no longer has it or failed, stopped or cancelled
      it; one still waiting in RQ is a genuine backlog and keeps
      waiting. A lost job is failed rather than re-run.

      Type:
         int

   classmethod call_function(async_job_id)

      Calls the defining function of a given async job.

   classmethod check_timeouts()

      Fail jobs that have timed out or were lost before starting.

      A job times out once it has run for longer than its "timeout". A
      job that has not started "max_queue_wait_sec" after being
      enqueued is failed if it is lost (see
      "_is_lost_before_start()"); otherwise it keeps waiting. Failed
      jobs are no longer pending. Each job is committed separately,
      and a job that cannot be failed is logged and skipped.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   enqueue()

      Save the job and launch it once the current transaction commits.

      If the transaction rolls back, the job is discarded and never
      launched.

      Returns:
         The job itself, so it can be enqueued as it is created.

      Return type:
         AsyncJob

      Raises:
         * **RuntimeError** -- If the job has already been enqueued.

         * **sqlalchemy.exc.IntegrityError** -- If the job was created
           with "unique" and a matching job exists.

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   property failure_cascade

      These are the objects that will be failed if the job fails.
      Ultimately we might want to add more objects to this list, for
      example participants, assets, and networks, but currently we're
      not confident that PsyNet supports failing those objects in that
      kind of way. An asset's job (e.g. an async deposit) fails the
      asset's trial, which could otherwise never be finalized; a trial
      that is already finalized is left alone.

   classmethod get_process(process_id)

      Deprecated alias of "get_async_job()".

   id

      a unique number for every entry. 1, 2, 3 and so on...

   log_time_started()

      Record the start time and start the timeout.

   classmethod preprocess_args(arguments)

      Preprocesses the arguments that are passed to the job's
      function.

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.async_job.LocalAsyncJob(*args, **kwargs)

   Bases: "AsyncJob"

   An async job that runs in a new thread of the current process.

   Accepts the same parameters as "AsyncJob".

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.async_job.WorkerAsyncJob(*args, **kwargs)

   Bases: "AsyncJob"

   An async job that runs on an RQ worker.

   Accepts the parameters of "AsyncJob". The worker also stops the
   job's function when its "timeout" expires.

   Parameters:
      **priority** (str, default ""high"") -- The RQ queue the job
      runs on, ""high"" or ""low"". Workers take jobs from the "high"
      queue before the "low" queue, but do not interrupt a running
      job: a high-priority job still waits for a free worker if every
      worker is busy.

   cancel()

      Cancel the job.

      The caller's transaction saves the change; the queued RQ job is
      cancelled once that transaction commits, and not at all if it
      rolls back.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   classmethod get_redis_queue(priority)

      Return the RQ queue for jobs of the given priority.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

psynet.async_job.check_priority(priority)

   Raise "ValueError" unless "priority" is one of "PRIORITIES".
