Skip to content

Storage topology and partition lifecycle

Status: Accepted architecture
Target envelope: up to 1 million tasks/day and hundreds of claims/second per workhold instance
Retention baseline: configurable 30–90 days

The document defines logical table roles and partitioning constraints. Exact DDL, index names, and partition counts are in the storage contract.

Design principle

Partitioning is a retention tool for append-only or terminal history. It is not a substitute for a small claim working set, correct indexes, or autovacuum.

Mutable scheduling rows and relay work stay outside time partitions. Historical rows use workhold store timestamps and native PostgreSQL declarative partitioning.

Logical layout

Relation Role Partition policy
queues Named queue identity, live state, active policy and config_version Unpartitioned
queue_policy_versions Immutable retry/lease/runtime policy versions Unpartitioned
admin_audit_log Authenticated runtime configuration changes Time-retained history
tasks_active Delayed, ready and leased scheduling projection Unpartitioned
task_payloads_active Opaque payload separated from lease updates Unpartitioned
delivery_events_active Pending and publishing relay work Unpartitioned
task_attempts Append-only claim history Daily RANGE (claimed_at)
tasks_terminal Succeeded, dead-lettered and cancelled history Daily RANGE (terminal_at)
delivery_events_terminal Published and dead-lettered delivery history Daily RANGE (terminal_at)
enqueue_dedup Producer idempotency and request fingerprint Unpartitioned or fixed HASH by full unique key
claim_registry Current claim lookup and fencing Unpartitioned; active claims only
complete_replay Terminal request fingerprint and replayable result Unpartitioned or fixed HASH by claim_id
admin_replay Admin mutation idempotency and replayable HTTP result Unpartitioned
completion_effects Unique spawn/event ordinal per accepted complete Unpartitioned
partition_maintenance_status Singleton partition maintenance cursor Unpartitioned
queue_counters Cheap operational snapshot Unpartitioned

Moving a task to a terminal state is one transaction: validate the claim, insert terminal history, append/close the attempt, create spawns/events, store the completion replay, and delete the active projection.

Task fields and the claim index

The hot claim path stores scheduling metadata on tasks_active:

  • task priority smallint NOT NULL DEFAULT 0 with CHECK BETWEEN -32768 AND 32767 (and a mirror CHECK on tasks_terminal for parent rows);
  • task available_at timestamptz NOT NULL (workhold store semantics);
  • attempt failure_code text NULL with a bounded machine-readable format;
  • attempt failure_detail text NULL with a hard size limit;
  • a versioned named-queue retry policy with enabled, max_attempts, backoff_strategy, and a fixed retry_delay_seconds;
  • task retry_policy_version, selected atomically at enqueue.

The claim index tasks_active_claim_idx on (queue_id, state_code, priority DESC, available_at, id) matches due-first tuple order. Migration 1201_bounded_priority_claim_ordering: a normal transactional DROP INDEX / CREATE INDEX on the hot path blocks writes to tasks_active for the duration of the rebuild.

Downgrade fail-closed: if tasks_active or the parent tasks_terminal contains priority <> 0, downgrade is rejected before any DDL; do not propose a destructive data reset.

The column catalog and CHECKs are in the storage contract.

Runtime queue state is active, paused, or draining. Policy activation and state changes compare the expected config_version, increment it atomically, and append audit in the same transaction.

Retry policy validation requires:

  • enabled=false behaves as one allowed processing attempt;
  • enabled=true requires max_attempts >= 1;
  • the initial backoff_strategy accepts only fixed;
  • the delay is non-negative and bounded by workhold configuration limits;
  • a queue configuration update creates a new immutable policy version;
  • retained tasks continue to reference the original version.

Time partitions

  • Bounds are UTC calendar days.
  • Partition keys are immutable PostgreSQL timestamptz values generated by workhold.
  • Partitions are created 14–30 days ahead.
  • Maintenance runs at least daily and is idempotent.
  • Fully expired partitions are detached concurrently, then dropped.
  • There is no ordinary DEFAULT partition. A missing future partition is detected by readiness before the premake horizon is exhausted.
  • Historical queries include the partition time key so PostgreSQL can prune.

