> For the complete AWA documentation index, see [`llms.txt`](../../llms.txt).

# ADR-055: Runtimes report the long-running attempts they hold

## Status

Accepted. Not yet implemented. The admin UI wants to show which runtime instance is executing a running job, link the job to that instance, and list an instance's in-flight jobs on its `/runtime/:id` page. The design bounds its cost for runtimes that process tens of thousands of jobs per second by publishing only attempts that have outlived a snapshot interval; [Cost](#cost) gives the bound and the measurements behind it.

## Context

Two records exist today and nothing joins them.

**Runtime instances.** Each runtime generates its `instance_id` (a UUID) when the client is built and upserts one `awa.runtime_instances` row per snapshot interval, 10 s by default. The row carries health flags, version, and a `queues` JSONB array whose entries hold a per-queue `in_flight` count (`QueueRuntimeSnapshot`), but no attempt identities. An instance is shown as stale when its `last_seen_at` is older than three snapshot intervals or 30 s, whichever is longer, and long-stale rows are deleted by `cleanup_runtime_snapshots`. The snapshot is written in a transaction that first takes the cron protocol lock, and a statement trigger on `runtime_instances` takes the same cluster-wide advisory lock on every write (`cron_lock_evidence`, migration v045), so every instance's snapshot write is serialised with every other.

**Claims.** Under queue storage ([ADR-019](../019-queue-storage-redesign/index.md), [ADR-023](../023-receipt-plane-ring-partitioning/index.md)) with receipts on, the default, one `claim_ready_runtime` call writes one `lease_claim_batches` row per `(ready slot, generation, queue, priority, shard)` group, holding arrays of job ids, run leases, receipt ids, lane positions, attempts and max attempts, plus one `ready_claim_attempt_batches` row. It writes no `lease_claims` row and no `leases` row. Row-local `lease_claims` rows exist for legacy in-flight claims and materialisation paths; `leases` rows are written when an attempt materialises for a callback or other mutable lease state, or for every claim when `lease_claim_receipts` is off. All four tables are partitioned by ring slot and reclaimed by `TRUNCATE` once every claim in the slot has closure evidence. `run_lease` is the per-attempt identity ([ADR-013](../013-run-lease-and-guarded-finalization/index.md)): every finalize matches `(job_id, run_lease)`, and the runtime keys its local in-flight registry by the same pair.

**Heartbeats.** The heartbeat loop sends, every heartbeat interval (30 s by default), a heartbeat for every attempt in the in-flight registry. For a compact receipt claim it upserts `attempt_state (job_id, run_lease, heartbeat_at)`; for a materialised lease it updates `leases.heartbeat_at`. A receipt attempt therefore has no stored heartbeat until the first heartbeat pass after its claim, and admin reads report `heartbeat_at` as null for it until then. That covers every job shorter than the heartbeat interval and the first part of every longer one, not only zero-deadline jobs.

**What the claim knows.** The dispatcher calls `claim_runtime_batch_with_aging_for_instance` with a `claimer_owner_id`, which is the runtime's `instance_id` for the first dispatcher of a queue and a random UUID for each further one (bounded-claimer lease tokens in `queue_claimer_leases`). The runtime's `instance_id` is in scope at the call, but `claim_ready_runtime(p_queue, p_max_batch, p_deadline_secs, p_aging_secs)` and the per-slot `claim_ready_slot_N` functions take no instance argument. Recording the instance in the claim means a new argument on those functions.

**Constraints on the claim path.** [ADR-053](../053-coordination-off-the-commit-path/index.md) requires that a job transition not wait on coordination work and that coordination that changes nothing writes nothing. [ADR-054](../054-claim-target-bound/index.md) changed the claim bodies without changing signatures, owners or grants precisely so that N-1 binaries keep calling the same functions, and notes that an older `prepare_schema` can reinstall an older claim body. [ADR-041](../041-rolling-upgrade-policy/index.md) requires every release's schema change to work with N-1 binaries on the N schema, N binaries on the N-1 schema, and mixed fleets.

**What the admin reads have.** Admin reads of running queue-storage jobs already collect the open claims, slot by slot, as `(job_id, run_lease, queue)` (`queue_storage_open_claims`, `open_receipt_running_claims_sql`). `JobRow` is `#[non_exhaustive]` and the UI receives it flattened into `JobResponse`, which already carries computed fields that are not stored in the database. The UI's `/runtime/:id` page has no endpoint of its own: it fetches the fleet overview from `/api/runtime` and picks the instance. The queue overview lists the instances serving a queue, which is the only job-to-instance link the UI has today.

