# Queues

A queue holds items in a Space until its consumer works them off. The consumer is
one routine entry: the routine's agent, or one script the published routine pins
(entry.kind script, alias). Flow: queues.create (consumer, batch_size,
max_concurrency, rate_per_second, max_attempts) -> queues.sources.set (webhook
and/or platform event) -> items arrive -> the platform claims batches and starts
runs on behalf of the user who last configured the queue -> queues.get shows
pending and dead items and the webhook URL.

Sources and ways in:
- Webhook (queues.sources.set webhook): every accepted delivery becomes one item
  with the delivery as payload ({method, path, query, headers, body}, providers
  add event and delivery_id). The delivery id is the dedupe_key, so a provider
  retry adds nothing. A paused queue keeps accepting. An inactive webhook or an
  organization in read-only mode holds the delivery instead of losing it (202
  {"status": "stored", "hold_reason": "trigger_inactive" | "organization_read_only"
  | "order_behind"}); held deliveries are enqueued in arrival order within a minute
  of the trigger being active again, and a new delivery waits behind older held
  ones. The first held delivery of a pause (not order_behind) at once alerts the
  Adlass team and sends a notification (also by mail) to the queue's run_as user, the person
  who set up the webhook and the organization's admins, once per pause; reactivate
  with queues.sources.set (webhook.active true, resend the event source too).
  queues.get and queues.list show on sources.webhook held_count, oldest_held_at,
  hold_reason, inactive_reason {code, message} (e.g. actor_removed when the
  person it ran as left), last_delivery_at and last_enqueued_at. After 7 days
  held the Adlass team gets an alert; after 30 days they are
  discarded with an alert that names the orders (the nightly reconciliation of a
  template queue looks 31 days back and finds those orders again). Events the
  webhook does not subscribe to still answer ignored. Shopify and Amazon SES (SNS) work as provider integrations. For
  `ses` in mode `subscription` Adlass creates the SNS topic and the event
  destinations itself; without `events` the recommended ones apply (bounce,
  complaint, reject, click). In mode `manual` `integration.source` holds the SNS
  topic ARN the user subscribes the webhook URL to.
  `bold` works in mode `manual` with `grant_id` of the Bold connection: Adlass
  checks the signature with the llave secreta stored on that connection, and the
  user registers the webhook URL in the Bold panel (Integraciones → Webhooks).
- Platform event (queues.sources.set event {event_type, entity_id, severity,
  filters, order_key_from, active}): one item per matching event of the queue's
  Space ({event_type, entity_type, entity_id, payload}). entity_id and severity
  narrow to one entity or severity. filters (at most 20, all must match) are
  {field, operator, value}; field is a dot path into the event payload (e.g.
  changed_values.stage), operator is one of:

  | operator | matches when |
  |---|---|
  | eq / neq | the field's text equals / differs from value; strings compare as they are, other values as JSON (true, ["a", "b"]); a missing or null field matches only neq |
  | contains | value is a case-insensitive substring of that text |
  | exists | the field is present and not null; value is required but ignored (send "") |

  Events caused by this queue's own batches are not added again.
- Script: ctx.queues.enqueue("slug", [{"payload": {...}, "dedupe_key": "..."}],
  delay_seconds=0), at most 1000 items per call. The slug must be a literal so
  the manifest lists it; the queue must be in the run's Space.
- API / agent: queues.items.enqueue(queue_id, items=[{"payload": {...}, "dedupe_key": "...",
  "order_key": "..."}], delay_seconds=0, idempotency_key), at most 1000 items per call;
  returns {queued, duplicates, item_ids}. Items are stored with source_kind api.
Items run with the rights of the queue's run_as user, so only Space managers (and
scripts or API callers that are run_as or a manager) may add them.
A payload is a JSON object of at most 1 MiB. An item whose dedupe_key the queue
still holds is not added again.

How batches run:
- Items run oldest due first. With ordered_by_key the items of one order_key run
  strictly one at a time in arrival order (an item in backoff holds its key; a dead
  item blocks it until queues.items.retry_many or queues.items.discard_many); other
  keys are not held back. A batch has at most one item per key. An ordered queue
  needs an order_key on every item (order_key_required); a webhook whose order_key
  path does not resolve stores the item dead (order_key_missing) and alerts.
  Queues of different Spaces share the global runner slots in turns, oldest last
  dispatch first.
