DocsOperationsRetries and recovery

Retries and recovery

Outbox retries, lease recovery, and stale event handling.

Outbox publication

Failed Kafka publication is retried with backoff under a processing lease. Exhausted rows become dead and remain visible for operational handling.

Kafka handlers

Partition processing distinguishes retryable from terminal outcomes. Records are committed only when policy permits.

Job execution

System failures can release eligible jobs for bounded retry. User workload failures are recorded without treating every failure as infrastructure instability.

An infrastructure Create fault retains its original diagnostic and uses the system retry budget; a typed invalid workload remains a user failure.

Docker-reported invalid configuration at Start, such as a missing or non-executable command, is classified as USER / EXECUTION_FAILED. Generic server or transport failures use the bounded system retry budget, including some invalid image metadata that Docker reports as a server error (for example, an unresolvable image USER). With the default limit of three total attempts, two retry releases are possible before FAILED / SYSTEM_ERROR. This policy does not infer workload fault from message text or exit code 137.

A failed container wait is never evidence of successful execution. A typed wait error is a system failure even when its response includes a nonzero status; that status is retained as diagnostic data, not NON_ZERO_EXIT. A normal received exit result remains authoritative if cancellation ends tail-log drain: zero stays successful and nonzero retains NON_ZERO_EXIT, subject to earlier independent stream errors. If the wait result and context are ready together, either branch may win; there is no priority guarantee before the result is received. The tail may be interrupted; final settlement still requires the caller context and current lease token. Only a configured workload deadline before a normal exit produces TIME_LIMIT_EXCEEDED; an inherited caller deadline remains a system context failure. Missing live follow-logs are system failures while retaining their NotFound diagnostic; log replay keeps its separate absence policy.

The first non-nil execution error determines classification. Later errors are retained only as internal diagnostic text, so a preceding log fault is not reclassified by a later nonzero exit. Rendered execution diagnostics are limited to 1536 UTF-8 bytes before status/context wrapping, including at most 512 bytes of secondary text. Long primary text leaves reserved space for that secondary hint. Invalid UTF-8 is replaced and NUL is visibly escaped before transport/storage; these are encoding safeguards, not secret redaction. Public terminal explanations remain canonical user-safe messages rather than raw diagnostics.

Expired leases

Recovery scans for expired running jobs, invalidates old ownership, attempts container cleanup, and either retries or terminates the job according to current state and retry limits.

Stale events

Generation, dispatch attempt, deterministic ID, and lease-token checks intentionally reject delayed work. A precondition failure can therefore indicate successful protection rather than a platform outage.

Container cleanup

Container cleanup is durable work with an immutable job, full container ID, original runtime instance and creation-intent identity. It survives deletion of its source job, workflow or owner. A worker stops the container, replays retained logs when enabled, removes it, then records an exact-identity completion receipt. A replay failure retains the container for another attempt.

Each cleanup generation permits three failed or abandoned attempts. An execution lease lasts four minutes around the three-minute cleanup budget. Failures back off for 30 seconds, then 60 seconds. Successfully reported caller cancellation refunds its attempt; repeated interruptions can postpone cleanup indefinitely. After exhaustion, persisted QUARANTINED lets the Kafka handler acknowledge that delivery while retaining the unfinished obligation. Publication DEAD is a separate state requiring operator repair.

Successful cleanup publication schedules replay after five minutes by default; successive successful waves wait ten, twenty, forty, then sixty minutes repeatedly. OUTBOX_RELAY_REPLAY_INTERVAL and OUTBOX_RELAY_REPLAY_MAX_INTERVAL configure these defaults with whole-millisecond precision. Durable pacing survives relay restarts, and publication capacity is shared fairly with initial deliveries. Consumer lag is not required. The cap is a scheduling interval, not a guaranteed delivery deadline during overload, key blocking, lease/backoff delays or outages. Ambiguous broker sends may still duplicate before that interval.

Replay scheduling and ordering

For grouped receipt/backlog counts and storage/runway interpretation, use the retained cleanup reports. These counts describe retained transport rows, not lifetime cleanup obligations.

Administrative redrive

Repair the original runtime or configuration first. Call the internal jobs-service RedriveContainerCleanup RPC over the deployment's authenticated TLS connection, using an admin JWT for the jobs-service audience. The request contains:

{
  "job_id": "<job UUID>",
  "container_id": "<full container ID>",
  "runtime_instance": "<original daemon ID>",
  "intent_id": "<creation intent UUID>",
  "generation": "1",
  "reason": "original daemon connectivity restored"
}

The generation is the observed cleanup generation, not workflow generation. The repair reason is required, cannot be whitespace-only and is limited to 2048 bytes. The audit actor is derived from the validated JWT subject, never from request fields or caller metadata. A shared credential identifies its principal, not the individual human using it.

An accepted redrive increments the generation, resets execution/publication budgets and requeues the original snapshot with initial-wave pacing. It may override READY, RETRY, quarantined or expired-lease work, but refuses a live execution lease. Repeating an old generation returns STALE without another reset or audit entry. A completion receipt returns COMPLETED without requeueing. Redrive cannot retarget the original runtime, manufacture removal proof, or repair a COMPLETED row that lacks exact receipt proof. Do not issue raw cleanup_state updates or insert receipts without confirmed removal.