**What a busy runtime holds.** A runtime's in-flight count is its throughput times its mean attempt duration, limited by its worker capacity: 20,000 jobs/s at 50 ms is about 1,000 attempts in flight, and at 2 s it is about 40,000. Between two snapshots 10 s apart nearly all of them are different attempts (every one, at 50 ms; 99% at a 2 s mean), so a published list of everything in flight changes on every snapshot and names attempts that have finished before anyone reads it.

**What already finds stuck jobs.** `GET /api/stats/attention` counts running jobs that are past their deadline or whose heartbeat is older than three heartbeat intervals, with up to five example job ids each, from storage alone; each runtime's snapshot now carries its `heartbeat_interval_ms` for that. It says that jobs are stuck and which, not where they run: attempts do not record their runtime, which is also why it has to measure every attempt against the longest heartbeat interval in the fleet. A stale heartbeat is at least 90 s old by default, so every job flagged for one is long-running. A job past a deadline shorter than a snapshot interval can be flagged before it is old enough to be published, and gains an instance within two snapshot intervals if it is still running.

## Decision

Each runtime publishes the identities of the long-running attempts it holds, off every job path, and admin reads join them to running jobs by `(job_id, run_lease)`. Claim, heartbeat and finalize rows are not changed. An attempt is long-running once the runtime has held it for a full snapshot interval. Shorter attempts are never published: they are what makes the set large and fast-changing on a busy runtime, and they are gone before an operator can look.

### Storage

A new table in the `awa` schema, one row per runtime instance:

```sql
CREATE TABLE awa.runtime_attempts (
    instance_id    UUID PRIMARY KEY,
    storage_schema TEXT,
    published_at   TIMESTAMPTZ NOT NULL,
    held_total     INTEGER NOT NULL,
    job_ids        BIGINT[] NOT NULL,
    run_leases     BIGINT[] NOT NULL,
    CHECK (cardinality(job_ids) = cardinality(run_leases))
) WITH (
    fillfactor = 50,
    autovacuum_vacuum_scale_factor = 0,
    autovacuum_vacuum_threshold = 50,
    toast.autovacuum_vacuum_scale_factor = 0,
    toast.autovacuum_vacuum_threshold = 200
);
```

- `held_total` is the number of long-running attempts the instance holds; the arrays list at most 1,000 of them. The instance's whole in-flight count is not stored here: it changes on every snapshot and is already in the runtime snapshot, per queue.
- `storage_schema` is the queue-storage schema the runtime claims from, null on canonical storage. Job ids are per schema and most run leases are 1, so two schemas in one database would otherwise produce matching pairs; a reader ignores rows for another schema.
- The arrays are plain `BIGINT[]` with the default compression. A list of up to about 120 attempts stays in the heap row, under 2 KB; a longer one is compressed and moved to TOAST. The storage parameters keep updates of short lists on their page (every update in the measured run with these parameters was a HOT update) and make autovacuum act on a fixed number of dead rows and TOAST chunks instead of a fraction of a table this small.
- It has no foreign key to `runtime_instances` and no trigger, so writing it takes no lock on `runtime_instances` and not the cron protocol lock. It is not a hot-path table under ADR-053: no job transition reads or writes it.

### Publishing

