Persistent PostgreSQL implementation of the four storage capabilities in componenta/idempotency. PHP 8.4+ (64-bit), PDO PostgreSQL, Cycle Database 2.24+, PostgreSQL 16+.
The core is currently consumed from its development branch. Until a stable core release is available, the application's root Composer configuration must allow it:
composer config repositories.idempotency vcs https://github.com/componenta/idempotency.git
composer config repositories.idempotency-cycle vcs https://github.com/componenta/idempotency-cycle.git
composer require componenta/idempotency-cycle:dev-main componenta/idempotency:dev-mainCreate a dedicated database schema in a migration, then install the tables once:
use Componenta\Idempotency\Cycle\{Schema, PostgresStore};
use Componenta\Idempotency\{Executor, Policy, Request};
// $database is a configured Cycle DatabaseInterface (write driver).
Schema::install($database, 'idempotency');
$store = new PostgresStore($database, 'idempotency');
$executor = new Executor($store, new Policy(30, 86400));
$request = Request::fromPayload('tenant:42:orders', 'operation-123', '{"sku":"A42"}');
$result = $executor->execute($request, static fn (): string => 'saved result');For a new deployment, the optional DedicatedDatabaseFactory creates a fresh,
nonpersistent, lazily connected Cycle database without query caching, SQL
parameter logging or a read replica. It uses exception-mode PDO and native
extended-protocol parameters without separate server-side PREPARE statements,
so uncached queries do not pay an extra prepare round trip. The existing constructor accepting a configured database remains valid.
use Componenta\Idempotency\Cycle\{DedicatedDatabaseFactory, PostgresStore};
// Use trusted deployment configuration, never request input.
$database = DedicatedDatabaseFactory::create($dsn, $user, $password);
$store = new PostgresStore($database, 'idempotency');Pass null instead of an empty username or password to use the DSN or
libpq defaults. Create a separate database/driver for each independent worker and use a separate
migration role for Schema::install. Do not reuse the factory-created database
for concurrent application transactions. The dedicated factory disables both BEGIN reconnect and Cycle 2.24's
out-of-transaction query retry. It sets PDO's finite connection timeout
(default 5 seconds) and initializes finite session statement and idle-in-transaction
timeouts (defaults 5000 ms and 30000 ms). The statement baseline applies before
SET LOCAL and to commit confirmation. Set these through the factory's named
timeout arguments. The factory does not guarantee failover durability,
end-to-end network deadlines or safe third-party logging.
Installation is explicit, transactional and fails if the tables already exist.
New installations include separate partial indexes for explicit Unknown and
active lease expiry. For older installations the split query is immediately
compatible, but run the one-time migration
Schema::upgradeDiscoveryIndexes($migrationDatabase, 'idempotency', 60000)
to add both indexes. Schedule maintenance because this transactional DDL locks
the two tables; choose a timeout suitable for the table size. No rows are
removed or rewritten by the migration. Running it twice fails rather than
silently accepting an index of the wrong definition.
The schema must exist and its name must be lowercase ASCII, 1–63 bytes, starting
with a letter or underscore. The default schema is public; use a dedicated schema
in production. Cycle table prefixes are deliberately not applied.
- All four core interfaces are implemented: StoreInterface, RecoveryStoreInterface, UnknownAttemptProviderInterface, PrunableStoreInterface.
- Scope, key and payload are binary-safe PostgreSQL bytea, with no text collation or Unicode normalization. Fingerprints and attempt IDs retain core semantics.
- Every acquisition generates a new 128-bit attempt ID and 256-bit owner token. Only the SHA-256 hash of the token is persisted.
- Expiry of an active lease is logically Unknown, never an automatic retry. A matching owner can settle after expiry; recovery requires the exact unknown attempt. Terminal transitions invalidate the token and begin retention.
- Cleanup removes only expired terminal rows, within the supplied positive limit. Unknown discovery is ordered by binary scope and key, with an exclusive cursor.
- Each operation samples PostgreSQL time after locking a persistent clock row. Its committed high-water mark prevents observed expiry from reviving on clock rollback, including across worker restarts. A forward jump can shorten deadlines. Lease and retention are measured from the locked time sample, not the COMMIT acknowledgement. Database work and network delays can consume the whole interval. An expired lease still blocks other executions; an expired terminal retention permits key reuse. Include transaction delays and the full retry horizon in the retention policy; do not assume a minimum remaining TTL after a successful call. A fresh acquisition rejects lease or retention durations that would overflow when added to its clock sample. At settlement, a terminal deadline reaching or exceeding PHP_INT_MAX is represented by RetentionDeadline::NEVER and never expires automatically. Lease deadlines remain exclusive. This requires no schema migration; the existing bigint column represents the sentinel. Retained results and blocked attempts ignore the newly supplied policy.
- Per-key operations can proceed concurrently using a transaction-scoped advisory lock over a schema-namespaced, framed binary identity, followed by a shared clock-row lock. A waiter for a busy identity holds neither storage relation locks nor the clock row. All operations on the same identity serialize. Advisory hash collisions can only cause extra contention, not identity aliasing. A preliminary clock sample selects a shared lock only if the stored high-water mark is current. Otherwise no shared tuple lock is taken and the clock advances exclusively in the same transaction. If time advances after the shared row is locked, roll back without accessing a record and retry once through the exclusive path. An unconfirmed rollback is never retried. Clock advancement, discovery and pruning use exclusive clock locks; all key operations hold their locks until commit. Older exclusive-only adapter versions serialize against the shared mode without a schema migration. When upgrading from a shared-clock-first version, drain old workers before starting new workers: mixed lock orders can cause PostgreSQL deadlock/timeout errors (no unverified claim is released). Application callbacks run outside store transactions; benchmark contention and keep retention large enough.
The default ConcurrencyMode::PerKey assumes that advisory-lock acquisition
is restricted to trusted database roles. PostgreSQL advisory lock identities
are database-wide, not schema-private. If unrelated or untrusted roles can
acquire arbitrary advisory locks in the same database, use the explicit
ConcurrencyMode::ExclusiveClock profile for every idempotency worker:
$store = new PostgresStore(
$database,
'idempotency',
concurrencyMode: \Componenta\Idempotency\Cycle\ConcurrencyMode::ExclusiveClock,
);This profile uses no advisory locks, requires no schema migration, and safely serializes with per-key transactions through the same clock row. It sacrifices parallelism, but avoids denial of service through advisory-lock namespace collisions. A dedicated database with trusted roles is preferable for parallel mode. See advisory-lock privileges before enabling per-key mode in a shared database.
The adapter uses the physical write driver, never a read replica. Configure
Cycle reconnect=false and do not share an actively used connection with another
fiber or transaction. Ordinary methods reject an existing transaction. A
successful result is returned only after the driver confirms commit and PostgreSQL
reports the exact transaction ID committed on the original backend (pg_xact_status). An uncertain
commit or rollback raises StoreException. The driver is quarantined and, when
the adapter established ownership of the transaction, disconnected on a
best-effort basis to release outstanding locks. A returned disconnect call
must also report an inactive connection and transaction level zero; otherwise
cleanup is recorded as unconfirmed. This is a driver-level check, not proof
of physical socket closure. An unconfirmed BEGIN, including a failed
post-BEGIN transaction-level check, never rolls back or disconnects a session
whose transaction ownership has not been established.
Discard the adapter and its physical connection, then inspect on a fresh
connection. Do not retry an uncertain
external operation simply because a lease expired.
Transactions set local statement_timeout, lock_timeout, and synchronous_commit=on
(preserving remote_apply). They use READ COMMITTED and a local safe search path.
On dedicated connections, transaction isolation, search path, row security
and timeout settings are initialized in one fixed, parameter-free PDO batch.
Borrowed drivers use the existing two-statement setup. Both profiles restore
the caller's session settings on commit and rollback.
Timeouts are installed before assigning the transaction ID. The default timeout
is 5000 ms; it does not cover transaction startup, the post-commit confirmation
query or end-to-end network time. For a borrowed driver, configure a finite baseline PostgreSQL statement_timeout
for the runtime role or connection startup so it also applies before the transaction
local settings and after commit; the adapter preserves the caller's session
settings. connect_timeout and suitable TCP keepalive settings are additional
operational controls, not end-to-end response deadlines. Durable
PostgreSQL configuration (including fsync), backups, failover guarantees and
exclusive table ownership remain operator responsibilities. Never write directly
to the adapter tables or reset the clock row. Restrict recovery and cleanup
to trusted callers. Authentication and authorization must precede replay.
The constructor's maxPayloadBytes bounds each newly stored result (default
16 MiB, configurable from 0 to 64 MiB). Oversized results fail without settlement.
This is a logical per-result write limit, not a PHP memory limit or total
storage quota. The dedicated factory uses native binary PDO bytea parameters
for writes, avoiding the base64 encoding copy and its wire expansion. Borrowed
drivers retain the portable base64 write path. Both paths replay exact bytes
through PostgreSQL base64 output (which is more compact than text hex bytea).
PHP/driver allocations can still require several times the result size in
process memory. The dedicated driver does not interpolate query parameters on
statement failure and never retries a failed statement on another backend.
A 64 MiB rejected binary write is exercised under a 256 MiB PHP memory limit;
the caller must receive a sanitized SQLSTATE and retain the original claim.
Borrowed Cycle drivers still control their own error formatting and may allocate
large interpolated SQL before the adapter can sanitize the exception. A lower configured
write limit does not restrict replay of previously stored larger results.
Size the PHP memory budget for the largest retained result plus application
overhead; memory exhaustion is not a recoverable StoreException. For example,
the CI boundary workload
observed approximately 69 MiB and 262 MiB of peak PHP allocation for 16 MiB
and 64 MiB results, respectively. These measurements are not upper bounds,
and do not include all native process allocations. Use an appropriate result
size limit, retention policy and bounded cleanup for the deployment.
maxBatchSize (default 1000, configurable from 100 to 10000) bounds both
administrative operations. A non-positive or larger limit throws
InvalidArgumentException before opening a transaction; it is never clamped.
Use exclusive cursors for discovery and repeated bounded cleanup calls.
No eviction of unresolved attempts occurs. Sensitive payloads, identifiers and
driver errors may contain private data: do not log SQL parameters or raw errors.
This adapter does not provide a business-transaction profile or exactly-once external effects. Use a downstream stable idempotency key and reconciliation. See the normative contract.
composer install
composer test:unit
IDEMPOTENCY_TEST_DSN='pgsql:host=127.0.0.1;port=5432;dbname=idempotency_test' \
IDEMPOTENCY_TEST_USER=idempotency_test IDEMPOTENCY_TEST_PASSWORD=test composer test:integration
composer analysecomposer test runs both suites; composer test:unit does not connect to a
database (the Composer dependencies, including the PDO extension, must still
be installed). Integration tests require a disposable PostgreSQL database and permission to create/drop
randomly named schemas. Never point them at production. CI provisions a database and runs both suites. The integration suite uses real
PostgreSQL; the unit suite exercises injected driver failures.
CI checks out the same reviewed core revision in every matrix job and verifies
its installed Composer reference before running tests. Other dependencies are
resolved normally by Composer. Separate current and lowest-resolution jobs use
the actual production Composer manifest and retain its resolved lock file;
this detects incompatibilities hidden by a pinned development checkout.
The production manifest still requires dev-main until a stable core release.
Applications should commit their own lock file and use composer install. To test against a particular local core checkout:
php tools/development.php ../idempotency-core
COMPOSER=composer.dev.json composer update
COMPOSER=composer.dev.json composer checkThe generated root uses a path repository, leaving composer.json untouched.
Keep the development manifest and lock file out of Git; they contain a checkout
path. One existing CI matrix cell (PHP 8.4 / PostgreSQL 16) collects Xdebug
line, branch and path coverage, HTML and Clover reports, JUnit results, and
its resolved development lock file as an Actions artifact. The coverage cell runs the 500-step model with path instrumentation and the
four extended seeds separately with Xdebug disabled to avoid multiplying
instrumentation overhead. Other cells run the complete suite without coverage. A configured report is not evidence that the suite
passed; inspect the actual run before relying on its metrics.
The Infection baseline covers production source with focused unit and real
PostgreSQL scenarios (transaction boundaries, state transitions, row guards,
recovery, and result replay). Expensive subprocess/network faults and the seeded
model remain in the full matrix but are excluded from per-mutant runs. The
mutation job retains all scores and escaped mutants and enforces a 90% minimum
MSI and covered MSI. Timeouts count as escaped. The score is for the focused
suite, not the full integration suite. Run mkdir -p build/coverage && infection --no-interaction
with Infection 0.35.14, a coverage driver and the isolated integration database.
Run php -d memory_limit=256M tools/benchmark.php in the same disposable
PostgreSQL environment used by the integration tests. It checks and measures
60 independent acquire/complete/replay cycles per worker with one and four
simultaneous processes, exact 16 MiB and 64 MiB incompressible binary results
and oversized result rejection, paginated discovery of 120 unresolved attempts,
and bounded cleanup of 302 terminal records. The primary measurement now uses
DedicatedDatabaseFactory; a separate disposable schema repeats both worker
waves and payload boundaries on the original borrowed-driver profile. A sparse
fixture with 20,000 active rows and 12 unknown attempts verifies sparse and
dense discovery (including pagination across both unresolved states), and
records EXPLAIN (ANALYZE, BUFFERS) for the actual split discovery query and the
previous combined predicate on equivalent fixtures. A separate disposable
workload compares insert/transition time and physical index sizes with and
without the two new partial indexes; these are measurements, not fixed
performance assertions. Both payloads are replayed from
an independent connection configured with the default 16 MiB write limit.
The 64 MiB worker has a 512 MiB PHP memory limit; the other workers use 256 MiB.
These are test-process budgets, not minimum application memory requirements.
Payload reports include separate write/replay durations and PHP peak allocation. It reports p50/p95/p99 cycle latency, throughput,
PHP worker peak memory and maintenance latency. CI retains the JSON with its
coverage evidence. Timings are runner-specific observations, not performance
thresholds or proof of a production service-level objective. The workload uses
a randomly created test schema and must never target a production database.
Stored record projections also validate state, positive lease/retention values, and the syntax of any loaded ownership hash before use. Unknown discovery validates both encoded binary identity components and the attempt/fingerprint before returning an attempt; malformed projections fail without decoding warnings. This is a fail-closed defense in depth, not support for arbitrary schema changes or database corruption.
System schemas (including pg_temp) are rejected. The adapter checks both tables
are ordinary permanent logged relations without inheritance parents or children,
triggers, rewrite rules, or row-level security under relation locks. The catalog
guard rejects all triggers, rules and policies, including dormant ones, and any
relation with enabled or forced row-level security. It also checks that the
clock has an immediate valid primary key on singleton and the records table
has an immediate valid primary key on (scope, operation_key), in that order.
This prevents ambiguous identity resolution when a migration removes or
replaces an essential key. Changing the behavior of these
physical tables is unsupported. The locking, read, update and delete statements explicitly
target the physical tables with ONLY; inherited rows must not participate.
It rejects
fsync=off or full_page_writes=off. Row-level security is disabled locally so a policy that hides a
record causes an error instead of being mistaken for absence. Do not install
policies on these tables. The adapter requires exclusive ownership of the
schema and does not defend against arbitrary privileged modifications. Use an exclusively
owned schema, a trusted driver and a direct or session-affine PostgreSQL
connection. Install the schema with a migration role. A separate runtime role
needs USAGE on that schema and SELECT, INSERT, UPDATE, DELETE on the two
idempotency tables; it does not need SUPERUSER, BYPASSRLS or DDL rights.
The CI suite verifies transitions, recovery, replay and cleanup with these grants.
The test uses a temporary non-login role in the isolated CI database; local
integration runs using a non-superuser test account skip only that fixture. A transaction-pooling proxy is not supported by the same-backend
commit check. Discard a write driver after an unconfirmed transaction; the
adapter also rejects reuse of that driver object by any other store instance
in the same PHP process. Do not share that driver with concurrent application
code. In particular, do not clone a connected Cycle driver or create another
driver wrapper sharing the same native PDO connection. Use a nonpersistent
dedicated connection with PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTION. For
large binary results or memory-sensitive workers, configure Cycle
queryCache: false to avoid retaining payload parameters in cached PDO
statements. The adapter does not mutate or clone the supplied driver to change
its cache configuration. Setting an appropriate server-side
idle_in_transaction_session_timeout is recommended as a fallback for
unreachable or abandoned sessions. The logical clock is locked on every
operation, but its stored value is
updated only when the observed second advances. Sampling and conditional
persistence use a single statement after the schema guard; the row remains
locked until commit, shared on stable per-key operations and exclusive for
clock advancement/maintenance. Per-key advisory locks are acquired before
storage relation and clock-row locks; the exclusive fallback and maintenance
never request an identity lock while holding the clock. An owned renewal with an
unchanged deadline and a repeated explicit Unknown transition do not rewrite
the record; both still lock the clock and confirm the transaction commit.
Mutating SQL statements also
verify the expected incarnation/state/deadline and ownership hash as a defense-in-depth measure;
unexpected changes fail closed. Direct writes to these tables remain unsupported.
Replay bytes are read only for
an unexpired matching completed record, never for conflicts or owner mutations.
A real independent-connection test holds one key lock while another key acquires, inspects and completes; attempts on the locked key and exclusive maintenance time out safely. A rollback fault test ensures the clock-advance fallback never starts a second transaction after an unconfirmed rollback.
The concurrency suite also races terminal pruning against a replacement claim, and two different fingerprints competing at the exact retention boundary. Both workers reach a real database lock barrier before the clock advances; assertions verify that only the winning incarnation remains.
A caller-owned transaction started through raw SQL is also tested: Cycle's nesting counter remains zero, but acquisition fails without committing, rolling back or disconnecting that session. The caller retains responsibility for resolving the transaction and must discard the quarantined driver before reusing it for idempotency operations.
The integration suite includes an explicit two-process database lock barrier and
checks both workers are waiting for a lock before releasing it.
The transition-race tests advance the logical clock while inspection and renewal
are blocked, and race owner completion against privileged recovery. They verify
that waiting operations see the committed expiry and only one terminal result
wins, without relying on wall-clock sleep for expiry. Fault tests
terminate the actual PostgreSQL backend before or after a commit, and separately
simulate a driver losing an acknowledgement. Another integration test applies a
finite session statement_timeout after commit, delays the actual confirmation
SQL and verifies that PostgreSQL cancellation quarantines the driver without
releasing the durable claim. A separate TCP relay drops COMMIT before forwarding it or suppresses the response
after the server reports COMMIT and idle ReadyForQuery. Independent connections
verify the durable outcome. The same pass-through and fault cases exercise both borrowed and dedicated
connections, including native binary settlement. A separate real backend-loss
test ensures that the dedicated driver does not reconnect an outside-transaction
query. The relay can target the second COMMIT to test the full Executor after
the callback ran. The suite also checks callback exceptions, invalid result
types, oversized results, reconciliation and replay without invoking the callback
again. The relay is test-only and uses cleartext on loopback; configure a simple
explicit TCP test DSN and never use this fixture with production data. The test role must be able to inspect and terminate its own
sessions in the isolated test database. Store/record debug output omits
credentials and results; sensitive callback arguments are redacted in PHP traces.
A 500-step coverage model and four extended seeded 1,000-step differential tests compare the SQL adapter with the core's
MemoryStore reference under the same logical clock, including stale ownership,
conflicts, pagination and retention.
Fault tests also leave an owned transaction open deliberately on failed COMMIT
or ROLLBACK and verify that the adapter disconnects the session and a separate
connection can make progress. Cleanup failure never replaces the original error
as the exception's previous cause; internal diagnostics retain rollback and
disconnect errors when present. If both cursor reading and cursor closure fail,
the adapter retains the read error as the primary cause and a separately
sanitized close failure, including when confirmation fails after commit. Driver-only unit tests cover failed ownership
checks, disconnect postconditions, rejection of unsafe database configuration
and reuse after a confirmed rollback separately from the real PostgreSQL suite.
The Unix subprocess helper uses nonblocking pipes and monotonic deadlines for
worker responses and exit, drains diagnostics, and bounds buffered output.
Database-free tests exercise real child PHP processes, including hung workers,
partial replies, excessive output and nonzero exit codes.
A reported network fault is accepted only after the relay exits successfully
without additional protocol output; receiving a marker alone is insufficient.
Database-free record tests also exercise exact expiry boundaries, byte-exact
ownership, binary payload hydration, malformed storage values and signed integer
limits using the actual core value objects.
The PHP 8.4 / PostgreSQL 16 CI cell also runs a separate crash-durability
check: a fresh process commits six records and an advanced logical clock,
the isolated PostgreSQL service is terminated with SIGKILL and restarted,
and another process verifies persisted deadlines, binary replay, ownership,
recovery, retry and pruning. The controller checks the service container
identity, image, exit code and readiness; its synthetic fixture is private
and is not uploaded. The log contains no result bytes or owner tokens.
This is a process/container crash check, not a power-loss, storage-device
failure or asynchronous replication failover test. Its result must be
confirmed by an actual CI run.
Cycle/PDO database exceptions crossing the adapter boundary are replaced by a safe StoreException; when available, the validated five-character SQLSTATE is retained. Raw SQL, driver messages, driver exception objects and their original traces are deliberately not chained. This applies also to commit, rollback and disconnect diagnostics. Non-database exceptions from trusted custom drivers are not sanitized. Cycle's own logger may emit a database error before the adapter can sanitize it, even with SQL interpolation disabled. Use a dedicated driver without a logger (or a strictly redacting logger), disable SQL parameter logging and query caching, and never log raw exceptions or traces in production.
Database-server logging is a separate confidentiality boundary. PostgreSQL may include the failing row in a constraint error's DETAIL, even when bind-parameter logging is disabled and the adapter returns a sanitized exception. Binary values in hex or base64 are reversible, not redacted. This behavior is visible in the integration suite's deliberately failing constraint test (synthetic data).
Review the dedicated database/runtime role's logging configuration with the DBA:
use log_parameter_max_length = 0 and log_parameter_max_length_on_error = 0,
consider log_error_verbosity = terse to omit error details, and review SQL
statement logging, audit extensions, proxies, monitoring and log access.
These controls reduce disclosure but do not guarantee that all messages or
third-party logs are free of sensitive values. Do not grant the runtime role
elevated privileges just to modify logging. The adapter does not change server
logging settings. See PostgreSQL error reporting and logging.
MIT.