Baseline retention:

  • attempts: 90 days;
  • terminal tasks: 90 days;
  • published delivery events: 30 days;
  • dead-lettered tasks/events: 90 days or until an explicitly configured policy.

Aggregated long-term history lives in the observability backend, not in workhold fact tables.

Correctness registries

PostgreSQL 18.6 (ADR 024) still cannot enforce a global unique key on a time-partitioned table unless the key includes every partition column. These guarantees therefore do not live only in daily partitions:

  • producer idempotency (producer_id, queue_id, key_hash);
  • a globally addressable claim token;
  • idempotent complete by claim_id;
  • a unique spawn/event ordinal on an accepted complete.

On the target envelope, dedup and replay registries may use a fixed number of HASH partitions whose partition key is the full uniqueness key. Their expiry is incremental batch deletion by expires_at, not time-partition detach. Phase 3.9 QUAL-03 accepted HASH modulus 1 (unpartitioned ordinary tables) for both enqueue_dedup and complete_replay from the checksum-valid candidate recommendation (benchmarks/results/phase-3.9-candidates/, evidence mode synthetic; see ADR 023). Partition count does not grow with named-queue cardinality.

Default correctness windows:

  • producer enqueue dedup: 90 days;
  • worker complete/fail/ack-cancel replay: 7 days;
  • admin replay idempotency: 30 days.

After expiry, endpoint-specific behavior is explicit: an old enqueue key may create a new operation; an expired terminal/admin replay lookup returns not-found. TTLs are deployment-configurable only inside validated bounds.

Referential integrity and retention

Foreign keys must not make it impossible to detach expired history partitions.

  • Correctness-critical references target unpartitioned registries.
  • Cross-history lineage uses stable IDs and is validated in an atomic workhold transaction.
  • There is no ON DELETE CASCADE that silently deletes attempts, completion replay, or delivery audit.
  • Retention order is explicit: replay/dedup policy, delivery history, attempts, and terminal history must agree on what may outlive what.

Partition maintenance contract

workhold provides an idempotent maintenance command or dedicated role that:

  1. takes a single-winner advisory lock;
  2. creates the required future partitions and their indexes;
  3. checks partition bounds and the premake horizon;
  4. detaches and drops fully expired partitions;
  5. batch-purges expired rows from HASH/unpartitioned registries;
  6. reports last success, horizon, retained bounds, rows deleted, and failures.

Native PostgreSQL partitioning is the default and does not require an extension. pg_partman/pg_cron may be documented as an operator-managed profile, but workhold correctness does not depend on them. TimescaleDB is not part of the product contract.

Forbidden layouts

  • RANGE(created_at) on the active claim table.
  • Partitioning by mutable status.
  • One LIST partition per named queue.
  • A global idempotency constraint implemented only inside time partitions.
  • Client-supplied time as the partition key.
  • Arbitrary analytics or payload indexes on the hot claim path.

Benchmark gates

Phase 3 must compare unpartitioned and proposed layouts on the target envelope:

  • 1, 10, and 100 named queues;
  • up to 1 million tasks/day and 32 concurrent claimers;
  • ready, empty, reclaim-heavy, and heartbeat-heavy workloads;
  • duplicate enqueue and complete-replay storms;
  • payloads from 1 KiB to the configured hard limit.

Record claim/enqueue/complete p50/p99, planning time, touched partitions, WAL, buffer hits, dead tuples, and autovacuum lag. Phase 3.9 QUAL-03 accepted the measured index signature (omit enqueue_dedup_expires_at_idx; retain tasks_active_claim_idx and the remaining baseline indexes) and HASH modulus 1 for both correctness registries. Exact values, candidate IDs, and bundle checksums are recorded in ADR 023 and applied by migration 039_apply_qualified_storage_layout.