- A script consumer gets the payloads as items; each item carries the reserved key
  _queue {item_id, ref, attempt, enqueued_at, source_kind, dedupe_key, order_key}.
  The script's input schema is checked without _queue; an item that fails it
  goes straight to the dead letter with payload_invalid.
- An agent consumer gets the batch as run items (batch_size 1 to 50, default 1); document
  events add their document to the run scope.
- rate_per_second limits items per second; fractions work (0.28 for items that
  each send one mail to 50 recipients at 14 mails/s). max_concurrency limits
  parallel batches.

Results per item (script consumer):
- No exception for the item: done.
- ctx.exception(i, code, message, retry=True): the item retries with backoff
  (30 s doubling, at most 1 h) and goes to the dead letter after max_attempts. retry=False sends it there at once.
  item_index -1 applies to the whole batch.
- A failed integration write of the batch, or a failed run, retries every item of
  the batch. integration_rate_limited defers without using up an attempt.
  integration_provider_rate_limited: the provider answered 429 four times; the item
  retries with backoff and spends an attempt.
- integration_write_uncertain, business_key_required and payload_invalid always
  go to the dead letter.
An agent batch is done when the run succeeds; a failed agent batch goes to the
dead letter at once (no automatic retry).

Idempotency (delivery is at least once):
- Every integration write in a queue batch needs a business_key; without it the
  call fails with business_key_required. Name the business object
  (shopify.com:order:41626#invoice); without one use
  f"{item['_queue']['ref']}#send". A retry then replays the first result instead
  of writing twice.
- One item is at most one external write. Bundle when adding items (one item with
  50 recipients), not inside the consumer: other bundles get other keys.
- Items a queue batch adds with ctx.queues.enqueue need a dedupe_key
  (dedupe_key_required), so a retried batch adds nothing twice.
- dedupe_key is stored in plain text: no personal data, hash mail addresses
  (sha256(email)[:16]).

Patterns:
- Webhook -> queue: Shopify orders/create into a queue with a script consumer,
  batch_size 1, max_concurrency 1.
- Mass sending: a script adds one item per 50 recipients (dedupe_key
  "<campaign>:<block>"); the consumer sends one bulk call per item;
  rate_per_second is the provider's limit divided by 50.
- Delayed step: ctx.queues.enqueue(..., delay_seconds=86400).
- Run a routine when a record field changes: a queue with the routine as
  consumer and the event source
  {"event_type": "record.updated", "filters": [{"field": "record_type_key",
  "operator": "eq", "value": "deals"}, {"field": "changed_field_keys",
  "operator": "contains", "value": "\"stage\""}]}. changed_field_keys is the
  list of changed field keys, relation and document fields included; contains
  matches its JSON text, so keep the quotes in value, or "stage" would also
  match "stage_note". For one target value filter
  {"field": "changed_values.stage", "operator": "eq", "value": "won"}:
  changed_values maps each changed text (up to 256 characters), number,
  boolean, date, datetime, single_select (option key), multi_select and user
  field to its new value (numbers as strings, null when cleared).
  record.created carries the same keys for a new record. records.rows.bulk_import
  and records.imports emit one records.bulk_imported event instead of one per
  row.

Silence: max_silence_minutes (queues.create/update, 15 to 10080, null = off)
alerts the same people as a held webhook when no webhook delivery and no item
arrived for that long, once per silence (silent_since shows it), and sends a
short notice when traffic resumes.

Control: queues.update with status "paused" stops new batches (running ones
finish, sources keep accepting), status "active" continues. The platform pauses a
queue itself when its consumer cannot start (unpublished routine, missing pin or
binding, inactive user); queues.get shows paused_reason. queues.items.list filters
by status, queues.items.get shows one payload, queues.items.retry_many puts dead
items back with fresh attempts; queues.items.discard_many (with
confirmation) closes dead or pending items by id for good as done with last_error_code
discarded; they never run and no longer block their order_key. A leased or done item
refuses the call (queue_item_not_discardable). queues.get counts.blocked shows the
pending items waiting behind a dead item of their order_key. Done and dead items are kept; no automatic purge runs.