- The reporter scans the in-flight registry (`InFlightRegistry`, the same set the heartbeat loop sends) once per snapshot interval and numbers its scans. The registry stamps each attempt with the current scan number when it registers it, which costs one atomic load and no clock read. A scan selects the attempts stamped at least two scans ago, so an attempt is first selected when it is between one and two snapshot intervals old, 10 to 20 s by default.
- It lists the 1,000 oldest of them, by stamp and then job id, and records how many there are in `held_total`. Oldest first keeps a stuck attempt listed however many newer ones the instance holds.
- It writes its row, in its own transaction, separate from the runtime snapshot, only when the list or `held_total` differs from what it last wrote, and so at most once per snapshot interval. There is no keepalive. A runtime whose attempts all finish within a snapshot interval writes its row once, empty, when it starts, and never again. The row is written only by its own instance, so the upsert meets no other writer. If cleanup removed the instance's rows while its snapshots were long stale, its next snapshot upsert inserts rather than updates (`xmax = 0` in its `RETURNING`), and on that tick it rewrites its attempts row even when the list is unchanged.
- The cap, the age rule and the cadence are fixed, not configuration. The cost bound in [Cost](#cost) depends on the cap and on the snapshot interval, which is already an operator setting.
- On clean shutdown the runtime deletes its row once its in-flight registry is empty. A shutdown that gives up on attempts still running, when the drain times out, leaves the row in place, so those attempts stay attributed while they wait for rescue; cleanup removes the row with the instance's snapshot. `cleanup_runtime_snapshots` deletes the `runtime_attempts` rows that have no `runtime_instances` row and whose `published_at` is older than the age at which it deletes snapshots, so a dead instance's list lasts as long as its snapshot does and a live instance's unchanged row is kept.
- An attempt leaves the set when the registry drops it, which is after its finalize is acknowledged, so the set includes attempts whose handler has returned and whose completion is still in flight.
- A failed write is logged and counted and retried on the next scan. The runtime records the time of the first failure since its last successful write and reports it in its next runtime snapshot as `attempts_unpublished_since`, cleared by the next successful write, so a list that is out of date is marked as such rather than read as unchanged. It does not affect `healthy`: a runtime that cannot publish attributions still runs its jobs.

### Reading

An attribution is the instance whose row lists `(job_id, run_lease)` for the reader's schema. A `waiting_external` job is attributed only while a handler holds it in `ctx.wait_for_callback`. A handler that returned `JobResult::WaitForCallback` has finalised its attempt, which leaves the registry, so a job parked that way is held by no runtime and has no attribution. Keying by `run_lease` means an old row can never attribute a newer attempt of the same job: a rescued and reclaimed job has a new `run_lease`. Admin reads show an attribution only for a job whose current stored state is `running` or `waiting_external` with that `run_lease`, so a published attempt that has since completed, failed or been rescued is not shown on the job.

The row's age does not decide whether an attribution is shown. While storage still has the attempt open under that `run_lease`, no other runtime can hold it, so the instance that listed it is its holder, or was its last holder if the instance has died. This keeps the attribution through the case that most needs it: an instance that died, whose attempts wait for heartbeat rescue. The read returns `published_at` and the UI takes the instance's liveness from its snapshot.

The table holds one row per instance, so lookups scan it without an index: a job page reads every row whose `job_ids` contains the job; a job list does the same for the running ids on the page.

### Admin API

- `JobResponse` gains `instance_id: Option<Uuid>` and `instance_reported_at: Option<DateTime<Utc>>`, filled for running and `waiting_external` jobs on the job detail and job list endpoints. The field goes on the API response rather than on `JobRow` because it is an observation with a freshness, not stored job state, and `JobRow` is also what handlers and the Python bindings receive. The JSON name is `instance_id`, as the UI plan uses. A model helper, `admin::attempt_instances(pool, &[(job_id, run_lease)])`, serves both endpoints and Rust callers of the admin API. The Python admin bindings do not expose it in the first version; they can call the same helper later without a schema change.
- A new `GET /api/runtime/{instance_id}` returns the `RuntimeInstance` and a `long_running` object: `reported_at`, `total` (`held_total`), `truncated`, and the listed attempts, each with `job_id`, `run_lease`, `queue` and `kind` from storage and `current: bool`, false when storage no longer has that attempt running (it was rescued, cancelled or finalised while the runtime still held it). It returns 404 for an unknown instance and a `long_running` of `null` for an instance that has no row.
- `GET /api/stats/attention` returns, beside each example job id, the instance that lists it, or null. The counts do not change: each attempt's heartbeat is still measured against the longest heartbeat interval in the fleet, because attempts younger than the age rule, past the cap or held by N-1 runtimes have no instance and would otherwise be measured by a different rule.
- `RuntimeInstance` gains `attempts_unpublished_since: Option<DateTime<Utc>>`, null when the last write succeeded and for runtimes that do not report it.
- The job list gets no `?instance=` filter. It could return only the listed long-running attempts, which is the runtime page's card, and as a job filter it would look complete when it is not.

### UI

- Job detail, for a running or waiting job: an "Instance" row linking to `/runtime/:id` with the instance label and how long ago it reported, marked when that instance's snapshot is stale or it reports `attempts_unpublished_since`. With no attribution it says why: "Waiting for its callback, not held by a runtime" for a `waiting_external` job that no instance lists; "Not reported yet" when the attempt started less than two snapshot intervals ago; "Not published" when a live instance serving the queue reports `attempts_unpublished_since`; "Not reported by this version" when every live instance serving the queue has no row and reports no publication failure; "Not listed" when a live instance serving the queue reports more long-running attempts than it lists; otherwise "Unknown".
- Runtime instance page: switch from the fleet overview to `GET /api/runtime/{instance_id}` and add a "Long-running jobs" card listing the attempts, oldest first, with job links, queue, kind and run lease; attempts with `current: false` are marked as held after rescue or finalisation, which is a useful sign of a stuck handler; "Showing 1,000 of N" when truncated, beside the in-flight count the snapshot already gives; an empty state that tells "none" from "this version does not report"; and, when `attempts_unpublished_since` is set, a note that the list has not been updated since then.
- The Overview's stuck-job examples from `GET /api/stats/attention` link to job pages and to the instance that holds each one. The attention counts find the stuck jobs; this decision adds where they run.
- The job list may show the short instance id for running jobs; it is not required by this decision.

### Migration and mixed fleets

One additive migration (v065 or the next free number) creates `awa.runtime_attempts` and adds a nullable `attempts_unpublished_since TIMESTAMPTZ` column to `awa.runtime_instances`. The column has no default, so adding it is a catalog change; it takes `ACCESS EXCLUSIVE` on `runtime_instances` for that moment, which waits only for snapshot writes and admin reads of a table with one row per instance. It scans nothing and needs no runtime version floor. It does not touch the claim, heartbeat or finalize functions, their signatures, owners or grants.

- **N-1 runtimes on the N schema** do not know the table and do not publish. Their snapshot upserts name their columns, so they leave `attempts_unpublished_since` null. Their jobs show no instance and their runtime pages show the "does not report" state, decided from the absence of a row. Nothing else changes for them.
- **N runtimes on the N-1 schema**, while the migration is pending, find the table missing (`to_regclass`) and skip publishing; they check again on each scan, so they write their row once the migration commits. The same check covers the `attempts_unpublished_since` column: the snapshot upsert names its columns, so an N runtime names that column only after it has seen it, and until then writes the snapshot it writes today. Naming a missing column would fail the whole snapshot write, which runs under the cron protocol lock, and the instance would go stale.
- **Mixed fleets** show attributions for jobs held by N runtimes and none for jobs held by N-1 runtimes. No reader treats a missing attribution as evidence of anything.
- **N admin on the N-1 schema** treats the missing table as no data. **Rolling back** binaries leaves the table in place and unused.

## Cost

### Workload model

For one runtime with throughput λ and attempt durations D, the in-flight count is λ·E[D]. The attempts older than an age a number λ·E[(D − a)⁺], and attempts cross that age at a rate of λ·P(D > a). The table gives those for a = 10 s, the youngest an attempt can be when first selected, under an exponential duration distribution and under a heavy-tailed one (lognormal, σ = 1.5) with the same mean. These are computed, not measured.

| Runtime | In flight | Replaced between snapshots | Long-running, exponential | Long-running, heavy tail | Crossing 10 s per second |
| --- | --: | --: | --: | --: | --: |
| 17 jobs/s, 1 s mean (one of three small runtimes) | 17 | 100% | 0 | 2 | 0 to 0.2 |
| 100 jobs/s, 3 s mean (one of 20) | 300 | 96% | 11 | 83 | 3.6 to 6 |
| 10 jobs/s, 30 s mean (one of 20) | 300 | 28% | 215 | 230 | 5 to 7 |
| 10,000 jobs/s, 50 ms mean | 500 | 100% | 0 | 0.4 | 0 to 0.1 |
| 20,000 jobs/s, 50 ms mean | 1,000 | 100% | 0 | 0.8 | 0 to 0.2 |
| 50,000 jobs/s, 50 ms mean | 2,500 | 100% | 0 | 2 | 0 to 0.5 |
| 10,000 jobs/s, 2 s mean | 20,000 | 99% | 135 | 4,050 | 67 to 340 |
| 20,000 jobs/s, 2 s mean | 40,000 | 99% | 270 | 8,100 | 135 to 680 |
| 50,000 jobs/s, 2 s mean | 100,000 | 99% | 670 | 20,300 | 340 to 1,700 |
| 667 jobs/s, 60 s mean | 40,000 | 15% | 33,900 | 34,500 | 450 to 560 |

Three things follow. A high-throughput runtime with short jobs has no long-running attempts, or a handful, and writes nothing. The age rule alone does not bound the set: a heavy tail at 2 s, or 40,000 minute-long attempts, leaves thousands, and they cross the threshold hundreds of times a second, so the cap and the once-per-interval write are what bound the cost, and writing on each crossing instead would not be bounded. And publishing everything in flight, as the earlier draft of this ADR proposed, has every runtime in the table rewrite its list on every snapshot, because part or nearly all of it is replaced; "write only when the set changes" saves nothing on a busy runtime.

### Method

PostgreSQL 18.7 in a container on a 4-vCPU, 15 GB virtual machine with a virtual disk: `shared_buffers` 128 MB, `checkpoint_timeout` 5 min, `max_wal_size` 1 GB, `full_page_writes` on, `wal_compression` off, `fsync` on, autovacuum on with its defaults (`autovacuum_naptime` 1 min), pglz TOAST compression. WAL is the difference of `pg_current_wal_insert_lsn()` around a run; other, idle databases shared the cluster. The numbers are bytes and row counts, which carry over to other hardware; times and rates on this machine do not.

- **Table writes.** A scratch database held the table above and variants. `pgbench` custom scripts ran the upsert with server-generated lists: job ids near 5×10⁹ drawn from a 40,000-wide window (a set that turns over) or a 5,000,000-wide window (long-running attempts claimed over minutes), run leases all 1 or 1 to 3. Ranges below run from the first kind to the second. "Per write" is 300 consecutive writes over 20 rows after a `CHECKPOINT`; "after a checkpoint" is 20 writes with a `CHECKPOINT` before each, so each pays its full-page images (and about 0.2 KB of checkpoint record).
- **Fleets in real time.** `pgbench -R` at one write per instance per 10 s for 330 s, one scenario at a time, sampling `pg_stat_user_tables`, `pg_stat_all_tables` for the TOAST table, and relation sizes every 30 s.
- **Job paths.** A scratch test on `main` at `e425808d`, debug build, default queue-storage configuration with receipts on: 200,000 no-op jobs enqueued in batches of 1,000 and run by one runtime with 256 workers; and 10,000 jobs claimed in batches of 16 and heartbeated in the heartbeat service's 500-attempt chunks.
- **Runtime CPU.** A standalone release-build stand-in for the registry (64 `RwLock<HashMap>` shards with entries of the registry's size), 200 scans per size.

### Measured: what the job paths already write

| Path | WAL |
| --- | --: |
| Enqueue, batches of 1,000 | 394 B per job |
| Claim and complete through a runtime, at about 5,000 jobs/s | 451 B per job (350 to 380 B in undisturbed 5 s windows) |
| Claim alone, batches of 16 | 446 B per job |
| First heartbeat pass over an attempt (inserts its `attempt_state` row) | 237 B per attempt |
| Later heartbeat passes | 206 to 274 B per attempt, 411 B on the first pass after a checkpoint |

Scaled linearly, which is an estimate: a runtime at 20,000 jobs/s writes about 9 MB/s of WAL to claim and complete, about 17 MB/s with the enqueues, and one with 40,000 attempts in flight writes about 320 KB/s of heartbeats at the default 30 s interval.

### Measured: one write of the table

| Listed attempts | Stored size of the two arrays | WAL per write | WAL for a write after a checkpoint |
| --: | --: | --: | --: |
| 0 | 26 B | 0.2 KB | |
| 10 | 0.2 KB | 0.3 to 0.4 KB | 4.9 KB |
| 100 | 1.6 KB, in the heap row, uncompressed | 1.2 to 2.1 KB | 11.6 KB |
| 250 | 1.0 to 1.4 KB | 1.4 to 1.9 KB | |
| 500 | 1.8 to 2.7 KB | 2.3 to 3.7 KB | |
| 1,000 | 3.4 to 5.2 KB | 4.3 to 6.6 KB | 25 to 28 KB |
| 5,000 | 15.8 KB | 23 KB | |
| 40,000 | 89 to 133 KB | 128 to 188 KB | 218 KB |

Job ids and near-constant run leases compress to between a fifth and a third of their 16 bytes per attempt under pglz. The 40,000 row is the uncapped case: several hundred times the write of a ten-attempt list.

### Measured: fleets in real time

| Scenario, one write per instance per 10 s | Writes | WAL per write | WAL per runtime | Heap | TOAST, range over the run |
| --- | --: | --: | --: | --: | --: |
| 20 instances, 1,000 attempts replaced on each write (earlier draft) | 597 | 4.9 KB | 0.49 KB/s | 8 KB | 0.3 to 0.6 MB |
| 200 instances, the same | 6,656 | 4.5 KB | 0.45 KB/s | 49 KB | 3.4 to 5.9 MB |
| 5 instances, 40,000 attempts each, uncapped | 153 | 187 KB | 17.3 KB/s | 8 KB | 2.7 to 5.2 MB |
| 200 instances, 1,000 long-running attempts, storage parameters as above (this decision's worst case) | 6,632 | 6.9 KB | 0.69 KB/s | 0.4 MB | 4.4 to 7.9 MB |

These totals include the checkpoint's full-page images and autovacuum's own WAL. The first row is the last 300 s of its run: its first 30 s contained 14.6 MB of WAL that the 60 writes in it cannot account for and that no other run showed, so it is excluded. All but 9 of 15,400 heap updates were HOT updates and no sample showed more than 57 dead heap rows. Autovacuum reached each TOAST table once a minute, which is the naptime; between passes dead chunks reached about 2,900 and the TOAST table of the 200-instance runs sat at four to eight times its live size (0.7 to 1.0 MB), without growing over the run.

### Measured: runtime and read cost

| In flight | Scan, collect and sort every attempt | Scan and select long-running, none | Scan and select long-running, all |
| --: | --: | --: | --: |
| 1,000 | 0.02 ms | 0.002 ms | 0.02 ms |
| 10,000 | 0.25 ms | 0.02 ms | 0.11 ms |
| 40,000 | 1.4 ms | 0.15 ms | 0.47 ms |
| 100,000 | 3.7 ms | 0.4 ms | 1.3 ms |

Collecting every attempt allocates 16 B each, 0.6 MB at 40,000; selecting allocates only for the long-running ones. Once per 10 s, either is under 0.05% of a core. The scan takes each shard's read lock in turn, as the heartbeat pass does every 30 s. Reading all 200 rows of 1,000 attempts, with detoasting, took 8 ms, and finding the rows that contain given job ids 12 ms; 20 rows took 2 to 3 ms.

### Bound

Per runtime, whatever its throughput, in-flight count or duration distribution:

- at most one row write per snapshot interval, of at most 1,000 attempts, and none while its list is unchanged;
- about 0.7 KB/s of WAL per runtime on average at the default 10 s interval (6.9 KB per write, measured at the cap over 330 s with checkpoints and autovacuum included). A single capped write just after a checkpoint is 25 to 28 KB, so the worst 10 s interval is about 2.8 KB/s. About 1.7 KB/s on average if the ids did not compress at all (estimated from 16 KB of array data plus TOAST and record overhead);
- at most one dead heap row and nine dead TOAST chunks per write;
- one scan of its registry per interval, measured at 0.15 to 1.3 ms for 40,000 to 100,000 attempts.

At 20,000 jobs/s the average is under 0.01% of what the runtime writes to claim and complete its jobs, and the worst 10 s interval under 0.05%; with jobs under 10 s it writes nothing after its first, empty row. A fleet multiplies it: 200 runtimes all at the cap wrote 139 KB/s.

The earlier draft's cap bounded its bytes to much the same figure, 0.45 to 0.49 KB/s per runtime measured. What it did not do was stay quiet on a busy runtime, or publish attempts that still existed when read. Without a cap the same design costs 17 KB/s per runtime at 40,000 in flight and grows with throughput.

### Mitigations

- The age rule removes the write entirely for runtimes whose jobs are short, which is where throughput is highest.
- The cap and the once-per-interval write bound everything else.
- Dropping the keepalive and the in-flight count from the row leaves nothing that changes on every snapshot.
- `fillfactor` and the per-table autovacuum thresholds keep the heap at a few pages and TOAST within a small multiple of its live size.

Tried and not adopted: lz4 instead of pglz stored the 1,000-attempt list larger (4.1 to 5.1 KB against 3.3 to 4.4 KB for `job_ids`). A custom sorted, delta-encoded `bytea` was sized, not implemented (random bytes of the estimated encoded length, 3 to 5 bytes per attempt): 0.7 KB per write against 1.2 to 2.1 KB at 100 attempts, and 4.0 to 6.3 KB against 4.3 to 6.6 KB at 1,000, where pglz already does the same work. It would save about 0.1 KB/s per runtime and make the row unreadable from `psql`. Lowering `toast_tuple_target` does not compress rows under 2 KB, and raising it to keep 1,000 attempts in the heap row saved about a tenth (5.3 KB per write against 6.0 KB) while putting one row on each heap page.

### What is left unbounded

- The total grows linearly with the number of runtimes, and with the inverse of the snapshot interval if an operator shortens it.
- The registry scan is linear in the in-flight count. It is cheaper than the heartbeat pass's scan of the same registry.
- An admin read of the table is linear in instances times listed attempts; it is served through the admin cache.
- TOAST bloat between autovacuum passes depends on autovacuum reaching the table; the measurements had it at the default naptime.
- Not measured: a runtime actually running at 10,000 to 50,000 jobs/s (the job-path figures are bytes per job from a 5,000 jobs/s debug-build run, scaled), PostgreSQL 17 and 19, a replica or WAL archive downstream, and the reporter's code itself, which does not exist yet.

## Consequences

- No cost on the claim, heartbeat, finalize, rescue or prune paths, and no change to any claim-ring or lease-ring table, so ADR-053 and ADR-054 are untouched and no TLA+ model changes.
- The write cost is bounded per runtime independent of throughput, as [Cost](#cost) states, and a runtime whose jobs finish within a snapshot interval writes only its first, empty row. The registry scan is not bounded by the cap: it grows with the in-flight count, at 0.15 to 1.3 ms per interval for 40,000 to 100,000 attempts. The write stays outside the cron protocol lock.
- A job becomes eligible for attribution once its attempt is between one and two snapshot intervals old (10 to 20 s by default), plus the admin cache. Jobs shorter than that are never attributed, which includes the receipt short-job case that also lacks a heartbeat. The UI's purpose, finding where a long-running or stuck job runs, is served. Age makes an attempt eligible, not certain to be listed: an instance at the 1,000 cap leaves out its newer long-running attempts, so a job the attention counts flag, such as one past a short deadline, can still show no instance.
- An instance holding more than 1,000 long-running attempts lists its oldest 1,000. Its other long-running jobs show no instance, and the runtime page says how many it holds. An instance of 40,000 minute-long attempts is therefore mostly unattributed; its stuck attempts, being the oldest, are still listed.
- After an instance dies its row lasts until its snapshot row is deleted, so its attempts stay attributed until they are rescued or, if rescue has not run by then, until cleanup deletes the instance's rows. Who held a rescued attempt is not recorded durably.
- Nothing refreshes an unchanged row. A reporter that cannot write is reported through the runtime snapshot's `attempts_unpublished_since`; if the snapshot cannot be written either, the instance goes stale, which the UI already shows.
- Canonical-storage runtimes publish too, since the registry is storage-independent, but canonical storage is deprecated ([ADR-037](../037-canonical-engine-deprecation/index.md)) and the admin join is only required for queue storage.

## Alternatives considered

### Every in-flight attempt, capped (the earlier draft)

Publish up to 1,000 of everything in flight on every snapshot, with a keepalive and an `in_flight_total`. Measured, it costs 4.5 to 4.9 KB per write and 0.45 to 0.49 KB/s per runtime, which is not much. It was dropped for what it publishes: on a runtime at 20,000 jobs/s the list names attempts that will nearly all have finished within the next snapshot interval (all of the 1,000 in flight at 50 ms, or 2.5% of the 40,000 at 2 s), and every busy runtime rewrites it every 10 s, so the fleet pays the worst-case write constantly for a list that is out of date when read. Without the cap it does not hold up at all (187 KB per write at 40,000 in flight).

### Instance id on the claim rows

Add `instance_id UUID` to `lease_claim_batches`, `lease_claims` and `leases`, written by the claim. Attribution is then exact, immediate, covers short jobs, and survives the instance's death until the claim slot is pruned.

- Bytes are not the problem, at any throughput. A batch row measured 958 B for 16 jobs and 1,789 B for 100, and 16 B more with the column, so the claim grows by 1 B per job at 16 per batch and 0.16 B at 100, against 446 B. At 20,000 jobs/s that is 3 to 20 KB/s, which grows with throughput but stays under 0.3% of the claim's own WAL. On row-local `lease_claims` and `leases` rows it adds roughly 15%. Prune and rescue would ignore the column, and the slot's `TRUNCATE` reclaims it. Reading by job uses the existing claim-batch `job_ids` GIN path; listing by instance filters the open-claim read the admin already does, whose cost follows the in-flight count.
- The claim functions need a new argument. The old `claim_ready_runtime` and `claim_ready_slot_N` signatures must stay for N-1 binaries, so every claim body exists twice until a contract release, ADR-054's "no signature changes" property is lost for this change, and an older `prepare_schema` reinstalling older bodies must not drop the new overload. With [ADR-043](../043-postgresql-capability-functions/index.md) it is also a new capability entry point.
- `ALTER TABLE ... ADD COLUMN` on the partitioned parents is catalog-only but takes `ACCESS EXCLUSIVE` on the parent and every partition, which every claim conflicts with; it needs a bounded `lock_timeout` and retries on a live fleet, and at tens of thousands of claims per second there is no quiet moment to take it in.
- The dispatcher passes a lease token, not the instance id, for its extra claimers, so the call has to pass the runtime's `instance_id` separately.

This is the path to take if exact attribution of short jobs becomes a requirement. It does not belong in an observability feature.

### A small numeric instance slot on the claim rows

The same as above with a `SMALLINT` mapped to instances through a registry. It saves 14 bytes per batch row, under 1 B per job, and adds an allocator whose slots cannot be reused until every claim naming the slot has been pruned, coupling the instance registry to claim-ring prune. `queue_claimer_leases.claimer_slot` is not usable: it is per queue, held only while claiming, and owned by a lease token. It keeps every cost of the claim-row option.

### Instance id written by heartbeats

Add `instance_id` to `attempt_state` and `leases` and set it in each heartbeat write, which already rewrites the row. This is the strongest alternative under the same workload. It attributes every attempt that lives to its first heartbeat, with no cap, and keeps the attribution until rescue. It publishes the same population as this decision, attempts older than some tens of seconds, so the earlier objection that its answer is staler (up to 30 s against 10 s) no longer separates them. Measured on a table of `attempt_state`'s shape, the column adds 16 B to the pass that inserts the row (224 to 240 B per attempt) and 5 B to each later pass (180.5 to 185.6 B), so with 40,000 attempts in flight it adds about 7 KB/s to 320 KB/s of heartbeats: more than this decision's bound, growing with the in-flight count, and still small.

It is not chosen because of where the change goes. The heartbeat is what keeps a live attempt from being rescued and run twice, and this would change four heartbeat write paths (compact claims, legacy leases, progress, callback heartbeats) for an observability feature. An N binary would have to detect the column before every one of those writes while the migration is pending, where a mistake fails heartbeats. `attempt_state` is unpartitioned and written by every heartbeat pass and every completion, so adding the column needs `ACCESS EXCLUSIVE` against all of them. And listing an instance's attempts reads `attempt_state`, which is as large as the fleet's in-flight count, or needs an index that every heartbeat then maintains. If listing only the oldest 1,000 per instance proves too little, this is the next step, not the claim rows.

### In-flight identities inside the runtime snapshot

Put the attempt list in the existing `runtime_instances` row, for instance in the `queues` JSON. It needs no new table, but it lengthens a write that holds the cluster-wide cron protocol lock and rewrites a wider row on every snapshot whether or not the list changed. A separate table keeps that write as it is.

### One row per in-flight attempt

A table keyed by `(instance_id, job_id, run_lease)`, inserted at start and deleted at finish. It gives an indexable, exact set, but it is per-attempt insert and delete churn, the MVCC source ADR-023 removed when it retired `open_receipt_claims`, and it puts a write on every attempt's start and finish: at 20,000 jobs/s, 40,000 row writes per second.

### Writing on each change instead of on a cadence

Write the row when an attempt becomes long-running or a listed one finishes. It attributes sooner, but the workload model has attempts crossing the threshold up to 1,700 times a second on one runtime, so the write rate would follow throughput. The scan coalesces any number of changes into one write.

### A smaller cap, or a custom encoding

A cap near 100 keeps every row in the heap and out of TOAST and lowers the bound to about 0.2 KB/s. The saving is 0.5 KB/s per runtime at most, and it would leave the middle of the range, an instance with a few hundred long-running attempts, unattributed in part where full attribution costs 1.4 to 3.7 KB per write. The `bytea` encoding is covered under [Mitigations](#mitigations).

### Status quo

The UI shows the instances serving a job's queue, as the queue overview does, and the attention counts name stuck jobs. It costs nothing and answers "where could this run" and "what is stuck" but not "where is it running", and the runtime page cannot list jobs.

## Decisions on the review questions

- The cap stays at 1,000, oldest first, and is not configurable. Recording the instance in heartbeat writes is the next step if instances holding more than 1,000 long-running attempts need full attribution.
- The age rule follows the snapshot interval, so a long-running attempt becomes eligible 10 to 20 s after its claim by default; the cap can leave it out after that.
- `GET /api/stats/attention` returns the instance beside each example job id. It keeps measuring every attempt against the fleet's longest heartbeat interval; measuring each against its own runtime's interval is revisited if fleets with mixed heartbeat intervals need it.
- A runtime that cannot write its row reports `attempts_unpublished_since` in its snapshot, rather than restoring a keepalive.
- The row records the queue-storage schema; the Python admin bindings do not expose the attribution in the first version; the job list gets no instance filter.