The generation change and audit insert commit together. History retains the immutable identity, authenticated actor, reason, expected/new generation and database timestamp, independently of source rows or later outbox pruning:

SELECT job_id, container_id, runtime_instance, intent_id,
       expected_generation, generation, actor, reason, created_at
FROM container_cleanup_redrives
ORDER BY created_at DESC, event_key, generation
LIMIT 100;

See the gRPC contract for attempt/receipt RPCs and monitoring for alert interpretation. Discovery inspection has its own RedriveContainerIntent operation and audit history; it does not reopen execution authority.

Complete cleanup inspection and grpcurl runbookdocs/operations.md

Cleanup loops

Ordinary published outbox rows and processed-event records are pruned in bounded batches after retention. Published unfinished container cleanup remains retained until matching removal evidence exists, including after quarantine. Cleanup audit history and creation-name discovery tombstones have no automatic expiry policy. Age alone does not prove physical absence or authorize releasing a gate or hold.

Published-outbox pruning uses two candidate-limited lanes: ordinary published events and COMPLETED cleanup awaiting exact receipt proof. A durable turn, committed before lane work, alternates the preferred lane across replicas and restarts; empty or failed calls still advance it. Busy reservations skip the call with a debug log, so aligned replica schedules can reduce achieved throughput. Each call selects at most OUTBOX_RELAY_CLEANUP_BATCH_SIZE candidate identities. The preferred lane is offered half rounded up; the other lane receives the batch size minus already charged candidates, and the preferred lane gets at most one final borrowed operation. A failed lane is not reentered in that call. Lanes lock candidates before proof, delete by candidate ID and commit independently, so a partial call can return confirmed deletions with an error. Failed lanes report charged allowances and zero known committed deletions; selected_known marks whether the selection count was observed. Retained proof requires exact job, container, original-runtime and text-intent matching; invalid job UUIDs and mismatched proof fail closed.

A COMPLETED row without exact proof is corruption and remains outside automatic deletion. It can block the cleanup lane while ordinary pruning continues. Find expired candidates lacking proof, replacing the interval with the configured OUTBOX_RELAY_PUBLISHED_RETENTION:

SELECT events.id, events.published_at, events.payload->>'JobID' AS job_id,
       events.payload->'ContainerCleanup'->>'ContainerID' AS container_id,
       events.payload->'ContainerCleanup'->>'RuntimeInstance' AS runtime_instance,
       events.payload->'ContainerCleanup'->>'IntentID' AS intent_id,
       events.cleanup_state, events.cleanup_generation
FROM outbox_events events
WHERE events.status = 'PUBLISHED'
  AND events.published_at < now() - interval '168h'
  AND events.payload->>'Action' = 'CONTAINER_CLEANUP'
  AND events.cleanup_state = 'COMPLETED'
  AND NOT EXISTS (
      SELECT 1
      FROM container_cleanup_receipts receipt
      WHERE receipt.job_id = CASE
              WHEN pg_input_is_valid(events.payload->>'JobID', 'uuid')
              THEN (events.payload->>'JobID')::uuid
            END
        AND receipt.container_id = events.payload->'ContainerCleanup'->>'ContainerID'
        AND receipt.runtime_instance = events.payload->'ContainerCleanup'->>'RuntimeInstance'
        AND receipt.intent_id::text = events.payload->'ContainerCleanup'->>'IntentID'
  )
ORDER BY events.published_at, events.id
LIMIT 100;

Receipt-present rows whose cleanup state is not COMPLETED, including NULL, are also outside pruning and indicate an invariant violation. Inspect them with:

SELECT events.id, events.status, events.published_at, events.cleanup_state,
       events.payload->>'JobID' AS job_id,
       events.payload->'ContainerCleanup'->>'ContainerID' AS container_id,
       events.payload->'ContainerCleanup'->>'RuntimeInstance' AS runtime_instance,
       events.payload->'ContainerCleanup'->>'IntentID' AS intent_id
FROM outbox_events events
JOIN container_cleanup_receipts receipt
  ON receipt.job_id = CASE
         WHEN pg_input_is_valid(events.payload->>'JobID', 'uuid')
         THEN (events.payload->>'JobID')::uuid
       END
 AND receipt.container_id = events.payload->'ContainerCleanup'->>'ContainerID'
 AND receipt.runtime_instance = events.payload->'ContainerCleanup'->>'RuntimeInstance'
 AND receipt.intent_id::text = events.payload->'ContainerCleanup'->>'IntentID'
WHERE events.payload->>'Action' = 'CONTAINER_CLEANUP'
  AND events.cleanup_state IS DISTINCT FROM 'COMPLETED'
ORDER BY events.published_at, events.id
LIMIT 100;

Audited administrative redrive is the repair path for unfinished cleanup under its normal preconditions, not a way to mark corrupt rows complete or supply missing proof.