diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index da2fff9..3ea725d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,21 +114,8 @@ jobs: run: composer check-platform-reqs - name: PHP syntax on this PHP minor run: composer syntax - - name: Dependency policy is configured fail-closed - run: | - set -euo pipefail - for variable in COMPOSER_POLICY COMPOSER_NO_BLOCKING COMPOSER_NO_AUDIT COMPOSER_AUDIT_ABANDONED COMPOSER_POLICY_ADVISORIES_BLOCK COMPOSER_POLICY_MALWARE_BLOCK; do - if [ -n "${!variable:-}" ]; then - echo "$variable weakens the dependency policy" >&2 - exit 1 - fi - done - composer config policy | jq -e ' - .advisories.block == true and .advisories.audit == "fail" - and .malware.block == true and .malware["block-scope"] == "all" and .malware.audit == "fail" - and .abandoned.audit == "fail"' - - name: Composer audit (advisories, malware, abandoned) - run: composer audit --no-interaction --abandoned=fail + - name: Composer dependency policy audit + run: php scripts/dependency-audit.php - name: Static analysis (PHPStan max) run: composer analyse # PHP CS Fixer 3.95.32 refuses PHP 8.6 (it supports syntax up to 8.5), so the formatter runs in its diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index bc93e22..50d6d4e 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -7,7 +7,7 @@ $finder = (new Finder()) ->in(__DIR__) - ->exclude(['vendor', 'docs']) + ->exclude('vendor') ->name('*.php') ->ignoreDotFiles(false); diff --git a/CHANGELOG.md b/CHANGELOG.md index b2e93ba..a6e35f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,18 +14,23 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and - Static composite and dynamic Offset sorting through separate entry points. Static plans define fixed trailing terms. Dynamic sorting accepts up to three allowlisted request sort keys with independent directions. - Protected Host write checkouts with registered commands and guarded Ordering. The Host directs transaction completion and uses the settlement to choose handoff or discard. - Verified Apply/Discard (C2) for package-owned and Host-owned transactions. It returns the decision payload after confirming the required control and reports the database outcome and connection disposition separately. +- JSON projections for C1, B, Protected and Verified settlement DTOs. Enum fields use stable uppercase codes and absent fields remain null. B's live PDO handoff uses `HostSnapshotRetirement`, and Verified callbacks return `VerifiedTransactionDecisionCommand`. - Protected UNIQUE-safe Ordering (B1) for eligible dense InnoDB lists. Hosts can allocate an append position, move rows, or run a registered delete with compaction under one scope anchor. ### Changed - Raised the Composer PHP patch floors from RC.2's `^8.4`. PHP 8.4.0–8.4.26 and 8.5.0–8.5.11 can no longer resolve this version. The admitted ranges start at 8.4.27 for PHP 8.4 and 8.5.12 for PHP 8.5, with forward eligibility within PHP 8. - Raw Ordering allocation through `ScopedOrderingManager::getNextPositionForUpdate()` stops after 64 locking tail reads by default. The optional `maxTailReads` argument accepts 2–512. A tail that would have stabilized later under RC.2 can now raise the existing `OrderingExecutionException` with `TAIL_READ_LIMIT_EXCEEDED` metadata. Existing positional and named calls remain valid. The Host retains control of transaction completion and acquired locks. +- Raw and protected `moveWithinScope()` validate `updatedAtValue` before issuing SQL. When `updatedAtColumn` is configured, provide a valid `YYYY-MM-DD HH:MM:SS` value with an optional 1–6 digit fraction. This narrows RC.2's driver-dependent acceptance. Convert other formats in the Host before calling the manager. +- Raw `moveWithinScope()` now throws when settlement of an otherwise ordinary `false` result fails. This changes RC.2 behavior for an unconfirmed package-owned rollback or failed local savepoint release. Handle the existing `TransactionExecutionException` or the original driver throwable and resolve connection state before reuse. Normal results and Host transaction ownership continue to follow the [Ordering contract](PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager). +- **Breaking from RC.2:** Constructors reject a trailing LF in direct `PageResultDTO` sort keys, `SortWhitelist` keys and SQL identifier paths, pagination binding keys, and `ScopedOrderingConfig` table and column names. RC.2 could accept these inputs under its published patterns. Supply canonical names at the call site and match binding keys to the SQL placeholders. See the [migration guidance](PHP_PERSISTENCE_PACKAGE_REFERENCE.md#15-rc2-constructor-input-migration). +- **Breaking from RC.2:** `SortDirectionEnum` declares `Asc` and `Desc`. The `ASC` and `DESC` aliases still resolve to the same direction values. Enum name reads, `cases()`, Reflection and native PHP serialized payloads now use PascalCase. Decode older persisted payloads with RC.2 before upgrading, or rebuild caches. Backing strings, SQL and pagination JSON retain `ASC` and `DESC`. See the [migration guidance](PHP_PERSISTENCE_PACKAGE_REFERENCE.md#16-rc2-sort-direction-migration). ### Fixed - Preserve the original transaction or savepoint failure when the cleanup state check also fails. - Attempt to release count and data cursors after pagination read, validation, or mapper failures while preserving the original error. -- Reject terminal newlines in trusted SQL identifiers, named binding keys, decimal COUNT values and direct result sort keys. +- Reject trailing LF in COUNT strings so they contain only decimal digits, as required by the RC.2 contract. ## [1.0.0-rc.2] - 2026-11-18 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 2631652..fb88f1b 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,7 +1,7 @@ # Code of Conduct — maatify/php-persistence [![Maatify PHP Persistence](https://img.shields.io/badge/Maatify-PHP_Persistence-blue?style=for-the-badge)](https://github.com/Maatify-ltd/php-persistence) -[![Maatify Ecosystem](https://img.shields.io/badge/Maatify-Ecosystem-9C27B0?style=for-the-badge)](https://github.com/Maatify) +[![Maatify Ecosystem](https://img.shields.io/badge/Maatify-Ecosystem-9C27B0?style=for-the-badge)](https://github.com/Maatify-ltd) ## Our Standard diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a1e8abd..7e1a15b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,15 +29,15 @@ composer validate --strict composer verify:php-constraint # Composer solver checks for the declared PHP boundaries composer check-platform-reqs composer dump-autoload --optimize --strict-psr -composer audit --no-interaction --abandoned=fail +php scripts/dependency-audit.php # Composer 2.10+ and a freshly resolved composer.lock composer analyse # PHPStan, level max, zero errors, no baseline composer format:check # full code-style check on PHP 8.4 or 8.5, non-mutating -composer syntax # php -l over src, tests, scripts, examples +composer syntax # lints PHP in src/, tests/, scripts/, examples/, harness/, docs/, and root .php-cs-fixer.php composer whitespace # git diff --check composer test:unit # no Docker needed composer test:regression # no Docker needed composer test:integration # needs Docker; starts a disposable MySQL/MariaDB service -composer examples:smoke # needs Docker; smoke-executes examples/ against a real engine +composer examples:smoke # needs Docker; runs standalone examples against a real engine composer test:consumer # needs Docker; two fresh external Composer verification runs actionlint .github/workflows/*.yml ``` diff --git a/PHP_PERSISTENCE_PACKAGE_REFERENCE.md b/PHP_PERSISTENCE_PACKAGE_REFERENCE.md index ad75d89..a0b59d7 100644 --- a/PHP_PERSISTENCE_PACKAGE_REFERENCE.md +++ b/PHP_PERSISTENCE_PACKAGE_REFERENCE.md @@ -26,7 +26,7 @@ The package offers three independent capabilities over a **caller-supplied `PDO` - It owns no table, schema, or domain-owned persisted state of its own. It operates entirely on tables the host application owns and names. - It contains no HTTP controllers, routes, middleware, permission checks, UI, or export logic. - Operation state is scoped to each call or operation object. The optional B source and the protected write checkout maintain their own reservation state across calls. The one-shot C1 operation retains its grant and terminal outcome on its own object, as specified by [DEC-018](docs/decisions/DEC-018-optional-delegated-snapshot-pagination.md). -- B is a stateful, opt-in exception. The source maintains a shared reservation, checkout and transaction generation across calls. A process-local `WeakMap` prevents rebinding the same PDO while that object still exists. Each page attempt retains its own terminal settlement. See [DEC-020](docs/decisions/DEC-020-optional-host-transaction-snapshot-pagination.md) and [§5.3.3](#533-optional-b-pagination-in-a-host-owned-transaction). +- B is a stateful, opt-in exception. The source maintains a shared reservation, checkout and transaction generation across calls. A process-local `WeakMap` prevents rebinding the same PDO while that object still exists. Each page attempt retains its own terminal settlement. See [DEC-036](docs/decisions/DEC-036-pascalcase-enums-and-stable-settlement-json.md) and [§5.3.3](#533-optional-b-pagination-in-a-host-owned-transaction). - A protected write checkout keeps one exclusive reservation, one Host-directed transaction, and its final settlement. Its registration is separate from Pagination checkout APIs. See [§5.2.1](#521-optional-protected-host-write-transaction). - It is not a connection factory and does not perform dependency injection wiring; a host wires it directly or through its own container. @@ -49,6 +49,25 @@ This package is a separate Composer package from the published `maatify/persiste The [README](README.md#installation) records the exact installation target and the condition for external Composer resolution. [`composer.json`](composer.json) governs the current package identity, PHP and extension requirements, and Composer dependencies. +### 1.5 RC.2 constructor input migration + +RC.2 documented identifier patterns using `$` as the end anchor. In PHP, those patterns can match immediately before a final line feed (LF). The `1.0.0` target checks the entire supplied name, so constructors reject inputs with an LF that RC.2 could accept. This is a breaking change at the input boundary. Callers can use the same constructors and pass canonical names. The array and JSON shape of valid page results stays the same. See [DEC-035](docs/decisions/DEC-035-reject-terminal-lf-in-constructor-inputs.md). + +| Constructor input | Exception | Migration | +| --- | --- | --- | +| Direct `PageResultDTO` sort key | `PaginationExecutionException` | Supply the intended canonical sort key in `sortBy`, for example `id` when that is the intended key. | +| `SortWhitelist` public keys and SQL identifier paths | `InvalidPaginationConfigurationException` | Correct the keys and trusted identifier path segments at their source. Use the corrected keys for the default and tie-breaker in `PaginationConfig`. | +| `PdoPaginationQueryDescriptor` binding keys | `InvalidPaginationQueryException` | Use the exact bare name of each SQL placeholder in the corresponding parameter map. For example, use the map key `status` for `:status` in SQL. | +| `ScopedOrderingConfig` table and column names | `InvalidOrderingConfigurationException` | Supply the intended trusted table or `schema.table` name and canonical column names. | + +The paginator still trims an Offset `PageRequest` sort key before whitelist lookup, as specified in [§5.3](#53-pdopaginatorpaginate). COUNT text returned by PDO must already consist of decimal digits within the documented range. A trailing LF in a COUNT string violates that published RC.2 requirement. + +### 1.6 RC.2 sort direction migration + +In RC.2, the PHP enum cases were `SortDirectionEnum::ASC` and `SortDirectionEnum::DESC`. This release declares `Asc` and `Desc` as its cases. Existing comparisons, arguments and defaults that use the old constants still resolve to the corresponding case through compatibility aliases. SQL receives the same direction tokens. `value`, `from()`, `tryFrom()` and pagination JSON continue to use the backing strings `ASC` and `DESC`. + +Code consuming `name`, `cases()` or Reflection's enum case list must use the PascalCase names. For persisted data, decode any RC.2 native PHP enum payloads with RC.2 before upgrading, then store the backing string and restore it with `SortDirectionEnum::from()`. Native serialized data names the case and an ordinary constant alias does not restore the RC.2 payload. Rebuild caches containing RC.2 serialized enums, including enums nested in DTOs. See [DEC-036](docs/decisions/DEC-036-pascalcase-enums-and-stable-settlement-json.md). + --- ## 2. Source topology @@ -82,11 +101,9 @@ src/ ├── Pagination/ │ ├── Config/PaginationConfig.php │ ├── Config/StaticSortPlan.php -│ ├── Criteria/HostSnapshotAttemptRecord.php (@internal) │ ├── Criteria/HostSnapshotBindings.php (@internal) │ ├── Criteria/HostSnapshotCatalog.php │ ├── Criteria/HostSnapshotCommandPlan.php -│ ├── Criteria/HostSnapshotGrantRegistration.php (@internal) │ ├── Criteria/HostSnapshotPageAttempt.php │ ├── Criteria/HostSnapshotPageGrant.php │ ├── Criteria/HostSnapshotPagePlan.php @@ -94,7 +111,6 @@ src/ │ ├── Criteria/PageRequest.php │ ├── Criteria/PdoPaginationQueryDescriptor.php │ ├── DTO/HostSnapshotPageSettlementDTO.php -│ ├── DTO/HostSnapshotRetirementDTO.php │ ├── DTO/KeysetPageResultDTO.php │ ├── DTO/MultiSortPageResultDTO.php │ ├── DTO/PageResultDTO.php @@ -116,8 +132,11 @@ src/ │ ├── Exception/InvalidPaginationQueryException.php │ ├── Exception/PaginationExecutionException.php │ ├── Exception/SnapshotPaginationException.php +│ ├── Repository/HostSnapshotAttemptRecord.php (@internal) │ ├── Repository/HostSnapshotConnection.php (@internal) +│ ├── Repository/HostSnapshotGrantRegistration.php (@internal) │ ├── Repository/HostSnapshotPageReader.php (@internal) +│ ├── Repository/HostSnapshotRetirement.php │ ├── Repository/KeysetCursor.php (@internal) │ ├── Repository/PdoHostSnapshotCheckout.php │ ├── Repository/PdoHostSnapshotPaginator.php @@ -133,8 +152,8 @@ src/ └── Transaction/ ├── Criteria/ProtectedTransactionCommandCatalog.php ├── Criteria/ProtectedTransactionCommandPlan.php + ├── Command/VerifiedTransactionDecisionCommand.php ├── DTO/ProtectedTransactionSettlementDTO.php - ├── DTO/VerifiedTransactionDecisionDTO.php ├── DTO/VerifiedTransactionSettlementDTO.php ├── Enum/ProtectedTransactionDispositionEnum.php ├── Enum/ProtectedTransactionReasonEnum.php @@ -260,7 +279,7 @@ public function discardForHost(): void `Criteria\ProtectedTransactionCommandCatalog::__construct(array $commands)` accepts a map of identifiers to `ProtectedTransactionCommandPlan` objects. A plan is constructed with `string $sql, array $parameterNames, ?int $maxRows = null`. A null bound requests affected-row count. A positive bound requests a list of associative result rows, with PDO column-key semantics, and rejects a result exceeding that bound. Bindings match the registered unique names exactly and carry strings, integers, booleans, or null. Names omit the colon. Plans accept statements beginning with SELECT, INSERT, UPDATE, DELETE, REPLACE or WITH, without semicolons. The Host warrants single-statement InnoDB behavior that preserves the session and transaction, including the behavior of any routines or triggers. -`DTO\ProtectedTransactionSettlementDTO` is readonly and exposes `public ProtectedTransactionDispositionEnum $disposition` and `public ProtectedTransactionReasonEnum $reason`. See §5.2.1 for the dispositions and reasons. +`DTO\ProtectedTransactionSettlementDTO` is readonly and exposes `public ProtectedTransactionDispositionEnum $disposition` and `public ProtectedTransactionReasonEnum $reason`. Its JSON object contains `disposition` and `reason` using the stable string codes in [§3.6](#36-settlement-enum-json-codes). See §5.2.1 for the dispositions and reasons. #### Optional verified write checkout @@ -268,11 +287,11 @@ public function discardForHost(): void ~~~php public static function attachExclusive(#[SensitiveParameter] PDO $pdo, ProtectedTransactionCommandCatalog $catalog): self -/** @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionDTO $operation */ +/** @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionCommand $operation */ public function runOwned(Closure $operation): mixed public function beginHost(): void public function runRegisteredCommand(string $commandId, array $bindings = []): int|array -/** @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionDTO $operation */ +/** @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionCommand $operation */ public function runInHost(Closure $operation): mixed public function commit(): void public function rollBack(): void @@ -281,9 +300,9 @@ public function returnForHost(): PDO public function discardForHost(): void ~~~ -`Repository\VerifiedTransactionCommandsInterface` exposes only `runRegisteredCommand(string $commandId, array $bindings = []): int|array`. `DTO\VerifiedTransactionDecisionDTO` is final readonly with `bool $isApply` and `mixed $payload` and the factories `apply(mixed $payload = null): self` and `discard(mixed $payload = null): self`. The payload may be false or null and its identity is preserved. +`Repository\VerifiedTransactionCommandsInterface` exposes only `runRegisteredCommand(string $commandId, array $bindings = []): int|array`. `Command\VerifiedTransactionDecisionCommand` is final readonly with `bool $isApply` and `mixed $payload` and the factories `apply(mixed $payload = null): self` and `discard(mixed $payload = null): self`. The payload may be false or null and its identity is preserved. The command is a PHP callback result with no JSON contract. -`DTO\VerifiedTransactionSettlementDTO` is final readonly. Its constructor takes the public properties in order, without defaults. +`DTO\VerifiedTransactionSettlementDTO` is final readonly. Its constructor takes the public properties in order, without defaults. Its JSON object uses the same five property names. Each populated enum field projects its stable string code from [§3.6](#36-settlement-enum-json-codes). Each unset field is null. | Property | Type | | --- | --- | @@ -293,7 +312,7 @@ public function discardForHost(): void | checkoutReason | ?VerifiedTransactionReasonEnum | | disposition | ?ProtectedTransactionDispositionEnum | -The unbacked `Enum\VerifiedTransactionOutcomeEnum` has NOT_STARTED, PENDING_HOST, LOCAL_UNDONE, COMMITTED, ROLLED_BACK and UNKNOWN. The unbacked `Enum\VerifiedTransactionReasonEnum` has QUALIFICATION_FAILED, START_UNCONFIRMED, CONTINUITY_UNCONFIRMED, SAVEPOINT_UNCONFIRMED, CALLBACK_FAILED, COMMAND_FAILED, CURSOR_UNCONFIRMED, ROLLBACK_TO_UNCONFIRMED, RELEASE_UNCONFIRMED, COMMIT_OUTCOME_UNKNOWN, ROLLBACK_UNCONFIRMED, HANDOFF_UNCONFIRMED, TRANSACTION_LOST and HOST_DISCARDED. The settlement is a PHP value, without a wire-format or authority to use PDO. See [§5.2.2](#522-optional-verified-apply-and-discard). +The unbacked `Enum\VerifiedTransactionOutcomeEnum` has `NotStarted`, `PendingHost`, `LocalUndone`, `Committed`, `RolledBack`, `Unknown`. The unbacked `Enum\VerifiedTransactionReasonEnum` has `QualificationFailed`, `StartUnconfirmed`, `ContinuityUnconfirmed`, `SavepointUnconfirmed`, `CallbackFailed`, `CommandFailed`, `CursorUnconfirmed`, `RollbackToUnconfirmed`, `ReleaseUnconfirmed`, `CommitOutcomeUnknown`, `RollbackUnconfirmed`, `HandoffUnconfirmed`, `TransactionLost`, `HostDiscarded`. The settlement carries data without authority to use PDO. Its JSON field names and codes follow the contract above. See [§5.2.2](#522-optional-verified-apply-and-discard). #### `Exception\InvalidTransactionConfigurationException` / `Exception\TransactionExecutionException` / `Exception\ProtectedTransactionException` @@ -392,12 +411,15 @@ The three SQL statements are the caller's own text: a count of the whole dataset ```php enum SortDirectionEnum: string { - case ASC = 'ASC'; - case DESC = 'DESC'; + case Asc = 'ASC'; + case Desc = 'DESC'; + + public const ASC = self::Asc; + public const DESC = self::Desc; } ``` -PHP provides the enum’s read-only `name` and `value` properties and the standard backed-enum methods `cases(): array`, `from(int|string $value): static`, and `tryFrom(int|string $value): ?static`. +PHP provides the enum’s read-only `name` and `value` properties and the standard backed-enum methods `cases(): array`, `from(int|string $value): static`, and `tryFrom(int|string $value): ?static`. The compatibility constants are aliases. Reflection and `cases()` report the two PascalCase cases. See [the RC.2 migration](#16-rc2-sort-direction-migration). #### `DTO\PageResultDTO` (`final readonly class`, implements `JsonSerializable`, `@template T of array|object`) @@ -529,8 +551,8 @@ public function paginate( public function connectionOutcome(): ?SnapshotConnectionOutcomeDTO; ``` -- `DTO\SnapshotConnectionOutcomeDTO` is readonly. The constructor takes `SnapshotConnectionDispositionEnum $disposition` and `?string $diagnostic`, also available as public readonly properties. A `DISCARD` outcome requires a non-blank diagnostic. Use the enum for decisions and the diagnostic for safe failure-stage information. -- `Enum\SnapshotConnectionDispositionEnum` has cases `UNCHANGED`, `REUSABLE` and `DISCARD`. +- `DTO\SnapshotConnectionOutcomeDTO` is readonly. The constructor takes `SnapshotConnectionDispositionEnum $disposition` and `?string $diagnostic`, also available as public readonly properties. A `Discard` outcome requires a non-blank diagnostic. Use the enum for decisions and the diagnostic for safe failure-stage information. Its JSON object contains `disposition` as a stable string code from [§3.6](#36-settlement-enum-json-codes) and `diagnostic` as a string or null. +- `Enum\SnapshotConnectionDispositionEnum` has cases `Unchanged`, `Reusable` and `Discard`. - `connectionOutcome()` returns null before a terminal outcome and the same immutable DTO afterward. The accessor performs no I/O. The operation releases its own reference to the PDO and the outcome holds only the enum and diagnostic. Behavior: see §5.3.1. @@ -592,11 +614,11 @@ B provides a source, an exclusive checkout, and a one-shot authorization per rea // Repository\PdoHostSnapshotSource public static function attachExclusive(PDO $pdo, HostSnapshotCatalog $catalog): self; public function checkout(): PdoHostSnapshotCheckout; -public function retireForHost(): HostSnapshotRetirementDTO; +public function retireForHost(): HostSnapshotRetirement; public function discardForHost(): void; // Repository\PdoHostSnapshotCheckout -public function beginRepeatableRead(HostSnapshotAccessModeEnum $mode = HostSnapshotAccessModeEnum::READ_WRITE): void; +public function beginRepeatableRead(HostSnapshotAccessModeEnum $mode = HostSnapshotAccessModeEnum::ReadWrite): void; public function runRegisteredCommand(string $commandId, array $bindings = []): int|array; public function commit(): void; public function rollBack(): void; @@ -633,13 +655,13 @@ public function __construct( array $parameterNames, HostSnapshotCommandResultModeEnum $resultMode, ?int $maxRows = null, - HostSnapshotCommandEffectEnum $effect = HostSnapshotCommandEffectEnum::INVALIDATE_GENERATION, + HostSnapshotCommandEffectEnum $effect = HostSnapshotCommandEffectEnum::InvalidateGeneration, ); ``` - The source issues the opaque checkout, grant, and attempt. These identities and the source reject cloning, serialization, and restoration. Members marked @internal are implementation details. Explicit B contract rejections use Pagination\Exception\HostSnapshotPaginationException and the package marker. -- `DTO\HostSnapshotPageSettlementDTO` is readonly with two public fields: `disposition` (`Enum\HostSnapshotPageDispositionEnum`) and `reason` (`Enum\HostSnapshotPageSettlementReasonEnum`). See the [page settlement contract in §5.3.3](#533-optional-b-pagination-in-a-host-owned-transaction) for their values and meaning. `DTO\HostSnapshotRetirementDTO` is readonly with public `HostSnapshotRetirementDispositionEnum disposition` and `PDO pdo` fields. -- Checkout state is IDLE, TRANSACTION_ACTIVE, TRANSACTION_UNQUALIFIED, BUSY, QUARANTINED, RELEASED, or RETIRED. The access modes are READ_WRITE and READ_ONLY. Command result modes are AFFECTED_ROWS and BOUNDED_ROWS. Effects are INVALIDATE_GENERATION and PRESERVES_TRANSACTION. +- `DTO\HostSnapshotPageSettlementDTO` is readonly with two public fields: `disposition` (`Enum\HostSnapshotPageDispositionEnum`) and `reason` (`Enum\HostSnapshotPageSettlementReasonEnum`). Its JSON object contains `disposition` and `reason` using the stable string codes in [§3.6](#36-settlement-enum-json-codes). See the [page settlement contract in §5.3.3](#533-optional-b-pagination-in-a-host-owned-transaction) for their values and meaning. `Repository\HostSnapshotRetirement` is readonly with public `HostSnapshotRetirementDispositionEnum disposition` and `PDO pdo` fields. It transfers the live connection in PHP with no JSON contract. +- Checkout states are `Idle`, `TransactionActive`, `TransactionUnqualified`, `Busy`, `Quarantined`, `Released`, and `Retired`. Access modes are `ReadWrite` and `ReadOnly`. Command result modes are `AffectedRows` and `BoundedRows`. Effects are `InvalidateGeneration` and `PreservesTransaction`. #### Pagination exceptions @@ -772,9 +794,9 @@ PHP can load these classes and reach public members marked `@internal`. These im - **`Pagination\Repository\SnapshotReadResources`** — tracks and confirms release of C1 statement cursors. - **`Pagination\Repository\HostSnapshotConnection`** — tracks B's PDO and statement lifetimes, executes SQL, and verifies session state. - **`Pagination\Repository\HostSnapshotPageReader`** — reads the registered page and releases statement resources before mapping. -- **`Pagination\Criteria\HostSnapshotAttemptRecord`** — holds one attempt's state and published settlement. +- **`Pagination\Repository\HostSnapshotAttemptRecord`** — holds one attempt's state and published settlement. - **`Pagination\Criteria\HostSnapshotBindings`** — validates registered parameter names and freezes typed binding values. -- **`Pagination\Criteria\HostSnapshotGrantRegistration`** — binds a registered read and request to the source's checkout identity and transaction generation. +- **`Pagination\Repository\HostSnapshotGrantRegistration`** — binds a registered read and request to the source's checkout identity and transaction generation. - **`Pagination\Exception\HostSnapshotRowLimitExceededException`** — signals that a result exceeded its row bound. B handles it during cleanup and reports the applicable public pagination exception. - **`Transaction\Repository\OwnedTransactionExecutor`** — the shared begin/callback/commit-with-replay mechanism behind both Transaction runners. Exposes `public const MAX_DEADLOCK_RETRIES = 3`, which is the same bound documented publicly through the runners' `$maxDeadlockRetries` constructor parameter (§3.2); this constant is not a separate contract. - **`Ordering\Repository\OrderingOperations`** — shared Ordering SQL and validation behind both managers. @@ -786,12 +808,26 @@ PHP can load these classes and reach public members marked `@internal`. These im --- +### 3.6 Settlement enum JSON codes + +C1, B, Protected, and Verified settlement DTOs project the following strings in fields that hold PHP enum values. The property retains its original unit enum type and the DTO preserves null fields. Enum case names in PHP use PascalCase. The JSON code remains stable if the PHP name changes. + +| PHP enum | PHP case → JSON code | +| --- | --- | +| `SnapshotConnectionDispositionEnum` | `Unchanged` → `UNCHANGED`, `Reusable` → `REUSABLE`, `Discard` → `DISCARD` | +| `HostSnapshotPageDispositionEnum` | `NotAccepted` → `NOT_ACCEPTED`, `ReturnedToHost` → `RETURNED_TO_HOST`, `HostActionRequired` → `HOST_ACTION_REQUIRED` | +| `HostSnapshotPageSettlementReasonEnum` | `SourceUnavailable` → `SOURCE_UNAVAILABLE`, `StaleContext` → `STALE_CONTEXT`, `GrantConsumed` → `GRANT_CONSUMED`, `Busy` → `BUSY`, `PageCompleted` → `PAGE_COMPLETED`, `ReadFailed` → `READ_FAILED`, `ResourceReleaseUnconfirmed` → `RESOURCE_RELEASE_UNCONFIRMED`, `ScopeUnconfirmed` → `SCOPE_UNCONFIRMED`, `SettlementUnconfirmed` → `SETTLEMENT_UNCONFIRMED` | +| `ProtectedTransactionDispositionEnum` | `Unchanged` → `UNCHANGED`, `Reusable` → `REUSABLE`, `DiscardRequired` → `DISCARD_REQUIRED` | +| `ProtectedTransactionReasonEnum` | `CancelledBeforeQualification` → `CANCELLED_BEFORE_QUALIFICATION`, `ServerQualificationFailed` → `SERVER_QUALIFICATION_FAILED`, `StartUnconfirmed` → `START_UNCONFIRMED`, `TransactionLost` → `TRANSACTION_LOST`, `OperationUnconfirmed` → `OPERATION_UNCONFIRMED`, `CommitOutcomeUnknown` → `COMMIT_OUTCOME_UNKNOWN`, `CommitConfirmedConnectionUnsafe` → `COMMIT_CONFIRMED_CONNECTION_UNSAFE`, `RollbackUnconfirmed` → `ROLLBACK_UNCONFIRMED`, `Committed` → `COMMITTED`, `RolledBack` → `ROLLED_BACK`, `HostDiscarded` → `HOST_DISCARDED` | +| `VerifiedTransactionOutcomeEnum` | `NotStarted` → `NOT_STARTED`, `PendingHost` → `PENDING_HOST`, `LocalUndone` → `LOCAL_UNDONE`, `Committed` → `COMMITTED`, `RolledBack` → `ROLLED_BACK`, `Unknown` → `UNKNOWN` | +| `VerifiedTransactionReasonEnum` | `QualificationFailed` → `QUALIFICATION_FAILED`, `StartUnconfirmed` → `START_UNCONFIRMED`, `ContinuityUnconfirmed` → `CONTINUITY_UNCONFIRMED`, `SavepointUnconfirmed` → `SAVEPOINT_UNCONFIRMED`, `CallbackFailed` → `CALLBACK_FAILED`, `CommandFailed` → `COMMAND_FAILED`, `CursorUnconfirmed` → `CURSOR_UNCONFIRMED`, `RollbackToUnconfirmed` → `ROLLBACK_TO_UNCONFIRMED`, `ReleaseUnconfirmed` → `RELEASE_UNCONFIRMED`, `CommitOutcomeUnknown` → `COMMIT_OUTCOME_UNKNOWN`, `RollbackUnconfirmed` → `ROLLBACK_UNCONFIRMED`, `HandoffUnconfirmed` → `HANDOFF_UNCONFIRMED`, `TransactionLost` → `TRANSACTION_LOST`, `HostDiscarded` → `HOST_DISCARDED` | + ## 4. Ownership vocabulary - **Caller-owned transaction** — a transaction under the caller's control. When a Transaction runner or Ordering operation joins an active caller transaction, the caller retains all final transaction control. A savepoint, where used, limits the effects of that individual operation. Ordinary and Keyset pagination read in the context supplied by the caller. - **Host-owned transaction through B** — the Host keeps transaction and connection ownership while delegating exclusive use of its PDO to a source. The source issues transaction control under the shared reservation in response to explicit Host commands, including `beginRepeatableRead()`, `commit()`, and `rollBack()`. Page reads participate in that transaction. The Host decides how to resolve failures and when to end the transaction, request handoff, or discard the source. See [§5.3.3](#533-optional-b-pagination-in-a-host-owned-transaction). - **Host-owned transaction through the protected write checkout** — the Host delegates exclusive PDO use for one write transaction. The checkout starts and ends that transaction under reservation in response to the Host's explicit `begin()`, `commit()`, or `rollBack()` calls. Registered commands and protected Ordering participate in the transaction. The Host directs handoff or discard and reconciles any unconfirmed outcome. See [§5.2.1](#521-optional-protected-host-write-transaction). -- **Package-owned transaction** — begun by the package itself because none was active when a Transaction-runner method, or `ScopedOrderingManager::moveWithinScope()`, was called, or when C1 accepted a qualified exclusive grant and confirmed the start of its read-only transaction. The package commits it on success. Transaction runners and Ordering attempt a best-effort rollback when their transaction is still active after a failure. C1 only attempts rollback after a read failure once cursor release and ownership of the active transaction on the same session are confirmed. See [§5.3.1](#531-optional-c1-snapshot-pagination). +- **Package-owned transaction** — begun by the package itself because none was active when a Transaction-runner method, or `ScopedOrderingManager::moveWithinScope()`, was called, or when C1 accepted a qualified exclusive grant and confirmed the start of its read-only transaction. The package commits it on success. Transaction runners and Ordering attempt a best-effort rollback when their transaction is still active after an original error. An ordinary false result from raw Ordering requires acknowledged rollback and idle PDO state (§5.4). C1 only attempts rollback after a read failure once cursor release and ownership of the active transaction on the same session are confirmed. See [§5.3.1](#531-optional-c1-snapshot-pagination). --- @@ -828,9 +864,9 @@ Host Input (callback) → run($callback) → caller-owned: participate The Host delegates a standard non-persistent pdo_mysql connection with exception error mode and the default PDOStatement class. The Host supplies it idle, with autocommit enabled, and transfers exclusive use at the successful return of `attachExclusive()`. Local attachment issues no SQL. `begin()` qualifies the server session under reservation before `START TRANSACTION READ WRITE`, then checks the start on the same session. The session's isolation policy remains Host-controlled. Until confirmation, workload and transaction completion are unavailable. Aliases, multiplexing, automatic reconnect and replay invalidate eligibility. The registration protects this path and does not detect enrollment of the same PDO in Pagination. MySQL and MariaDB deployments must route the guarded unit through this checkout. -The reservation spans registered commands, protected Ordering, finish and disposition. Re-entry is rejected. A successfully completed lease command checks the same session, released resources and the expected transaction state before handing out its result. A result that exceeds its row bound raises `ProtectedTransactionException`. The checkout remains active if the result is released and the same active transaction is confirmed. Engine failures fence the checkout and prevent further application SQL. If guarded savepoint control fails, the first failure escapes instead of a boolean result. Cursor cleanup cannot replace that failure. Raw Ordering keeps its existing best-effort savepoint cleanup. +The reservation spans registered commands, protected Ordering, finish and disposition. Re-entry is rejected. A successfully completed lease command checks the same session, released resources and the expected transaction state before handing out its result. A result that exceeds its row bound raises `ProtectedTransactionException`. The checkout remains active if the result is released and the same active transaction is confirmed. Engine failures fence the checkout and prevent further application SQL. If guarded savepoint control fails, the first failure escapes instead of a boolean result. Cursor cleanup cannot replace that failure. When raw Ordering already has an original failure, it retains best-effort savepoint cleanup to preserve that failure. See [§5.4](#54-scopedorderingmanager) for the separate requirements for a normal false result. -| Disposition | Reason and meaning for the Host | +| Disposition JSON code | Reason JSON code and meaning for the Host | |---|---| | `UNCHANGED` | `CANCELLED_BEFORE_QUALIFICATION` when `returnForHost()` cancels a checkout before server work. The original connection is handed back. This conveys no server qualification. | | `REUSABLE` | `COMMITTED` or `ROLLED_BACK` after the Host's explicit completion, verified on the same idle session with released resources. The Host may retrieve the same PDO once. | @@ -840,18 +876,18 @@ The reservation spans registered commands, protected Ordering, finish and dispos #### 5.2.2 Optional verified apply and discard -[DEC-022](docs/decisions/DEC-022-verified-apply-discard.md) defines one exclusive delegation for one transaction. The Host supplies an exact PDO or Pdo\Mysql object from pdo_mysql with native prepares, exception mode, the default statement class, no persistence and autocommit enabled. Supply it idle, with no pending transaction settings or resources and multi-statements disabled at construction. Keep raw aliases out of use, including through pools, reconnect, multiplexing or simultaneous enrollment in another capability. The package reserves the PDO object between Verified and Protected Transaction checkouts. Pagination registries remain separate. A trusted plan must preserve the same session and transaction, including the effects of its routines and triggers. The API does not establish safety for an external alias, a non-transactional side effect or a transaction-changing command. +[DEC-036](docs/decisions/DEC-036-pascalcase-enums-and-stable-settlement-json.md) defines one exclusive delegation for one transaction. The Host supplies an exact PDO or Pdo\Mysql object from pdo_mysql with native prepares, exception mode, the default statement class, no persistence and autocommit enabled. Supply it idle, with no pending transaction settings or resources and multi-statements disabled at construction. Keep raw aliases out of use, including through pools, reconnect, multiplexing or simultaneous enrollment in another capability. The package reserves the PDO object between Verified and Protected Transaction checkouts. Pagination registries remain separate. A trusted plan must preserve the same session and transaction, including the effects of its routines and triggers. The API does not establish safety for an external alias, a non-transactional side effect or a transaction-changing command. Attachment performs no SQL. A refusal leaves the Host in control. The first start qualifies the session under reservation and verifies the qualified generation before work. The existing Catalog and Plan are used for both modes. Registered commands bind the exact named scalar values. The interface exposes a count or bounded rows, never a statement or PDO. The scope is valid only in the invoking Fiber or root context and closes before finalization. Reentry, stale scopes and a second operation are rejected before SQL. The checkout does not replay callbacks. | Mode | APPLY | DISCARD | | --- | --- | --- | | Owned | Starts once, commits, and confirms the same idle session before returning payload. | Starts once, rolls back, and confirms the same idle session before returning payload. | -| Host | Host starts and may issue registered commands before or after one operation. The operation releases its savepoint and confirms continuity, then returns payload with PENDING_HOST. | Acknowledged ROLLBACK TO and RELEASE plus confirmed continuity permit payload and LOCAL_UNDONE. The Host decides the outer end in either case. | +| Host | Host starts and may issue registered commands before or after one operation. The operation releases its savepoint and confirms continuity, then returns payload with `PendingHost`. | Acknowledged ROLLBACK TO and RELEASE plus confirmed continuity permit payload and `LocalUndone`. The Host decides the outer end in either case. | -An escaping callback Throwable retains its identity, including after a caught driver failure or a cleanup failure. The receiver preserves the first safety failure for fencing and settlement. A normal return from the callback after a latched failure is suppressed and that failure is thrown. A healthy generation may be rolled back or undone after a clean callback error. A failed control or uncertainty fences the checkout, suppresses payload and prevents further queries and handoff. A lost end reply records UNKNOWN. An acknowledged end remains COMMITTED or ROLLED_BACK if the later handoff check fails. ACK of ROLLBACK TO remains LOCAL_UNDONE even when release or continuity cannot be confirmed. +An escaping callback Throwable retains its identity, including after a caught driver failure or a cleanup failure. The receiver preserves the first safety failure for fencing and settlement. A normal return from the callback after a latched failure is suppressed and that failure is thrown. A healthy generation may be rolled back or undone after a clean callback error. A failed control or uncertainty fences the checkout, suppresses payload and prevents further queries and handoff. A lost end reply records `Unknown`. An acknowledged end remains `Committed` or `RolledBack` if the later handoff check fails. Acknowledged rollback to the savepoint remains `LocalUndone` even when release or continuity cannot be confirmed. -The immutable snapshot is a local read and publishes before release of the reservation. Operation facts survive a later Host end. Transaction outcome is null while active. Disposition null means the checkout holds the connection, UNCHANGED is an untouched cancellation without server qualification, and REUSABLE attests eligibility at confirmed completion. DISCARD_REQUIRED bars handoff even when the database effect is known. Successful handoff returns the same object once, while discard releases library references without an explicit database command. Disposal and loss of the final PDO reference do not attest transaction outcome. +The immutable snapshot is a local read and publishes before release of the reservation. Operation facts survive a later Host end. Transaction outcome is null while active. Disposition null means the checkout holds the connection, `Unchanged` is an untouched cancellation without server qualification, and `Reusable` attests eligibility at confirmed completion. `DiscardRequired` bars handoff even when the database effect is known. Successful handoff returns the same object once, while discard releases library references without an explicit database command. Disposal and loss of the final PDO reference do not attest transaction outcome. See the [runnable Owned, Host and exception examples](examples/verified_transaction_usage.php). @@ -885,7 +921,7 @@ C1 takes an already built descriptor and begins one owned `READ ONLY` transactio C1 closes its read resources and verifies the delegated transaction and session before and after its own `COMMIT` or `ROLLBACK`. It explicitly suppresses chaining and release on these commands. It preserves session settings and PDO attributes. Page output requires confirmed completion. A PDO or mapper throwable escapes unchanged. On failure, C1 attempts rollback only for a confirmed owned scope with confirmed resource cleanup. An unconfirmed start, cleanup or finish keeps the checkout out of circulation. -| Outcome | Meaning for the Host | +| Outcome JSON code | Meaning for the Host | | --- | --- | | `UNCHANGED` | Known ineligibility before starting the transaction. The original Host policy retains the connection. This outcome grants no clearance for a new checkout. | | `REUSABLE` | Confirmed completion of the owned transaction on the same session with released resources. A read failure followed by confirmed cleanup can also produce this outcome. | @@ -911,36 +947,23 @@ Pass an eligible `pdo_mysql` connection, in `ERRMODE_EXCEPTION` and `CASE_NATURA **Ownership and eligibility.** The Host supplies its exclusively owned, non-persistent pdo_mysql PDO or Pdo\Mysql object with ERRMODE_EXCEPTION and the default PDOStatement class. The Host routes connection use through the source for the duration of delegation and retains it until handoff or discard. Shared references from before delegation, automatic reconnect or replay, and session multiplexing invalidate eligibility. B leaves connection attributes in the Host's control. It requires one stable session with autocommit enabled. One live source registration per PDO object is enforced in the process, including after handoff when that object still exists. The source permits one active checkout. -**Registration and transaction proof.** Register non-locking, side-effect-free InnoDB page plans and trusted Host commands. Each SQL statement declares its own unique names. The values are an exact named map of string, int, bool, or null. The Host is responsible for SQL semantics and template placeholder positions. Catalog lookups use PHP array-key semantics, including decimal string identifiers that PHP stores as integer keys. A bounded command must set a positive maxRows. If it exceeds the bound, it reports the row-limit failure after cleanup and scope confirmation. If confirmation fails, the source quarantines and still reports the row-limit failure. Its rows preserve the aliases and keys returned by PDO::FETCH_ASSOC, including numeric keys. Pagination data rows require string keys before mapping. A command declared PRESERVES_TRANSACTION must be incapable of changing the session or current transaction. The default effect invalidates the generation before the command is sent. Ambiguity quarantines the source. The Host requests beginRepeatableRead() on an idle checkout. Under the reservation, B sends SET TRANSACTION ISOLATION LEVEL REPEATABLE READ followed immediately by START TRANSACTION in the requested access mode. The confirmed same session and active transaction establish a new generation. An idle session with a pending next-transaction setting that B has not confirmed consumed is eligible for reconciliation, and becomes eligible for ordinary release after a qualified begin and confirmed end. The Host's explicit commit() and rollBack() use AND NO CHAIN NO RELEASE and confirm the same session without an active transaction. There is no retry or automatic completion on a page path. +**Registration and transaction proof.** Register non-locking, side-effect-free InnoDB page plans and trusted Host commands. Each SQL statement declares its own unique names. The values are an exact named map of string, int, bool, or null. The Host is responsible for SQL semantics and template placeholder positions. Catalog lookups use PHP array-key semantics, including decimal string identifiers that PHP stores as integer keys. A bounded command must set a positive maxRows. If it exceeds the bound, it reports the row-limit failure after cleanup and scope confirmation. If confirmation fails, the source quarantines and still reports the row-limit failure. Its rows preserve the aliases and keys returned by PDO::FETCH_ASSOC, including numeric keys. Pagination data rows require string keys before mapping. A command declared `PreservesTransaction` must be incapable of changing the session or current transaction. The default effect invalidates the generation before the command is sent. Ambiguity quarantines the source. The Host requests beginRepeatableRead() on an idle checkout. Under the reservation, B sends SET TRANSACTION ISOLATION LEVEL REPEATABLE READ followed immediately by START TRANSACTION in the requested access mode. The confirmed same session and active transaction establish a new generation. An idle session with a pending next-transaction setting that B has not confirmed consumed is eligible for reconciliation, and becomes eligible for ordinary release after a qualified begin and confirmed end. The Host's explicit commit() and rollBack() use AND NO CHAIN NO RELEASE and confirm the same session without an active transaction. There is no retry or automatic completion on a page path. **Page and settlement.** The Host authorizes a page on the proven generation, then creates an attempt before calling the paginator. A single reservation covers Host commands and page reads. Authorizations are consumed only on admission. A busy but otherwise eligible grant can be used in a fresh attempt. B completes and closes the count and data statements before calling the mapper. It checks the transaction again before publishing the terminal settlement and opening the reservation. Driver and mapper throwables propagate as the original objects. After a statement-level cardinality, data, or syntax/access-rule error in an eligible registered read, B still checks resource and transaction continuity. A driver failure that leaves the transaction effect uncertain quarantines the source. Ordinary exception arguments from B carry no PDO or statement, including through recoverable wrappers. -An attempt is NEW, RUNNING, or TERMINAL. settlement() returns null before it is terminal and returns the same immutable, resource-free value afterward, including after a subsequent read, release, retirement, or discard. A repeat invocation of the same attempt rejects without changing its settlement. +An attempt is `New`, `Running`, or `Terminal`. settlement() returns null before it is terminal and returns the same immutable, resource-free value afterward, including after a subsequent read, release, retirement, or discard. A repeat invocation of the same attempt rejects without changing its settlement. -| Disposition | Reasons and effect | +| Disposition JSON code | Reason JSON codes and effect | | --- | --- | | NOT_ACCEPTED | SOURCE_UNAVAILABLE, STALE_CONTEXT, GRANT_CONSUMED, or BUSY, in that order when several apply. The attempt has performed no database I/O. | | RETURNED_TO_HOST | PAGE_COMPLETED or READ_FAILED after confirmation of the resource and transaction scope. The source still holds the connection. | | HOST_ACTION_REQUIRED | RESOURCE_RELEASE_UNCONFIRMED, SCOPE_UNCONFIRMED, or SETTLEMENT_UNCONFIRMED. B invalidates the generation and quarantines the source before relinquishing the reservation. In an accepted invocation that returns or throws, a terminal fallback remains available even if ordinary settlement cannot finish. | -**Release, retirement, and discard.** release() makes the source available to another checkout only after confirmed idle status and resolution of pending settings and resources. retireForHost() permanently invalidates the source and transfers the same PDO after confirmed resource release. RETURNED_IDLE certifies the known idle state; RETURNED_FOR_RECONCILIATION asks the Host to resolve the connection before further circulation. An unresolved resource prevents transfer. The Host can call discardForHost() to permanently invalidate the source and drop the library's references. This call initiates zero explicit SQL, state probes, or transaction-end commands. PDO or its driver may automatically send ROLLBACK or perform other I/O or close the session when the last reference is released. The caller does not receive an acknowledgement of transaction outcome, timing, or server closure. A retirement or discard request while a reservation is held is rejected. +**Release, retirement, and discard.** release() makes the source available to another checkout only after confirmed idle status and resolution of pending settings and resources. retireForHost() permanently invalidates the source and transfers the same PDO after confirmed resource release. `ReturnedIdle` certifies the known idle state. `ReturnedForReconciliation` asks the Host to resolve the connection before further circulation. An unresolved resource prevents transfer. The Host can call discardForHost() to permanently invalidate the source and drop the library's references. This call initiates zero explicit SQL, state probes, or transaction-end commands. PDO or its driver may automatically send ROLLBACK or perform other I/O or close the session when the last reference is released. The caller does not receive an acknowledgement of transaction outcome, timing, or server closure. A retirement or discard request while a reservation is held is rejected. -```php -$checkout = $source->checkout(); -$checkout->beginRepeatableRead(); -$grant = $checkout->authorizePage('items', ['tenant' => 7], new PageRequest()); -$attempt = $checkout->newAttempt($grant); -try { - $page = $paginator->paginate($attempt); -} finally { - $settlement = $attempt->settlement(); -} -// The Host uses $settlement on either path and explicitly ends its transaction. -// The Host can reconcile after a classified handoff. Unresolved resources prevent handoff; -// the Host may explicitly discard that connection. -``` +See the [Host Snapshot B example](examples/pagination_host_snapshot_usage.php) for a read-only page attempt, qualified rollback on read failure, and explicit connection disposition. -See [DEC-020](docs/decisions/DEC-020-optional-host-transaction-snapshot-pagination.md). +See [DEC-036](docs/decisions/DEC-036-pascalcase-enums-and-stable-settlement-json.md). ### 5.3.4 Optional static composite Offset pagination @@ -970,7 +993,9 @@ Existing `paginate()`, static sort, C1, B, and Keyset calls keep their own resul The host owns the table schema. The locking and rollback behavior described below requires a transactional storage engine that provides row locks and savepoints. Integration tests use InnoDB on MySQL and MariaDB. On a nontransactional table, a failed move can leave earlier shifts in place. -`$updatedAtValue` must be null if and only if `updatedAtColumn` is null. When configured, the timestamp is written only to the target row when it actually moves. All four methods first validate scope usage (`$scopeValue` consistent with `$config->scopeColumn`/`$config->nullableScope`); `getNextPosition`, `getNextPositionForUpdate`, and `moveWithinScope` throw `InvalidOrderingOperationException` on misuse, while `rowExistsInScope` additionally just returns `false` for `$id <= 0` without throwing (`moveWithinScope` throws `InvalidOrderingOperationException` for `$id <= 0` or `$newOrder <= 0`). +`$updatedAtValue` must be null if and only if `updatedAtColumn` is null. When configured, raw and protected moves require a valid Gregorian date and 24-hour time in `YYYY-MM-DD HH:MM:SS` format, with an optional decimal point and 1–6 fractional-second digits. Invalid values raise `InvalidOrderingOperationException` before Ordering SQL. The accepted string is bound unchanged and is written only to the target row when it actually moves. Format the value in the intended Host timezone and choose precision supported by the underlying column. [DEC-033](docs/decisions/DEC-033-validate-ordering-mutation-timestamps.md) records this change from RC.2, which passed a supplied string through to the driver. + +All four methods first validate scope usage (`$scopeValue` consistent with `$config->scopeColumn`/`$config->nullableScope`); `getNextPosition`, `getNextPositionForUpdate`, and `moveWithinScope` throw `InvalidOrderingOperationException` on misuse, while `rowExistsInScope` additionally just returns `false` for `$id <= 0` without throwing (`moveWithinScope` throws `InvalidOrderingOperationException` for `$id <= 0` or `$newOrder <= 0`). The host selects the PDO error mode. Ordering uses it as configured, including `ERRMODE_EXCEPTION`, `ERRMODE_SILENT`, and `ERRMODE_WARNING`. A statement failure reported through a return value raises `OrderingExecutionException`. In warning mode, PDO can also emit its usual warning. Any throwable from PDO or the host's warning handler propagates unchanged. A successful empty scope or missing row keeps the result documented below. @@ -992,14 +1017,15 @@ Existing positional and named calls keep their argument names, defaults and `int #### `moveWithinScope()` -Never trusts a caller-supplied "current order"; it first locks the active ordering scope and derives its maximum from that locking read. It then reads the target’s current order through a separate locking query. A positive `$newOrder` is limited to `min($newOrder, max(1, $lockedMaximum))`. Runs through `PdoTransactionRunner` (so it owns a transaction when none is active, or participates in the caller's with the behavior of §5.1). +Never trusts a caller-supplied "current order"; it first locks the active ordering scope and derives its maximum from that locking read. It then reads the target’s current order through a separate locking query. A positive `$newOrder` is limited to `min($newOrder, max(1, $lockedMaximum))`. Starts and owns a transaction if none is active. Otherwise the caller retains transaction control. The range shift runs while the target row still occupies its original position. A uniqueness constraint on the order column or on the scope and order columns can reject an intermediate update, even when the intended final order would satisfy the constraint. For general reordering, use a schema that permits these intermediate positions. If the Host requires unique dense positions, see the [protected B1 profile](#541-protected-unique-safe-ordering-b1). - Returns `true` on a successful move, and `true` (as a no-op, no SQL mutation issued beyond the scope lock and the read) when the row is already at the requested/clamped position. -- Returns `false` when the target row does not exist in the given scope at the moment it is read under the scope lock — **this is not an exception**, and in this common case **no savepoint statement is issued at all**: the absence is detected before any savepoint is opened. -- **Participating in a caller-owned transaction:** only once the row is confirmed to exist *and* its clamped target order actually differs from its current order (the no-op and missing-row cases above never reach this point) does it open an operation-local savepoint (`SavepointScope::begin()`), immediately before the first mutating statement. A `Throwable` from the range-shift or target-write statements triggers best-effort `cleanupAfterFailure()`. The cleanup attempts `ROLLBACK TO` only if PDO reports an active transaction, and attempts `RELEASE` only after the rollback is acknowledged. The original `Throwable` is rethrown unchanged. In the narrower case where the shifts succeed but the final target-row `UPDATE` itself still affects zero rows, the open savepoint is undone through `undoOrFail()` before returning `false` — there, `ROLLBACK TO` is **not** best-effort: its own failure is thrown instead of the `false` result; the following `RELEASE SAVEPOINT` is still best effort. If releasing the savepoint after a successful update fails, the method attempts to undo the operation and throws the release failure. The caller owns the surrounding transaction and its earlier work while that transaction remains active. -- **Owned path (no active caller transaction):** the method uses no savepoint. It requests a whole-transaction rollback on an exception, on a missing target, or when the target update affects zero rows. Rollback is best effort through `PdoTransactionRunner`. +- Returns `false` for a missing target or a zero-row target update once the required settlement below succeeds. The caller-owned path detects a missing target before opening a savepoint. +- **Participating in a caller-owned transaction:** only once the row is confirmed to exist *and* its clamped target order actually differs from its current order (the no-op and missing-row cases above never reach this point) does it open an operation-local savepoint (`SavepointScope::begin()`), immediately before the first mutating statement. A `Throwable` from the range-shift or target-write statements triggers best-effort `cleanupAfterFailure()`. The cleanup attempts `ROLLBACK TO` only if PDO reports an active transaction, and attempts `RELEASE` only after the rollback is acknowledged. The original `Throwable` is rethrown unchanged. When the shifts succeed and the target update reports zero affected rows, both `ROLLBACK TO SAVEPOINT` and the subsequent `RELEASE SAVEPOINT` must succeed before returning `false`. If rollback fails, its error propagates and release is skipped. If release fails after rollback, its error propagates. If releasing the savepoint after a successful update fails, the method attempts to undo the operation and throws the release failure. The caller owns the surrounding transaction and its earlier work while that transaction remains active. +- **Owned path (no active caller transaction):** the method uses no savepoint. A missing target or zero-row target update requires PDO to report the owned transaction active, acknowledge the rollback, and report an idle transaction state before the method returns `false`. A statement or commit error keeps precedence over best-effort rollback. +- **Settlement failure without a prior error:** a failed control return or an unconfirmed owned rollback raises the existing `TransactionExecutionException`. A thrown driver failure propagates unchanged. The Host checks and resolves the surrounding transaction and connection state before reuse. RC.2 could return ordinary `false` after a failed owned rollback or a failed savepoint release. [DEC-034](docs/decisions/DEC-034-raw-ordering-settlement-failures.md) records this approved behavior change. - A deadlock (`1213`), the MariaDB `1020` hazard (§7.3), or a lock-wait timeout with `innodb_rollback_on_timeout=ON` can end the **caller's whole transaction** on the server. If PDO throws, that exception propagates unchanged. If PDO reports the statement failure by return value, the method raises `OrderingExecutionException`. This method does not retry either failure. #### `rowExistsInScope()` @@ -1048,7 +1074,7 @@ DELETE FROM `app`.`playlist_items` WHERE `id` = :id AND `scope_id` = :scope_id A Invalid identifiers, bounds, or target positions raise the corresponding Ordering configuration or operation exception. `OrderingExecutionException::getMeta()['reason']` reports `SCHEMA_UNVERIFIED`, `INELIGIBLE_SCHEMA`, `ANCHOR_MISSING`, `SCOPE_NOT_DENSE`, `SCOPE_ROW_LIMIT`, `NO_STAGING_POSITION`, `MOVE_INVARIANT_FAILED` or `DELETE_INVARIANT_FAILED`. A positive move order beyond `N` is invalid when the target exists. A failed count or local verification cannot return a success result. -For confirmed local failures after mutation, the package undoes and releases the local savepoint only while it can verify continuity. A driver, cursor, savepoint, or continuity failure can fence the whole checkout. The original failure is propagated. Follow `settlement()` and discard on `DISCARD_REQUIRED` without any further SQL. Preserve earlier Host writes only if continuity and local undo were confirmed. The Host controls commit and rollback, and the library does not retry. See the [Basic and Professional workflows](docs/guides/USAGE_GUIDE.md#protected-unique-safe-ordering-b1). +For confirmed local failures after mutation, the package undoes and releases the local savepoint only while it can verify continuity. A driver, cursor, savepoint, or continuity failure can fence the whole checkout. The original failure is propagated. Follow `settlement()` and discard on `DiscardRequired` without any further SQL. Preserve earlier Host writes only if continuity and local undo were confirmed. The Host controls commit and rollback, and the library does not retry. See the [Basic and Professional workflows](docs/guides/USAGE_GUIDE.md#protected-unique-safe-ordering-b1). ## 6. Exceptions reference @@ -1078,7 +1104,7 @@ External `\PDOException` or callback/mapper `Throwable` generally propagates unc | Exception | Base | Thrown when | |---|---|---| | `InvalidTransactionConfigurationException` | `SystemMaatifyException` | A transaction-runner constructor receives `$maxDeadlockRetries` outside `[0, 3]`. | -| `TransactionExecutionException` | `SystemMaatifyException` | A PDO transaction-control statement (`BEGIN`, `COMMIT`, `SAVEPOINT`, `RELEASE SAVEPOINT`, `ROLLBACK TO SAVEPOINT`) returns `false` instead of throwing; or the shared savepoint helper observes that a caller-owned transaction is no longer active immediately after a successful `SAVEPOINT`, before the callback or Ordering mutation. | +| `TransactionExecutionException` | `SystemMaatifyException` | A PDO transaction-control statement (`BEGIN`, `COMMIT`, `SAVEPOINT`, `RELEASE SAVEPOINT`, `ROLLBACK TO SAVEPOINT`, or the required raw Ordering `ROLLBACK`) returns `false` instead of throwing. It is also raised when the package cannot confirm the required owned rollback and idle PDO state, or when the shared helper observes that a caller-owned transaction is no longer active immediately after `SAVEPOINT`. | | `ProtectedTransactionException` | `SystemMaatifyException` | The optional [Protected](#521-optional-protected-host-write-transaction) and [Verified](#522-optional-verified-apply-and-discard) paths reject a connection, lifecycle action, command registration, lookup, bindings or row bound, or cannot confirm a resource, session or control operation when the driver does not throw. Verified also rejects an invalid callback decision, an unavailable command grant and an unsafe PDO handoff. Propagated driver and callback throwables retain their identity under the precedence rules in §5.2.1 and §5.2.2. | ### 6.2 Pagination @@ -1110,6 +1136,7 @@ External `\PDOException` or callback/mapper `Throwable` generally propagates unc |---|---| | Transaction runner or Ordering operation that owns transaction control, with no active transaction | Begin, run the operation, commit. On failure, roll back (best effort) and rethrow the original `Throwable`. A `false` from `beginTransaction()`/`commit()` fails closed with `TransactionExecutionException`. | | Transaction runner or Ordering operation joins an active caller transaction | The caller retains final transaction control. A savepoint, when used, limits only the effects of this operation. | +| Raw Ordering reports a missing target or zero-row target update | A caller-owned missing target requires no savepoint. Otherwise `false` requires the appropriate rollback, including release of a caller-local savepoint or idle PDO state after owned rollback. Failed settlement throws. See [§5.4](#54-scopedorderingmanager). | | Callback/operation throws | The original `Throwable` is rethrown unchanged. A cleanup (rollback/savepoint-undo) failure never replaces it. | | Deadlock (`40001`/`1213`) in a package-owned transaction | Replayed only under the exact conditions of §5.1, default off (`$maxDeadlockRetries = 0`). | | Deadlock or any error in a caller-owned transaction | Never replayed by this package; it propagates to the caller, which decides. | @@ -1183,7 +1210,7 @@ A detailed, dated per-behavior mapping (the B-01 to B-16 rows, each with its leg - [README.md](README.md) — quick overview, installation/access status, requirements. - [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md) — capability map, walkthroughs, and the boundaries of each capability before its examples. -- [examples/](examples/) — runnable, Public-API-only examples for all three capabilities. +- [examples/](examples/) — standalone and Host-dependent examples using only the Public API across all three capabilities. - [llms.txt](llms.txt) — AI consumer navigation map. - [docs/architecture/ARCHITECTURE.md](docs/architecture/ARCHITECTURE.md), [CONTRACT_MATRIX.md](docs/architecture/CONTRACT_MATRIX.md), [BEHAVIOR_CONTRACT.md](docs/architecture/BEHAVIOR_CONTRACT.md), [DATABASE_SUPPORT_AND_TEST_POLICY.md](docs/architecture/DATABASE_SUPPORT_AND_TEST_POLICY.md), [CI_AND_INTEGRATION.md](docs/architecture/CI_AND_INTEGRATION.md) — design, legacy-mapping, and test-matrix detail, dated and framed as historical/evidence records rather than a second current contract. - [docs/decisions/DECISIONS_INDEX.md](docs/decisions/DECISIONS_INDEX.md) — durable decisions this reference applies. diff --git a/README.md b/README.md index 58e50d5..7c251f7 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ $orderId = $runner->run(function () use ($pdo): int { }); ``` -See [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md) for a capability map covering Transaction, Pagination, and Ordering, each with its own `Input → Public Call → Result → Boundary` walkthrough, and [examples/](examples/) for complete, runnable scripts. +See [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md) for a capability map covering Transaction, Pagination, and Ordering, each with its own `Input → Public Call → Result → Boundary` walkthrough, and [examples/](examples/) for standalone scripts and the Host Snapshot B integration example. ## Public Runtime API @@ -147,13 +147,13 @@ Table and column identifiers passed to `ScopedOrderingConfig` and sort-key ident ## Examples -Runnable [examples](examples/) cover Transaction, Pagination and Ordering on a real MySQL/MariaDB connection. The [opt-in Snapshot example](examples/pagination_snapshot_usage.php) shows a single page with Host-owned connection settlement. See the [C1 contract](PHP_PERSISTENCE_PACKAGE_REFERENCE.md#531-optional-c1-snapshot-pagination) for eligibility and usage. +Runnable [examples](examples/) cover Transaction, Pagination and Ordering on a real MySQL/MariaDB connection. The [opt-in Snapshot example](examples/pagination_snapshot_usage.php) shows a single page with Host-owned connection settlement. See the [C1 contract](PHP_PERSISTENCE_PACKAGE_REFERENCE.md#531-optional-c1-snapshot-pagination) for eligibility and usage. The [Host Snapshot B example](examples/pagination_host_snapshot_usage.php) requires an application-owned PDO and page-plan catalog. ## Documentation - [PHP_PERSISTENCE_PACKAGE_REFERENCE.md](PHP_PERSISTENCE_PACKAGE_REFERENCE.md) — canonical Public Runtime API, behavior, and exception contract. - [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md) — capability map and walkthroughs. -- [examples/](examples/) — runnable examples. +- [examples/](examples/) — standalone and Host-dependent examples. - [CHANGELOG.md](CHANGELOG.md) · [SECURITY.md](SECURITY.md) · [CONTRIBUTING.md](CONTRIBUTING.md) - [llms.txt](llms.txt) — AI consumer navigation map. - [docs/architecture/ARCHITECTURE.md](docs/architecture/ARCHITECTURE.md) — design and topology (dated design record). @@ -174,19 +174,20 @@ composer format:check # PER-CS 3.1, non-mutating composer test:unit # no Docker needed composer test:regression composer test:integration # needs Docker; starts a disposable MySQL/MariaDB service -composer examples:smoke # needs Docker; smoke-executes examples/ against a real engine +composer examples:smoke # needs Docker; runs standalone examples against a real engine ``` See [docs/architecture/QUALITY_TOOLING.md](docs/architecture/QUALITY_TOOLING.md), [docs/architecture/CI_AND_INTEGRATION.md](docs/architecture/CI_AND_INTEGRATION.md), and [CONTRIBUTING.md](CONTRIBUTING.md) for the full local-verification contract. ## License -This package is proprietary. For use under the terms on this branch, request -a free written license from [support@maatify.dev](mailto:support@maatify.dev). +This package is proprietary. Under the terms on this branch, obtain written +authorization from Maatify Ltd. before use, subject to the exceptions in +[LICENSE](LICENSE). Request a free written license from [support@maatify.dev](mailto:support@maatify.dev). Include your organization name, if applicable, and an email address for security advisories and critical update notices. Maatify Ltd. uses these details -to administer licenses and send those notices. See [LICENSE](LICENSE) for -the terms. Published versions carry their own license file. +to administer licenses and send those notices. Published versions carry their +own license file. ## 👤 Author diff --git a/SECURITY.md b/SECURITY.md index da131f8..31eb80e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -24,7 +24,7 @@ See [Packagist](https://packagist.org/packages/maatify/php-persistence) for curr support@maatify.dev ``` -Maatify publishes this private vulnerability-reporting address in its [security reporting instructions](https://github.com/Maatify/persistence/blob/main/SECURITY.md). It is also the contact in this repository’s [LICENSE](LICENSE). Include the affected file(s) or capability (Transaction, Pagination, or Ordering), the commit SHA you observed it on, and, where possible, a minimal reproduction. +This private contact is listed in this package's [LICENSE](LICENSE). Include the affected file(s) or capability (Transaction, Pagination, or Ordering), the commit SHA you observed it on, and, where possible, a minimal reproduction. ## Scope diff --git a/composer.json b/composer.json index 5b9f589..0d66b8e 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,8 @@ ], "support": { "issues": "https://github.com/Maatify-ltd/php-persistence/issues", - "source": "https://github.com/Maatify-ltd/php-persistence" + "source": "https://github.com/Maatify-ltd/php-persistence", + "security": "https://github.com/Maatify-ltd/php-persistence/security/policy" }, "autoload": { "psr-4": { @@ -59,7 +60,7 @@ "@php scripts/check-per-cs-3-1.php" ], "verify:php-constraint": "bash scripts/check-php-constraint.sh", - "syntax": "find src tests scripts examples harness .php-cs-fixer.php -name '*.php' -print0 | xargs -0 -n1 php -l > /dev/null", + "syntax": "bash -o pipefail -c 'find src tests scripts examples harness docs .php-cs-fixer.php -name \"*.php\" -print0 | xargs -0 -n1 php -l > /dev/null'", "whitespace": "git diff --check 4b825dc642cb6eb9a060e54bf8d69288fbee4904 HEAD -- . ':!docs/php-engineering-standards'", "test": [ "@test:unit", diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md index 54f1182..0ff0240 100644 --- a/docs/architecture/ARCHITECTURE.md +++ b/docs/architecture/ARCHITECTURE.md @@ -58,6 +58,8 @@ Capabilities: - Transaction ``` +Representative paths are shown below. See the [Package Reference](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#2-source-topology) for the complete source inventory. + ```text src/ ├── Exception/PhpPersistenceExceptionInterface.php @@ -74,9 +76,10 @@ src/ │ ├── Exception/{InvalidPaginationConfigurationException, │ │ InvalidPaginationQueryException, │ │ PaginationExecutionException}.php -│ ├── Repository/PdoPaginator.php +│ ├── Repository/{HostSnapshotRetirement,PdoPaginator}.php │ └── ValueObject/SortWhitelist.php └── Transaction/ + ├── Command/VerifiedTransactionDecisionCommand.php ├── Exception/{InvalidTransactionConfigurationException, │ TransactionExecutionException}.php └── Repository/{TransactionRunnerInterface, @@ -101,6 +104,7 @@ The table describes the raw Transaction runners and raw Ordering paths where the |---|---| | No transaction active | Begin, run, commit; on failure roll back (best effort) and rethrow the original. A `false` from begin or commit fails closed with `TransactionExecutionException`. | | Caller's transaction active | Participate. Never begin, commit or finally roll back it. Use a savepoint only to limit the failed operation (savepoint runner, `moveWithinScope`). | +| Raw Ordering reports a missing target or zero-row write | A missing target in a caller-owned transaction returns `false` without a savepoint. Other ordinary `false` outcomes require the appropriate rollback and settlement to succeed. [DEC-034](../decisions/DEC-034-raw-ordering-settlement-failures.md) governs failures. | | Callback throws | The original `Throwable` is rethrown unchanged. Cleanup failures never replace it. | | Deadlock (`40001`/`1213`) in a package-owned transaction | Replay only under the exact conditions of B-12, default off. | | Deadlock or any error in a caller-owned transaction | Never replayed; propagates. The caller decides. | diff --git a/docs/architecture/CI_AND_INTEGRATION.md b/docs/architecture/CI_AND_INTEGRATION.md index ec556bd..9d6b108 100644 --- a/docs/architecture/CI_AND_INTEGRATION.md +++ b/docs/architecture/CI_AND_INTEGRATION.md @@ -15,7 +15,7 @@ Every CI gate runs a repository-owned command that a developer can run locally w | Strict PSR-4 | `composer dump-autoload --optimize --strict-psr` | Static checks | | PHP syntax | `composer syntax` | Static checks (PHP 8.4), Compat (every PHP minor, including 8.6) | | Whitespace | `composer whitespace` | Static checks | -| Dependency policy audit | `composer audit --no-interaction --abandoned=fail` (Composer 2.10+) | Compat (all six cells) | +| Dependency policy audit | `php scripts/dependency-audit.php` after dependency resolution with Composer 2.10+ | Compat (all six cells) | | Static analysis | `composer analyse` | Compat | | Code style and PER-CS 3.1 | `composer format:check` | Compat on PHP 8.4 and 8.5 (§3.1) | | PER-CS 3.1 verifier alone | `php scripts/check-per-cs-3-1.php` | Compat on PHP 8.6 (§3.1) | @@ -30,6 +30,8 @@ Every CI gate runs a repository-owned command that a developer can run locally w Unit and Regression need no Docker. `composer test` runs Unit, Regression, and Integration locally. The required `CI gate` aggregates Workflow lint, Static checks, Compat, Integration, Examples smoke, Consumer verification and coexistence, and Release artifact verification. The exploratory cell is optional and runs only when requested in a manual dispatch. +Run the dependency policy audit after `composer update` generates a current root lock. The same command in Compat checks applicable environment overrides, effective project and global Composer policy, and the secure default Packagist source. It accepts no arguments and audits all packages in that lock, including development dependencies. The legacy abandonment exception in [DEC-016](../decisions/DEC-016-legacy-coexistence-abandonment-audit.md) applies only to the separate coexistence fixture. + On pull requests, Workflow lint, Static checks, Compat, Integration, and Examples smoke use [the default merge checkout](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#how-the-merge-branch-affects-your-workflow). Consumer verification and the Stable archive check use the PR head. On pushes to `main`, those jobs verify the pushed commit. A manual dispatch uses the dispatched SHA for those same checks. The historical RC.2 check always uses its pinned tag. [Release evidence](../guides/RELEASE_ARTIFACT_VERIFICATION.md#release-evidence-handoff) must identify the actual candidate commit in `main`. ## 2. Integration lifecycle @@ -93,7 +95,7 @@ composer examples:smoke PP_DB_CELL=mariadb-11.8.9 composer examples:smoke ``` -CI requires both `mysql-8.4.13` and `mariadb-11.8.9` smoke jobs on PHP 8.4 and on PHP 8.6. This smoke matrix is separate from the capability Integration matrix below. +CI requires both `mysql-8.4.13` and `mariadb-11.8.9` smoke jobs on PHP 8.4 and on PHP 8.6. This smoke matrix is separate from the capability Integration matrix below. The [Host Snapshot B example](../../examples/pagination_host_snapshot_usage.php) requires an application-owned source and registered page plan. It runs under the PHP syntax and static-analysis gates, with Host B behavior exercised independently in the installed Consumer Verification Harness. On each of PHP 8.4 and 8.6, [Consumer verification](../guides/CONSUMER_VERIFICATION.md) runs two fresh lifecycles per engine on MySQL 8.4.13 and MariaDB 11.8.9, with separate production Composer roots. diff --git a/docs/architecture/QUALITY_TOOLING.md b/docs/architecture/QUALITY_TOOLING.md index d28e674..56ecf4a 100644 --- a/docs/architecture/QUALITY_TOOLING.md +++ b/docs/architecture/QUALITY_TOOLING.md @@ -19,7 +19,7 @@ The constraints are caret ranges, not patch pins. Versions actually resolved on |---|---| | `composer analyse` | PHPStan, level `max`, over `src`, `tests`, `scripts`, and `examples` | | `composer format` | Mutating formatter (`php-cs-fixer fix`) | -| `composer format:check` | Non-mutating formatter check, then the PER-CS 3.1 delta check | +| `composer format:check` | Non-mutating formatter check, then the supplemental PER-CS 3.1 check | | `composer test` | Unit, Regression, and Integration | | `composer test:unit` | The `unit` suite | | `composer test:regression` | The `regression` suite | @@ -28,22 +28,25 @@ The constraints are caret ranges, not patch pins. Versions actually resolved on ## 3. PER Coding Style 3.1 coverage -The pinned PHP Coding Style Standard names PHP-FIG **PER Coding Style 3.1** as the baseline and requires the combined verification surface to cover all of it. PHP CS Fixer implements PER Coding Style only up to 3.0: version 3.95.27 lists `@PER-CS3x0` as its newest versioned set (`php-cs-fixer list-sets`), and its upstream repository has no 3.1 set. PHP CS Fixer 3.95.32 also refuses to run on PHP 8.6, so in CI the formatter runs on PHP 8.4 and 8.5 and the PHP 8.6 cells run the 3.1 verifier alone ([CI_AND_INTEGRATION.md §3.1](./CI_AND_INTEGRATION.md#31-code-style-on-php-86)). The formatter therefore verifies the 3.0 baseline, and `scripts/check-per-cs-3-1.php` verifies the eight changes of 3.1 listed in the PHP-FIG [migration document](https://www.php-fig.org/per/coding-style/meta/migration-3.1/) on the token stream: +The pinned PHP Coding Style Standard names PHP-FIG **PER Coding Style 3.1** as the baseline and requires the combined verification surface to cover all of it. PHP CS Fixer implements PER Coding Style only up to 3.0: version 3.95.27 lists `@PER-CS3x0` as its newest versioned set (`php-cs-fixer list-sets`), and its upstream repository has no 3.1 set. PHP CS Fixer 3.95.32 also refuses to run on PHP 8.6, so in CI the formatter runs on PHP 8.4 and 8.5 and the PHP 8.6 cells run the 3.1 verifier alone ([CI_AND_INTEGRATION.md §3.1](./CI_AND_INTEGRATION.md#31-code-style-on-php-86)). The formatter checks the rules implemented in its 3.0 preset. The supplemental token verifier implements the 3.1 changes in the PHP-FIG [migration document](https://www.php-fig.org/per/coding-style/meta/migration-3.1/) and fills identified gaps in the baseline: -| 3.1 change | Verification | +| Requirement | Verification | |---|---| | `clone` always with parentheses | script: `clone` must be followed by `(` | | `case` body not wrapped in braces; every non-empty `case` ends with a terminating statement, also the last; multi-line `case` condition in parentheses with `)` and `:` alone on the last line | script: parses every `switch` block, accepts conforming switches and rejects the others. A non-empty case that falls through to the next case is accepted only with a clear comment ("No break", "Deliberate fall-through"), as the specification requires; the last case must always terminate | | Pipe operator `\|>` spaced on both sides | script: checks spacing when the tokenizer supports the operator (PHP 8.5+); on PHP 8.4 the syntax does not parse, so the syntax check rejects it first | -| Split pipe chain starts each line with the operator, continuation lines indented | script, same condition as above | +| Split pipe chain starts each line with one operator and indents continuation lines | script: a chain splits when its operators span multiple lines or when a line break separates an operator from an adjacent operand, including across comments. Every operator in a split chain starts its line one level deeper than the start of the expression. Separate arguments, branches and nested chains are checked independently. A single pipe can stay inline adjacent to a multiline operand | | Empty closure written as `{}` after one space on the same line | script | | Attributes on anonymous classes start on the line after `new`, indented once, class declaration on its own line with the same indentation | script | -| Enum constants follow the `private` instead of `protected` rule (as methods already did) | script: no `protected` member at the level of an `enum` body; method bodies and classes nested inside the enum are not enum members and are not checked by this rule | -| Opening bracket of a multi-line array not alone on its line, in all contexts | script | +| Enum cases use PascalCase and non-public enum members use `private` | script: checks direct enum cases, constants and methods. An uppercase enum constant is valid; nested anonymous class methods keep their own visibility rules | +| PSR-1 named declarations and method names | script: a named class, interface, trait or enum has a formal namespace and its own, case-matching source file. Methods use camelCase except for PHP magic methods. Anonymous classes and standalone functions retain their applicable rules. Composer autoload and entry-point tests establish discovery | +| Multiline array layout | script: the opening bracket stays with the declaration, each direct value starts on a separate line, and the closing bracket follows the last value on its own line. A nested unkeyed list can open on its own line as in PER-CS §11 | +| Split ternary layout | script: both operators start lines indented once from their condition when the operators themselves split across lines. A multiline operand can retain an otherwise inline ternary | +| Split binary operator layout, including short ternary `?:` | script: the operator starts the line carrying its right operand, indented one level. Logical operators in multiline control conditions follow the indentation of the condition group. Type separators, references and unary signs retain their own syntax rules | -Scope: the script scans every PHP file of the repository except `vendor`, `docs`, `.git` and tool caches, so the root configuration file `.php-cs-fixer.php` and `scripts/` are included. `tests/Regression/PerCodingStyleDeltaCheckTest.php` has an accepting and a rejecting case for each rule and asserts the scan scope. +Scope: the formatter and supplemental verifier scan handwritten PHP, including PHP under `docs/`, the root configuration file `.php-cs-fixer.php`, and `scripts/`. Dependency and tool directories remain excluded as applicable. `composer syntax` also lints PHP under `docs/`. `tests/Regression/PerCodingStyleDeltaCheckTest.php` has accepting and rejecting cases and checks default discovery of a PHP example in an isolated documentation tree. -Limits that remain: the script is a repository-owned verifier written for these eight rules and is not the PHP-FIG reference implementation. The pipe-operator rules cannot be exercised on PHP 8.4. Their fixtures (`PerCodingStyleDeltaCheckTest`: a conforming chain, no spaces, operator at the end of a line, unindented continuation) assert the real rules on PHP 8.5 and assert that the verifier refuses the operator on earlier versions; the PHP 8.5 CI cells run the real-rule branch (WU-5). The rest of the 3.1 text is covered by the 3.0 rules the formatter implements. When PHP CS Fixer ships a 3.1 rule set, the configuration moves to it and the script is reduced to what the set does not cover. +Limits that remain: the script is a repository-owned supplemental verifier and is not the PHP-FIG reference implementation. The pipe-operator rules cannot be exercised on PHP 8.4. Their fixtures (`PerCodingStyleDeltaCheckTest`: a conforming chain, no spaces, operator at the end of a line, unindented continuation) assert the real rules on PHP 8.5 and assert that the verifier refuses the operator on earlier versions; the PHP 8.5 CI cells run the real-rule branch (WU-5). A passing check proves the configured rules for the files it scanned. The full normative reference remains PHP-FIG PER Coding Style 3.1. Before switching to a future formatter preset, verify each supplemental rule against it and retain coverage for any rule it omits. ## 4. Historical planning inputs for WU-5 @@ -51,7 +54,7 @@ These requirements guided the original CI setup. The [test matrix in CI and Inte - PHP: the oldest supported minor, `8.4`, and the latest released minor allowed by `^8.4`, for Unit, Regression and Integration (implemented in WU-5: [CI_AND_INTEGRATION.md](./CI_AND_INTEGRATION.md)). - Dependencies: a latest-compatible resolution and a lowest-supported resolution (`composer update --prefer-lowest --prefer-stable`) on PHP 8.4, running analysis and tests. -- Composer: run the dependency-policy audit with Composer 2.10 or later (CI Workflow Standard §5.1), provisioned deterministically by the CI tooling. `composer.json` carries `config.policy` (advisories block and audit `fail`, malware block with scope `all` and audit `fail`, abandoned audit `fail`). The local verification of this policy with Composer 2.10.3 is recorded in section 6. +- Composer: run `php scripts/dependency-audit.php` after resolving dependencies with Composer 2.10 or later (CI Workflow Standard §5.1). The [CI parity guide](CI_AND_INTEGRATION.md#1-local-and-ci-parity) documents the required gate. Section 6 records the original WU-4 policy experiments with Composer 2.10.3. - Database services, matrix cells and pinned images per [DATABASE_SUPPORT_AND_TEST_POLICY.md](./DATABASE_SUPPORT_AND_TEST_POLICY.md) and [DEC-013](../decisions/DEC-013-test-only-database-version-boundary.md) (DEC-009 covers the optional protected write checkout). - A required gate job, workflow lint, immutable action pinning, and the whitespace check (`git diff --check`). diff --git a/docs/decisions/DEC-004-package-identity-namespace-and-exception-marker.md b/docs/decisions/DEC-004-package-identity-namespace-and-exception-marker.md index 63e683e..38554db 100644 --- a/docs/decisions/DEC-004-package-identity-namespace-and-exception-marker.md +++ b/docs/decisions/DEC-004-package-identity-namespace-and-exception-marker.md @@ -8,7 +8,7 @@ - **Scope / Concern:** Public identity of the package: Composer name, PSR-4 root namespace, package-wide exception marker, and the DTO naming of the pagination result. - **Supersedes:** `—` - **Superseded By:** `—` -- **Canonical Contract / Current Owner:** This record for the identity values. The naming rules they follow are owned by the pinned [Package Building Standard](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md) and [Composer Package Standard](../php-engineering-standards/standards/packages/COMPOSER_PACKAGE_STANDARD.md). The resulting public type inventory is [CONTRACT_MATRIX.md](../architecture/CONTRACT_MATRIX.md). +- **Canonical Contract / Current Owner:** This record for the identity values. The naming rules they follow are owned by the pinned [Package Building Standard](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md) and [Composer Package Standard](../php-engineering-standards/standards/packages/COMPOSER_PACKAGE_STANDARD.md). The [Package Reference §3](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#3-public-runtime-api-inventory) is the canonical public type inventory. ## Context diff --git a/docs/decisions/DEC-007-legacy-source-baseline-and-deprecated-retirement.md b/docs/decisions/DEC-007-legacy-source-baseline-and-deprecated-retirement.md index 178afc2..c4ae264 100644 --- a/docs/decisions/DEC-007-legacy-source-baseline-and-deprecated-retirement.md +++ b/docs/decisions/DEC-007-legacy-source-baseline-and-deprecated-retirement.md @@ -8,7 +8,7 @@ - **Scope / Concern:** Which legacy state is the behavioral and source starting point, which legacy types are retired, how the runner names are reused, and what must be checked before any legacy code is copied. - **Supersedes:** `—` - **Superseded By:** `—` -- **Canonical Contract / Current Owner:** This record for the strategy. The per-type disposition is [CONTRACT_MATRIX.md](../architecture/CONTRACT_MATRIX.md); the per-behavior baseline is [BEHAVIOR_CONTRACT.md](../architecture/BEHAVIOR_CONTRACT.md). +- **Canonical Contract / Current Owner:** This record governs the legacy-source baseline, type disposition and provenance checks. The [Contract Matrix](../architecture/CONTRACT_MATRIX.md) and [Behavior Contract](../architecture/BEHAVIOR_CONTRACT.md) record the historical type and behavior comparisons. The [Package Reference](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md) governs the current package contract. ## Context diff --git a/docs/decisions/DEC-011-responsibility-placement-and-savepoint-helper.md b/docs/decisions/DEC-011-responsibility-placement-and-savepoint-helper.md index 6e826b3..4c292cd 100644 --- a/docs/decisions/DEC-011-responsibility-placement-and-savepoint-helper.md +++ b/docs/decisions/DEC-011-responsibility-placement-and-savepoint-helper.md @@ -8,7 +8,7 @@ - **Scope / Concern:** Which responsibility folder holds the classes that issue SQL or transaction-control statements, who owns the savepoint helper, and whether optional renames beyond those already decided are made. - **Supersedes:** `—` - **Superseded By:** `—` -- **Canonical Contract / Current Owner:** The responsibility vocabulary and the SQL-placement rules are owned by the pinned [Package Building Standard](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md). The layout is [ARCHITECTURE.md](../architecture/ARCHITECTURE.md) §4; per-type placement is [CONTRACT_MATRIX.md](../architecture/CONTRACT_MATRIX.md). +- **Canonical Contract / Current Owner:** The responsibility vocabulary and the SQL-placement rules are owned by the pinned [Package Building Standard](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md). [Architecture §4](../architecture/ARCHITECTURE.md#4-source-topology) documents the current source topology. The [Package Reference §3](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#3-public-runtime-api-inventory) is the canonical public type inventory. ## Context @@ -30,6 +30,6 @@ The pinned standard says SQL lives in Repositories or package-local SQL support ## Consequences -- The folder names in [CONTRACT_MATRIX.md](../architecture/CONTRACT_MATRIX.md) column "New package" are the placement of record. -- Activation does not remove the gates: WU-6 must pass the characterization tests of item 3 against the merged helper before the public API and the Package Reference are frozen (item 4). Merging the savepoint logic without them is not allowed. +- The [Contract Matrix §3](../architecture/CONTRACT_MATRIX.md#3-type-matrix) records the original per-type placements and their implementation. +- The [historical WU-6 evidence](../architecture/BEHAVIOR_CONTRACT.md#transaction-wu-6) records the Transaction verification. Items 3 and 4 required the characterization tests to pass first against the unmerged logic and again against the shared savepoint helper before the original public API and Package Reference freeze. - Changing item 1, 2 or 5 later needs a new record that supersedes this one; the namespace root, type short names and capability split stay as decided in [DEC-004](./DEC-004-package-identity-namespace-and-exception-marker.md) and [DEC-010](./DEC-010-package-topology-multi-capability.md). diff --git a/docs/decisions/DEC-014-free-license-registration.md b/docs/decisions/DEC-014-free-license-registration.md index 67ce3f8..c74abb2 100644 --- a/docs/decisions/DEC-014-free-license-registration.md +++ b/docs/decisions/DEC-014-free-license-registration.md @@ -10,6 +10,15 @@ - **Superseded By:** `—` - **Canonical Contract / Current Owner:** [LICENSE](../../LICENSE) +## Context + +[DEC-002 at the time](https://github.com/Maatify-ltd/php-persistence/blob/f74917cf3df95437d42360ff5d3b83a7e63584d5/docs/decisions/DEC-002-proprietary-licensing.md#decision) +established the proprietary licensing model. The published +[RC.1 license](https://github.com/Maatify-ltd/php-persistence/blob/34c3b874525d36ae064c162cdd553bc75d18772b/LICENSE#L5-L15) +already required prior written authorization or a separate written license +agreement for uses outside the permissions it stated. [PR #30](https://github.com/Maatify-ltd/php-persistence/pull/30) +documented how to obtain a license at no charge and how registration would work. + ## Decision The package retains the Maatify Proprietary License and Maatify remains the @@ -19,6 +28,21 @@ and critical update notices. Composer continues to identify the license as `proprietary`. The provenance and third-party notice requirements in DEC-002 continue to apply. +## Rationale + +The [registration terms merged in PR #30](https://github.com/Maatify-ltd/php-persistence/blob/0ca8d4a45daf09480fec5f02d31ab579170ea8f6/LICENSE#L15-L24) +give the purpose for collecting designated contact details. Maatify uses them +to administer licenses and send security advisories and critical update notices. +The contemporaneous records establish the no-charge policy. A separate reason +for setting the fee at zero remains undocumented in those records. + +## Consequences + +The [original application instructions](https://github.com/Maatify-ltd/php-persistence/blob/0ca8d4a45daf09480fec5f02d31ab579170ea8f6/README.md#L151-L158) +ask applicants for an organization name where applicable and an email address +for notices. The [original changelog entry](https://github.com/Maatify-ltd/php-persistence/blob/0ca8d4a45daf09480fec5f02d31ab579170ea8f6/CHANGELOG.md#L7-L15) +records the change under `Unreleased` for the next RC or Stable release. + ## Release boundary Include these terms with the next RC or Stable release through the usual diff --git a/docs/decisions/DEC-018-optional-delegated-snapshot-pagination.md b/docs/decisions/DEC-018-optional-delegated-snapshot-pagination.md index 96c3e8b..f078b66 100644 --- a/docs/decisions/DEC-018-optional-delegated-snapshot-pagination.md +++ b/docs/decisions/DEC-018-optional-delegated-snapshot-pagination.md @@ -22,4 +22,4 @@ The operation-local lifecycle and terminal outcome are an explicit exception to ## Consequences -Consumers explicitly choose C1 for qualifying descriptor reads in a single InnoDB snapshot. Connection acquisition, pooling and configuration remain with the Host. The professional path on Host transactions and Keyset remain deferred. Engine claims require the verification boundary defined by [DEC-008](./DEC-008-database-engine-targets-and-verification-policy.md) and [DEC-013](./DEC-013-test-only-database-version-boundary.md). +Consumers explicitly choose C1 for qualifying descriptor reads in a single InnoDB snapshot. Connection acquisition, pooling and configuration remain with the Host. At the time of the C1 decision, the professional Host-transaction path and Keyset were deferred. [DEC-036](./DEC-036-pascalcase-enums-and-stable-settlement-json.md) now governs Host-transaction snapshot pagination, and [DEC-019](./DEC-019-optional-forward-keyset-pagination.md) governs forward Keyset pagination. Engine claims require the verification boundary defined by [DEC-008](./DEC-008-database-engine-targets-and-verification-policy.md) and [DEC-013](./DEC-013-test-only-database-version-boundary.md). diff --git a/docs/decisions/DEC-020-optional-host-transaction-snapshot-pagination.md b/docs/decisions/DEC-020-optional-host-transaction-snapshot-pagination.md index f2db1a3..3531c12 100644 --- a/docs/decisions/DEC-020-optional-host-transaction-snapshot-pagination.md +++ b/docs/decisions/DEC-020-optional-host-transaction-snapshot-pagination.md @@ -1,13 +1,13 @@ # DEC-020 — Optional pagination in a Host-owned transaction - **Decision ID:** DEC-020 -- **Status:** ACTIVE +- **Status:** `SUPERSEDED` - **Decision Authority:** Project Owner. [Design and Public API approval](https://github.com/Maatify-ltd/php-persistence/issues/35#issuecomment-7066152213) and [execution authorization](https://github.com/Maatify-ltd/php-persistence/issues/35#issuecomment-7066221226). - **Date:** 2026-11-21 - **Scope / Concern:** Optional professional pagination path on the Host's own transaction. -- **Canonical Contract / Current Owner:** [Package Reference §5.3.3](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#533-optional-b-pagination-in-a-host-owned-transaction). +- **Canonical Contract / Current Owner:** Historical record. [DEC-036](./DEC-036-pascalcase-enums-and-stable-settlement-json.md) governs the current contract. - **Supersedes:** — -- **Superseded By:** — +- **Superseded By:** [DEC-032](./DEC-032-settlement-json-and-execution-contracts.md) ## Context diff --git a/docs/decisions/DEC-022-verified-apply-discard.md b/docs/decisions/DEC-022-verified-apply-discard.md index 69c5299..4c24503 100644 --- a/docs/decisions/DEC-022-verified-apply-discard.md +++ b/docs/decisions/DEC-022-verified-apply-discard.md @@ -1,11 +1,12 @@ # DEC-022 — Optional verified apply and discard - **Decision ID:** DEC-022 -- **Status:** ACTIVE +- **Status:** `SUPERSEDED` - **Date:** 2026-11-22 - **Decision Authority:** Project Owner, [contract approval](https://github.com/Maatify-ltd/php-persistence/issues/73#issuecomment-7078581978), following [focused technical acceptance](https://github.com/Maatify-ltd/php-persistence/issues/73#issuecomment-7078479638). [WU-B3](https://github.com/Maatify-ltd/php-persistence/issues/74) authorizes implementation. - **Scope:** Optional Verified Apply/Discard within Transaction. -- **Canonical Contract:** [Package Reference §5.2.2](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#522-optional-verified-apply-and-discard) and the [approved contract](https://github.com/Maatify-ltd/php-persistence/issues/73#issuecomment-7078289307). +- **Canonical Contract / Current Owner:** Historical record. [DEC-036](./DEC-036-pascalcase-enums-and-stable-settlement-json.md) governs the current contract. +- **Superseded By:** [DEC-032](./DEC-032-settlement-json-and-execution-contracts.md) ## Context diff --git a/docs/decisions/DEC-032-settlement-json-and-execution-contracts.md b/docs/decisions/DEC-032-settlement-json-and-execution-contracts.md new file mode 100644 index 0000000..3f831aa --- /dev/null +++ b/docs/decisions/DEC-032-settlement-json-and-execution-contracts.md @@ -0,0 +1,29 @@ +# DEC-032 — Settlement JSON and execution contracts + +- **Decision ID:** `DEC-032` +- **Status:** `SUPERSEDED` +- **Date:** `2026-11-27` +- **Decision Authority:** Project Owner. [Approval recorded in Issue #65](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7227930099). +- **Scope / Concern:** Intent, live PDO handoff, and immutable outcome contracts for the first Stable candidate. +- **Supersedes:** [DEC-020](./DEC-020-optional-host-transaction-snapshot-pagination.md) and [DEC-022](./DEC-022-verified-apply-discard.md). +- **Superseded By:** [DEC-036](./DEC-036-pascalcase-enums-and-stable-settlement-json.md) +- **Canonical Contract / Current Owner:** [Package Reference §3.2](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#32-transaction-capability--maatifyphppersistencetransaction) for Transaction and [§3.3](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#33-pagination-capability--maatifyphppersistencepagination) for Pagination. + +## Context + +The approved designs for [B](https://github.com/Maatify-ltd/php-persistence/issues/35#issuecomment-7065436693) and [C2](https://github.com/Maatify-ltd/php-persistence/issues/73#issuecomment-7078289307) used DTO names for a live PDO handoff and a callback's intent. C2 described its DTOs as local PHP values without a JSON contract. The adopted [Package Building Standard §§8–9](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md#8-command-rules) assigns execution intent to a command and requires JSON for data result DTOs. The affected types are absent from the exact published RC.2, `71dc61548e48fd053376db69149a00bc87069b70`. The earlier design and Owner approvals remain in DEC-020 and DEC-022. + +## Decision + +1. C2 callbacks return `Transaction\Command\VerifiedTransactionDecisionCommand`. The final readonly command keeps its private constructor, `isApply` and `payload` properties and the `apply(mixed $payload = null)` and `discard(mixed $payload = null)` factories. Callback payload identity and the distinction between `false` and `null` remain intact. The command has no JSON contract. +2. B presents the handoff as `Pagination\Repository\HostSnapshotRetirement`, a final readonly PHP value with the same `disposition` and live `pdo` properties. The Host receives the same PDO once, with the connection-free page settlement retained separately. Handoff has no JSON contract. It still depends on confirmed resource release and the classified reuse or reconciliation disposition. +3. `HostSnapshotPageSettlementDTO`, `SnapshotConnectionOutcomeDTO`, `ProtectedTransactionSettlementDTO`, and `VerifiedTransactionSettlementDTO` expose JSON projections of their existing named fields. Unit enum fields use case-name strings. Unset fields retain `null`, and C1's optional diagnostic retains its string or null value. These snapshots carry data only. Reading the PHP properties still returns their original types. JSON carries no PDO, command payload, or authority to settle, replay, or resume work. +4. The approval updates only the contracts in items 1–3. It carries forward the ownership, API operations, guards, state transitions, failure and settlement semantics, database verification and authority boundaries from DEC-020 and DEC-022. In B, keep the one-source, one-checkout reservation for registered commands and page attempts, RR generation proof, one-shot page authorization, settlement before reservation release, original error identity, quarantine, and Host-directed handoff or discard, including the possibility of automatic driver cleanup on discard. In C2, keep exclusive delegation with the approved genuine PDO eligibility, command catalog and scope controls, Owned and Host modes, acknowledged end and local undo, fencing, first-error precedence, immutable outcome snapshots, returning the original PDO once, and discarding without issuing transaction SQL or certifying server cleanup. Preserve the Transaction weak claims, shared savepoint helper, and capability dependency boundaries. The C1 and Protected outcome policies in [DEC-018](./DEC-018-optional-delegated-snapshot-pagination.md) and [DEC-009](./DEC-009-proposed-version-matrix-and-mariadb-snapshot-isolation.md) remain active. Their JSON projections add a representation of the existing outcomes. + +## Rationale + +A callback uses the command to select an effect before the result exists. The live PDO handoff transfers an object under the Host's existing authority. The outcome DTOs contain the facts needed for JSON diagnostics independently of either operation. + +## Consequences + +Candidate users importing the draft DTO names for the command and handoff use the types in this record. Published RC.2 consumers have neither of those types. Public entry point and outcome tests must verify the unchanged behavior together with the new representations under the existing MySQL/MariaDB verification policy. This decision carries no merge, release, or consumer adoption authority. diff --git a/docs/decisions/DEC-033-validate-ordering-mutation-timestamps.md b/docs/decisions/DEC-033-validate-ordering-mutation-timestamps.md new file mode 100644 index 0000000..3bf3836 --- /dev/null +++ b/docs/decisions/DEC-033-validate-ordering-mutation-timestamps.md @@ -0,0 +1,29 @@ +# DEC-033 — Validate Ordering mutation timestamps + +- **Decision ID:** `DEC-033` +- **Status:** `ACTIVE` +- **Date:** `2026-11-27` +- **Decision Authority:** Project Owner. [Approval recorded in Issue #65](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7227930099). +- **Scope / Concern:** The `updatedAtValue` argument of raw and protected `moveWithinScope()`. +- **Supersedes:** — +- **Superseded By:** — +- **Canonical Contract / Current Owner:** [Package Reference §5.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager). + +## Context + +[Published RC.2](https://github.com/Maatify-ltd/php-persistence/blob/71dc61548e48fd053376db69149a00bc87069b70/PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager) documented the optional timestamp and required it exactly when the timestamp column was configured. The raw manager passed a supplied string to the driver without calendar or format validation. Driver and column behavior then determined which values succeeded. The [Package Building Standard §8](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md#8-command-rules) places date-time validation at the input boundary. + +## Decision + +1. When `updatedAtColumn` is configured, require a real Gregorian date and a 24-hour clock time in the exact ASCII format `YYYY-MM-DD HH:MM:SS`, followed optionally by a decimal point and 1–6 fractional-second digits. Validate calendar and clock fields. Reject a malformed or missing value with `InvalidOrderingOperationException` before the move issues SQL. When the column is absent, the only accepted value remains null. +2. Bind the original accepted string as the target row's timestamp. The Host owns timezone conversion, and the database column retains responsibility for supported range and precision. The signature, default, named parameter, target-only update, connection ownership and locking behavior stay as published. Protected UNIQUE-safe Ordering B1 still requires an absent timestamp column. +3. Classify the narrower acceptance boundary as `BREAKING` against published pre-Stable RC.2. A database could previously accept an alternate input or interpret an unvalidated string. Record the required consumer change in the first-Stable changelog and [compatibility gate #43](https://github.com/Maatify-ltd/php-persistence/issues/43). Record behavior evidence at [#44](https://github.com/Maatify-ltd/php-persistence/issues/44). RC.2 retains its historical behavior. +4. The Host supplies the required format before calling the manager. For example, format an existing date-time object with `Y-m-d H:i:s` or `Y-m-d H:i:s.u` after choosing the appropriate Host timezone and database precision. Keep valid existing strings and exact RC.2 pins until the consumer can migrate through its own release gate. + +## Rationale + +Validating before SQL keeps malformed inputs from affecting the move or depending on the server's coercion settings. Keeping the accepted bytes preserves fractional digits and leaves timezone and database choices with the Host. + +## Consequences + +Verify rejection before PDO work, valid leap dates and fractional bounds, byte-for-byte binding, and the protected checkout's availability after validation failure. This scope preserves the raw cleanup and MariaDB `1020` protections described in [DEC-009](./DEC-009-proposed-version-matrix-and-mariadb-snapshot-isolation.md). Changing the ordering cleanup contract requires a separate decision. This decision carries no merge, release, or consumer adoption authority. diff --git a/docs/decisions/DEC-034-raw-ordering-settlement-failures.md b/docs/decisions/DEC-034-raw-ordering-settlement-failures.md new file mode 100644 index 0000000..0de1d51 --- /dev/null +++ b/docs/decisions/DEC-034-raw-ordering-settlement-failures.md @@ -0,0 +1,28 @@ +# DEC-034 — Surface settlement failures in raw Ordering + +- **Decision ID:** `DEC-034` +- **Status:** `ACTIVE` +- **Date:** `2026-11-27` +- **Decision Authority:** Project Owner. [Approval recorded in Issue #65](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7228781651). +- **Scope / Concern:** Settlement of a missing target or zero-row target update in raw `ScopedOrderingManager::moveWithinScope()`. +- **Supersedes:** — +- **Superseded By:** — +- **Canonical Contract / Current Owner:** [Package Reference §5.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager). + +## Context + +[Published RC.2](https://github.com/Maatify-ltd/php-persistence/blob/71dc61548e48fd053376db69149a00bc87069b70/PHP_PERSISTENCE_PACKAGE_REFERENCE.md#movewithinscope) documented best-effort rollback for an owned Ordering move and best-effort savepoint release after a successful local undo. The [F108-05 correctness evidence](https://github.com/Maatify-ltd/php-persistence/issues/44#issuecomment-7228136280) found that a failed owned rollback can leave the range shift pending while the call returns ordinary `false`. A failed release can also leave the savepoint live after a successful local undo. + +## Decision + +1. A missing row or zero-row update may return `false` once the required cleanup is confirmed. For an owned move, PDO must report an active transaction before rollback, acknowledge the rollback, and report no active transaction afterward. In a Host transaction, a missing row needs no savepoint. A zero-row update requires acknowledged `ROLLBACK TO SAVEPOINT` and then acknowledged `RELEASE SAVEPOINT`. +2. When settlement is the first failure, propagate the original driver throwable. Use the existing `TransactionExecutionException` for a failed control return or an unconfirmed owned rollback. When an earlier operation failed by throwing, preserve that original throwable across best-effort cleanup. An Ordering statement failure reported by return value still raises `OrderingExecutionException` under its existing contract. +3. Preserve caller ownership of the enclosing transaction, the public method signature, and the existing statement error mode behavior. The generic Transaction runners retain their callback result contracts. [DEC-009](./DEC-009-proposed-version-matrix-and-mariadb-snapshot-isolation.md) governs protected checkout fencing and the MariaDB `1020` behavior, [DEC-015](./DEC-015-ordering-pdo-error-modes.md) governs statement failures, and [DEC-033](./DEC-033-validate-ordering-mutation-timestamps.md) governs timestamp validation. + +## Rationale + +Returning ordinary `false` after a failed owned rollback lets a consumer continue with a pending range shift and can allow partial writes to be committed. An opt-in replacement would leave that failure indistinguishable on the existing call. The approved change is `BREAKING` against published pre-Stable RC.2 and confines the change to unconfirmed settlement of an ordinary outcome, using the data-integrity path in the [Public Contract Evolution Standard §10](../php-engineering-standards/standards/contracts/PUBLIC_CONTRACT_EVOLUTION_STANDARD_AR.md#10-مسار-الاستثناء-خطر-أمني-أو-فساد-بيانات). + +## Consequences + +Consumers on RC.2 that handle unsuccessful moves solely through the boolean return should catch settlement exceptions and resolve transaction and connection state before retry or reuse. A Host that owns the transaction still decides how to finish it. The first-Stable changelog records the compatibility delta. [Issue #65](https://github.com/Maatify-ltd/php-persistence/issues/65) tracks the exact audit and implementation. [Issue #43](https://github.com/Maatify-ltd/php-persistence/issues/43) and [Issue #44](https://github.com/Maatify-ltd/php-persistence/issues/44) govern consumer compatibility and correctness at release qualification. Verify driver false and throwable outcomes, state confirmation, normal returns, local control order, and original error identity. This decision carries no merge, release, or consumer adoption authority. diff --git a/docs/decisions/DEC-035-reject-terminal-lf-in-constructor-inputs.md b/docs/decisions/DEC-035-reject-terminal-lf-in-constructor-inputs.md new file mode 100644 index 0000000..d828233 --- /dev/null +++ b/docs/decisions/DEC-035-reject-terminal-lf-in-constructor-inputs.md @@ -0,0 +1,28 @@ +# DEC-035 — Reject trailing LF in published constructor inputs + +- **Decision ID:** `DEC-035` +- **Status:** `ACTIVE` +- **Date:** `2026-11-28` +- **Decision Authority:** Project Owner. [Approval recorded in Issue #65](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7230226330). +- **Scope / Concern:** The first Stable `1.0.0` boundary for `maatify/php-persistence`, covering the direct `PageResultDTO` sort key, `SortWhitelist` keys and identifier paths, `PdoPaginationQueryDescriptor` binding keys, and `ScopedOrderingConfig` table and column names. +- **Supersedes:** — +- **Superseded By:** — +- **Canonical Contract / Current Owner:** [Package Reference §1.5](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#15-rc2-constructor-input-migration) for migration and exception boundaries, §§3.3–3.4 for constructor contracts, and §5.3 for request normalization and COUNT results. + +## Context + +The [published RC.2 Package Reference](https://github.com/Maatify-ltd/php-persistence/blob/71dc61548e48fd053376db69149a00bc87069b70/PHP_PERSISTENCE_PACKAGE_REFERENCE.md) specified identifier patterns with the PHP regex end anchor `$`. It can match before a final LF. In the [review of the installed RC.2 distribution](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7230164181), direct `PageResultDTO` construction with `sortBy: "id\n"` succeeded and preserved that value in JSON. The review also reproduced the acceptance difference for a whitelist key, a binding key, and a table name. The full-string checks already present in the Stable candidate reject these names during construction. + +## Decision + +1. Retain full-string validation on the four constructors in scope. Classify the narrower acceptance of inputs with trailing LF as `BREAKING` against `PUBLISHED_PRE_STABLE` RC.2 for the first Stable `1.0.0` target. Constructor signatures and exception types stay the same. Calls with canonical names keep their behavior and result representations. The published RC.2 artifact retains its original behavior. +2. Consumers supply canonical sort keys and correct trusted SQL identifier constants at their source. Binding keys must match the bare names of the corresponding SQL placeholders. A direct DTO caller supplies the confirmed canonical sort key before construction. `PaginationConfig` defaults and tie-breakers must refer to the corrected whitelist keys. +3. Preserve the existing Offset `PageRequest` trimming behavior. Rejecting trailing LF in COUNT text remains a fix for enforcing the published requirement that COUNT strings consist of decimal digits. The change to constructor acceptance is recorded under `Changed` in [CHANGELOG](../../CHANGELOG.md#changed) and in the [Package Reference](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#15-rc2-constructor-input-migration). + +## Rationale + +An accepted name becomes a lookup key, SQL name, binding key, or serialized value. Validating every supplied byte keeps those uses consistent and lets the caller choose the intended name. Trimming a trusted identifier inside the library can change which identifier the host meant. Preserving an opt-in strict path alongside permissive default validation would leave the mismatch on those same constructors. The pre-Stable classification and the consumer migration follow [Public Contract Evolution §§4 and 9](../php-engineering-standards/standards/contracts/PUBLIC_CONTRACT_EVOLUTION_STANDARD_AR.md#4-تصنيف-التوافق-compatibility-classification). + +## Consequences + +The runtime already implements the rejection and the existing exception types. Review the exact candidate's behavior for canonical names, terminal LF inputs, the DTO JSON projection, and the independent request and COUNT behaviors. [Issue #43](https://github.com/Maatify-ltd/php-persistence/issues/43) tracks the published-contract comparison and the remaining release-candidate consumer evidence. The approved decision concerns this constructor delta. Merge, release, and consumer rollout retain their own authorization and verification gates. diff --git a/docs/decisions/DEC-036-pascalcase-enums-and-stable-settlement-json.md b/docs/decisions/DEC-036-pascalcase-enums-and-stable-settlement-json.md new file mode 100644 index 0000000..ebf97af --- /dev/null +++ b/docs/decisions/DEC-036-pascalcase-enums-and-stable-settlement-json.md @@ -0,0 +1,29 @@ +# DEC-036 — PascalCase enum cases and stable settlement JSON + +- **Decision ID:** `DEC-036` +- **Status:** `ACTIVE` +- **Date:** `2026-11-28` +- **Decision Authority:** Project Owner. [Approval recorded in Issue #65](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7231034094). +- **Scope / Concern:** Enum case naming, the published RC.2 sort-direction contract, and the first Stable candidate's C1, B, Protected and Verified settlement JSON. B handoff and Verified execution intent retain their approved contracts. +- **Supersedes:** [DEC-032](./DEC-032-settlement-json-and-execution-contracts.md). +- **Superseded By:** — +- **Canonical Contract / Current Owner:** [Package Reference §1.6](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#16-rc2-sort-direction-migration) for RC.2 migration and [§§3.2–3.6](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#32-transaction-capability--maatifyphppersistencetransaction) for the runtime contracts. + +## Context + +The adopted [PHP Coding Style Standard](../php-engineering-standards/standards/php/PHP_CODING_STYLE_STANDARD.md) specifies PHP-FIG PER Coding Style 3.1. [PER-CS §9](https://www.php-fig.org/per/coding-style/#9-enumerations) requires PascalCase for enum case declarations and permits uppercase constant names. Published RC.2 at `71dc61548e48fd053376db69149a00bc87069b70` declares `ASC` and `DESC` as cases of `SortDirectionEnum`. The [conformance review](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7230975588) identified the impact on PHP case identity and the candidate's JSON projections, which DEC-032 derived from unit enum case names. + +## Decision + +1. Use PascalCase for PHP enum case declarations. `SortDirectionEnum` declares `Asc` and `Desc`, retains backing strings `ASC` and `DESC`, and exposes `ASC` and `DESC` class constants as aliases for existing case expressions. Preserve enum class and parameter types, SQL direction tokens, and pagination result JSON. Classify the changed enum names, case introspection and native serialized representation as `BREAKING` against `PUBLISHED_PRE_STABLE` RC.2 at the first Stable `1.0.0` boundary. +2. `HostSnapshotPageSettlementDTO`, `SnapshotConnectionOutcomeDTO`, `ProtectedTransactionSettlementDTO` and `VerifiedTransactionSettlementDTO` keep their existing JSON field names, stable uppercase string codes, field order, nulls and diagnostics. The codes are explicit mappings independent of PHP case names. DTO properties retain their respective unit enum types. Their JSON carries no PDO, command payload or authority to settle, replay or resume work. +3. C2 callbacks return the final readonly `Transaction\Command\VerifiedTransactionDecisionCommand` through its existing `apply()` and `discard()` factories. They preserve payload identity and distinguish false from null. B hands off the exact PDO once through the final readonly `Pagination\Repository\HostSnapshotRetirement`, after resource release is confirmed and classified. The command and handoff remain PHP-only contracts. +4. Carry forward the ownership, guards, transaction boundaries, state transitions, failure and settlement semantics, and database verification from [DEC-032](./DEC-032-settlement-json-and-execution-contracts.md), including the inherited B and C2 boundaries. C1 and Protected outcome policies under [DEC-018](./DEC-018-optional-delegated-snapshot-pagination.md) and [DEC-009](./DEC-009-proposed-version-matrix-and-mariadb-snapshot-isolation.md) stay active. No production behavior or release authorization changes beyond the representation decision. + +## Rationale + +An alias preserves the enum object and backing value for an old case expression. It does not create a second case. A native serialized enum is identified by its declared case name, so the compatibility constants cannot preserve that part of the published contract. Explicit settlement codes prevent a source-level rename from silently changing JSON. The candidate settlement DTOs are absent from RC.2. + +## Consequences + +Update code that consumes case names or Reflection, and decode stored RC.2 native payloads before upgrading or invalidate caches. Persist `value` and restore through `SortDirectionEnum::from()` when the stored contract is the direction. Verify the alias identities, backing behavior, PHP case inventory, native serialization and every JSON code on the exact candidate. [Issue #43](https://github.com/Maatify-ltd/php-persistence/issues/43) tracks the published-contract comparison and the final consumer evidence. This decision does not authorize merge, publication or consumer migration. diff --git a/docs/decisions/DECISIONS_INDEX.md b/docs/decisions/DECISIONS_INDEX.md index 424e0cb..e794c94 100644 --- a/docs/decisions/DECISIONS_INDEX.md +++ b/docs/decisions/DECISIONS_INDEX.md @@ -7,14 +7,14 @@ Current-state discovery surface for durable decisions of this repository. It is | `DEC-001` | Initial default-branch bootstrap of the empty repository | `ACTIVE` | One-time creation of `main` by direct initial commit; contents and authorized Git operations. | [DEC-001-initial-repository-bootstrap.md](./DEC-001-initial-repository-bootstrap.md) | This record (the central standards define no empty-repository procedure). | — | — | | `DEC-002` | Proprietary licensing | `SUPERSEDED` | Repository license: Maatify Proprietary License, not MIT. | [DEC-002-proprietary-licensing.md](./DEC-002-proprietary-licensing.md) | `LICENSE` | — | `DEC-014` | | `DEC-003` | Selective pinned standards adoption at an exact upstream commit | `SUPERSEDED` | Pinned engineering standards snapshot `ebcf55b…` (Owner decision M-5) and adoption scope. | [DEC-003-pinned-standards-adoption.md](./DEC-003-pinned-standards-adoption.md) | [STANDARDS_MANIFEST.md](../php-engineering-standards/STANDARDS_MANIFEST.md) | — | `DEC-029` | -| `DEC-004` | Package identity, root namespace and exception marker | `ACTIVE` | `maatify/php-persistence`, `Maatify\PhpPersistence\`, `PhpPersistenceExceptionInterface`, `PageResultDTO`. | [DEC-004-package-identity-namespace-and-exception-marker.md](./DEC-004-package-identity-namespace-and-exception-marker.md) | This record; [CONTRACT_MATRIX.md](../architecture/CONTRACT_MATRIX.md) | — | — | +| `DEC-004` | Package identity, root namespace and exception marker | `ACTIVE` | `maatify/php-persistence`, `Maatify\PhpPersistence\`, `PhpPersistenceExceptionInterface`, `PageResultDTO`. | [DEC-004-package-identity-namespace-and-exception-marker.md](./DEC-004-package-identity-namespace-and-exception-marker.md) | This record for package identity. [Package Reference §3](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#3-public-runtime-api-inventory) for the public inventory. | — | — | | `DEC-005` | Coexistence with the legacy package, without compatibility shortcuts | `ACTIVE` | Both packages installable together; no `replace`, `provide`, `conflict`, `class_alias` or bridges. | [DEC-005-coexistence-with-legacy-package.md](./DEC-005-coexistence-with-legacy-package.md) | This record | — | — | | `DEC-006` | Successor intent and the boundary with central standards ownership | `SUPERSEDED` | Original successor intent and release-first sequence at the original standards pin. | [DEC-006-successor-intent-and-standards-ownership-boundary.md](./DEC-006-successor-intent-and-standards-ownership-boundary.md) | Historical record. Current transition in [DEC-030](./DEC-030-successor-transition-before-first-stable.md). | — | `DEC-030` | -| `DEC-007` | Legacy source baseline, Gen2 runner reuse and deprecated retirement | `ACTIVE` | Starting point is legacy `main`; three deprecated types retired; provenance gate before copying. | [DEC-007-legacy-source-baseline-and-deprecated-retirement.md](./DEC-007-legacy-source-baseline-and-deprecated-retirement.md) | [CONTRACT_MATRIX.md](../architecture/CONTRACT_MATRIX.md), [BEHAVIOR_CONTRACT.md](../architecture/BEHAVIOR_CONTRACT.md) | — | — | +| `DEC-007` | Legacy source baseline, Gen2 runner reuse and deprecated retirement | `ACTIVE` | Starting point is legacy `main`; three deprecated types retired; provenance gate before copying. | [DEC-007-legacy-source-baseline-and-deprecated-retirement.md](./DEC-007-legacy-source-baseline-and-deprecated-retirement.md) | This record for source selection and provenance. [Contract Matrix](../architecture/CONTRACT_MATRIX.md) and [Behavior Contract](../architecture/BEHAVIOR_CONTRACT.md) for historical evidence. | — | — | | `DEC-008` | Database engine targets and endpoint verification policy | `ACTIVE` | MySQL and MariaDB design targets; MySQL minimum `8.0.16`; oldest/newest real-database verification per engine; no unverified claims. | [DEC-008-database-engine-targets-and-verification-policy.md](./DEC-008-database-engine-targets-and-verification-policy.md) | [DATABASE_SUPPORT_AND_TEST_POLICY.md](../architecture/DATABASE_SUPPORT_AND_TEST_POLICY.md) | — | — | | `DEC-009` | Protect delegated Host transactions from uncertain outcomes | `ACTIVE` | Optional protected Host write transaction and Ordering fence for MariaDB `1020` and other uncertain outcomes. | [DEC-009-proposed-version-matrix-and-mariadb-snapshot-isolation.md](./DEC-009-proposed-version-matrix-and-mariadb-snapshot-isolation.md) | [Package Reference §5.2.1](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#521-optional-protected-host-write-transaction) | — | — | | `DEC-010` | Package topology: one package, three capabilities | `ACTIVE` | Multi Capability (`Ordering`, `Pagination`, `Transaction`); no `Pdo/` root or `Internal/` folder. | [DEC-010-package-topology-multi-capability.md](./DEC-010-package-topology-multi-capability.md) | Pinned [Package Building Standard](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md); [ARCHITECTURE.md](../architecture/ARCHITECTURE.md) | — | — | -| `DEC-011` | Responsibility placement, savepoint helper ownership and retained names | `ACTIVE` | `Repository/` for SQL-issuing classes, single `@internal` savepoint helper, no optional renames. WU-6 characterization tests remain mandatory before the API freeze. | [DEC-011-responsibility-placement-and-savepoint-helper.md](./DEC-011-responsibility-placement-and-savepoint-helper.md) | [ARCHITECTURE.md](../architecture/ARCHITECTURE.md) | — | — | +| `DEC-011` | Responsibility placement, savepoint helper ownership and retained names | `ACTIVE` | `Repository/` for SQL-issuing classes, single `@internal` savepoint helper, no optional renames. Original WU-6 characterization and freeze gate. | [DEC-011-responsibility-placement-and-savepoint-helper.md](./DEC-011-responsibility-placement-and-savepoint-helper.md) | [Architecture §4](../architecture/ARCHITECTURE.md#4-source-topology) for current topology. [Package Reference §3](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#3-public-runtime-api-inventory) for the public inventory. | — | — | | `DEC-012` | Mandatory PDO MySQL driver | `ACTIVE` | `ext-pdo` and `ext-pdo_mysql` as unconditional `require` entries; no optional-driver path; `maatify/exceptions` declared ahead of the first exception class. | [DEC-012-mandatory-pdo-mysql-driver.md](./DEC-012-mandatory-pdo-mysql-driver.md) | `composer.json`; pinned [Composer Package Standard](../php-engineering-standards/standards/packages/COMPOSER_PACKAGE_STANDARD.md) §15.2 | — | — | | `DEC-013` | Test-only database version boundary | `ACTIVE` | Real-database test matrix: MySQL `8.0.16`, `8.4.13`, `9.7.4`; MariaDB `10.11.19`, `11.4.13`, `11.8.9`, `12.3.3`; Innovation exploratory only; upper edge capped at the highest verified endpoint. Not a support claim. | [DEC-013-test-only-database-version-boundary.md](./DEC-013-test-only-database-version-boundary.md) | `docker/integration-matrix.json`; [CI_AND_INTEGRATION.md](../architecture/CI_AND_INTEGRATION.md) | — | — | | `DEC-014` | Free written licenses and registration | `ACTIVE` | Proprietary terms for the next release and security notices for license holders. | [DEC-014-free-license-registration.md](./DEC-014-free-license-registration.md) | `LICENSE` | `DEC-002` | — | @@ -23,9 +23,9 @@ Current-state discovery surface for durable decisions of this repository. It is | `DEC-017` | Enforce PHP integer bounds for Ordering | `ACTIVE` | Validation of stored positions and next-position arithmetic. | [DEC-017-ordering-integer-boundaries.md](./DEC-017-ordering-integer-boundaries.md) | [Package Reference §5.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager) | — | — | | `DEC-018` | Optional consistent pagination on a delegated read connection | `ACTIVE` | C1 connection grant, one-shot operation state, and Host disposition; caller-controlled Pagination contract preserved. | [DEC-018-optional-delegated-snapshot-pagination.md](./DEC-018-optional-delegated-snapshot-pagination.md) | [Package Reference §5.3.1](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#531-optional-c1-snapshot-pagination) | — | — | | `DEC-019` | Optional forward Keyset pagination | `ACTIVE` | An opt-in forward read with signed continuation on Host-owned PDO. | [DEC-019-optional-forward-keyset-pagination.md](./DEC-019-optional-forward-keyset-pagination.md) | [Package Reference §5.3.2](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#532-optional-forward-only-keyset-pagination) | — | — | -| `DEC-020` | Optional pagination in a Host-owned transaction | `ACTIVE` | Shared reservation, actual RR generation, per-attempt settlement, and explicit Host handoff or discard. | [DEC-020-optional-host-transaction-snapshot-pagination.md](./DEC-020-optional-host-transaction-snapshot-pagination.md) | [Package Reference §5.3.3](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#533-optional-b-pagination-in-a-host-owned-transaction) | — | — | +| `DEC-020` | Optional pagination in a Host-owned transaction | `SUPERSEDED` | Historical B design and original Host handoff. | [DEC-020-optional-host-transaction-snapshot-pagination.md](./DEC-020-optional-host-transaction-snapshot-pagination.md) | Historical record. Current contract in [DEC-036](./DEC-036-pascalcase-enums-and-stable-settlement-json.md). | — | `DEC-032` | | `DEC-021` | Bound raw Ordering tail reads | `ACTIVE` | Default 64 and an optional per-call budget of 2–512 with explicit exhaustion. | [DEC-021-bound-ordering-tail-reads.md](./DEC-021-bound-ordering-tail-reads.md) | [Package Reference §5.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#getnextpositionforupdate) | — | — | -| `DEC-022` | Optional verified apply and discard | `ACTIVE` | Exclusive Owned and Host transactions, verified decision settlement and explicit PDO disposition. | [DEC-022-verified-apply-discard.md](./DEC-022-verified-apply-discard.md) | [Package Reference §5.2.2](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#522-optional-verified-apply-and-discard) | — | — | +| `DEC-022` | Optional verified apply and discard | `SUPERSEDED` | Historical C2 design and original PHP-local decision/settlement types. | [DEC-022-verified-apply-discard.md](./DEC-022-verified-apply-discard.md) | Historical record. Current contract in [DEC-036](./DEC-036-pascalcase-enums-and-stable-settlement-json.md). | — | `DEC-032` | | `DEC-023` | Domain-owned UNIQUE-safe ordering for the planned release | `SUPERSEDED` | Next release in Roadmap #65 only, as approved on 2026-11-23. Domain owns UNIQUE-safe moves, with no new package API. | [DEC-023-unique-ordering-release-domain-ownership.md](./DEC-023-unique-ordering-release-domain-ownership.md) | [Package Reference §5.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager); [Roadmap #65](https://github.com/Maatify-ltd/php-persistence/issues/65) | — | `DEC-026` | | `DEC-027` | Owned database test work and fixture cleanup | `ACTIVE` | Positive worker-group completion, fixture-owned cleanup and the original immediate residue gate. | [DEC-027-database-test-work-ownership.md](./DEC-027-database-test-work-ownership.md) | [CI_AND_INTEGRATION.md §2](../architecture/CI_AND_INTEGRATION.md#database-worker-ownership-and-fixture-cleanup) | — | — | | `DEC-024` | Optional static composite Offset pagination | `ACTIVE` | Host-defined reusable sort profiles in an opt-in Offset entry point. | [DEC-024-optional-static-composite-offset-pagination.md](./DEC-024-optional-static-composite-offset-pagination.md) | [Package Reference §5.3.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#534-optional-static-composite-offset-pagination) | — | — | @@ -35,3 +35,8 @@ Current-state discovery surface for durable decisions of this repository. It is | `DEC-029` | Selective pinned standards upgrade | `ACTIVE` | Exact central snapshot `c1dbb2d…` for `composer-package` and `repository-governance` at `/`. | [DEC-029-selective-pinned-standards-upgrade.md](./DEC-029-selective-pinned-standards-upgrade.md) | [STANDARDS_MANIFEST.md](../php-engineering-standards/STANDARDS_MANIFEST.md) | `DEC-003` | — | | `DEC-030` | Successor transition before first Stable | `ACTIVE` | Standards adoption and normative ownership before first Stable. Publication, consumer migration and legacy lifecycle remain separately authorized. | [DEC-030-successor-transition-before-first-stable.md](./DEC-030-successor-transition-before-first-stable.md) | [Package Building §11](../php-engineering-standards/standards/packages/PACKAGE_BUILDING_STANDARD.md#11-shared-ordering-and-pagination-utilities); [DEC-029](./DEC-029-selective-pinned-standards-upgrade.md) for the pin. | `DEC-006` | — | | `DEC-031` | First-Stable Real Host Validation exception | `ACTIVE` | Full Real Host Validation exception for `maatify/php-persistence` at `/` for first Stable `1.0.0`. Published RC and same-RC Harness remain required. | [DEC-031-first-stable-real-host-exception.md](./DEC-031-first-stable-real-host-exception.md) | [Library Presentation §14.1](../php-engineering-standards/standards/packages/LIBRARY_PRESENTATION_STANDARD.md#141-first-stable-release-gate) | — | — | +| `DEC-032` | Settlement JSON and execution contracts | `SUPERSEDED` | B PDO handoff, C2 execution intent and data-only settlement projections. | [DEC-032-settlement-json-and-execution-contracts.md](./DEC-032-settlement-json-and-execution-contracts.md) | Historical record. Current contract in [DEC-036](./DEC-036-pascalcase-enums-and-stable-settlement-json.md). | `DEC-020`, `DEC-022` | `DEC-036` | +| `DEC-033` | Validate Ordering mutation timestamps | `ACTIVE` | Exact timestamp format and calendar/clock validation for raw and protected moves. | [DEC-033-validate-ordering-mutation-timestamps.md](./DEC-033-validate-ordering-mutation-timestamps.md) | [Package Reference §5.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager) | — | — | +| `DEC-034` | Surface settlement failures in raw Ordering | `ACTIVE` | Confirm owned rollback or local savepoint undo before a false result. Preserve primary errors and Host ownership. | [DEC-034-raw-ordering-settlement-failures.md](./DEC-034-raw-ordering-settlement-failures.md) | [Package Reference §5.4](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#54-scopedorderingmanager) | — | — | +| `DEC-035` | Reject trailing LF in published constructor inputs | `ACTIVE` | Retain strict full-string validation at the first Stable boundary and classify narrower constructor acceptance as breaking from RC.2. | [DEC-035-reject-terminal-lf-in-constructor-inputs.md](./DEC-035-reject-terminal-lf-in-constructor-inputs.md) | [Package Reference §1.5](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#15-rc2-constructor-input-migration) | — | — | +| `DEC-036` | PascalCase enum cases and stable settlement JSON | `ACTIVE` | PHP enum names, RC.2 sort-direction migration and preserved settlement codes. Carries forward B handoff and C2 execution intent. | [DEC-036-pascalcase-enums-and-stable-settlement-json.md](./DEC-036-pascalcase-enums-and-stable-settlement-json.md) | [Package Reference §§1.6 and 3.6](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#16-rc2-sort-direction-migration) | `DEC-032` | — | diff --git a/docs/guides/USAGE_GUIDE.md b/docs/guides/USAGE_GUIDE.md index ec60e9c..a02808b 100644 --- a/docs/guides/USAGE_GUIDE.md +++ b/docs/guides/USAGE_GUIDE.md @@ -16,20 +16,22 @@ This guide covers the Stable `1.0.0` target. Follow the [installation instructio | Capability | Primary call | Walkthrough | Example | |---|---|---|---| | Transaction | `PdoTransactionRunner::run()` / `PdoSavepointTransactionRunner::run()` | [§1](#1-transaction) | [examples/transaction_basic_usage.php](../../examples/transaction_basic_usage.php) | -| Transaction · Optional protected Host write checkout | `PdoProtectedTransactionCheckout::attachExclusive()` then `begin()` and `runRegisteredCommand()` | [Protected Host write checkout](#optional-protected-host-write-checkout) | Walkthrough only | +| Transaction · Optional protected Host write checkout | `PdoProtectedTransactionCheckout::attachExclusive()` then `begin()` and `runRegisteredCommand()` | [Protected Host write checkout](#optional-protected-host-write-checkout) | [Protected checkout in the B1 example](../../examples/ordering_unique_usage.php) | | Transaction · Optional verified checkout | `PdoVerifiedTransactionCheckout::attachExclusive()` then `runOwned()` or `beginHost()` and `runInHost()` | [Verified checkout](#optional-verified-checkout-c2) | [examples/verified_transaction_usage.php](../../examples/verified_transaction_usage.php) | | Pagination | `PdoPaginator::paginate()` | [§2](#2-pagination) | [examples/pagination_basic_usage.php](../../examples/pagination_basic_usage.php) | | Pagination · Optional static composite sort | `PdoPaginator::paginateWithStaticSort()` | [Static composite sorting](#optional-static-composite-sorting) | [examples/pagination_static_sort_usage.php](../../examples/pagination_static_sort_usage.php) | | Pagination · Optional dynamic sort | `PdoPaginator::paginateWithDynamicSort()` | [Dynamic sorting](#optional-dynamic-sorting) | [examples/pagination_dynamic_sort_usage.php](../../examples/pagination_dynamic_sort_usage.php) | | Pagination · Optional delegated snapshot (C1) | `PdoSnapshotPaginator::forExclusiveRead()` then `paginate()` | [C1 snapshot pagination](#optional-c1-snapshot-pagination) | [examples/pagination_snapshot_usage.php](../../examples/pagination_snapshot_usage.php) | -| Pagination · Optional Host transaction snapshot (B) | `PdoHostSnapshotSource::attachExclusive()` then `PdoHostSnapshotPaginator::paginate()` with an authorized page attempt | [B pagination in a Host transaction](#optional-b-pagination-in-a-host-transaction) | Walkthrough only | +| Pagination · Optional Host transaction snapshot (B) | `PdoHostSnapshotSource::attachExclusive()` then `PdoHostSnapshotPaginator::paginate()` with an authorized page attempt | [B pagination in a Host transaction](#optional-b-pagination-in-a-host-transaction) | [Host integration example](../../examples/pagination_host_snapshot_usage.php) | | Pagination · Optional forward-only Keyset | `PdoKeysetPaginator::paginate()` | [Forward-only Keyset pagination](#optional-forward-only-keyset-pagination) | [examples/pagination_keyset_usage.php](../../examples/pagination_keyset_usage.php) | | Ordering | `ScopedOrderingManager::moveWithinScope()` (and the next-position reads) | [§3](#3-ordering) | [examples/ordering_basic_usage.php](../../examples/ordering_basic_usage.php) | | Ordering · Optional protected UNIQUE-safe lists (B1) | `ProtectedScopedOrderingManager::getNextUniquePositionForAppend()`, `moveUniqueWithinScope()`, or `deleteUniqueWithinScope()` | [Protected UNIQUE-safe Ordering B1](#protected-unique-safe-ordering-b1) | [examples/ordering_unique_usage.php](../../examples/ordering_unique_usage.php) | ## Run the examples from a 1.0.0 install -After [installing the exact version](../../README.md#installation), choose a row with a linked PHP file in the capability map. Create an `examples/` directory in your Composer project and copy that file and `_bootstrap.php` from `vendor/maatify/php-persistence/examples/`. Run the copied file with PHP from your project root so it loads your Composer autoloader. Use a disposable InnoDB database with the connection variables and privileges in the example setup below. The B1 example also requires `DELETE`. For rows marked “Walkthrough only,” follow the linked steps in your Host integration. +After [installing the exact version](../../README.md#installation), choose a standalone example from the capability map. Create an `examples/` directory in your Composer project and copy that file and `_bootstrap.php` from `vendor/maatify/php-persistence/examples/`. Run the copied file with PHP from your project root so it loads your Composer autoloader. Use a disposable InnoDB database with the connection variables and privileges in the example setup below. The B1 example also requires `DELETE`. + +Load the [Host Snapshot B example](../../examples/pagination_host_snapshot_usage.php) within an application that has loaded its production Composer autoloader. Use the [Host B walkthrough](#optional-b-pagination-in-a-host-transaction) to attach an eligible idle `pdo_mysql` connection exclusively to a source with a registered InnoDB page plan. Call `Maatify\PhpPersistence\Examples\readHostSnapshotPage()` with that source, the registered plan ID, its bindings, and a page request. The example depends on those application objects and is outside standalone smoke execution. The Host accesses the delegated connection only through its source and checkout. The example discards the source when a normal commit leaves reuse unconfirmed. On failure it attempts to discard the source and rethrows the original failure. After discard or a thrown failure, drop all retained references to the original PDO and keep it out of circulation even if discard could not complete. A returned page does not authorize direct reuse of that PDO. ## Run the published RC.2 examples from a clean install @@ -82,7 +84,7 @@ Each command provisions two disposable services for that engine. Look for `CONSU ### Run examples from the repository checkout -With the checkout's Composer dependencies installed and Docker running, `composer examples:smoke` provisions a disposable database and runs the examples. To run an individual example manually, use the disposable database variables above and run the script from the repository root. +With the checkout's Composer dependencies installed and Docker running, `composer examples:smoke` provisions a disposable database and runs the standalone examples. To run a standalone example manually, use the disposable database variables above and run the script from the repository root. For Host Snapshot B, follow the [application integration instructions](#run-the-examples-from-a-100-install) above. --- @@ -148,7 +150,7 @@ Use a protected checkout when the Host needs to keep transaction control while r 1. Build a `ProtectedTransactionCommandCatalog` from trusted `ProtectedTransactionCommandPlan` entries. Delegate an eligible idle PDO through `PdoProtectedTransactionCheckout::attachExclusive($pdo, $catalog)` and keep raw aliases out of use. 2. Call `$checkout->begin()`. Execute the registered operation through `$checkout->runRegisteredCommand('invoice.updateStatus', ['id' => $invoiceId, 'status' => $status])`. Check the affected-row result against the Host's business rule. For guarded Ordering within the same transaction, use the [protected Ordering path](#protected-ordering-and-domain-constraints). -3. Inspect `settlement()` after an error. A `null` settlement means the checkout has yet to record a terminal outcome. The Host ends a confirmed active transaction with `commit()` or `rollBack()` before any handoff. Read the terminal settlement after attempting to end it. On `REUSABLE`, retrieve the same connection once with `returnForHost()`. On `DISCARD_REQUIRED`, stop issuing SQL, call `discardForHost()`, and reconcile any uncertain database effect before deciding whether to repeat the work. +3. Inspect `settlement()` after an error. A `null` settlement means the checkout has yet to record a terminal outcome. The Host ends a confirmed active transaction with `commit()` or `rollBack()` before any handoff. Read the terminal settlement after attempting to end it. On `Reusable`, retrieve the same connection once with `returnForHost()`. On `DiscardRequired`, stop issuing SQL, call `discardForHost()`, and reconcile any uncertain database effect before deciding whether to repeat the work. See the [protected Host write contract](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#521-optional-protected-host-write-transaction) for PDO eligibility, failure reasons and handoff. @@ -160,10 +162,10 @@ The Host supplies an idle, non-persistent `PDO` or `Pdo\Mysql` connection from ` #### Walkthrough — Input → Public Call → Result → Boundary -1. **Input** — Register each transaction-preserving command in a `ProtectedTransactionCommandCatalog` and pass the catalog and PDO to `PdoVerifiedTransactionCheckout::attachExclusive()`. The callback receives a `VerifiedTransactionCommandsInterface` grant. Use its `runRegisteredCommand()` with an ID and matching named bindings, then return `VerifiedTransactionDecisionDTO::apply($payload)` or `VerifiedTransactionDecisionDTO::discard($payload)`. Both decisions accept `false` or `null` as payload. +1. **Input** — Register each transaction-preserving command in a `ProtectedTransactionCommandCatalog` and pass the catalog and PDO to `PdoVerifiedTransactionCheckout::attachExclusive()`. The callback receives a `VerifiedTransactionCommandsInterface` grant. Use its `runRegisteredCommand()` with an ID and matching named bindings, then return `VerifiedTransactionDecisionCommand::apply($payload)` or `VerifiedTransactionDecisionCommand::discard($payload)`. Both decisions accept `false` or `null` as payload. 2. **Public call** — In **Owned** mode, call `runOwned($operation)`. The checkout starts and ends the transaction. In **Host** mode, call `beginHost()`, optionally run registered Host commands, and call `runInHost($operation)` for one savepoint-scoped operation. The Host can continue with registered commands after a confirmed operation and chooses the outer `commit()` or `rollBack()`. -3. **Result** — In Owned mode, the payload follows a confirmed commit or rollback and an idle-session check. In Host mode, Apply records `PENDING_HOST` after savepoint release and confirmed continuity. Discard records `LOCAL_UNDONE` once rollback to the savepoint is acknowledged. Returning the Discard payload also requires acknowledged release and confirmed continuity. Read `settlement()` after return or exception for the operation outcome, transaction outcome and PDO disposition. A later Host end preserves the operation outcome. -4. **Boundary** — An exception escaping the callback keeps its identity. An uncertain control result suppresses the payload. A lost end reply leaves the transaction outcome `UNKNOWN` and the connection `DISCARD_REQUIRED`. A failed final connection check can require discard even when the database outcome is known. Return the original PDO once with `returnForHost()` after `REUSABLE` or an untouched `UNCHANGED` cancellation. For `DISCARD_REQUIRED`, retire it with `discardForHost()` and reconcile any uncertain database effect before deciding whether to repeat work. The checkout performs no replay. Its guarantees cover eligible transactional effects under exclusive delegation. +3. **Result** — In Owned mode, the payload follows a confirmed commit or rollback and an idle-session check. In Host mode, Apply records `PendingHost` after savepoint release and confirmed continuity. Discard records `LocalUndone` once rollback to the savepoint is acknowledged. Returning the Discard payload also requires acknowledged release and confirmed continuity. Read `settlement()` after return or exception for the operation outcome, transaction outcome and PDO disposition. A later Host end preserves the operation outcome. The settlement's JSON projection preserves null fields and uses [stable uppercase codes](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#36-settlement-enum-json-codes). +4. **Boundary** — An exception escaping the callback keeps its identity. An uncertain control result suppresses the payload. A lost end reply leaves the transaction outcome `Unknown` and the connection `DiscardRequired`. A failed final connection check can require discard even when the database outcome is known. Return the original PDO once with `returnForHost()` after `Reusable` or an untouched `Unchanged` cancellation. For `DiscardRequired`, retire it with `discardForHost()` and reconcile any uncertain database effect before deciding whether to repeat work. The checkout performs no replay. Its guarantees cover eligible transactional effects under exclusive delegation. Run `php examples/verified_transaction_usage.php` from the project root with the disposable database settings above. The example covers Owned Apply and Discard, Host Discard followed by an outer commit, and settlement after a callback throws. See the [runnable example](../../examples/verified_transaction_usage.php) and the [complete Verified Checkout contract](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#522-optional-verified-apply-and-discard). @@ -205,9 +207,9 @@ $request = new PageRequest( $config = new PaginationConfig( sortWhitelist: new SortWhitelist(['created_at' => 'orders.created_at', 'id' => 'orders.id']), defaultSortBy: 'created_at', - defaultSortDirection: SortDirectionEnum::DESC, + defaultSortDirection: SortDirectionEnum::Desc, tieBreakerSortBy: 'id', - tieBreakerDirection: SortDirectionEnum::ASC, + tieBreakerDirection: SortDirectionEnum::Asc, ); $query = new PdoPaginationQueryDescriptor( @@ -270,7 +272,7 @@ Use C1 when all reads for one page can run through the same eligible InnoDB conn 1. Build the same descriptor, request and configuration used for standard pagination. 2. Create the one-shot operation with `PdoSnapshotPaginator::forExclusiveRead($pdo)` and call `paginate()`. -3. On return or exception, inspect `connectionOutcome()` on that operation. The Host can use `REUSABLE` after confirmed cleanup, retains its policy for `UNCHANGED`, and retires a `DISCARD` checkout. Hold the connection out of circulation if an attempted call finishes without an outcome. Preserve the page failure if Host settlement also fails. +3. On return or exception, inspect `connectionOutcome()` on that operation. The Host can use `Reusable` after confirmed cleanup, retains its policy for `Unchanged`, and retires a `Discard` checkout. Hold the connection out of circulation if an attempted call finishes without an outcome. Preserve the page failure if Host settlement also fails. The [snapshot example](../../examples/pagination_snapshot_usage.php) runs successful and failing reads against a disposable database. To run it from an independent Composer project using the installed package, copy the example and `examples/_bootstrap.php` into that project's `examples/` directory. It loads that project's production autoloader. The package's [C1 contract](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#531-optional-c1-snapshot-pagination) defines the eligibility, read scope and settlement rules. @@ -281,9 +283,9 @@ Use B when the Host needs eligible page reads, including its earlier writes, wit 1. **Input** — Start with an idle, exclusively delegated, non-persistent `pdo_mysql` PDO with exception mode, the default statement class and autocommit enabled. Register non-locking, side-effect-free InnoDB page plans and trusted commands in a `HostSnapshotCatalog`. Route all use of the connection through the checkout during delegation. 2. **Start** — Create the source with `PdoHostSnapshotSource::attachExclusive($pdo, $catalog)`, obtain a lease with `$source->checkout()`, then call `$checkout->beginRepeatableRead()`. Checkout rejects an already active transaction. At the Host's request, B issues `SET TRANSACTION ISOLATION LEVEL REPEATABLE READ` for the next transaction, starts it, and confirms the same session and active transaction. The Host's session and server defaults stay in effect for later transactions. For writes before a page, use `runRegisteredCommand()` on that checkout in read-write mode with commands registered to preserve the transaction. 3. **Read** — Call `$checkout->authorizePage($queryId, $bindings, $request)`, pass the grant to `$checkout->newAttempt()`, and use `(new PdoHostSnapshotPaginator())->paginate($attempt)` to receive a `PageResultDTO`. -4. **Boundary** — Eligible page reads share the InnoDB read view within the confirmed transaction and can see the Host's own writes in that transaction. A later transaction has its own read view. Inspect `$attempt->settlement()` after return or exception. The Host directs `commit()` or `rollBack()` on the checkout and handles handoff or discard. If B cannot confirm that startup consumed the isolation setting, the Host must reconcile the connection before reuse. +4. **Boundary** — Eligible page reads share the InnoDB read view within the confirmed transaction and can see the Host's own writes in that transaction. A later transaction has its own read view. Inspect `$attempt->settlement()` after return or exception. The Host directs `commit()` or `rollBack()` on the checkout and handles handoff or discard. The page settlement has a JSON projection of disposition and reason. If the Host calls `retireForHost()` on the source, the returned `HostSnapshotRetirement` transfers the original PDO as a PHP object. If B cannot confirm that startup consumed the isolation setting, the Host must reconcile the connection before reuse. -See the [B contract](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#533-optional-b-pagination-in-a-host-owned-transaction) for a page-attempt example, confirmation and handoff rules. The [installed consumer verification](CONSUMER_VERIFICATION.md) exercises a registered write followed by a page in the same transaction. +See the [B contract](../../PHP_PERSISTENCE_PACKAGE_REFERENCE.md#533-optional-b-pagination-in-a-host-owned-transaction) for confirmation and handoff rules. The [Host integration example](../../examples/pagination_host_snapshot_usage.php) shows a read-only page transaction and a conservative discard policy. The [installed consumer verification](CONSUMER_VERIFICATION.md) exercises a registered write followed by a page in the same transaction. ### Optional forward-only Keyset pagination @@ -305,6 +307,10 @@ Use an InnoDB table for the locking and rollback behavior shown here. A failed m **Inputs:** a `PDO` connection, a `ScopedOrderingConfig`, a scope value (or `null` for global/nullable-scope ordering), and — for a move — a row id and target order. **Outputs:** `int` (next position) or `bool` (whether the move succeeded, including a no-op). +When you configure `updatedAtColumn`, supply `updatedAtValue` as a valid `YYYY-MM-DD HH:MM:SS` timestamp with optional 1–6 fractional digits. For example, format a date-time object with `Y-m-d H:i:s` in the intended Host timezone. Omit the value when the column is absent. Both raw and protected moves apply this check before Ordering SQL and bind the accepted string unchanged. [Migration from RC.2](../decisions/DEC-033-validate-ordering-mutation-timestamps.md) + +For a raw move, `false` means the target was missing or the zero-row update was undone, with any required settlement confirmed. If PDO fails to confirm that settlement, handle `TransactionExecutionException` or the original driver throwable, then resolve the transaction and connection state before reuse. The Host retains final control of a transaction it supplied. [Migration from RC.2](../decisions/DEC-034-raw-ordering-settlement-failures.md) + **Boundary:** `moveWithinScope()` always locks the whole scope and re-reads the current order from the database before deciding anything; it never trusts a caller-supplied "current order". ### Append the first item in an empty scope @@ -433,7 +439,7 @@ try { } throw $failure; } finally { - if ($checkout->settlement()?->disposition === ProtectedTransactionDispositionEnum::DISCARD_REQUIRED) { + if ($checkout->settlement()?->disposition === ProtectedTransactionDispositionEnum::DiscardRequired) { $checkout->discardForHost(); } else { $hostPdo = $checkout->returnForHost(); diff --git a/examples/_bootstrap.php b/examples/_bootstrap.php index 27a0c98..b738522 100644 --- a/examples/_bootstrap.php +++ b/examples/_bootstrap.php @@ -24,11 +24,11 @@ function php_persistence_example_env(string $name): string fwrite( STDERR, "Missing required environment variable {$name}.\n" - . "This example needs a real MySQL/MariaDB connection. Run it through\n" - . "'composer examples:smoke' (starts a disposable service via the\n" - . "repository's Integration infrastructure), or set PHP_PERSISTENCE_IT_*\n" - . "yourself to point at a disposable database; see\n" - . "docs/guides/USAGE_GUIDE.md and CONTRIBUTING.md.\n", + . "This example needs a real MySQL/MariaDB connection. Run it through\n" + . "'composer examples:smoke' (starts a disposable service via the\n" + . "repository's Integration infrastructure), or set PHP_PERSISTENCE_IT_*\n" + . "yourself to point at a disposable database; see\n" + . "docs/guides/USAGE_GUIDE.md and CONTRIBUTING.md.\n", ); exit(1); } diff --git a/examples/ordering_basic_usage.php b/examples/ordering_basic_usage.php index 27257cb..ba6dc07 100644 --- a/examples/ordering_basic_usage.php +++ b/examples/ordering_basic_usage.php @@ -55,10 +55,10 @@ function php_persistence_example_read_orders(PDO $pdo, string $quotedTable, int php_persistence_example_assert( $pdo->exec( "CREATE TABLE {$quotedTable} (" - . 'id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, ' - . 'method_id INT UNSIGNED NOT NULL, ' - . 'display_order INT UNSIGNED NOT NULL, ' - . 'KEY method_order (method_id, display_order)) ENGINE=InnoDB', + . 'id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, ' + . 'method_id INT UNSIGNED NOT NULL, ' + . 'display_order INT UNSIGNED NOT NULL, ' + . 'KEY method_order (method_id, display_order)) ENGINE=InnoDB', ) !== false, 'failed to create the ordering fixture table', ); diff --git a/examples/ordering_unique_usage.php b/examples/ordering_unique_usage.php index 10b3e3d..ffb63c7 100644 --- a/examples/ordering_unique_usage.php +++ b/examples/ordering_unique_usage.php @@ -95,7 +95,7 @@ function b1_example_fingerprint(PDO $pdo, string $table): string } throw $primary; } finally { - if ($checkout->settlement()?->disposition === ProtectedTransactionDispositionEnum::DISCARD_REQUIRED) { + if ($checkout->settlement()?->disposition === ProtectedTransactionDispositionEnum::DiscardRequired) { $checkout->discardForHost(); } else { $checkout->returnForHost(); diff --git a/examples/pagination_basic_usage.php b/examples/pagination_basic_usage.php index c1a55fc..74d74d8 100644 --- a/examples/pagination_basic_usage.php +++ b/examples/pagination_basic_usage.php @@ -29,8 +29,8 @@ php_persistence_example_assert( $pdo->exec( "CREATE TABLE {$quotedTable} (" - . 'id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, ' - . "status VARCHAR(16) NOT NULL)", + . 'id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, ' + . "status VARCHAR(16) NOT NULL)", ) !== false, 'failed to create the pagination fixture table', ); @@ -53,9 +53,9 @@ $config = new PaginationConfig( sortWhitelist: new SortWhitelist(['id' => 'id', 'status' => 'status']), defaultSortBy: 'id', - defaultSortDirection: SortDirectionEnum::ASC, + defaultSortDirection: SortDirectionEnum::Asc, tieBreakerSortBy: 'id', - tieBreakerDirection: SortDirectionEnum::ASC, + tieBreakerDirection: SortDirectionEnum::Asc, ); $query = new PdoPaginationQueryDescriptor( diff --git a/examples/pagination_dynamic_sort_usage.php b/examples/pagination_dynamic_sort_usage.php index a03e792..19b0fa6 100644 --- a/examples/pagination_dynamic_sort_usage.php +++ b/examples/pagination_dynamic_sort_usage.php @@ -21,9 +21,9 @@ $config = new PaginationConfig( sortWhitelist: new SortWhitelist(['status' => 'o.status', 'priority' => 'o.priority', 'internal_row' => 'o.id']), defaultSortBy: 'status', - defaultSortDirection: SortDirectionEnum::ASC, + defaultSortDirection: SortDirectionEnum::Asc, tieBreakerSortBy: 'internal_row', - tieBreakerDirection: SortDirectionEnum::ASC, + tieBreakerDirection: SortDirectionEnum::Asc, ); // The application adapter maps a grid request to public keys and directions. diff --git a/examples/pagination_host_snapshot_usage.php b/examples/pagination_host_snapshot_usage.php new file mode 100644 index 0000000..3672a74 --- /dev/null +++ b/examples/pagination_host_snapshot_usage.php @@ -0,0 +1,81 @@ + $bindings Exact named bindings for the plan. + * @return PageResultDTO|object> + * @throws Throwable The original page failure or the failure to start, authorize, or settle the checkout. + */ +function readHostSnapshotPage( + PdoHostSnapshotSource $source, + string $queryId, + array $bindings, + PageRequest $request, +): PageResultDTO { + try { + $checkout = $source->checkout(); + $checkout->beginRepeatableRead(HostSnapshotAccessModeEnum::ReadOnly); + $grant = $checkout->authorizePage($queryId, $bindings, $request); + $attempt = $checkout->newAttempt($grant); + + try { + $page = (new PdoHostSnapshotPaginator())->paginate($attempt); + } catch (Throwable $readFailure) { + // Roll back only while the settlement confirms control of the transaction. + if ($attempt->settlement()?->disposition === HostSnapshotPageDispositionEnum::ReturnedToHost) { + try { + $checkout->rollBack(); + } catch (Throwable) { + // Discard below and preserve the original read failure. + } + } + + throw $readFailure; + } + + // The successful page returns control to the Host. The Host ends the transaction. + $checkout->commit(); + if ($checkout->state() === HostSnapshotCheckoutStateEnum::Idle) { + $checkout->release(); + } else { + // A completed transaction alone does not clear the connection for reuse. + $source->discardForHost(); + } + + return $page; + } catch (Throwable $failure) { + // The Host keeps the connection out of circulation, even if discard fails. + try { + $source->discardForHost(); + } catch (Throwable) { + // Preserve the failure that put the connection out of circulation. + } + + throw $failure; + } +} diff --git a/examples/pagination_snapshot_usage.php b/examples/pagination_snapshot_usage.php index 9b37677..82775c3 100644 --- a/examples/pagination_snapshot_usage.php +++ b/examples/pagination_snapshot_usage.php @@ -35,9 +35,9 @@ $config = new PaginationConfig( new SortWhitelist(['id' => 'id']), 'id', - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, 'id', - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, ); $mapperFailure = new RuntimeException('Example mapper failure.'); @@ -67,7 +67,7 @@ static function (array $row) use ($expectedFailure): array { // This example's Host keeps an eligible reader only on confirmed reuse. // For any other outcome it retires its reference to the fresh reader. - if ($operation->connectionOutcome()?->disposition !== SnapshotConnectionDispositionEnum::REUSABLE) { + if ($operation->connectionOutcome()?->disposition !== SnapshotConnectionDispositionEnum::Reusable) { $reader = null; } if ($failure !== null && $failure !== $expectedFailure) { diff --git a/examples/pagination_static_sort_usage.php b/examples/pagination_static_sort_usage.php index 48eabf4..dd6e421 100644 --- a/examples/pagination_static_sort_usage.php +++ b/examples/pagination_static_sort_usage.php @@ -25,14 +25,14 @@ config: new PaginationConfig( sortWhitelist: new SortWhitelist(['workflow' => 'status', 'id' => 'id']), defaultSortBy: 'workflow', - defaultSortDirection: SortDirectionEnum::ASC, + defaultSortDirection: SortDirectionEnum::Asc, tieBreakerSortBy: 'id', - tieBreakerDirection: SortDirectionEnum::ASC, + tieBreakerDirection: SortDirectionEnum::Asc, ), profiles: [ 'workflow' => [ - ['identifier' => 'priority', 'direction' => SortDirectionEnum::DESC], - ['identifier' => 'id', 'direction' => SortDirectionEnum::ASC], + ['identifier' => 'priority', 'direction' => SortDirectionEnum::Desc], + ['identifier' => 'id', 'direction' => SortDirectionEnum::Asc], ], 'id' => null, ], @@ -50,7 +50,7 @@ plan: $plan, mapper: static fn(array $row): array => ['id' => php_persistence_example_to_int($row['id'])], ); - php_persistence_example_assert($page->sortBy === 'workflow' && $page->sortDirection === SortDirectionEnum::ASC, 'unexpected sort metadata'); + php_persistence_example_assert($page->sortBy === 'workflow' && $page->sortDirection === SortDirectionEnum::Asc, 'unexpected sort metadata'); php_persistence_example_assert($page->page === $pageNumber && $page->filtered === 5, 'unexpected page or count'); array_push($observed, ...array_column($page->data, 'id')); } diff --git a/examples/verified_transaction_usage.php b/examples/verified_transaction_usage.php index 5bed13c..f2e407c 100644 --- a/examples/verified_transaction_usage.php +++ b/examples/verified_transaction_usage.php @@ -5,7 +5,7 @@ /** Verified Owned and Host transactions against disposable InnoDB tables. */ use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandCatalog; use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandPlan; -use Maatify\PhpPersistence\Transaction\DTO\VerifiedTransactionDecisionDTO as Decision; +use Maatify\PhpPersistence\Transaction\Command\VerifiedTransactionDecisionCommand as Decision; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum as Disposition; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionOutcomeEnum as Outcome; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionReasonEnum as Reason; @@ -55,7 +55,7 @@ }; $dispose = static function (Checkout $checkout): void { - if ($checkout->settlement()->disposition === Disposition::REUSABLE) { + if ($checkout->settlement()->disposition === Disposition::Reusable) { $pdo = $checkout->returnForHost(); php_persistence_example_assert(!$pdo->inTransaction(), 'Expected a finished connection.'); } else { @@ -70,7 +70,7 @@ try { $payload = $checkout->runOwned($work($id, $apply ? 20 : 19)); php_persistence_example_assert($payload === ($apply ? false : null), 'Unexpected Owned payload.'); - $expected = $apply ? Outcome::COMMITTED : Outcome::ROLLED_BACK; + $expected = $apply ? Outcome::Committed : Outcome::RolledBack; php_persistence_example_assert($checkout->settlement()->transactionOutcome === $expected, 'Unexpected Owned end.'); } finally { $dispose($checkout); @@ -84,9 +84,9 @@ $result = $checkout->runInHost($work(4, 19)); php_persistence_example_assert($result === null, 'Unexpected Host payload.'); $local = $checkout->settlement(); - php_persistence_example_assert($local->operationOutcome === Outcome::LOCAL_UNDONE && $local->transactionOutcome === null, 'Expected only local undo.'); + php_persistence_example_assert($local->operationOutcome === Outcome::LocalUndone && $local->transactionOutcome === null, 'Expected only local undo.'); $checkout->commit(); - php_persistence_example_assert($checkout->settlement()->operationOutcome === Outcome::LOCAL_UNDONE, 'Local evidence changed.'); + php_persistence_example_assert($checkout->settlement()->operationOutcome === Outcome::LocalUndone, 'Local evidence changed.'); } finally { $dispose($checkout); } @@ -102,8 +102,8 @@ } catch (DomainException $caught) { php_persistence_example_assert($caught === $domain, 'The original error must escape.'); $snapshot = $checkout->settlement(); - php_persistence_example_assert($snapshot->operationReason === Reason::CALLBACK_FAILED - && $snapshot->transactionOutcome === Outcome::ROLLED_BACK, 'Expected verified cleanup.'); + php_persistence_example_assert($snapshot->operationReason === Reason::CallbackFailed + && $snapshot->transactionOutcome === Outcome::RolledBack, 'Expected verified cleanup.'); } } finally { $dispose($checkout); diff --git a/harness/Consumer/CatalogConnection.php b/harness/Consumer/CatalogConnection.php new file mode 100644 index 0000000..6848c0a --- /dev/null +++ b/harness/Consumer/CatalogConnection.php @@ -0,0 +1,25 @@ +beforePrepare)?->__invoke($query); + + return parent::prepare($query, $options); + } +} diff --git a/harness/consumer.php b/harness/consumer.php index 12f04de..49baea5 100644 --- a/harness/consumer.php +++ b/harness/consumer.php @@ -27,8 +27,12 @@ use Maatify\PhpPersistence\Pagination\ValueObject\SortWhitelist; use Maatify\PhpPersistence\Transaction\Repository\PdoSavepointTransactionRunner; use Maatify\PhpPersistence\Transaction\Repository\PdoTransactionRunner; +use Maatify\PhpPersistence\Verification\Consumer\CatalogConnection; -require __DIR__ . '/vendor/autoload.php'; +$loader = require __DIR__ . '/vendor/autoload.php'; +$loader->addPsr4('Maatify\\PhpPersistence\\Verification\\Consumer\\', __DIR__ . '/Consumer'); + +const ORDERING_CHECK_FAILURE_TIMESTAMP = '2026-01-01 00:00:00'; function verifySame(mixed $expected, mixed $actual, string $description): void { @@ -47,29 +51,15 @@ function consumerEnvironment(string $key): string return $value; } -/** - * A PDO connection that can coordinate a second real connection before a specific query. - */ -final class CatalogConnection extends PDO +/** Opens the consumer fixture PDO with the environment supplied by its supervisor. */ +function catalogConnection(): CatalogConnection { - public ?Closure $beforePrepare = null; - - public function __construct() - { - parent::__construct( - 'mysql:host=' . consumerEnvironment('HOST') . ';port=' . consumerEnvironment('PORT') . ';dbname=' . consumerEnvironment('DATABASE'), - consumerEnvironment('USER'), - consumerEnvironment('PASSWORD'), - [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false], - ); - } - - public function prepare(string $query, array $options = []): PDOStatement|false - { - ($this->beforePrepare)?->__invoke($query); - - return parent::prepare($query, $options); - } + return new CatalogConnection( + 'mysql:host=' . consumerEnvironment('HOST') . ';port=' . consumerEnvironment('PORT') . ';dbname=' . consumerEnvironment('DATABASE'), + consumerEnvironment('USER'), + consumerEnvironment('PASSWORD'), + [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false], + ); } function createCatalog(PDO $pdo, string $table): void @@ -79,8 +69,8 @@ function createCatalog(PDO $pdo, string $table): void scope_id INT NULL, position INT NOT NULL, deleted_at DATETIME NULL, - stamp VARCHAR(8) NOT NULL DEFAULT 'ready', - CHECK (stamp <> 'blocked'), + stamp VARCHAR(19) NOT NULL DEFAULT 'ready', + CHECK (stamp <> '" . ORDERING_CHECK_FAILURE_TIMESTAMP . "'), KEY scope_position (scope_id, position) ) ENGINE=InnoDB"); } @@ -107,7 +97,7 @@ function catalogPage(PDO $pdo, string $table, bool $legacy): array $paginator = new PdoPaginator(); $query = new PdoPaginationQueryDescriptor($total, [], $filtered, [], $data, []); $request = new PageRequest(page: '9999', perPage: '0', sortBy: 'invalid'); - $config = new PaginationConfig(new SortWhitelist(['position' => 'position', 'id' => 'id']), 'position', SortDirectionEnum::ASC, 'id', SortDirectionEnum::DESC); + $config = new PaginationConfig(new SortWhitelist(['position' => 'position', 'id' => 'id']), 'position', SortDirectionEnum::Asc, 'id', SortDirectionEnum::Desc); } $result = $paginator->paginate($pdo, $query, $request, $config, $mapper); verifySame($result->toArray(), json_decode(json_encode($result, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR), 'Pagination array and JSON agree'); @@ -119,7 +109,7 @@ function catalogPage(PDO $pdo, string $table, bool $legacy): array function exerciseCatalog(CatalogConnection $pdo, string $table, bool $legacy): array { createCatalog($pdo, $table); - $writer = new CatalogConnection(); + $writer = catalogConnection(); try { $runner = $legacy ? new LegacySourceRunner($pdo) : new PdoTransactionRunner($pdo); $manager = $legacy ? new LegacyOrdering() : new ScopedOrderingManager(); @@ -180,7 +170,7 @@ function exerciseCatalog(CatalogConnection $pdo, string $table, bool $legacy): a $pdo->beginTransaction(); $pdo->exec("UPDATE `{$table}` SET stamp = 'earlier' WHERE id = 4"); try { - $manager->moveWithinScope($pdo, $timestampedConfig, 7, 1, 1, 'blocked'); + $manager->moveWithinScope($pdo, $timestampedConfig, 7, 1, 1, ORDERING_CHECK_FAILURE_TIMESTAMP); throw new LogicException('Target write unexpectedly passed its CHECK constraint'); } catch (PDOException $error) { verifySame($mariaDb ? 4025 : 3819, (int) ($error->errorInfo[1] ?? 0), 'Target write failed after the range shift'); @@ -206,9 +196,15 @@ function exerciseCatalog(CatalogConnection $pdo, string $table, bool $legacy): a $page = catalogPage($pdo, $table, $legacy); verifySame([['id' => 4, 'position' => 1]], $page['data'], 'Normalized page applies deterministic tie-breaker'); verifySame([ - 'page' => 1, 'per_page' => 1, 'total' => 5, 'filtered' => 4, - 'total_pages' => 4, 'has_next' => true, 'has_previous' => false, - 'sort_by' => 'position', 'sort_direction' => 'ASC', + 'page' => 1, + 'per_page' => 1, + 'total' => 5, + 'filtered' => 4, + 'total_pages' => 4, + 'has_next' => true, + 'has_previous' => false, + 'sort_by' => 'position', + 'sort_direction' => 'ASC', ], $page['pagination'], 'Observable pagination envelope'); $pdo->beforePrepare = static function (string $sql) use ($pdo, $writer, $table): void { @@ -301,7 +297,7 @@ function exerciseSharedConnection(PDO $pdo, bool $legacySource): void */ function runRetryPartner(): void { - $pdo = new CatalogConnection(); + $pdo = catalogConnection(); $pdo->exec('SET SESSION innodb_lock_wait_timeout = 10'); $pdo->beginTransaction(); try { @@ -380,7 +376,7 @@ function induceConsumerDeadlock(PDO $pdo): never function exerciseDeadlockRetry(PDO $pdo, bool $legacy): array { $pdo->exec('CREATE TABLE consumer_retry (id INT PRIMARY KEY, weight INT NOT NULL) ENGINE=InnoDB'); - $observer = new CatalogConnection(); + $observer = catalogConnection(); try { $pdo->exec('INSERT INTO consumer_retry VALUES (1, 0), (2, 0), (3, 0)'); $pdo->exec('INSERT INTO consumer_retry WITH RECURSIVE seq(n) AS (SELECT 100 UNION ALL SELECT n + 1 FROM seq WHERE n < 163) SELECT n, 0 FROM seq'); @@ -435,7 +431,7 @@ function exerciseDeadlockRetry(PDO $pdo, bool $legacy): array verifySame(true, InstalledVersions::isInstalled('maatify/persistence', false), 'Legacy installed via Composer'); verifySame(false, InstalledVersions::isInstalled('phpunit/phpunit'), 'Consumer does not install package development dependencies'); verifySame(false, class_exists(Maatify\PhpPersistence\Tests\Integration\IntegrationTestCase::class), 'Production autoload excludes package tests'); -$pdo = new CatalogConnection(); +$pdo = catalogConnection(); exerciseSharedConnection($pdo, $scenario === 'differential'); $candidate = exerciseCatalog($pdo, 'consumer_candidate', false); if ($scenario === 'differential') { diff --git a/harness/host-snapshot-api.php b/harness/host-snapshot-api.php index c313ee5..4e150c2 100644 --- a/harness/host-snapshot-api.php +++ b/harness/host-snapshot-api.php @@ -46,9 +46,9 @@ $config = new PaginationConfig( new SortWhitelist(['id' => 'id']), 'id', - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, 'id', - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, 10, 1, 50, @@ -67,8 +67,8 @@ $insert = new HostSnapshotCommandPlan( "INSERT INTO $table VALUES (:id)", ['id'], - HostSnapshotCommandResultModeEnum::AFFECTED_ROWS, - effect: HostSnapshotCommandEffectEnum::PRESERVES_TRANSACTION, + HostSnapshotCommandResultModeEnum::AffectedRows, + effect: HostSnapshotCommandEffectEnum::PreservesTransaction, ); $source = PdoHostSnapshotSource::attachExclusive($connect(), new HostSnapshotCatalog(['items' => $pagePlan], ['insert' => $insert])); $lease = $source->checkout(); @@ -82,7 +82,7 @@ return (int) $statement->fetchColumn(); }; if ($page->total !== 2 || array_column($page->data, 'id') !== [1, 2] - || $attempt->settlement()?->reason !== HostSnapshotPageSettlementReasonEnum::PAGE_COMPLETED + || $attempt->settlement()?->reason !== HostSnapshotPageSettlementReasonEnum::PageCompleted || $readCommittedCount() !== 1 ) { throw new RuntimeException('The installed B surface failed its page or transaction contract.'); @@ -91,8 +91,8 @@ $lease->release(); $returned = $source->retireForHost(); if ($readCommittedCount() !== 2 || $returned->pdo->inTransaction() - || $returned->disposition !== HostSnapshotRetirementDispositionEnum::RETURNED_IDLE - || $attempt->settlement()?->reason !== HostSnapshotPageSettlementReasonEnum::PAGE_COMPLETED + || $returned->disposition !== HostSnapshotRetirementDispositionEnum::ReturnedIdle + || $attempt->settlement()?->reason !== HostSnapshotPageSettlementReasonEnum::PageCompleted ) { throw new RuntimeException('The installed B surface failed its Host handoff or historical settlement.'); } diff --git a/harness/keyset-api.php b/harness/keyset-api.php index 0fdd5c3..ce09811 100644 --- a/harness/keyset-api.php +++ b/harness/keyset-api.php @@ -13,15 +13,28 @@ require __DIR__ . '/vendor/autoload.php'; $paginatorParameters = [ - ['activeKeyId', 'string'], ['keys', 'array'], ['defaultLimit', 'int', 20], ['maxLimit', 'int', 200], + ['activeKeyId', 'string'], + ['keys', 'array'], + ['defaultLimit', 'int', 20], + ['maxLimit', 'int', 200], ]; $paginateParameters = [ - ['pdo', PDO::class], ['query', KeysetQueryDescriptor::class], ['scope', 'string'], - ['bindings', 'array'], ['mapper', 'callable'], ['cursor', '?string', null], ['limit', '?int', null], + ['pdo', PDO::class], + ['query', KeysetQueryDescriptor::class], + ['scope', 'string'], + ['bindings', 'array'], + ['mapper', 'callable'], + ['cursor', '?string', null], + ['limit', '?int', null], ]; $descriptorParameters = [ - ['queryId', 'string'], ['revision', 'string'], ['table', 'string'], ['columns', 'array'], - ['scopePredicate', 'string'], ['parameterNames', 'array'], ['filterPredicate', 'string', '1 = 1'], + ['queryId', 'string'], + ['revision', 'string'], + ['table', 'string'], + ['columns', 'array'], + ['scopePredicate', 'string'], + ['parameterNames', 'array'], + ['filterPredicate', 'string', '1 = 1'], ]; $resultParameters = [['data', 'array'], ['hasNext', 'bool'], ['nextCursor', '?string']]; $signatures = [ diff --git a/harness/protected-transaction-api.php b/harness/protected-transaction-api.php index 7381c4b..2fb0b9c 100644 --- a/harness/protected-transaction-api.php +++ b/harness/protected-transaction-api.php @@ -65,7 +65,7 @@ throw new RuntimeException('The protected operations did not share the Host transaction.'); } $checkout->commit(); - if ($outside() !== [2, 1, 3] || $checkout->settlement()?->reason !== ProtectedTransactionReasonEnum::COMMITTED) { + if ($outside() !== [2, 1, 3] || $checkout->settlement()?->reason !== ProtectedTransactionReasonEnum::Committed) { throw new RuntimeException('The Host commit was not confirmed.'); } $pdo = $checkout->returnForHost(); @@ -80,7 +80,7 @@ $checkout->runRegisteredCommand('fail'); throw new RuntimeException('Expected a real PDO exception.'); } catch (PDOException $error) { - if (($error->errorInfo[1] ?? null) !== 1054 || $checkout->settlement()?->disposition !== ProtectedTransactionDispositionEnum::DISCARD_REQUIRED) { + if (($error->errorInfo[1] ?? null) !== 1054 || $checkout->settlement()?->disposition !== ProtectedTransactionDispositionEnum::DiscardRequired) { throw $error; } } diff --git a/harness/unique-ordering/UniqueOrderingProofTest.php b/harness/unique-ordering/UniqueOrderingProofTest.php index ae833b3..29fe7ff 100644 --- a/harness/unique-ordering/UniqueOrderingProofTest.php +++ b/harness/unique-ordering/UniqueOrderingProofTest.php @@ -206,7 +206,7 @@ public function testProtectedUniqueFailureFencesCallerCommandsWithoutClaimingRol $manager = new ProtectedScopedOrderingManager(); $this->duplicate(self::failureOf(fn() => $manager->moveWithinScope($checkout, self::config($table, 'global'), null, 4, 1))); $settlement = $checkout->settlement(); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $settlement?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement?->disposition); $refused = 0; foreach ([$checkout->commit(...), $checkout->returnForHost(...), static fn() => $checkout->runRegisteredCommand('mark')] as $call) { try { diff --git a/harness/verified-apply-discard/Decision.php b/harness/verified-apply-discard/Decision.php new file mode 100644 index 0000000..033c9c2 --- /dev/null +++ b/harness/verified-apply-discard/Decision.php @@ -0,0 +1,15 @@ +checkout = PdoProtectedTransactionCheckout::attachExclusive($pdo, $catalog); + $this->window = new Window($this->checkout, $catalog); + } + + public function beginHost(): void + { + $this->checkout->begin(); + } + + /** @param array $bindings */ + public function hostCommand(string $id, array $bindings = []): int|array + { + return $this->checkout->runRegisteredCommand($id, $bindings); + } + + /** + * Uses the local savepoint and returns the payload after applying or undoing + * the window. The Host still controls the outer transaction. + * + * @param Closure(Closure(string, array): (int|array)): Decision $work + */ + public function runInHost(Closure $work, ?Closure $fault = null): mixed + { + return $this->window->run($work, beforeControl: $fault); + } + + /** + * Starts and ends the entire fixture transaction according to the explicit + * decision before returning its payload. An escaping callback error remains + * primary if cleanup also fails. + * + * @param Closure(Closure(string, array): (int|array)): Decision $work + */ + public function runOwned(Closure $work): mixed + { + $this->checkout->begin(); + try { + $decision = $this->window->run($work, host: false); + if (!$decision instanceof Decision) { + throw new LogicException('Unexpected owned decision type in proof.'); + } + } catch (Throwable $primary) { + $this->ownedEffect = $this->window->entered() ? 'UNKNOWN' : 'NOT_STARTED'; + if ($this->checkout->settlement() === null) { + try { + $this->rollBack(); + } catch (Throwable) { + // Keep the callback as the primary failure. + } finally { + $this->ownedEffect = $this->endEffect ?? $this->ownedEffect; + } + } + + throw $primary; + } + + try { + $this->finish($decision->intent === Intent::Apply); + } finally { + $this->ownedEffect = $this->endEffect ?? 'UNKNOWN'; + } + + return $decision->value; + } + + public function commit(): void + { + $this->finish(true); + } + + public function rollBack(): void + { + $this->finish(false); + } + + public function endEffect(): ?string + { + return $this->endEffect; + } + + /** + * Compare C2's end-effect projection under the real lease. Capture the ACK + * between the end SQL and idle probe. The existing settlement is retained + * as the source of the connection disposition, with its original enum. + */ + private function finish(bool $commit): void + { + $finish = Closure::bind( + static function (PdoProtectedTransactionCheckout $checkout, bool $commit, Closure $effect): void { + $session = $checkout->activeSession(); + $checkout->reserve(); + $reason = Reason::OperationUnconfirmed; + try { + $effect('UNKNOWN'); + $checkout->inspect(true, $session); + $reason = $commit ? Reason::CommitOutcomeUnknown : Reason::RollbackUnconfirmed; + $checkout->control($commit ? 'COMMIT AND NO CHAIN NO RELEASE' : 'ROLLBACK AND NO CHAIN NO RELEASE'); + $effect($commit ? 'COMMITTED' : 'ROLLED_BACK'); + if ($commit) { + $reason = Reason::CommitConfirmedConnectionUnsafe; + } + $checkout->inspect(false, $session); + $checkout->settle(Disposition::Reusable, $commit ? Reason::Committed : Reason::RolledBack); + } catch (Throwable $failure) { + $checkout->settle(Disposition::DiscardRequired, $reason); + + throw $failure; + } finally { + $checkout->busy = false; + } + }, + null, + PdoProtectedTransactionCheckout::class, + ); + if ($finish === null) { + throw new LogicException('Experiment could not reach the existing end reservation.'); + } + + $finish($this->checkout, $commit, function (string $effect): void { + $this->endEffect = $effect; + }); + } + + public function settlement(): ?ProtectedTransactionSettlementDTO + { + return $this->checkout->settlement(); + } + + public function returnForHost(): PDO + { + return $this->checkout->returnForHost(); + } + + public function discardForHost(): void + { + $this->checkout->discardForHost(); + } +} diff --git a/harness/verified-apply-discard/VerifiedApplyDiscardTest.php b/harness/verified-apply-discard/VerifiedApplyDiscardTest.php index b2de552..1577c4f 100644 --- a/harness/verified-apply-discard/VerifiedApplyDiscardTest.php +++ b/harness/verified-apply-discard/VerifiedApplyDiscardTest.php @@ -19,7 +19,8 @@ use RuntimeException; use Throwable; -require_once __DIR__ . '/CheckoutProof.php'; +$loader = require dirname(__DIR__, 2) . '/vendor/autoload.php'; +$loader->addPsr4(__NAMESPACE__ . '\\', __DIR__); final class VerifiedApplyDiscardTest extends IntegrationTestCase { @@ -51,8 +52,8 @@ public function testHostControlsFinalityAfterANormalResult(string $mode, bool $a self::assertSame([], $this->values($observer, $table)); $commit ? $checkout->commit() : $checkout->rollBack(); self::assertSame($commit ? $pending : [], $this->values($observer, $table)); - self::assertSame($commit ? 'COMMITTED' : 'ROLLED_BACK', $checkout->settlement()?->reason->name); - self::assertSame('REUSABLE', $checkout->settlement()?->disposition->name); + self::assertSame($commit ? 'Committed' : 'RolledBack', $checkout->settlement()?->reason->name); + self::assertSame('Reusable', $checkout->settlement()?->disposition->name); self::assertSame($writer, $checkout->returnForHost()); self::assertInstanceOf(ProtectedTransactionException::class, self::raised($checkout->returnForHost(...))); } @@ -97,7 +98,7 @@ public function testOwnedCanDeliverAResultOnlyAfterItsOwnEnd(bool $apply): void })); self::assertSame($apply ? [20] : [], $this->values($observer, $table)); self::assertSame($apply ? 'COMMITTED' : 'ROLLED_BACK', $checkout->ownedEffect); - self::assertSame('REUSABLE', $checkout->settlement()?->disposition->name); + self::assertSame('Reusable', $checkout->settlement()?->disposition->name); self::assertSame($writer, $checkout->returnForHost()); } @@ -255,11 +256,11 @@ public function testTransportSeparatesEndAcknowledgementFromConnectionDispositio self::assertSame($stage === 'after-ack' ? ($commit ? 'COMMITTED' : 'ROLLED_BACK') : 'UNKNOWN', $checkout->endEffect()); } $settlement = $checkout->settlement(); - self::assertSame('DISCARD_REQUIRED', $settlement?->disposition->name); + self::assertSame('DiscardRequired', $settlement?->disposition->name); self::assertSame(match (true) { - !$commit => 'ROLLBACK_UNCONFIRMED', - $stage === 'after-ack' => 'COMMIT_CONFIRMED_CONNECTION_UNSAFE', - default => 'COMMIT_OUTCOME_UNKNOWN', + !$commit => 'RollbackUnconfirmed', + $stage === 'after-ack' => 'CommitConfirmedConnectionUnsafe', + default => 'CommitOutcomeUnknown', }, $settlement?->reason->name); $expected = $commit && $stage !== 'before' ? ($mode === 'C2 owned' ? [20] : [10, 20]) : []; self::assertSame($expected, $this->values($observer, $table)); @@ -287,8 +288,8 @@ public function testOwnedThrowRetainsIdentityWhenRollbackReplyIsWithheld(): void self::assertSame('SERVER OK WITHHELD', $relay->readLine(12.0)); self::assertSame([], $this->values($observer, $table)); self::assertSame('UNKNOWN', $checkout->ownedEffect); - self::assertSame('ROLLBACK_UNCONFIRMED', $checkout->settlement()?->reason->name); - self::assertSame('DISCARD_REQUIRED', $checkout->settlement()?->disposition->name); + self::assertSame('RollbackUnconfirmed', $checkout->settlement()?->reason->name); + self::assertSame('DiscardRequired', $checkout->settlement()?->disposition->name); self::assertInstanceOf(ProtectedTransactionException::class, self::raised($checkout->returnForHost(...))); $checkout->discardForHost(); } finally { @@ -384,7 +385,7 @@ public function testTimeoutSwallowedByCallbackRemainsLatchedAndFences(string $mo $seen = self::failureOf(fn() => $command('update', ['id' => 3, 'value' => 32])); self::assertSame($seen, self::raised(fn() => $command('visible'))); - return new Decision(Intent::APPLY, false); + return new Decision(Intent::Apply, false); }; $failure = self::failureOf(fn() => $run($work)); self::assertSame($seen, $failure); @@ -420,7 +421,7 @@ public function testEndingAndRestartingThroughAnIneligibleAliasCannotPassUndo(st self::assertTrue($writer->inTransaction()); self::assertSame($session, $this->scalar($writer, 'SELECT CONNECTION_ID()')); - return new Decision(Intent::DISCARD, null); + return new Decision(Intent::Discard, null); })); self::assertSame(1305, self::driverCode($failure)); self::assertSame(['effect' => 'UNKNOWN', 'unconfirmed' => 'ROLLBACK TO SAVEPOINT'], $window->evidence()); @@ -550,7 +551,7 @@ private function businessOperation(bool $apply): Closure $row = $command('read', ['id' => 2]); self::assertSame([['v' => 20]], $row); - return $row[0]['v'] <= $limit ? new Decision(Intent::APPLY, false) : new Decision(Intent::DISCARD, null); + return $row[0]['v'] <= $limit ? new Decision(Intent::Apply, false) : new Decision(Intent::Discard, null); }; } @@ -565,7 +566,7 @@ private function assertHostRows(ProtectedCheckout|ParallelCheckout $checkout, ar private function assertFenced(ProtectedCheckout|ParallelCheckout $checkout, Closure $run): void { - self::assertSame('DISCARD_REQUIRED', $checkout->settlement()?->disposition->name); + self::assertSame('DiscardRequired', $checkout->settlement()?->disposition->name); self::assertInstanceOf(ProtectedTransactionException::class, self::raised($checkout->commit(...))); self::assertInstanceOf(ProtectedTransactionException::class, self::raised($checkout->rollBack(...))); self::assertInstanceOf(ProtectedTransactionException::class, self::raised($checkout->returnForHost(...))); diff --git a/harness/verified-apply-discard/CheckoutProof.php b/harness/verified-apply-discard/Window.php similarity index 55% rename from harness/verified-apply-discard/CheckoutProof.php rename to harness/verified-apply-discard/Window.php index 26cf518..b0755f6 100644 --- a/harness/verified-apply-discard/CheckoutProof.php +++ b/harness/verified-apply-discard/Window.php @@ -7,31 +7,11 @@ use Closure; use LogicException; use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandCatalog; -use Maatify\PhpPersistence\Transaction\DTO\ProtectedTransactionSettlementDTO; -use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum as Disposition; -use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionReasonEnum as Reason; use Maatify\PhpPersistence\Transaction\Repository\PdoProtectedTransactionCheckout; use Maatify\PhpPersistence\Transaction\Repository\ProtectedTransactionConnection; -use PDO; use RuntimeException; use Throwable; -enum Intent -{ - case APPLY; - case DISCARD; -} - -/** - * The proof callback's explicit Apply or Discard intent and independent - * result payload. The selected intent, rather than payload truthiness, - * controls how the fixture resolves the operation. - */ -final readonly class Decision -{ - public function __construct(public Intent $intent, public mixed $value) {} -} - /** * Experimental operation window. C1 uses this with the existing Host checkout. * C2 uses the same mechanism under a separate caller-facing fixture below. @@ -128,7 +108,7 @@ static function (PdoProtectedTransactionCheckout $checkout, Closure $operation): // A callback can catch a driver exception. It cannot clear the receiver's latch. $receiver->ensureAvailable(); if ($host) { - if ($result->intent === Intent::DISCARD) { + if ($result->intent === Intent::Discard) { $this->undo($receiver, $beforeControl); } else { $this->control($receiver, 'RELEASE SAVEPOINT', $beforeControl); @@ -144,7 +124,7 @@ static function (PdoProtectedTransactionCheckout $checkout, Closure $operation): if (!$host) { return $decision; } - if ($decision->intent === Intent::APPLY) { + if ($decision->intent === Intent::Apply) { $this->effect = 'PENDING_HOST'; } @@ -228,156 +208,3 @@ private function control(ProtectedTransactionConnection $receiver, string $comma $this->unconfirmed = null; } } - -/** - * Historical proof fixture for verified Apply and Discard. Both paths use - * the Protected checkout claim and private reservation seam to test actual - * exclusivity. The production Verified checkout is implemented separately. - */ -final class ParallelCheckout -{ - private readonly PdoProtectedTransactionCheckout $checkout; - public readonly Window $window; - public string $ownedEffect = 'NOT_STARTED'; - private ?string $endEffect = null; - - public function __construct(PDO $pdo, ProtectedTransactionCommandCatalog $catalog) - { - $this->checkout = PdoProtectedTransactionCheckout::attachExclusive($pdo, $catalog); - $this->window = new Window($this->checkout, $catalog); - } - - public function beginHost(): void - { - $this->checkout->begin(); - } - - /** @param array $bindings */ - public function hostCommand(string $id, array $bindings = []): int|array - { - return $this->checkout->runRegisteredCommand($id, $bindings); - } - - /** - * Uses the local savepoint and returns the payload after applying or undoing - * the window. The Host still controls the outer transaction. - * - * @param Closure(Closure(string, array): (int|array)): Decision $work - */ - public function runInHost(Closure $work, ?Closure $fault = null): mixed - { - return $this->window->run($work, beforeControl: $fault); - } - - /** - * Starts and ends the entire fixture transaction according to the explicit - * decision before returning its payload. An escaping callback error remains - * primary if cleanup also fails. - * - * @param Closure(Closure(string, array): (int|array)): Decision $work - */ - public function runOwned(Closure $work): mixed - { - $this->checkout->begin(); - try { - $decision = $this->window->run($work, host: false); - if (!$decision instanceof Decision) { - throw new LogicException('Unexpected owned decision type in proof.'); - } - } catch (Throwable $primary) { - $this->ownedEffect = $this->window->entered() ? 'UNKNOWN' : 'NOT_STARTED'; - if ($this->checkout->settlement() === null) { - try { - $this->rollBack(); - } catch (Throwable) { - // Keep the callback as the primary failure. - } finally { - $this->ownedEffect = $this->endEffect ?? $this->ownedEffect; - } - } - - throw $primary; - } - - try { - $this->finish($decision->intent === Intent::APPLY); - } finally { - $this->ownedEffect = $this->endEffect ?? 'UNKNOWN'; - } - - return $decision->value; - } - - public function commit(): void - { - $this->finish(true); - } - - public function rollBack(): void - { - $this->finish(false); - } - - public function endEffect(): ?string - { - return $this->endEffect; - } - - /** - * Compare C2's end-effect projection under the real lease. Capture the ACK - * between the end SQL and idle probe. The existing settlement is retained - * as the source of the connection disposition, with its original enum. - */ - private function finish(bool $commit): void - { - $finish = Closure::bind( - static function (PdoProtectedTransactionCheckout $checkout, bool $commit, Closure $effect): void { - $session = $checkout->activeSession(); - $checkout->reserve(); - $reason = Reason::OPERATION_UNCONFIRMED; - try { - $effect('UNKNOWN'); - $checkout->inspect(true, $session); - $reason = $commit ? Reason::COMMIT_OUTCOME_UNKNOWN : Reason::ROLLBACK_UNCONFIRMED; - $checkout->control($commit ? 'COMMIT AND NO CHAIN NO RELEASE' : 'ROLLBACK AND NO CHAIN NO RELEASE'); - $effect($commit ? 'COMMITTED' : 'ROLLED_BACK'); - if ($commit) { - $reason = Reason::COMMIT_CONFIRMED_CONNECTION_UNSAFE; - } - $checkout->inspect(false, $session); - $checkout->settle(Disposition::REUSABLE, $commit ? Reason::COMMITTED : Reason::ROLLED_BACK); - } catch (Throwable $failure) { - $checkout->settle(Disposition::DISCARD_REQUIRED, $reason); - - throw $failure; - } finally { - $checkout->busy = false; - } - }, - null, - PdoProtectedTransactionCheckout::class, - ); - if ($finish === null) { - throw new LogicException('Experiment could not reach the existing end reservation.'); - } - - $finish($this->checkout, $commit, function (string $effect): void { - $this->endEffect = $effect; - }); - } - - public function settlement(): ?ProtectedTransactionSettlementDTO - { - return $this->checkout->settlement(); - } - - public function returnForHost(): PDO - { - return $this->checkout->returnForHost(); - } - - public function discardForHost(): void - { - $this->checkout->discardForHost(); - } -} diff --git a/llms.txt b/llms.txt index 9e869a4..cee3927 100644 --- a/llms.txt +++ b/llms.txt @@ -9,7 +9,7 @@ This map is for package consumers. Use the Package Reference for the public runt - [PHP_PERSISTENCE_PACKAGE_REFERENCE.md](PHP_PERSISTENCE_PACKAGE_REFERENCE.md): the canonical, complete Public Runtime API inventory, behavior contracts, exception semantics, concurrency/transaction limits, and database-support claim. - [README.md](README.md): package overview, installation/access state, requirements, and a Public Runtime API overview. - [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md): a capability map and an `Input → Public Call → Result → Boundary` walkthrough for each capability. -- [examples/](examples/): maintained, runnable examples that use only the Public API and the production autoload. +- [examples/](examples/): maintained standalone and Host-dependent examples that use only the Public API and the production autoload. ## Release and support diff --git a/scripts/Tooling/IntegrationInterrupted.php b/scripts/Tooling/IntegrationInterrupted.php new file mode 100644 index 0000000..65b9093 --- /dev/null +++ b/scripts/Tooling/IntegrationInterrupted.php @@ -0,0 +1,12 @@ + 'UNKNOWN', 'transactions' => array_map( static fn(array $row): array => [ - 'id' => $row['id'], 'process' => $row['thread'], 'thread' => null, - 'event' => null, 'eventState' => null, 'endEvent' => null, 'state' => 'UNKNOWN', 'reason' => $reason, + 'id' => $row['id'], + 'process' => $row['thread'], + 'thread' => null, + 'event' => null, + 'eventState' => null, + 'endEvent' => null, + 'state' => 'UNKNOWN', + 'reason' => $reason, ], $transactions, ), diff --git a/scripts/Tooling/OrchestrationBudget.php b/scripts/Tooling/OrchestrationBudget.php new file mode 100644 index 0000000..5deb1cd --- /dev/null +++ b/scripts/Tooling/OrchestrationBudget.php @@ -0,0 +1,13 @@ + all tokens including whitespace and comments + * Delimiters and operators of lower precedence than a pipe in PHP 8.5. + * Closing delimiters also end the innermost expression. + */ +const PIPE_CHAIN_BOUNDARIES = [ + ')', + ']', + '}', + T_ATTRIBUTE, + T_CURLY_OPEN, + T_DOLLAR_OPEN_CURLY_BRACES, + ',', + ';', + '?', + ':', + '=', + '|', + '^', + '<', + '>', + T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, + T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, + T_BOOLEAN_AND, + T_BOOLEAN_OR, + T_COALESCE, + T_COALESCE_EQUAL, + T_DOUBLE_ARROW, + T_IS_EQUAL, + T_IS_NOT_EQUAL, + T_IS_IDENTICAL, + T_IS_NOT_IDENTICAL, + T_IS_SMALLER_OR_EQUAL, + T_IS_GREATER_OR_EQUAL, + T_SPACESHIP, + T_LOGICAL_AND, + T_LOGICAL_OR, + T_LOGICAL_XOR, + T_PLUS_EQUAL, + T_MINUS_EQUAL, + T_MUL_EQUAL, + T_DIV_EQUAL, + T_CONCAT_EQUAL, + T_MOD_EQUAL, + T_AND_EQUAL, + T_OR_EQUAL, + T_XOR_EQUAL, + T_SL_EQUAL, + T_SR_EQUAL, + T_POW_EQUAL, + T_THROW, + T_INCLUDE, + T_INCLUDE_ONCE, + T_REQUIRE, + T_REQUIRE_ONCE, + T_PRINT, + T_YIELD, + T_YIELD_FROM, + T_CLOSE_TAG, +]; + +/** + * @return list all tokens including whitespace and comments */ function tokenize(string $source): array { $tokens = []; $line = 1; + $startsLine = true; foreach (token_get_all($source) as $token) { - if (is_array($token)) { - $tokens[] = ['id' => $token[0], 'text' => $token[1], 'line' => $token[2]]; - $line = $token[2] + substr_count($token[1], "\n"); - - continue; + [$id, $text, $line] = is_array($token) ? $token : [$token, $token, $line]; + $tokens[] = ['id' => $id, 'text' => $text, 'line' => $line, 'startsLine' => $startsLine]; + $lastBreak = strrpos($text, "\n"); + if ($lastBreak === false) { + $startsLine = $startsLine && trim($text, " \t") === ''; + } else { + $line += substr_count($text, "\n"); + $startsLine = trim(substr($text, $lastBreak + 1), " \t") === ''; } - $tokens[] = ['id' => $token, 'text' => $token, 'line' => $line]; - $line += substr_count($token, "\n"); } return $tokens; } /** - * @param list $tokens - * @return list significant tokens only + * @param list $tokens + * @return list significant tokens only */ function significant(array $tokens): array { @@ -359,51 +441,89 @@ function endsWithTerminator(array $sig, int $first, int $semicolon): bool } /** + * Collects operator token positions by expression. A separator finishes the + * current chain without combining separate arguments, branches, or statements. + * Nested expressions have their own chains. + * * @param list $tokens + * @return list> + */ +function pipeChains(array $tokens, int $pipe): array +{ + $chains = []; + $active = []; + $depth = 0; + foreach ($tokens as $i => $token) { + $id = $token['id']; + if ($id === $pipe) { + $active[$depth][] = $i; + } elseif (in_array($id, ['(', '[', '{', T_ATTRIBUTE, T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) { + $depth++; + } elseif (in_array($id, PIPE_CHAIN_BOUNDARIES, true)) { + if (isset($active[$depth])) { + $chains[] = $active[$depth]; + unset($active[$depth]); + } + if (in_array($id, [')', ']', '}'], true)) { + $depth--; + } + } + } + + return [...$chains, ...array_values($active)]; +} + +/** + * @param list $tokens + * @param list $sig * @param list $lines * @return list */ -function checkPipe(string $file, array $tokens, array $lines): array +function checkPipe(string $file, array $tokens, array $sig, array $lines): array { $findings = []; $pipe = defined('T_PIPE') ? constant('T_PIPE') : null; - $count = count($tokens); - $baseIndent = 0; - $lastLineChecked = 0; + if (!is_int($pipe)) { + foreach ($tokens as $i => $token) { + if ($token['id'] === '|' && ($tokens[$i + 1]['id'] ?? null) === '>') { + $findings[] = $file . ':' . $token['line'] . ': pipe operator requires a PHP version that supports it'; + } + } - for ($i = 0; $i < $count; $i++) { - $token = $tokens[$i]; - $isPipe = $pipe !== null && $token['id'] === $pipe; - if ($pipe === null && $token['id'] === '|' && ($tokens[$i + 1]['id'] ?? null) === '>') { - $findings[] = $file . ':' . $token['line'] . ': pipe operator requires a PHP version that supports it'; + return $findings; + } - continue; - } - if (!$isPipe) { - continue; - } - $before = $tokens[$i - 1] ?? null; - $after = $tokens[$i + 1] ?? null; - if ($before === null || $before['id'] !== T_WHITESPACE || $after === null || $after['id'] !== T_WHITESPACE) { + foreach ($tokens as $i => $token) { + if ($token['id'] === $pipe && (($tokens[$i - 1]['id'] ?? null) !== T_WHITESPACE + || ($tokens[$i + 1]['id'] ?? null) !== T_WHITESPACE) + ) { $findings[] = $file . ':' . $token['line'] . ': the pipe operator needs a space before and after'; + } + } - continue; + foreach (pipeChains($sig, $pipe) as $chain) { + $first = $chain[0]; + $last = $chain[count($chain) - 1]; + $split = $sig[$first]['line'] !== $sig[$last]['line']; + foreach ($chain as $i) { + if (firstOnLine($sig, $i) || (isset($sig[$i + 1]) && endsLine($sig[$i], $sig[$i + 1]))) { + $split = true; + break; + } } - if (str_contains($after['text'], "\n")) { - $findings[] = $file . ':' . $token['line'] . ': in a split pipe chain each line starts with the operator'; + if (!$split) { + continue; } - if (str_contains($before['text'], "\n") && $token['line'] !== $lastLineChecked) { - $lastLineChecked = $token['line']; - $pipeIndent = indentOf($lines, $token['line']); - for ($line = $token['line'] - 1; $line >= 1; $line--) { - if (!str_starts_with(ltrim($lines[$line - 1] ?? ''), '|>')) { - $baseIndent = indentOf($lines, $line); - break; - } - } - if ($pipeIndent <= $baseIndent) { - $findings[] = $file . ':' . $token['line'] . ': continuation lines of a pipe chain must be indented'; + $start = operatorExpressionStart($sig, $first, extraBoundaries: PIPE_CHAIN_BOUNDARIES); + $indent = indentOf($lines, $sig[$start]['line']) + 4; + foreach ($chain as $i) { + $token = $sig[$i]; + $line = $token['line']; + if (!$token['startsLine'] || !isset($sig[$i + 1]) || endsLine($token, $sig[$i + 1])) { + $findings[] = $file . ':' . $line . ': in a split pipe chain each line starts with the operator'; + } elseif (!isIndentation($lines, $line, $indent)) { + $findings[] = $file . ':' . $line . ': continuation lines of a pipe chain must be indented once'; } } } @@ -524,63 +644,709 @@ function checkAnonymousClassAttributes(string $file, array $sig, array $lines): return $findings; } +/** Checks a declared PascalCase name, allowing an intentional one-letter name. */ +function usesPascalCase(string $name): bool +{ + return preg_match('/\A[A-Z][a-zA-Z0-9]*\z/', $name) === 1 + && (strlen($name) === 1 || preg_match('/[a-z]/', $name) === 1); +} + +/** + * Finds the opening class body brace, skipping anonymous constructor arguments. + * + * @param list $sig + */ +function classBodyStart(array $sig, int $start): ?int +{ + $i = $start + 1; + if (($sig[$i]['id'] ?? null) === '(') { + $close = matching($sig, $i); + if ($close === null) { + return null; + } + $i = $close + 1; + } + for (; isset($sig[$i]) && !in_array($sig[$i]['id'], [';', '}'], true); $i++) { + if ($sig[$i]['id'] === '{') { + return $i; + } + } + + return null; +} + +/** + * Inspects direct declarations in one class body, excluding nested blocks, + * arguments and attributes. The outer scan finds nested anonymous classes. + * + * @param list $sig + * @return list + */ +function checkClassBody(string $file, array $sig, int $open, int $close, bool $isEnum): array +{ + $findings = []; + for ($i = $open + 1; $i < $close; $i++) { + $token = $sig[$i]; + $id = $token['id']; + if ($id === T_FUNCTION) { + $nameIndex = ($sig[$i + 1]['text'] ?? '') === '&' ? $i + 2 : $i + 1; + $name = $sig[$nameIndex] ?? null; + if ($name !== null && $name['id'] !== '(' + && !in_array($name['text'], MAGIC_METHODS, true) + && preg_match('/\A[a-z][a-zA-Z0-9]*\z/', $name['text']) !== 1 + ) { + $findings[] = $file . ':' . $name['line'] . ': method names must use camelCase'; + } + } elseif ($isEnum && $id === T_CASE && isset($sig[$i + 1])) { + if (!usesPascalCase($sig[$i + 1]['text'])) { + $findings[] = $file . ':' . $token['line'] . ': enum case names must use PascalCase'; + } + } elseif ($isEnum && $id === T_PROTECTED) { + $findings[] = $file . ':' . $token['line'] . ': enum members use private instead of protected'; + } elseif (in_array($id, ['(', '[', '{', T_ATTRIBUTE, T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) { + $i = matching($sig, $i) ?? $i; + } + } + + return $findings; +} + /** + * Checks PSR-1 named class-like declarations and methods, and enum case style + * from PER Coding Style 3.1. Standalone functions and anonymous class names + * are outside the named declaration checks. + * * @param list $sig * @return list */ -function checkEnumMembers(string $file, array $sig): array +function checkDeclarations(string $file, array $sig): array { $findings = []; + $hasNamespace = false; + $namedTypes = 0; foreach ($sig as $i => $token) { - if ($token['id'] !== T_ENUM || ($sig[$i + 1]['id'] ?? null) !== T_STRING) { + $id = $token['id']; + $next = $sig[$i + 1]['id'] ?? null; + if ($id === T_NAMESPACE && in_array($next, [T_STRING, T_NAME_QUALIFIED, '{'], true)) { + $hasNamespace = $next !== '{'; + continue; } - $open = null; - for ($k = $i + 2; $k < count($sig); $k++) { - if ($sig[$k]['id'] === '{') { - $open = $k; - - break; - } + if (!in_array($id, [T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], true) + || ($sig[$i - 1]['id'] ?? null) === T_DOUBLE_COLON + || ($next !== T_STRING && !($id === T_CLASS && in_array($next, ['{', '(', T_EXTENDS, T_IMPLEMENTS], true))) + ) { + continue; } + $open = classBodyStart($sig, $i); $close = $open === null ? null : matching($sig, $open); if ($open === null || $close === null) { continue; } - for ($k = $open + 1; $k < $close; $k++) { - if ($sig[$k]['id'] === '{') { - // Method bodies and nested classes are not members of the enum. - $k = matching($sig, $k) ?? $k; + if ($next === T_STRING) { + $name = $sig[$i + 1]['text']; + $location = $file . ':' . $token['line'] . ': '; + if (++$namedTypes > 1) { + $findings[] = $location . 'each named class-like declaration must be in its own file'; + } + if (!$hasNamespace) { + $findings[] = $location . 'named class-like declarations require a formal namespace'; + } + if (!usesPascalCase($name)) { + $findings[] = $location . 'named class-like declarations must use PascalCase'; + } + if (basename($file) !== $name . '.php') { + $findings[] = $location . 'a named class-like declaration must match its filename'; + } + } + array_push($findings, ...checkClassBody($file, $sig, $open, $close, $id === T_ENUM)); + } + + return $findings; +} + +/** + * Recognizes the return-type colon after a closure variable or parameter list. + * + * @param list $sig + */ +function isClosureReturnTypeColon(array $sig, int $colon): bool +{ + if (($sig[$colon - 1]['id'] ?? null) !== ')') { + return false; + } + $open = matchingOpen($sig, $colon - 1); + if ($open === null) { + return false; + } + $declaration = $open - (($sig[$open - 1]['text'] ?? '') === '&' ? 2 : 1); + + return in_array($sig[$declaration]['id'] ?? null, [T_FN, T_FUNCTION, T_USE], true); +} + +/** + * Returns the ternary separator for a question mark at expression level, ignoring + * nested groups and nullable types in closure signatures. + * + * @param list $sig + */ +function ternaryColon(array $sig, int $question): ?int +{ + $nested = 0; + $inReturnType = false; + for ($i = $question + 1; isset($sig[$i]); $i++) { + $id = $sig[$i]['id']; + if (in_array($id, [')', ']', '}', ',', ';', T_CLOSE_TAG], true)) { + return null; + } + if ($id === ':' && isClosureReturnTypeColon($sig, $i)) { + $inReturnType = true; + } elseif ($id === T_DOUBLE_ARROW || $id === '{') { + $inReturnType = false; + } + if (in_array($id, ['(', '[', '{', T_ATTRIBUTE, T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) { + $end = matching($sig, $i); + if ($end === null) { + return null; + } + $i = $end; + + continue; + } + if ($inReturnType) { + continue; + } + if ($id === '?') { + $nested++; + } elseif ($id === ':') { + if ($nested === 0) { + return $i; + } + $nested--; + } + } + + return null; +} + +/** Identifies tokens that can finish a left operand of a source operator. */ +function endsOperatorOperand(int|string|null $id): bool +{ + return in_array($id, [ + T_VARIABLE, + T_STRING, + T_LNUMBER, + T_DNUMBER, + T_CONSTANT_ENCAPSED_STRING, + T_END_HEREDOC, + T_NAME_QUALIFIED, + T_NAME_FULLY_QUALIFIED, + T_NAME_RELATIVE, + T_LINE, + T_FILE, + T_DIR, + T_CLASS_C, + T_CLASS, + T_METHOD_C, + T_FUNC_C, + T_NS_C, + T_TRAIT_C, + T_PROPERTY_C, + T_INC, + T_DEC, + ')', + ']', + '}', + '"', + '`', + ], true); +} + +/** + * A brace can close an operand (such as a match expression or a closure) + * or a statement which can be followed by a standalone unary expression. + * + * @param list $sig + */ +function endsBraceOperand(array $sig, int $close): bool +{ + $open = matchingOpen($sig, $close); + if ($open === null) { + return false; + } + if (in_array($sig[$open]['id'], [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true) + || in_array($sig[$open - 1]['id'] ?? null, [T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR, '$'], true) + ) { + return true; + } + for ($i = $open - 1; $i >= 0; $i--) { + $id = $sig[$i]['id']; + if ($id === T_MATCH) { + return true; + } + if ($id === T_CLASS) { + return in_array($sig[$i + 1]['id'], ['{', '(', T_EXTENDS, T_IMPLEMENTS], true); + } + if ($id === T_FUNCTION) { + $parameters = $sig[$i + 1]['text'] === '&' ? $i + 2 : $i + 1; + + return $sig[$parameters]['id'] === '('; + } + if (in_array($id, [ + T_IF, + T_ELSEIF, + T_ELSE, + T_WHILE, + T_FOR, + T_FOREACH, + T_SWITCH, + T_CATCH, + T_TRY, + T_FINALLY, + T_DO, + T_NAMESPACE, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ';', + '{', + '}', + '[', + '=', + '(', + ], true)) { + return false; + } + if ($id === ')') { + $i = matchingOpen($sig, $i) ?? $i; + } + } + return false; +} + +/** + * Checks the required space-only indentation at a continuation line. + * + * @param list $lines + */ +function isIndentation(array $lines, int $line, int $spaces): bool +{ + $text = $lines[$line - 1] ?? ''; + + return substr($text, 0, indentOf($lines, $line)) === str_repeat(' ', $spaces); +} + +/** + * Finds the first token of an expression at its own nesting level. + * Closing groups inside the expression are skipped while walking backward. + * + * @param list $sig + * @param list $extraBoundaries + */ +function operatorExpressionStart( + array $sig, + int $operator, + bool $lowPrecedence = false, + bool $shortTernary = false, + array $extraBoundaries = [], +): int { + $boundaries = [ + '(', + '[', + '{', + ',', + ';', + '=', + '?', + ':', + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + T_ECHO, + T_RETURN, + T_THROW, + T_YIELD, + T_YIELD_FROM, + T_DOUBLE_ARROW, + T_COALESCE_EQUAL, + T_PLUS_EQUAL, + T_MINUS_EQUAL, + T_MUL_EQUAL, + T_DIV_EQUAL, + T_CONCAT_EQUAL, + T_MOD_EQUAL, + T_AND_EQUAL, + T_OR_EQUAL, + T_XOR_EQUAL, + T_SL_EQUAL, + T_SR_EQUAL, + T_POW_EQUAL, + ]; + if (!$lowPrecedence) { + array_push($boundaries, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR); + } + for ($i = $operator - 1; $i >= 0; $i--) { + $id = $sig[$i]['id']; + if ($shortTernary && $id === ':' && ($sig[$i - 1]['id'] ?? null) === '?') { + $i--; + + continue; + } + if (in_array($id, [')', ']', '}'], true) && ($open = matchingOpen($sig, $i)) !== null) { + $i = $open; + + continue; + } + if (in_array($id, $boundaries, true) || in_array($id, $extraBoundaries, true)) { + return $i + 1; + } + } + + return 0; +} + +/** + * Marks operator-shaped tokens in parameter types and references, excluding + * attributes and default value expressions. + * + * @param list $sig + * @param array $symbols + */ +function markParameterSymbols(array $sig, int $open, int $close, array &$symbols): void +{ + $beforeName = true; + for ($i = $open + 1; $i < $close; $i++) { + $id = $sig[$i]['id']; + if ($id === T_ATTRIBUTE || (!$beforeName && in_array($id, ['(', '[', '{'], true))) { + $i = matching($sig, $i) ?? $i; + } elseif ($id === ',') { + $beforeName = true; + } elseif ($id === T_VARIABLE) { + $beforeName = false; + } elseif ($beforeName && ($id === '|' || $sig[$i]['text'] === '&')) { + $symbols[$i] = true; + } + } +} + +/** + * Collects positions of union/intersection tokens used by PHP declarations. + * PHP uses the same token IDs for bitwise expressions, type syntax and references. + * + * @param list $sig + * @return array + */ +function declarationSymbols(array $sig): array +{ + $symbols = []; + $memberTypes = [ + T_STRING, + T_NAME_QUALIFIED, + T_NAME_FULLY_QUALIFIED, + T_NAME_RELATIVE, + T_STATIC, + T_ARRAY, + T_CALLABLE, + T_FINAL, + T_READONLY, + T_PRIVATE, + T_PROTECTED, + T_PUBLIC, + T_PRIVATE_SET, + T_PROTECTED_SET, + T_PUBLIC_SET, + '?', + '|', + '(', + ')', + T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, + T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, + ]; + foreach ($sig as $i => $token) { + $kind = $token['id']; + if (in_array($kind, [T_FUNCTION, T_FN, T_CATCH], true)) { + $parameter = $i + 1; + if (($sig[$parameter]['text'] ?? null) === '&') { + $parameter++; + } + // Named declarations have one token between the keyword and the parameter list. + if (($sig[$parameter]['id'] ?? null) !== '(') { + $parameter++; + } + $end = ($sig[$parameter]['id'] ?? null) === '(' ? matching($sig, $parameter) : null; + if ($end === null) { continue; } - if ($sig[$k]['id'] === T_PROTECTED) { - $findings[] = $file . ':' . $sig[$k]['line'] . ': enum members use private instead of protected'; + markParameterSymbols($sig, $parameter, $end, $symbols); + if (($sig[$end + 1]['id'] ?? null) === T_USE && ($sig[$end + 2]['id'] ?? null) === '(') { + $end = matching($sig, $end + 2) ?? $end; + } + if (($sig[$end + 1]['id'] ?? null) !== ':') { + continue; + } + for ($type = $end + 2; isset($sig[$type]) && in_array($sig[$type]['id'], $memberTypes, true); $type++) { + if ($sig[$type]['text'] === '|' || $sig[$type]['text'] === '&') { + $symbols[$type] = true; + } + } + } elseif (in_array($kind, [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_PRIVATE_SET, T_PROTECTED_SET, T_PUBLIC_SET, T_READONLY, T_VAR, T_CONST], true)) { + $typePositions = []; + for ($type = $i + 1; isset($sig[$type]) && in_array($sig[$type]['id'], $memberTypes, true); $type++) { + if ($sig[$type]['text'] === '|' || $sig[$type]['text'] === '&') { + $typePositions[$type] = true; + } + } + $afterType = $sig[$type]['id'] ?? null; + if ($afterType === T_VARIABLE || ($kind === T_CONST && $afterType === '=')) { + $symbols += $typePositions; } } } - return $findings; + return $symbols; } /** + * Returns the opening token to which a split logical condition is aligned. + * Parenthesized subconditions can group their own lines. A call or an indexing + * expression inside a control condition instead has its own expression rules. + * * @param list $sig + */ +function logicalControlStart(array $sig, int $index): ?int +{ + $anchor = null; + for ($i = $index - 1; $i > 0; $i--) { + $id = $sig[$i]['id']; + if ($id === '(') { + $before = $sig[$i - 1]['id']; + if (in_array($before, [T_IF, T_ELSEIF, T_WHILE, T_FOR, T_FOREACH, T_SWITCH, T_MATCH, T_CASE], true)) { + return $anchor ?? $i - 1; + } + if (endsOperatorOperand($before)) { + return null; + } + $anchor ??= $i; + } elseif (in_array($id, ['[', '{', T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_ATTRIBUTE, T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) { + return null; + } elseif (in_array($id, [')', ']', '}'], true)) { + $i = matchingOpen($sig, $i) ?? $i; + } + } + + return null; +} + +/** + * Checks operators whose placement actually breaks a line. Indentation is + * relative to their expression, or the keyword for a direct control condition. + * Inline operators inside otherwise multiline expressions stay inline. + * + * @param list $sig + * @param list $lines * @return list */ -function checkArrayBrackets(string $file, array $sig): array +function checkSplitBinaryOperators(string $file, array $sig, array $lines): array { $findings = []; + $operators = [ + T_POW, + '*', + '/', + '%', + '+', + '-', + '<', + T_IS_SMALLER_OR_EQUAL, + '>', + T_IS_GREATER_OR_EQUAL, + T_IS_EQUAL, + T_IS_NOT_EQUAL, + T_IS_IDENTICAL, + T_IS_NOT_IDENTICAL, + T_SPACESHIP, + '=', + T_PLUS_EQUAL, + T_MINUS_EQUAL, + T_MUL_EQUAL, + T_POW_EQUAL, + T_DIV_EQUAL, + T_CONCAT_EQUAL, + T_MOD_EQUAL, + T_AND_EQUAL, + T_OR_EQUAL, + T_XOR_EQUAL, + T_SL_EQUAL, + T_SR_EQUAL, + T_COALESCE_EQUAL, + T_SL, + T_SR, + T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, + T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, + '^', + '|', + T_BOOLEAN_AND, + T_BOOLEAN_OR, + T_LOGICAL_AND, + T_LOGICAL_XOR, + T_LOGICAL_OR, + T_COALESCE, + '.', + T_INSTANCEOF, + ]; + $declarations = declarationSymbols($sig); foreach ($sig as $i => $token) { - if ($token['id'] !== '[' || $i === 0 || !firstOnLine($sig, $i)) { + $shortTernary = $token['id'] === '?' && ($sig[$i + 1]['id'] ?? null) === ':'; + if ((!$shortTernary && !in_array($token['id'], $operators, true)) + || isset($declarations[$i]) || !endsOperatorOperand($sig[$i - 1]['id'] ?? null) + ) { + continue; + } + $last = $i + (int) $shortTernary; + $next = $sig[$last + 1] ?? null; + $first = firstOnLine($sig, $i); + if ($next === null || (!$first && !endsLine($sig[$i], $next))) { continue; } - if (in_array($sig[$i - 1]['id'], EXPRESSION_PREVIOUS, true)) { + $line = $token['line']; + $name = $shortTernary ? '?:' : $token['text']; + if (in_array($token['id'], ['+', '-'], true) && ($sig[$i - 1]['id'] ?? null) === '}' + && !endsBraceOperand($sig, $i - 1) + ) { + // After a standalone block, a unary sign can begin a new statement. + continue; + } + if (!$first || !$token['startsLine'] || endsLine($sig[$i], $next)) { + $findings[] = $file . ':' . $line . ': a split operator must start its operand line (' . $name . ')'; + + continue; + } + $lowPrecedence = in_array($token['id'], [T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR], true); + $logical = $lowPrecedence || in_array($token['id'], [T_BOOLEAN_AND, T_BOOLEAN_OR], true); + $control = $logical ? logicalControlStart($sig, $i) : null; + $start = $control ?? operatorExpressionStart($sig, $i, $lowPrecedence, $shortTernary); + if (!isIndentation($lines, $line, indentOf($lines, $sig[$start]['line']) + 4)) { + $findings[] = $file . ':' . $line . ': each split operator continuation must be indented once (' . $name . ')'; + } + } + + return $findings; +} + +/** + * Checks the two operators of a split ternary. A multiline call or array within + * an operand does not split the ternary unless an operator itself breaks a line. + * + * @param list $sig + * @param list $lines + * @return list + */ +function checkSplitTernaries(string $file, array $sig, array $lines): array +{ + $findings = []; + foreach ($sig as $i => $token) { + if ($token['id'] !== '?' || !isset($sig[$i + 1]) || $sig[$i + 1]['id'] === ':' + || !endsOperatorOperand($sig[$i - 1]['id'] ?? null) + ) { + continue; + } + $colon = ternaryColon($sig, $i); + if ($colon === null || !isset($sig[$colon + 1])) { + continue; + } + $split = firstOnLine($sig, $i) || firstOnLine($sig, $colon) + || endsLine($token, $sig[$i + 1]) || endsLine($sig[$colon], $sig[$colon + 1]); + if (!$split) { + continue; + } + if (!$token['startsLine'] || !$sig[$colon]['startsLine'] + || endsLine($token, $sig[$i + 1]) || endsLine($sig[$colon], $sig[$colon + 1]) + ) { + $findings[] = $file . ':' . $token['line'] . ': a split ternary must put each operator on its own continuation line'; + + continue; + } + $conditionLine = $sig[operatorExpressionStart($sig, $i)]['line']; + $indent = indentOf($lines, $conditionLine) + 4; + foreach ([$token['line'], $sig[$colon]['line']] as $line) { + if (!isIndentation($lines, $line, $indent)) { + $findings[] = $file . ':' . $line . ': each split ternary continuation must be indented once from its condition'; + } + } + } + + return $findings; +} + +/** + * A multiline unkeyed list value may open on its own line, as shown by + * the nested array in PER Coding Style 3.1 section 11. + * + * @param list $sig + */ +function isNestedListValue(array $sig, int $open): bool +{ + if (!in_array($sig[$open - 1]['id'] ?? null, ['[', ','], true)) { + return false; + } + for ($i = $open - 1; $i > 0; $i--) { + $id = $sig[$i]['id']; + if ($id === '[') { + return !in_array($sig[$i - 1]['id'], EXPRESSION_PREVIOUS, true); + } + if (in_array($id, ['(', '{', ';', T_OPEN_TAG], true)) { + return false; + } + if (in_array($id, [')', ']', '}'], true)) { + $i = matchingOpen($sig, $i) ?? $i; + } + } + + return false; +} + +/** + * Checks multiline short-array declarations without inspecting values inside + * nested expressions, and leaves multiline index access to the base formatter. + * + * @param list $sig + * @return list + */ +function checkArrays(string $file, array $sig): array +{ + $findings = []; + foreach ($sig as $i => $token) { + if ($token['id'] !== '[' || $i === 0 || in_array($sig[$i - 1]['id'], EXPRESSION_PREVIOUS, true)) { continue; } $close = matching($sig, $i); - if ($close !== null && $sig[$close]['line'] > $token['line']) { + if ($close === null || $sig[$close]['line'] <= $token['line']) { + continue; + } + if (firstOnLine($sig, $i) && !isNestedListValue($sig, $i)) { $findings[] = $file . ':' . $token['line'] . ': the opening bracket of a multi-line array must not stand alone on its line'; } + if ($i + 1 === $close || ($sig[$close + 1]['id'] ?? null) === '=' || $sig[$i - 1]['id'] === T_AS) { + // Empty arrays and short destructuring patterns have no declared values to check. + continue; + } + if (!endsLine($token, $sig[$i + 1])) { + $findings[] = $file . ':' . $sig[$i + 1]['line'] . ': the first value of a multi-line array must start on the line after its opening bracket'; + } + $lastValue = $sig[$close - 1]['id'] === ',' ? $close - 2 : $close - 1; + if (!endsLine($sig[$lastValue], $sig[$close])) { + $findings[] = $file . ':' . $sig[$close]['line'] . ': the closing bracket of a multi-line array must start on the line after its last value'; + } + for ($j = $i + 1; $j < $close; $j++) { + $id = $sig[$j]['id']; + if (in_array($id, ['(', '[', '{', T_ATTRIBUTE, T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) { + $j = matching($sig, $j) ?? $j; + } elseif ($id === ',' && $j + 1 < $close && !endsLine($sig[$j - 1], $sig[$j + 1])) { + $findings[] = $file . ':' . $sig[$j + 1]['line'] . ': each value of a multi-line array must start on a separate line'; + } + } } return $findings; @@ -604,11 +1370,13 @@ function checkSource(string $file, string $source): array return [ ...checkClone($file, $sig), ...checkSwitch($file, $sig, $comments), - ...checkPipe($file, $tokens, $lines), + ...checkPipe($file, $tokens, $sig, $lines), ...checkEmptyClosure($file, $tokens, $sig), ...checkAnonymousClassAttributes($file, $sig, $lines), - ...checkEnumMembers($file, $sig), - ...checkArrayBrackets($file, $sig), + ...checkDeclarations($file, $sig), + ...checkSplitTernaries($file, $sig, $lines), + ...checkSplitBinaryOperators($file, $sig, $lines), + ...checkArrays($file, $sig), ]; } @@ -618,7 +1386,7 @@ function checkSource(string $file, string $source): array */ function collectFiles(array $paths): array { - $skipped = ['vendor', '.git', 'docs', 'node_modules', '.phpunit.cache', '.phpstan']; + $skipped = ['vendor', '.git', 'node_modules', '.phpunit.cache', '.phpstan']; $files = []; foreach ($paths as $path) { if (is_file($path)) { diff --git a/scripts/consumer-verification.php b/scripts/consumer-verification.php index 0705fcf..e6d8720 100644 --- a/scripts/consumer-verification.php +++ b/scripts/consumer-verification.php @@ -5,6 +5,10 @@ /** * Runs Composer consumer and coexistence verification on two fresh services for the selected cell. */ + +use Maatify\PhpPersistence\Tooling\IntegrationInterrupted; +use Maatify\PhpPersistence\Tooling\OrchestrationBudget; + require __DIR__ . '/integration-support.php'; const CONSUMER_PACKAGE = 'maatify/php-persistence'; @@ -59,9 +63,15 @@ function runConsumerRoot(string $workspace, string $scenario, string $candidateR ]; $repositories = [$candidateRepository]; if ($scenario === 'differential') { - $repositories[] = ['type' => 'path', 'url' => $workspace . '/persistence-' . LEGACY_SOURCE_REF, 'options' => [ - 'symlink' => false, 'reference' => 'none', 'versions' => [LEGACY_PACKAGE => $legacyVersion], - ]]; + $repositories[] = [ + 'type' => 'path', + 'url' => $workspace . '/persistence-' . LEGACY_SOURCE_REF, + 'options' => [ + 'symlink' => false, + 'reference' => 'none', + 'versions' => [LEGACY_PACKAGE => $legacyVersion], + ], + ]; } $manifest = [ @@ -115,11 +125,13 @@ function runConsumerRoot(string $workspace, string $scenario, string $candidateR if (!is_array($abandoned) || ($abandoned['audit'] ?? null) !== 'fail' || array_key_exists('ignore', $abandoned)) { throw new RuntimeException('DEC-016 requires the default abandoned audit policy with no existing ignores'); } - $abandoned['ignore'] = [LEGACY_PACKAGE => [ - 'constraint' => LEGACY_RELEASE, - 'on-block' => false, - 'reason' => 'DEC-016: the exact legacy release is used only to verify migration coexistence.', - ]]; + $abandoned['ignore'] = [ + LEGACY_PACKAGE => [ + 'constraint' => LEGACY_RELEASE, + 'on-block' => false, + 'reason' => 'DEC-016: the exact legacy release is used only to verify migration coexistence.', + ], + ]; $manifest['config']['policy']['abandoned'] = $abandoned; $auditManifest = json_encode($manifest, JSON_THROW_ON_ERROR); if (file_put_contents($directory . '/composer.json', $auditManifest) !== strlen($auditManifest)) { @@ -243,8 +255,16 @@ function verifyConsumer(string $root, string $candidateRef, string $candidateTre /** @var array $policy */ $policy = $config['policy']; $legacyArchive = $workspace . '/legacy.tar.gz'; - consumerCommand(['curl', '--fail', '--silent', '--show-error', '--location', '--output', $legacyArchive, - 'https://codeload.github.com/Maatify/persistence/tar.gz/' . LEGACY_SOURCE_REF], $workspace); + consumerCommand([ + 'curl', + '--fail', + '--silent', + '--show-error', + '--location', + '--output', + $legacyArchive, + 'https://codeload.github.com/Maatify/persistence/tar.gz/' . LEGACY_SOURCE_REF, + ], $workspace); consumerCommand(['tar', '-xzf', $legacyArchive], $workspace); $status = EXIT_TEST_FAILURE; diff --git a/scripts/dependency-audit.php b/scripts/dependency-audit.php new file mode 100644 index 0000000..6d5b842 --- /dev/null +++ b/scripts/dependency-audit.php @@ -0,0 +1,154 @@ + ['composer.json'], + 'COMPOSER_VENDOR_DIR' => ['vendor'], + 'COMPOSER_POLICY' => ['1', 'true', 'on'], + 'COMPOSER_NO_BLOCKING' => ['0'], + 'COMPOSER_NO_SECURITY_BLOCKING' => ['0'], + 'COMPOSER_NO_AUDIT' => ['0'], + 'COMPOSER_NO_DEV' => ['0'], + 'COMPOSER_DISABLE_NETWORK' => ['0'], + 'COMPOSER_AUDIT_ABANDONED' => ['fail'], + 'COMPOSER_POLICY_ADVISORIES_BLOCK' => ['1', 'true', 'on'], + 'COMPOSER_POLICY_MALWARE_BLOCK' => ['1', 'true', 'on'], + ]; + + foreach ($allowed as $variable => $values) { + $value = getenv($variable); + if ($value !== false && !in_array($value, $values, true)) { + throw new RuntimeException($variable . ' is incompatible with the required dependency audit'); + } + } +} + +/** Reads the effective value reported by Composer, without printing its configuration. */ +function dependencyAuditConfig(string $key, string $directory): mixed +{ + [$status, $output] = execute([...DEPENDENCY_AUDIT_COMPOSER, 'config', $key], [], $directory); + if ($status !== 0) { + throw new RuntimeException('Cannot read Composer config ' . $key . ' (exit ' . $status . ')'); + } + + return json_decode($output, true, 512, JSON_THROW_ON_ERROR); +} + +/** Validates the policy and advisory source after Composer merges project and global config. */ +function checkDependencyAuditConfig(string $directory): void +{ + $policy = dependencyAuditConfig('policy', $directory); + $required = [ + 'advisories' => ['block' => true, 'audit' => 'fail'], + 'malware' => ['block' => true, 'block-scope' => 'all', 'audit' => 'fail'], + 'abandoned' => ['audit' => 'fail'], + ]; + $allowedExtras = [ + 'advisories' => ['ignore' => [], 'ignore-id' => [], 'ignore-severity' => []], + 'malware' => ['ignore' => [], 'ignore-source' => []], + 'abandoned' => ['ignore' => []], + ]; + if (!is_array($policy) || array_diff_key($policy, $required + ['ignore-unreachable' => null]) !== []) { + throw new RuntimeException('Unexpected Composer dependency policy configuration'); + } + + foreach ($required as $name => $settings) { + $actual = $policy[$name] ?? null; + if ($name === 'abandoned' && is_array($actual) && is_bool($actual['block'] ?? null)) { + unset($actual['block']); + } + if (!is_array($actual) || array_diff_key($actual, $settings + $allowedExtras[$name]) !== []) { + throw new RuntimeException('Unexpected Composer dependency policy settings for ' . $name); + } + foreach ($settings as $key => $value) { + if (($actual[$key] ?? null) !== $value) { + throw new RuntimeException('Required Composer dependency policy setting: ' . $name . '.' . $key); + } + } + foreach ($allowedExtras[$name] as $key => $value) { + if (($actual[$key] ?? []) !== $value) { + throw new RuntimeException('Dependency policy exceptions are prohibited for ' . $name . '.' . $key); + } + } + } + + $ignoreUnreachable = $policy['ignore-unreachable'] ?? null; + if ($ignoreUnreachable === null) { + $legacyAudit = dependencyAuditConfig('audit', $directory); + if (!is_array($legacyAudit)) { + throw new RuntimeException('Unexpected Composer audit configuration'); + } + $ignoreUnreachable = $legacyAudit['ignore-unreachable'] ?? false; + } + $isResolutionScope = static fn(mixed $scope): bool => in_array($scope, ['install', 'update'], true); + if ($ignoreUnreachable !== false && (!is_array($ignoreUnreachable) + || !array_is_list($ignoreUnreachable) + || array_filter($ignoreUnreachable, $isResolutionScope) !== $ignoreUnreachable) + ) { + throw new RuntimeException('Composer may not ignore an unreachable source during audit'); + } + + $repositories = dependencyAuditConfig('repositories', $directory); + $packagist = is_array($repositories) && count($repositories) === 1 ? ($repositories['packagist.org'] ?? null) : null; + if (!is_array($packagist) || count($packagist) !== 2 + || ($packagist['type'] ?? null) !== 'composer' + || ($packagist['url'] ?? null) !== 'https://repo.packagist.org' + ) { + throw new RuntimeException('Expected Composer to use the default Packagist advisory source'); + } + if (dependencyAuditConfig('disable-tls', $directory) !== false + || dependencyAuditConfig('secure-http', $directory) !== true + ) { + throw new RuntimeException('Composer audit requires secure HTTPS transport'); + } +} + +if (($argc ?? 0) !== 1) { + fwrite(STDERR, "Usage: php scripts/dependency-audit.php\n"); + exit(2); +} + +$directory = dirname(__DIR__); +try { + checkDependencyAuditEnvironment(); + [$status, $version] = execute([...DEPENDENCY_AUDIT_COMPOSER, '--version'], [], $directory); + if ($status !== 0 + || preg_match('/\AComposer version (\d+\.\d+\.\d+)(?:\s|\z)/', $version, $matches) !== 1 + || version_compare($matches[1], '2.10.0', '<') + ) { + throw new RuntimeException('Composer 2.10.0 or later is required'); + } + checkDependencyAuditConfig($directory); + $lock = $directory . '/composer.lock'; + if (!is_file($lock) || is_link($lock)) { + throw new RuntimeException('Resolve dependencies with composer update before running the dependency audit'); + } +} catch (JsonException|RuntimeException $error) { + fwrite(STDERR, 'Dependency audit: ' . $error->getMessage() . "\n"); + exit(1); +} + +$status = passthrough( + [...DEPENDENCY_AUDIT_COMPOSER, 'validate', '--strict', '--no-check-publish', '--check-lock'], + [], + $directory, + 120, +); +if ($status !== 0) { + exit($status); +} + +exit(passthrough( + [...DEPENDENCY_AUDIT_COMPOSER, 'audit', '--locked', '--abandoned=fail'], + [], + $directory, + 120, +)); diff --git a/scripts/examples-smoke.php b/scripts/examples-smoke.php index b088753..c5ed005 100644 --- a/scripts/examples-smoke.php +++ b/scripts/examples-smoke.php @@ -21,6 +21,8 @@ * Exit status: 0 success, 1 an example failed, 2 invalid usage or configuration, 3 infrastructure failure, 130 interrupted. */ +use Maatify\PhpPersistence\Tooling\IntegrationInterrupted; + require __DIR__ . '/integration-support.php'; /** @var list $argv */ diff --git a/scripts/integration-support.php b/scripts/integration-support.php index 18ebf6b..c819784 100644 --- a/scripts/integration-support.php +++ b/scripts/integration-support.php @@ -2,7 +2,11 @@ declare(strict_types=1); -require_once __DIR__ . '/integration-residue-shadow.php'; +use Maatify\PhpPersistence\Tooling\IntegrationInterrupted; +use Maatify\PhpPersistence\Tooling\IntegrationResidueShadow; +use Maatify\PhpPersistence\Tooling\OrchestrationBudget; + +require_once __DIR__ . '/Tooling/autoload.php'; /** * Functions of the Integration orchestration (see integration.php). @@ -21,11 +25,6 @@ const TIMEOUT_EXIT_STATUS = 124; const TERMINATION_GRACE_SECONDS = 5; -/** - * A catchable signal that unwinds owned work before Compose teardown. - */ -final class IntegrationInterrupted extends Exception {} - /** * Positive integer seconds from an environment variable, or the default when it is not set. * A set but invalid value is a configuration error. @@ -74,14 +73,6 @@ function startBudget(): void OrchestrationBudget::$deadline = microtime(true) + $budget; } -/** - * Absolute end of the overall budget; null until startBudget() ran. - */ -final class OrchestrationBudget -{ - public static ?float $deadline = null; -} - /** * Whole seconds of work that still fit in the budget once the teardown reserve is kept free. */ diff --git a/scripts/published-artifact.php b/scripts/published-artifact.php index 3f2a057..dad0b04 100644 --- a/scripts/published-artifact.php +++ b/scripts/published-artifact.php @@ -27,11 +27,19 @@ function publishedCommand(array $command, string $directory): string function publishedComposer(array $arguments, string $workspace): array { [$status, $output] = execute([ - 'env', '-i', 'PATH=' . (getenv('PATH') ?: '/usr/bin:/bin'), 'HOME=' . $workspace, + 'env', + '-i', + 'PATH=' . (getenv('PATH') ?: '/usr/bin:/bin'), + 'HOME=' . $workspace, 'COMPOSER_HOME=' . $workspace . '/composer-home', 'COMPOSER_CACHE_DIR=' . $workspace . '/composer-cache', - 'COMPOSER_NO_INTERACTION=1', 'GIT_CONFIG_NOSYSTEM=1', - 'composer', '--no-interaction', '--no-plugins', '--no-scripts', ...$arguments, + 'COMPOSER_NO_INTERACTION=1', + 'GIT_CONFIG_NOSYSTEM=1', + 'composer', + '--no-interaction', + '--no-plugins', + '--no-scripts', + ...$arguments, ], [], $workspace, 180); return [$status, trim($output)]; @@ -110,6 +118,10 @@ function publishedPackageEvidence(array $entry): array ]; } +/** + * Returns a recognizable version string for diagnostics, null when absent, + * or the redaction marker when the supplied value fails the evidence format. + */ function publishedVersionEvidence(mixed $version): ?string { return publishedSafeValue($version, '~\A(?:dev-main|v?[0-9]{1,8}(?:\.[0-9]{1,8}){1,3}(?:-(?:alpha|beta|rc)[.-]?[0-9]{1,8})?)\z~i'); @@ -388,8 +400,12 @@ function publishedContents(string $reference, string $installed, array $runtime, $root = dirname(__DIR__); $tag = 'refs/tags/v' . RELEASE_TARGET; publishedLog('EXPECTED', [ - 'package' => RELEASE_PACKAGE, 'target' => RELEASE_TARGET, 'sha' => $sha, 'tag' => $tag, - 'installationSource' => 'dist', 'installPath' => '../' . RELEASE_PACKAGE, + 'package' => RELEASE_PACKAGE, + 'target' => RELEASE_TARGET, + 'sha' => $sha, + 'tag' => $tag, + 'installationSource' => 'dist', + 'installPath' => '../' . RELEASE_PACKAGE, ]); $workspace = sys_get_temp_dir() . '/pp-published-' . bin2hex(random_bytes(12)); @@ -424,7 +440,9 @@ function publishedContents(string $reference, string $installed, array $runtime, 'composerExitCode' => $composerStatus, 'repository' => 'https://repo.packagist.org', 'installPreference' => 'dist', - 'plugins' => false, 'scripts' => false, 'isolatedHomeAndCache' => true, + 'plugins' => false, + 'scripts' => false, + 'isolatedHomeAndCache' => true, ]); if ($composerStatus !== 0 || !isset($versionMatches[1])) { throw new RuntimeException('Composer version is unavailable'); diff --git a/scripts/release-artifact.php b/scripts/release-artifact.php index 7c77b28..434e071 100644 --- a/scripts/release-artifact.php +++ b/scripts/release-artifact.php @@ -22,6 +22,7 @@ 'examples/ordering_unique_usage.php', 'examples/pagination_basic_usage.php', 'examples/pagination_dynamic_sort_usage.php', + 'examples/pagination_host_snapshot_usage.php', 'examples/pagination_keyset_usage.php', 'examples/pagination_snapshot_usage.php', 'examples/pagination_static_sort_usage.php', diff --git a/src/Ordering/Config/ScopedOrderingConfig.php b/src/Ordering/Config/ScopedOrderingConfig.php index f9a50a2..7110a58 100644 --- a/src/Ordering/Config/ScopedOrderingConfig.php +++ b/src/Ordering/Config/ScopedOrderingConfig.php @@ -30,12 +30,15 @@ { /** * @param non-empty-string $table Trusted table identifier, e.g. "maa_shipping_rates". - * @param non-empty-string|null $scopeColumn Optional scope column, e.g. "method_id". + * @param non-empty-string|null $scopeColumn Scope column, e.g. "method_id", or null for global ordering. * @param non-empty-string $idColumn Primary key column. Defaults to "id". * @param non-empty-string $orderColumn Ordering column. Defaults to "display_order". - * @param non-empty-string|null $deletedAtColumn Optional soft-delete column. Pass null for tables without soft delete. + * @param non-empty-string|null $deletedAtColumn Soft-delete column. Defaults to "deleted_at". Null disables filtering. * @param bool $nullableScope Whether a configured scope column may use NULL as a scope value. * @param non-empty-string|null $updatedAtColumn Optional mutation timestamp column updated with the target order. + * + * @throws InvalidOrderingConfigurationException If any supplied SQL identifier is invalid or a nullable scope + * is enabled without a scope column. */ public function __construct( public string $table, diff --git a/src/Ordering/Repository/OrderingOperations.php b/src/Ordering/Repository/OrderingOperations.php index 80dba8a..3e71b84 100644 --- a/src/Ordering/Repository/OrderingOperations.php +++ b/src/Ordering/Repository/OrderingOperations.php @@ -7,7 +7,7 @@ use Maatify\PhpPersistence\Ordering\Config\ScopedOrderingConfig; use Maatify\PhpPersistence\Ordering\Exception\InvalidOrderingOperationException; use Maatify\PhpPersistence\Ordering\Exception\OrderingExecutionException; -use Maatify\PhpPersistence\Transaction\Repository\PdoTransactionRunner; +use Maatify\PhpPersistence\Transaction\Repository\OwnedTransactionExecutor; use Maatify\PhpPersistence\Transaction\Repository\ProtectedTransactionConnection; use Maatify\PhpPersistence\Transaction\Repository\ProtectedTransactionStatement; use Maatify\PhpPersistence\Transaction\Repository\SavepointScope; @@ -37,7 +37,7 @@ public function getNextPosition( __FUNCTION__, 'SELECT COALESCE(MAX(' . $config->quotedOrderColumn() . '), 0) FROM ' . $config->quotedTable() - . $whereSql, + . $whereSql, ); $this->executeStatement($stmt, $params, __FUNCTION__); @@ -90,8 +90,8 @@ public function readStableTail( $operation, 'SELECT ' . $config->quotedOrderColumn() . ' FROM ' . $config->quotedTable() - . $whereSql - . ' ORDER BY ' . $config->quotedOrderColumn() . ' DESC, ' . $config->quotedIdColumn() . ' DESC + . $whereSql + . ' ORDER BY ' . $config->quotedOrderColumn() . ' DESC, ' . $config->quotedIdColumn() . ' DESC LIMIT 1 FOR UPDATE', ); @@ -137,33 +137,14 @@ public function moveWithinScope( ?string $updatedAtValue = null, ): bool { $this->validateMove($config, $scopeValue, $id, $newOrder, $updatedAtValue); - $rollbackResult = new class extends \RuntimeException {}; - $participating = $pdo->inTransaction(); - - try { - return (new PdoTransactionRunner($pdo))->run(function () use ( - $pdo, - $config, - $scopeValue, - $id, - $newOrder, - $updatedAtValue, - $participating, - $rollbackResult, - ): bool { - if (!$this->move($pdo, $config, $scopeValue, $id, $newOrder, $updatedAtValue, $participating)) { - throw $rollbackResult; - } - - return true; - }); - } catch (Throwable $failure) { - if ($failure === $rollbackResult) { - return false; - } - - throw $failure; + if ($pdo->inTransaction()) { + return $this->move($pdo, $config, $scopeValue, $id, $newOrder, $updatedAtValue, participating: true); } + + return (new OwnedTransactionExecutor($pdo, maxDeadlockRetries: 0))->run( + fn(): bool => $this->move($pdo, $config, $scopeValue, $id, $newOrder, $updatedAtValue, participating: false), + rollBackOnFalse: true, + ); } /** @@ -330,8 +311,8 @@ private function lockScopeForUpdate( __FUNCTION__, 'SELECT ' . $config->quotedIdColumn() . ', ' . $config->quotedOrderColumn() . ' FROM ' . $config->quotedTable() - . $whereSql - . ' ORDER BY ' . $config->quotedOrderColumn() . ' ASC, ' . $config->quotedIdColumn() . ' ASC + . $whereSql + . ' ORDER BY ' . $config->quotedOrderColumn() . ' ASC, ' . $config->quotedIdColumn() . ' ASC FOR UPDATE', ); @@ -704,9 +685,7 @@ private function assertScopeUsage( /** * Ensures that timestamp configuration and the operation value are used - * consistently. - * - * @param string|null $updatedAtValue Timestamp value for the target mutation. + * consistently and the supplied timestamp has an exact SQL date-time format. */ private function assertUpdatedAtUsage( ScopedOrderingConfig $config, @@ -723,5 +702,14 @@ private function assertUpdatedAtUsage( 'An updated-at column requires an updated-at value.', ); } + + if ($updatedAtValue !== null && ( + preg_match('/\A([0-9]{4})-([0-9]{2})-([0-9]{2}) (?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]{1,6})?\z/', $updatedAtValue, $date) !== 1 + || !checkdate((int) $date[2], (int) $date[3], (int) $date[1]) + )) { + throw new InvalidOrderingOperationException( + 'An updated-at value must be a valid YYYY-MM-DD HH:MM:SS timestamp with up to six fractional digits.', + ); + } } } diff --git a/src/Ordering/Repository/ProtectedScopedOrderingManager.php b/src/Ordering/Repository/ProtectedScopedOrderingManager.php index 77f37b0..338c205 100644 --- a/src/Ordering/Repository/ProtectedScopedOrderingManager.php +++ b/src/Ordering/Repository/ProtectedScopedOrderingManager.php @@ -60,7 +60,9 @@ public function getNextPositionForUpdate( * The positive target position is capped at the locked scope maximum, * with a minimum cap of 1. A null scope means global Ordering or the * configured nullable scope. Supply a timestamp exactly when an updated-at - * column is configured. + * column is configured. Use YYYY-MM-DD HH:MM:SS with an optional fraction of + * 1–6 digits. Invalid calendar and clock values are rejected before Ordering + * SQL is issued. The original string is bound to the target update. * * A successful move or no-op returns true. A missing row or an undone * zero-row update returns false. A mutating move uses a local savepoint. @@ -102,7 +104,7 @@ public function moveWithinScope( * * An eligibility rejection can leave the checkout active if resource * cleanup and transaction continuity are confirmed. After an exception, - * read the checkout's settlement(). DISCARD_REQUIRED fences further SQL + * read the checkout's settlement(). DiscardRequired fences further SQL * and requires the Host to call discardForHost(). * * @throws InvalidOrderingOperationException For a scope ID outside the profile. @@ -132,7 +134,7 @@ public function getNextUniquePositionForAppend( * * After a mutation fails, the checkout can remain active only if local * undo, resource cleanup and continuity are confirmed. After an exception, - * read the checkout's settlement(). DISCARD_REQUIRED fences further SQL + * read the checkout's settlement(). DiscardRequired fences further SQL * and requires the Host to call discardForHost(). * * @throws InvalidOrderingOperationException For an invalid identifier or position. @@ -164,7 +166,7 @@ public function moveUniqueWithinScope( * * After a mutation fails, the checkout can remain active only if local * undo, resource cleanup and continuity are confirmed. After an exception, - * read the checkout's settlement(). DISCARD_REQUIRED fences further SQL + * read the checkout's settlement(). DiscardRequired fences further SQL * and requires the Host to call discardForHost(). * * @throws InvalidOrderingOperationException For an invalid identifier or ineligible DELETE plan. diff --git a/src/Ordering/Repository/ScopedOrderingManager.php b/src/Ordering/Repository/ScopedOrderingManager.php index dfc73f2..b71fe0e 100644 --- a/src/Ordering/Repository/ScopedOrderingManager.php +++ b/src/Ordering/Repository/ScopedOrderingManager.php @@ -7,6 +7,7 @@ use Maatify\PhpPersistence\Ordering\Config\ScopedOrderingConfig; use Maatify\PhpPersistence\Ordering\Exception\InvalidOrderingOperationException; use Maatify\PhpPersistence\Ordering\Exception\OrderingExecutionException; +use Maatify\PhpPersistence\Transaction\Exception\TransactionExecutionException; use PDO; use Throwable; @@ -188,6 +189,8 @@ public function getNextPositionForUpdate( * - true when the target row is already at the requested/clamped position. * - false when the target row does not exist in the given scope. * - false when the target update affects zero rows and the move is undone. + * A false result from an owned move requires rollback acknowledgement and + * an idle PDO transaction state. A rollback failure propagates. * * In a caller-owned transaction, a range-shift or target-write failure * triggers best-effort cleanup of the operation-local savepoint @@ -195,7 +198,8 @@ public function getNextPositionForUpdate( * The helper attempts rollback to the savepoint if PDO reports an active * transaction, then attempts release only after rollback is acknowledged. * The original Throwable propagates unchanged. A zero-row target update - * requires a successful rollback to the savepoint before returning false. + * requires successful rollback to the savepoint and release before returning + * false. A failure of either control operation propagates. * A no-op move and a missing row issue no savepoint statement. A successful * mutation releases its savepoint. While the transaction remains active, * it retains the scope lock and the caller keeps earlier work and their @@ -215,10 +219,11 @@ public function getNextPositionForUpdate( * the server. * * @param int|string|null $scopeValue Required when config has a non-null scope column; null means global ordering or the configured nullable scope. - * @param string|null $updatedAtValue Timestamp value bound to the target update when updatedAtColumn is configured. + * @param string|null $updatedAtValue Valid YYYY-MM-DD HH:MM:SS with an optional fraction of 1–6 digits when configured. The original value is bound. * - * @throws InvalidOrderingOperationException When id/order/scope arguments are invalid. + * @throws InvalidOrderingOperationException When the row ID, order, scope or timestamp is invalid. * @throws OrderingExecutionException When a statement fails without throwing or a stored order cannot be represented as a PHP integer. + * @throws TransactionExecutionException When transaction control fails without throwing or required settlement cannot be confirmed. * @throws Throwable When a PDO/database operation throws. */ public function moveWithinScope( diff --git a/src/Pagination/Criteria/HostSnapshotCommandPlan.php b/src/Pagination/Criteria/HostSnapshotCommandPlan.php index e389c38..f9b0437 100644 --- a/src/Pagination/Criteria/HostSnapshotCommandPlan.php +++ b/src/Pagination/Criteria/HostSnapshotCommandPlan.php @@ -36,10 +36,10 @@ public function __construct( /** @internal */ public ?int $maxRows = null, /** @internal */ - public HostSnapshotCommandEffectEnum $effect = HostSnapshotCommandEffectEnum::INVALIDATE_GENERATION, + public HostSnapshotCommandEffectEnum $effect = HostSnapshotCommandEffectEnum::InvalidateGeneration, ) { if (trim($sql) === '' || str_contains($sql, ';') - || ($resultMode === HostSnapshotCommandResultModeEnum::BOUNDED_ROWS && ($maxRows === null || $maxRows < 1)) + || ($resultMode === HostSnapshotCommandResultModeEnum::BoundedRows && ($maxRows === null || $maxRows < 1)) ) { throw new HostSnapshotPaginationException('Invalid Host snapshot command plan.'); } diff --git a/src/Pagination/Criteria/HostSnapshotGrantRegistration.php b/src/Pagination/Criteria/HostSnapshotGrantRegistration.php deleted file mode 100644 index 0686f3d..0000000 --- a/src/Pagination/Criteria/HostSnapshotGrantRegistration.php +++ /dev/null @@ -1,20 +0,0 @@ -record->state; @@ -55,14 +62,14 @@ public function settlement(): ?HostSnapshotPageSettlementDTO */ public function read(): PageResultDTO { - if ($this->state() !== State::NEW) { + if ($this->state() !== State::New) { throw new HostSnapshotPaginationException('The Host snapshot attempt was already invoked.'); } $source = $this->source->get(); if ($source === null) { $this->record->finish(new HostSnapshotPageSettlementDTO( - HostSnapshotPageDispositionEnum::NOT_ACCEPTED, - HostSnapshotPageSettlementReasonEnum::SOURCE_UNAVAILABLE, + HostSnapshotPageDispositionEnum::NotAccepted, + HostSnapshotPageSettlementReasonEnum::SourceUnavailable, )); throw new HostSnapshotPaginationException('The Host snapshot source is unavailable.'); } @@ -72,13 +79,21 @@ public function read(): PageResultDTO private function __clone() {} - /** @return array */ + /** + * @return array + * + * @throws HostSnapshotPaginationException Always. The source tracks this invocation and its settlement by object identity. + */ public function __serialize(): array { throw new HostSnapshotPaginationException('A Host snapshot attempt cannot be serialized.'); } - /** @param array $data */ + /** + * @param array $data + * + * @throws HostSnapshotPaginationException Always. A page attempt must be registered with its source. + */ public function __unserialize(array $data): void { throw new HostSnapshotPaginationException('A Host snapshot attempt cannot be restored.'); diff --git a/src/Pagination/Criteria/HostSnapshotPageGrant.php b/src/Pagination/Criteria/HostSnapshotPageGrant.php index 5fe54fc..a2744aa 100644 --- a/src/Pagination/Criteria/HostSnapshotPageGrant.php +++ b/src/Pagination/Criteria/HostSnapshotPageGrant.php @@ -19,13 +19,21 @@ public static function issue(): self private function __clone() {} - /** @return array */ + /** + * @return array + * + * @throws HostSnapshotPaginationException Always. The grant is tied to a source's transaction generation. + */ public function __serialize(): array { throw new HostSnapshotPaginationException('A Host snapshot grant cannot be serialized.'); } - /** @param array $data */ + /** + * @param array $data + * + * @throws HostSnapshotPaginationException Always. The source must issue the page authorization. + */ public function __unserialize(array $data): void { throw new HostSnapshotPaginationException('A Host snapshot grant cannot be restored.'); diff --git a/src/Pagination/DTO/HostSnapshotPageSettlementDTO.php b/src/Pagination/DTO/HostSnapshotPageSettlementDTO.php index debca56..d0839dd 100644 --- a/src/Pagination/DTO/HostSnapshotPageSettlementDTO.php +++ b/src/Pagination/DTO/HostSnapshotPageSettlementDTO.php @@ -4,6 +4,7 @@ namespace Maatify\PhpPersistence\Pagination\DTO; +use JsonSerializable; use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotPageDispositionEnum; use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotPageSettlementReasonEnum; @@ -12,11 +13,24 @@ * The disposition describes the Host's authority after the attempt. The * reason explains the outcome and does not replace its original throwable. */ -final readonly class HostSnapshotPageSettlementDTO +final readonly class HostSnapshotPageSettlementDTO implements JsonSerializable { /** @internal Recorded by the source. */ public function __construct( public HostSnapshotPageDispositionEnum $disposition, public HostSnapshotPageSettlementReasonEnum $reason, ) {} + + /** + * Projects the stable settlement codes as strings. + * + * @return array{disposition: string, reason: string} + */ + public function jsonSerialize(): array + { + return [ + 'disposition' => $this->disposition->settlementCode(), + 'reason' => $this->reason->settlementCode(), + ]; + } } diff --git a/src/Pagination/DTO/SnapshotConnectionOutcomeDTO.php b/src/Pagination/DTO/SnapshotConnectionOutcomeDTO.php index c338dd3..b51b0ce 100644 --- a/src/Pagination/DTO/SnapshotConnectionOutcomeDTO.php +++ b/src/Pagination/DTO/SnapshotConnectionOutcomeDTO.php @@ -4,23 +4,37 @@ namespace Maatify\PhpPersistence\Pagination\DTO; +use JsonSerializable; use Maatify\PhpPersistence\Pagination\Enum\SnapshotConnectionDispositionEnum; use Maatify\PhpPersistence\Pagination\Exception\SnapshotPaginationException; /** Terminal disposition and optional safe diagnostic, separate from the page. */ -final readonly class SnapshotConnectionOutcomeDTO +final readonly class SnapshotConnectionOutcomeDTO implements JsonSerializable { /** * Records the terminal disposition independently of the page result or - * throwable. DISCARD requires a non-blank diagnostic describing the + * throwable. Discard requires a non-blank diagnostic describing the * unconfirmed stage, so the Host can retire the checkout. */ public function __construct( public SnapshotConnectionDispositionEnum $disposition, public ?string $diagnostic, ) { - if ($disposition === SnapshotConnectionDispositionEnum::DISCARD && ($diagnostic === null || trim($diagnostic) === '')) { + if ($disposition === SnapshotConnectionDispositionEnum::Discard && ($diagnostic === null || trim($diagnostic) === '')) { throw new SnapshotPaginationException('A discard outcome requires a diagnostic.'); } } + + /** + * Projects the stable disposition code and the optional diagnostic. + * + * @return array{disposition: string, diagnostic: ?string} + */ + public function jsonSerialize(): array + { + return [ + 'disposition' => $this->disposition->settlementCode(), + 'diagnostic' => $this->diagnostic, + ]; + } } diff --git a/src/Pagination/Enum/HostSnapshotAccessModeEnum.php b/src/Pagination/Enum/HostSnapshotAccessModeEnum.php index 620ecbe..ca2706d 100644 --- a/src/Pagination/Enum/HostSnapshotAccessModeEnum.php +++ b/src/Pagination/Enum/HostSnapshotAccessModeEnum.php @@ -6,6 +6,6 @@ enum HostSnapshotAccessModeEnum: string { - case READ_WRITE = 'READ WRITE'; - case READ_ONLY = 'READ ONLY'; + case ReadWrite = 'READ WRITE'; + case ReadOnly = 'READ ONLY'; } diff --git a/src/Pagination/Enum/HostSnapshotCheckoutStateEnum.php b/src/Pagination/Enum/HostSnapshotCheckoutStateEnum.php index de3badc..399be0e 100644 --- a/src/Pagination/Enum/HostSnapshotCheckoutStateEnum.php +++ b/src/Pagination/Enum/HostSnapshotCheckoutStateEnum.php @@ -6,20 +6,20 @@ /** * Authority and availability of a Host snapshot checkout. Only the qualified - * active state can authorize pages. RELEASED ends one handle's authority, while - * RETIRED denotes permanent retirement of its source. + * active state can authorize pages. Released ends one handle's authority, while + * Retired denotes permanent retirement of its source. */ enum HostSnapshotCheckoutStateEnum { /** The checkout is ready to begin. Release also requires resolved transaction settings. */ - case IDLE; - case TRANSACTION_ACTIVE; + case Idle; + case TransactionActive; /** An active transaction outlived invalidation and cannot authorize new pages. */ - case TRANSACTION_UNQUALIFIED; + case TransactionUnqualified; /** A reserved operation is still in progress. */ - case BUSY; + case Busy; /** The source fences further SQL pending the Host's retirement or discard decision. */ - case QUARANTINED; - case RELEASED; - case RETIRED; + case Quarantined; + case Released; + case Retired; } diff --git a/src/Pagination/Enum/HostSnapshotCommandEffectEnum.php b/src/Pagination/Enum/HostSnapshotCommandEffectEnum.php index 2b75dd4..547c3d8 100644 --- a/src/Pagination/Enum/HostSnapshotCommandEffectEnum.php +++ b/src/Pagination/Enum/HostSnapshotCommandEffectEnum.php @@ -11,6 +11,6 @@ */ enum HostSnapshotCommandEffectEnum { - case INVALIDATE_GENERATION; - case PRESERVES_TRANSACTION; + case InvalidateGeneration; + case PreservesTransaction; } diff --git a/src/Pagination/Enum/HostSnapshotCommandResultModeEnum.php b/src/Pagination/Enum/HostSnapshotCommandResultModeEnum.php index 596a9ee..65ccef3 100644 --- a/src/Pagination/Enum/HostSnapshotCommandResultModeEnum.php +++ b/src/Pagination/Enum/HostSnapshotCommandResultModeEnum.php @@ -10,6 +10,6 @@ */ enum HostSnapshotCommandResultModeEnum { - case AFFECTED_ROWS; - case BOUNDED_ROWS; + case AffectedRows; + case BoundedRows; } diff --git a/src/Pagination/Enum/HostSnapshotPageAttemptStateEnum.php b/src/Pagination/Enum/HostSnapshotPageAttemptStateEnum.php index 2e523ee..15283d7 100644 --- a/src/Pagination/Enum/HostSnapshotPageAttemptStateEnum.php +++ b/src/Pagination/Enum/HostSnapshotPageAttemptStateEnum.php @@ -10,7 +10,7 @@ */ enum HostSnapshotPageAttemptStateEnum { - case NEW; - case RUNNING; - case TERMINAL; + case New; + case Running; + case Terminal; } diff --git a/src/Pagination/Enum/HostSnapshotPageDispositionEnum.php b/src/Pagination/Enum/HostSnapshotPageDispositionEnum.php index aa2715c..f7831c2 100644 --- a/src/Pagination/Enum/HostSnapshotPageDispositionEnum.php +++ b/src/Pagination/Enum/HostSnapshotPageDispositionEnum.php @@ -11,7 +11,17 @@ */ enum HostSnapshotPageDispositionEnum { - case NOT_ACCEPTED; - case RETURNED_TO_HOST; - case HOST_ACTION_REQUIRED; + case NotAccepted; + case ReturnedToHost; + case HostActionRequired; + + /** @internal Stable code for settlement JSON. */ + public function settlementCode(): string + { + return match ($this) { + self::NotAccepted => 'NOT_ACCEPTED', + self::ReturnedToHost => 'RETURNED_TO_HOST', + self::HostActionRequired => 'HOST_ACTION_REQUIRED', + }; + } } diff --git a/src/Pagination/Enum/HostSnapshotPageSettlementReasonEnum.php b/src/Pagination/Enum/HostSnapshotPageSettlementReasonEnum.php index d89fe33..384e91c 100644 --- a/src/Pagination/Enum/HostSnapshotPageSettlementReasonEnum.php +++ b/src/Pagination/Enum/HostSnapshotPageSettlementReasonEnum.php @@ -12,20 +12,36 @@ */ enum HostSnapshotPageSettlementReasonEnum { - case SOURCE_UNAVAILABLE; + case SourceUnavailable; /** The grant belongs to a transaction generation that has been invalidated. */ - case STALE_CONTEXT; + case StaleContext; /** An earlier admitted attempt already used the grant. */ - case GRANT_CONSUMED; + case GrantConsumed; /** No admission while reserved. The Host can reuse an otherwise eligible grant in a fresh attempt. */ - case BUSY; - case PAGE_COMPLETED; + case Busy; + case PageCompleted; /** Read or mapping failed, but cursor release and transaction scope were confirmed. */ - case READ_FAILED; + case ReadFailed; /** A statement remains outstanding, preventing PDO handoff. */ - case RESOURCE_RELEASE_UNCONFIRMED; + case ResourceReleaseUnconfirmed; /** The source could not establish continued use of the qualified transaction. */ - case SCOPE_UNCONFIRMED; + case ScopeUnconfirmed; /** The fallback outcome if ordinary settlement cannot finish. */ - case SETTLEMENT_UNCONFIRMED; + case SettlementUnconfirmed; + + /** @internal Stable code for settlement JSON. */ + public function settlementCode(): string + { + return match ($this) { + self::SourceUnavailable => 'SOURCE_UNAVAILABLE', + self::StaleContext => 'STALE_CONTEXT', + self::GrantConsumed => 'GRANT_CONSUMED', + self::Busy => 'BUSY', + self::PageCompleted => 'PAGE_COMPLETED', + self::ReadFailed => 'READ_FAILED', + self::ResourceReleaseUnconfirmed => 'RESOURCE_RELEASE_UNCONFIRMED', + self::ScopeUnconfirmed => 'SCOPE_UNCONFIRMED', + self::SettlementUnconfirmed => 'SETTLEMENT_UNCONFIRMED', + }; + } } diff --git a/src/Pagination/Enum/HostSnapshotRetirementDispositionEnum.php b/src/Pagination/Enum/HostSnapshotRetirementDispositionEnum.php index 396be04..7fb0d26 100644 --- a/src/Pagination/Enum/HostSnapshotRetirementDispositionEnum.php +++ b/src/Pagination/Enum/HostSnapshotRetirementDispositionEnum.php @@ -10,6 +10,6 @@ */ enum HostSnapshotRetirementDispositionEnum { - case RETURNED_IDLE; - case RETURNED_FOR_RECONCILIATION; + case ReturnedIdle; + case ReturnedForReconciliation; } diff --git a/src/Pagination/Enum/SnapshotConnectionDispositionEnum.php b/src/Pagination/Enum/SnapshotConnectionDispositionEnum.php index 1b975b5..475573e 100644 --- a/src/Pagination/Enum/SnapshotConnectionDispositionEnum.php +++ b/src/Pagination/Enum/SnapshotConnectionDispositionEnum.php @@ -10,13 +10,23 @@ enum SnapshotConnectionDispositionEnum /** * A known pre-start refusal. Return control to the Host without granting fresh checkout clearance. */ - case UNCHANGED; + case Unchanged; /** * The same session was confirmed idle after the acknowledged end and cursor release. */ - case REUSABLE; + case Reusable; /** * Session, resources or completion could not be confirmed. The Host must retire the checkout. */ - case DISCARD; + case Discard; + + /** @internal Stable code for settlement JSON. */ + public function settlementCode(): string + { + return match ($this) { + self::Unchanged => 'UNCHANGED', + self::Reusable => 'REUSABLE', + self::Discard => 'DISCARD', + }; + } } diff --git a/src/Pagination/Enum/SortDirectionEnum.php b/src/Pagination/Enum/SortDirectionEnum.php index 5486a47..fd04514 100644 --- a/src/Pagination/Enum/SortDirectionEnum.php +++ b/src/Pagination/Enum/SortDirectionEnum.php @@ -4,8 +4,15 @@ namespace Maatify\PhpPersistence\Pagination\Enum; +/** Sort direction backed by its SQL token. */ enum SortDirectionEnum: string { - case ASC = 'ASC'; - case DESC = 'DESC'; + case Asc = 'ASC'; + case Desc = 'DESC'; + + /** Compatibility alias for the ascending case published in RC.2. */ + public const ASC = self::Asc; + + /** Compatibility alias for the descending case published in RC.2. */ + public const DESC = self::Desc; } diff --git a/src/Pagination/Criteria/HostSnapshotAttemptRecord.php b/src/Pagination/Repository/HostSnapshotAttemptRecord.php similarity index 80% rename from src/Pagination/Criteria/HostSnapshotAttemptRecord.php rename to src/Pagination/Repository/HostSnapshotAttemptRecord.php index 5a5abbf..df5accf 100644 --- a/src/Pagination/Criteria/HostSnapshotAttemptRecord.php +++ b/src/Pagination/Repository/HostSnapshotAttemptRecord.php @@ -2,15 +2,16 @@ declare(strict_types=1); -namespace Maatify\PhpPersistence\Pagination\Criteria; +namespace Maatify\PhpPersistence\Pagination\Repository; +use Maatify\PhpPersistence\Pagination\Criteria\HostSnapshotPageGrant; use Maatify\PhpPersistence\Pagination\DTO\HostSnapshotPageSettlementDTO; use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotPageAttemptStateEnum; /** @internal Private to the source and the attempt it issued. Contains no driver resources. */ final class HostSnapshotAttemptRecord { - public HostSnapshotPageAttemptStateEnum $state = HostSnapshotPageAttemptStateEnum::NEW; + public HostSnapshotPageAttemptStateEnum $state = HostSnapshotPageAttemptStateEnum::New; /** Null until this invocation publishes its terminal, connection-free outcome. */ public ?HostSnapshotPageSettlementDTO $settlement = null; @@ -24,6 +25,6 @@ public function finish(HostSnapshotPageSettlementDTO $settlement): void { $this->settlement = $settlement; $this->grant = null; - $this->state = HostSnapshotPageAttemptStateEnum::TERMINAL; + $this->state = HostSnapshotPageAttemptStateEnum::Terminal; } } diff --git a/src/Pagination/Repository/HostSnapshotConnection.php b/src/Pagination/Repository/HostSnapshotConnection.php index 3b289b8..20f351c 100644 --- a/src/Pagination/Repository/HostSnapshotConnection.php +++ b/src/Pagination/Repository/HostSnapshotConnection.php @@ -4,7 +4,6 @@ namespace Maatify\PhpPersistence\Pagination\Repository; -use Maatify\PhpPersistence\Pagination\DTO\HostSnapshotRetirementDTO; use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotRetirementDispositionEnum; use Maatify\PhpPersistence\Pagination\Exception\HostSnapshotPaginationException; use Maatify\PhpPersistence\Pagination\Exception\HostSnapshotRowLimitExceededException; @@ -102,6 +101,10 @@ public function execute(string $sql, array $bindings, ?int $maxRows, bool $posit $rows = []; $fetchMode = $positional ? PDO::FETCH_NUM : PDO::FETCH_ASSOC; + /** + * The raw fetch yields list in FETCH_NUM mode and array + * in FETCH_ASSOC mode. Both modes also yield false on exhaustion or failure. + */ while (($row = $statement->fetch($fetchMode)) !== false) { if (count($rows) === $maxRows) { throw new HostSnapshotRowLimitExceededException(); @@ -144,9 +147,9 @@ public function transactionActive(): bool } /** Builds the handoff with the same PDO and the disposition determined by the source. */ - public function handoff(HostSnapshotRetirementDispositionEnum $disposition): HostSnapshotRetirementDTO + public function handoff(HostSnapshotRetirementDispositionEnum $disposition): HostSnapshotRetirement { - return new HostSnapshotRetirementDTO($disposition, $this->pdo); + return new HostSnapshotRetirement($disposition, $this->pdo); } /** diff --git a/src/Pagination/Repository/HostSnapshotGrantRegistration.php b/src/Pagination/Repository/HostSnapshotGrantRegistration.php new file mode 100644 index 0000000..69a4045 --- /dev/null +++ b/src/Pagination/Repository/HostSnapshotGrantRegistration.php @@ -0,0 +1,30 @@ +source->beginCheckout($this, $mode); } @@ -48,12 +50,12 @@ public function beginRepeatableRead(HostSnapshotAccessModeEnum $mode = HostSnaps * driver keys. The default effect invalidates existing page grants before * execution and leaves next-transaction characteristics unconfirmed. * After session confirmation, an invalidating command leaves the checkout - * TRANSACTION_UNQUALIFIED if PDO reports an active transaction, or - * QUARANTINED if PDO reports idle. An uncertain session or transaction + * TransactionUnqualified if PDO reports an active transaction, or + * Quarantined if PDO reports idle. An uncertain session or transaction * effect can also quarantine the source. The Host can explicitly end the * unqualified transaction. A quarantined checkout rejects release(). * The Host can discard the source or call PdoHostSnapshotSource::retireForHost(), - * which returns the PDO as RETURNED_FOR_RECONCILIATION after confirming + * which returns the PDO as ReturnedForReconciliation after confirming * resource release. The Host must reconcile the returned PDO's state before reuse. * * @param array $bindings @@ -68,14 +70,14 @@ public function runRegisteredCommand(string $commandId, array $bindings = []): i * Ends a qualified or unqualified active transaction by committing without * chaining or releasing the session. Invalidates its grants before the command. * After confirming the same idle session, this call returns normally. - * The checkout becomes IDLE if the next-transaction characteristics are - * resolved, or QUARANTINED if they remain unconfirmed. Failed confirmation + * The checkout becomes Idle if the next-transaction characteristics are + * resolved, or Quarantined if they remain unconfirmed. Failed confirmation * also quarantines the source and throws. release() permits a later - * checkout only from IDLE, after confirming the same idle session and + * checkout only from Idle, after confirming the same idle session and * resolved settings. * In quarantine the Host can discard the source or call * PdoHostSnapshotSource::retireForHost(), which returns the PDO as - * RETURNED_FOR_RECONCILIATION after confirming resource release. + * ReturnedForReconciliation after confirming resource release. * The Host must reconcile the returned PDO's state before reuse. */ public function commit(): void @@ -87,14 +89,14 @@ public function commit(): void * Ends a qualified or unqualified active transaction by rolling back without * chaining or releasing the session. Invalidates its grants before the * command. After confirming the same idle session, this call returns - * normally. The checkout becomes IDLE if the next-transaction characteristics - * are resolved, or QUARANTINED if they remain unconfirmed. Failed + * normally. The checkout becomes Idle if the next-transaction characteristics + * are resolved, or Quarantined if they remain unconfirmed. Failed * confirmation also quarantines the source and throws. release() permits a - * later checkout only from IDLE, after confirming the same idle session + * later checkout only from Idle, after confirming the same idle session * and resolved settings. * In quarantine the Host can discard the source or call * PdoHostSnapshotSource::retireForHost(), which returns the PDO as - * RETURNED_FOR_RECONCILIATION after confirming resource release. + * ReturnedForReconciliation after confirming resource release. * The Host must reconcile the returned PDO's state before reuse. */ public function rollBack(): void @@ -134,13 +136,21 @@ public function release(): void private function __clone() {} - /** @return array */ + /** + * @return array + * + * @throws HostSnapshotPaginationException Always. The checkout holds authority issued by its live source. + */ public function __serialize(): array { throw new HostSnapshotPaginationException('A Host snapshot checkout cannot be serialized.'); } - /** @param array $data */ + /** + * @param array $data + * + * @throws HostSnapshotPaginationException Always. Checkout authority must be issued by the source. + */ public function __unserialize(array $data): void { throw new HostSnapshotPaginationException('A Host snapshot checkout cannot be restored.'); diff --git a/src/Pagination/Repository/PdoHostSnapshotSource.php b/src/Pagination/Repository/PdoHostSnapshotSource.php index db4dc3f..3cd886b 100644 --- a/src/Pagination/Repository/PdoHostSnapshotSource.php +++ b/src/Pagination/Repository/PdoHostSnapshotSource.php @@ -4,15 +4,12 @@ namespace Maatify\PhpPersistence\Pagination\Repository; -use Maatify\PhpPersistence\Pagination\Criteria\HostSnapshotAttemptRecord; use Maatify\PhpPersistence\Pagination\Criteria\HostSnapshotBindings; use Maatify\PhpPersistence\Pagination\Criteria\HostSnapshotCatalog; -use Maatify\PhpPersistence\Pagination\Criteria\HostSnapshotGrantRegistration; use Maatify\PhpPersistence\Pagination\Criteria\HostSnapshotPageAttempt; use Maatify\PhpPersistence\Pagination\Criteria\HostSnapshotPageGrant; use Maatify\PhpPersistence\Pagination\Criteria\PageRequest; use Maatify\PhpPersistence\Pagination\DTO\HostSnapshotPageSettlementDTO; -use Maatify\PhpPersistence\Pagination\DTO\HostSnapshotRetirementDTO; use Maatify\PhpPersistence\Pagination\DTO\PageResultDTO; use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotAccessModeEnum; use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotCheckoutStateEnum as State; @@ -63,7 +60,7 @@ final class PdoHostSnapshotSource private WeakMap $grants; /** @var WeakMap */ private WeakMap $attempts; - private State $state = State::IDLE; + private State $state = State::Idle; private bool $busy = false; private ?string $sessionId = null; /** Identifies the qualified transaction against which the source checks page grants. */ @@ -113,7 +110,7 @@ public static function attachExclusive(PDO $pdo, HostSnapshotCatalog $catalog): */ public function checkout(): PdoHostSnapshotCheckout { - if ($this->busy || $this->checkout !== null || $this->state !== State::IDLE) { + if ($this->busy || $this->checkout !== null || $this->state !== State::Idle) { throw new HostSnapshotPaginationException('The Host snapshot source is unavailable.'); } $this->busy = true; @@ -125,7 +122,7 @@ public function checkout(): PdoHostSnapshotCheckout return $checkout; } catch (Throwable $error) { - $this->state = State::QUARANTINED; + $this->state = State::Quarantined; throw $error; } finally { $this->busy = false; @@ -138,7 +135,7 @@ public function checkout(): PdoHostSnapshotCheckout * and a resolved next-transaction setting. Otherwise the Host receives the * PDO for reconciliation. A held reservation or unresolved cursor blocks transfer. */ - public function retireForHost(): HostSnapshotRetirementDTO + public function retireForHost(): HostSnapshotRetirement { $this->reserveRetirement(); try { @@ -146,9 +143,9 @@ public function retireForHost(): HostSnapshotRetirementDTO $this->quarantine(); throw new HostSnapshotPaginationException('Host snapshot resources still prevent a handoff.'); } - $disposition = $this->state === State::IDLE && $this->sessionId !== null && ! $this->nextTransactionUnconfirmed - ? HostSnapshotRetirementDispositionEnum::RETURNED_IDLE - : HostSnapshotRetirementDispositionEnum::RETURNED_FOR_RECONCILIATION; + $disposition = $this->state === State::Idle && $this->sessionId !== null && ! $this->nextTransactionUnconfirmed + ? HostSnapshotRetirementDispositionEnum::ReturnedIdle + : HostSnapshotRetirementDispositionEnum::ReturnedForReconciliation; $handoff = $this->connection->handoff($disposition); $this->markRetired(); $this->connection->detach(); @@ -179,7 +176,7 @@ public function discardForHost(): void /** Takes exclusive use for retirement, including when the source is quarantined. */ private function reserveRetirement(): void { - if ($this->busy || $this->state === State::RETIRED) { + if ($this->busy || $this->state === State::Retired) { throw new HostSnapshotPaginationException('The Host snapshot source cannot be retired.'); } $this->busy = true; @@ -195,20 +192,20 @@ private function markRetired(): void $this->checkout = null; $this->checkoutIdentity = null; $this->generation = null; - $this->state = State::RETIRED; + $this->state = State::Retired; } - /** @internal Reports BUSY under reservation and distinguishes release from retirement. */ + /** @internal Reports Busy under reservation and distinguishes release from retirement. */ public function checkoutState(PdoHostSnapshotCheckout $checkout): State { if ($this->retiredCheckout?->get() === $checkout) { - return State::RETIRED; + return State::Retired; } if ($this->checkout?->get() !== $checkout) { - return State::RELEASED; + return State::Released; } - return $this->busy ? State::BUSY : $this->state; + return $this->busy ? State::Busy : $this->state; } /** @@ -218,7 +215,7 @@ public function checkoutState(PdoHostSnapshotCheckout $checkout): State */ public function releaseCheckout(PdoHostSnapshotCheckout $checkout): void { - $this->reserve($checkout, State::IDLE); + $this->reserve($checkout, State::Idle); try { if ($this->nextTransactionUnconfirmed) { throw new HostSnapshotPaginationException('The next Host snapshot transaction setting is unresolved.'); @@ -227,7 +224,7 @@ public function releaseCheckout(PdoHostSnapshotCheckout $checkout): void $this->checkout = null; $this->checkoutIdentity = null; } catch (Throwable $error) { - $this->state = State::QUARANTINED; + $this->state = State::Quarantined; throw $error; } finally { $this->busy = false; @@ -241,7 +238,7 @@ public function releaseCheckout(PdoHostSnapshotCheckout $checkout): void */ public function beginCheckout(PdoHostSnapshotCheckout $checkout, HostSnapshotAccessModeEnum $mode): void { - $this->reserve($checkout, State::IDLE); + $this->reserve($checkout, State::Idle); try { $this->confirmSession(false); $this->connection->control('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'); @@ -249,7 +246,7 @@ public function beginCheckout(PdoHostSnapshotCheckout $checkout, HostSnapshotAcc $this->confirmSession(true); $this->nextTransactionUnconfirmed = false; $this->generation = new stdClass(); - $this->state = State::TRANSACTION_ACTIVE; + $this->state = State::TransactionActive; } catch (Throwable $error) { $this->quarantine(); throw $error; @@ -270,19 +267,19 @@ public function beginCheckout(PdoHostSnapshotCheckout $checkout, HostSnapshotAcc */ public function executeCheckoutCommand(PdoHostSnapshotCheckout $checkout, string $id, array $bindings): int|array { - $this->reserve($checkout, State::IDLE, State::TRANSACTION_ACTIVE, State::TRANSACTION_UNQUALIFIED); + $this->reserve($checkout, State::Idle, State::TransactionActive, State::TransactionUnqualified); try { $command = $this->catalog->command($id); $params = HostSnapshotBindings::exact($command->parameterNames, $bindings); - $preserves = $command->effect === HostSnapshotCommandEffectEnum::PRESERVES_TRANSACTION; - $active = $this->state !== State::IDLE; + $preserves = $command->effect === HostSnapshotCommandEffectEnum::PreservesTransaction; + $active = $this->state !== State::Idle; if (! $preserves) { $this->generation = null; // A trusted, invalidating single statement may also set a next-transaction override. $this->nextTransactionUnconfirmed = true; } try { - $maxRows = $command->resultMode === HostSnapshotCommandResultModeEnum::BOUNDED_ROWS ? $command->maxRows : null; + $maxRows = $command->resultMode === HostSnapshotCommandResultModeEnum::BoundedRows ? $command->maxRows : null; try { $result = $this->connection->execute($command->sql, $params, $maxRows); } catch (HostSnapshotRowLimitExceededException) { @@ -290,7 +287,7 @@ public function executeCheckoutCommand(PdoHostSnapshotCheckout $checkout, string } $this->confirmSession($preserves ? $active : null); if (! $preserves) { - $this->state = $this->connection->transactionActive() ? State::TRANSACTION_UNQUALIFIED : State::QUARANTINED; + $this->state = $this->connection->transactionActive() ? State::TransactionUnqualified : State::Quarantined; } } catch (Throwable $error) { @@ -314,13 +311,13 @@ public function executeCheckoutCommand(PdoHostSnapshotCheckout $checkout, string */ public function finishCheckout(PdoHostSnapshotCheckout $checkout, bool $commit): void { - $this->reserve($checkout, State::TRANSACTION_ACTIVE, State::TRANSACTION_UNQUALIFIED); + $this->reserve($checkout, State::TransactionActive, State::TransactionUnqualified); $this->generation = null; try { $this->confirmSession(true); $this->connection->control($commit ? 'COMMIT AND NO CHAIN NO RELEASE' : 'ROLLBACK AND NO CHAIN NO RELEASE'); $this->confirmSession(false); - $this->state = $this->nextTransactionUnconfirmed ? State::QUARANTINED : State::IDLE; + $this->state = $this->nextTransactionUnconfirmed ? State::Quarantined : State::Idle; } catch (Throwable $error) { $this->quarantine(); throw $error; @@ -344,7 +341,7 @@ public function authorizeCheckoutPage( PageRequest $request, ): HostSnapshotPageGrant { if ($this->busy || $this->checkout?->get() !== $checkout || $this->checkoutIdentity === null - || $this->state !== State::TRANSACTION_ACTIVE || $this->generation === null + || $this->state !== State::TransactionActive || $this->generation === null ) { throw new HostSnapshotPaginationException('The Host snapshot transaction cannot authorize a page.'); } @@ -406,31 +403,31 @@ public function readAttempt(HostSnapshotPageAttempt $attempt): PageResultDTO { // First-use autoloading may run Host code. Materialize the outcomes before // checking the generation, then admit without anything that invokes a callback. - $fallback = new HostSnapshotPageSettlementDTO(Disposition::HOST_ACTION_REQUIRED, Reason::SETTLEMENT_UNCONFIRMED); - $scopeUnconfirmed = new HostSnapshotPageSettlementDTO(Disposition::HOST_ACTION_REQUIRED, Reason::SCOPE_UNCONFIRMED); - $resourcesUnconfirmed = new HostSnapshotPageSettlementDTO(Disposition::HOST_ACTION_REQUIRED, Reason::RESOURCE_RELEASE_UNCONFIRMED); + $fallback = new HostSnapshotPageSettlementDTO(Disposition::HostActionRequired, Reason::SettlementUnconfirmed); + $scopeUnconfirmed = new HostSnapshotPageSettlementDTO(Disposition::HostActionRequired, Reason::ScopeUnconfirmed); + $resourcesUnconfirmed = new HostSnapshotPageSettlementDTO(Disposition::HostActionRequired, Reason::ResourceReleaseUnconfirmed); $record = $this->attempts[$attempt] ?? null; - if ($record === null || $record->state !== Stage::NEW || $record->grant === null) { + if ($record === null || $record->state !== Stage::New || $record->grant === null) { throw new HostSnapshotPaginationException('The Host snapshot attempt is unavailable.'); } $grant = $this->grants[$record->grant]; $rejected = match (true) { $this->checkout?->get() === null || $grant->checkoutIdentity !== $this->checkoutIdentity - || $this->state === State::QUARANTINED || $this->state === State::RETIRED => Reason::SOURCE_UNAVAILABLE, - $this->generation !== $grant->generation => Reason::STALE_CONTEXT, - $grant->consumed => Reason::GRANT_CONSUMED, - $this->busy => Reason::BUSY, + || $this->state === State::Quarantined || $this->state === State::Retired => Reason::SourceUnavailable, + $this->generation !== $grant->generation => Reason::StaleContext, + $grant->consumed => Reason::GrantConsumed, + $this->busy => Reason::Busy, default => null, }; if ($rejected !== null) { - $record->finish(new HostSnapshotPageSettlementDTO(Disposition::NOT_ACCEPTED, $rejected)); + $record->finish(new HostSnapshotPageSettlementDTO(Disposition::NotAccepted, $rejected)); throw new HostSnapshotPaginationException('The Host snapshot attempt was not accepted.'); } $this->busy = true; $grant->consumed = true; - $record->state = Stage::RUNNING; + $record->state = Stage::Running; $settlement = $scopeUnconfirmed; $primary = null; $mapping = false; @@ -454,8 +451,8 @@ public function readAttempt(HostSnapshotPageAttempt $attempt): PageResultDTO $this->confirmSession(true); $settlement = $fallback; $settlement = new HostSnapshotPageSettlementDTO( - Disposition::RETURNED_TO_HOST, - $primary === null ? Reason::PAGE_COMPLETED : Reason::READ_FAILED, + Disposition::ReturnedToHost, + $primary === null ? Reason::PageCompleted : Reason::ReadFailed, ); if ($primary !== null) { throw $primary; @@ -468,7 +465,7 @@ public function readAttempt(HostSnapshotPageAttempt $attempt): PageResultDTO if (! $this->connection->resourcesReleased()) { $settlement = $resourcesUnconfirmed; } - if ($settlement->disposition === Disposition::HOST_ACTION_REQUIRED) { + if ($settlement->disposition === Disposition::HostActionRequired) { $this->quarantine(); } $record->finish($settlement); @@ -480,7 +477,7 @@ public function readAttempt(HostSnapshotPageAttempt $attempt): PageResultDTO private function quarantine(): void { $this->generation = null; - $this->state = State::QUARANTINED; + $this->state = State::Quarantined; } /** Takes the shared reservation only for the registered checkout in an allowed state. */ @@ -511,13 +508,21 @@ private function confirmSession(?bool $active): string private function __clone() {} - /** @return array */ + /** + * @return array + * + * @throws HostSnapshotPaginationException Always. The source owns an in-process Host connection registration. + */ public function __serialize(): array { throw new HostSnapshotPaginationException('A Host snapshot source cannot be serialized.'); } - /** @param array $data */ + /** + * @param array $data + * + * @throws HostSnapshotPaginationException Always. The source must establish exclusive use through live attachment. + */ public function __unserialize(array $data): void { throw new HostSnapshotPaginationException('A Host snapshot source cannot be restored.'); diff --git a/src/Pagination/Repository/PdoKeysetPaginator.php b/src/Pagination/Repository/PdoKeysetPaginator.php index 4192639..741615f 100644 --- a/src/Pagination/Repository/PdoKeysetPaginator.php +++ b/src/Pagination/Repository/PdoKeysetPaginator.php @@ -111,7 +111,12 @@ public function paginate( return new KeysetPageResultDTO($data, $hasNext, $nextCursor); } - /** @return array{defaultLimit: int, maxLimit: int} */ + /** + * Reports only the default and maximum page limits in PHP debug output. + * Omits cursor signing data. + * + * @return array{defaultLimit: int, maxLimit: int} + */ public function __debugInfo(): array { return ['defaultLimit' => $this->defaultLimit, 'maxLimit' => $this->maxLimit]; diff --git a/src/Pagination/Repository/PdoPaginationExecution.php b/src/Pagination/Repository/PdoPaginationExecution.php index ff18d2a..3c00fe9 100644 --- a/src/Pagination/Repository/PdoPaginationExecution.php +++ b/src/Pagination/Repository/PdoPaginationExecution.php @@ -213,8 +213,8 @@ public function resolveSortDirection(?string $sortDirection, PaginationConfig $c } return match (strtoupper(trim($sortDirection))) { - 'ASC' => SortDirectionEnum::ASC, - 'DESC' => SortDirectionEnum::DESC, + 'ASC' => SortDirectionEnum::Asc, + 'DESC' => SortDirectionEnum::Desc, default => $config->defaultSortDirection, }; } diff --git a/src/Pagination/Repository/PdoSnapshotPaginator.php b/src/Pagination/Repository/PdoSnapshotPaginator.php index c4e8cc1..a69b724 100644 --- a/src/Pagination/Repository/PdoSnapshotPaginator.php +++ b/src/Pagination/Repository/PdoSnapshotPaginator.php @@ -61,12 +61,12 @@ public function paginate( // Consume the operation before any driver call or mapper reentry. $this->pdo = null; $resources = new SnapshotReadResources(); - $disposition = SnapshotConnectionDispositionEnum::DISCARD; + $disposition = SnapshotConnectionDispositionEnum::Discard; $stage = 'eligibility'; try { if (! $this->hasEligibleDriver($pdo) || $pdo->inTransaction()) { - $disposition = SnapshotConnectionDispositionEnum::UNCHANGED; + $disposition = SnapshotConnectionDispositionEnum::Unchanged; throw new SnapshotPaginationException('The Host connection does not qualify for snapshot pagination.'); } @@ -74,7 +74,7 @@ public function paginate( $eligibleSettings = $autocommit && $this->hasRepeatableRead($pdo, $resources); $this->assertSession($pdo, $resources, $session, false); if (! $eligibleSettings) { - $disposition = SnapshotConnectionDispositionEnum::UNCHANGED; + $disposition = SnapshotConnectionDispositionEnum::Unchanged; throw new SnapshotPaginationException('Snapshot pagination requires an idle REPEATABLE READ session with autocommit enabled.'); } @@ -90,9 +90,9 @@ public function paginate( $resources->release(); $stage = 'rollback'; $this->finishTransaction($pdo, $resources, $session, 'ROLLBACK AND NO CHAIN NO RELEASE'); - $disposition = SnapshotConnectionDispositionEnum::REUSABLE; + $disposition = SnapshotConnectionDispositionEnum::Reusable; } catch (Throwable) { - // The checkout remains DISCARD. Preserve the original read failure. + // The disposition remains Discard. Preserve the original read failure. } throw $failure; @@ -101,13 +101,13 @@ public function paginate( $stage = 'commit'; $this->finishTransaction($pdo, $resources, $session, 'COMMIT AND NO CHAIN NO RELEASE'); - $disposition = SnapshotConnectionDispositionEnum::REUSABLE; + $disposition = SnapshotConnectionDispositionEnum::Reusable; return $page; } finally { $this->outcome = new SnapshotConnectionOutcomeDTO( $disposition, - $disposition === SnapshotConnectionDispositionEnum::DISCARD ? $stage : null, + $disposition === SnapshotConnectionDispositionEnum::Discard ? $stage : null, ); } } @@ -123,13 +123,21 @@ public function connectionOutcome(): ?SnapshotConnectionOutcomeDTO private function __clone() {} - /** @return array */ + /** + * @return array + * + * @throws SnapshotPaginationException Always. The instance represents a one-shot, Host-delegated read operation. + */ public function __serialize(): array { throw new SnapshotPaginationException('A snapshot operation cannot be serialized.'); } - /** @param array $data */ + /** + * @param array $data + * + * @throws SnapshotPaginationException Always. The Host must supply the connection for a new read operation. + */ public function __unserialize(array $data): void { throw new SnapshotPaginationException('A snapshot operation cannot be restored from serialized data.'); @@ -217,6 +225,7 @@ private function rows(PDO $pdo, SnapshotReadResources $resources, string $sql): } $resources->track($statement); + /** @var list $raw Expected list> from FETCH_NUM. Fetch failures throw in exception mode. */ $raw = $statement->fetchAll(PDO::FETCH_NUM); $resources->release(); $rows = []; diff --git a/src/Transaction/DTO/VerifiedTransactionDecisionDTO.php b/src/Transaction/Command/VerifiedTransactionDecisionCommand.php similarity index 87% rename from src/Transaction/DTO/VerifiedTransactionDecisionDTO.php rename to src/Transaction/Command/VerifiedTransactionDecisionCommand.php index da87f85..9ab4290 100644 --- a/src/Transaction/DTO/VerifiedTransactionDecisionDTO.php +++ b/src/Transaction/Command/VerifiedTransactionDecisionCommand.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace Maatify\PhpPersistence\Transaction\DTO; +namespace Maatify\PhpPersistence\Transaction\Command; /** * An explicit transaction decision with an independent application payload. * Payloads, including false, null and objects, pass through unchanged when * the checkout confirms the requested effect. */ -final readonly class VerifiedTransactionDecisionDTO +final readonly class VerifiedTransactionDecisionCommand { private function __construct(public bool $isApply, public mixed $payload) {} diff --git a/src/Transaction/DTO/ProtectedTransactionSettlementDTO.php b/src/Transaction/DTO/ProtectedTransactionSettlementDTO.php index 97bf43f..7dcaa92 100644 --- a/src/Transaction/DTO/ProtectedTransactionSettlementDTO.php +++ b/src/Transaction/DTO/ProtectedTransactionSettlementDTO.php @@ -4,6 +4,7 @@ namespace Maatify\PhpPersistence\Transaction\DTO; +use JsonSerializable; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionReasonEnum; @@ -12,11 +13,24 @@ * governs handoff, while the reason records what the checkout observed. An * acknowledged database effect can coexist with a required discard. */ -final readonly class ProtectedTransactionSettlementDTO +final readonly class ProtectedTransactionSettlementDTO implements JsonSerializable { /** @internal Issued by the checkout when its outcome is terminal. */ public function __construct( public ProtectedTransactionDispositionEnum $disposition, public ProtectedTransactionReasonEnum $reason, ) {} + + /** + * Projects the stable settlement codes as strings. + * + * @return array{disposition: string, reason: string} + */ + public function jsonSerialize(): array + { + return [ + 'disposition' => $this->disposition->settlementCode(), + 'reason' => $this->reason->settlementCode(), + ]; + } } diff --git a/src/Transaction/DTO/VerifiedTransactionSettlementDTO.php b/src/Transaction/DTO/VerifiedTransactionSettlementDTO.php index 40ad181..3fea693 100644 --- a/src/Transaction/DTO/VerifiedTransactionSettlementDTO.php +++ b/src/Transaction/DTO/VerifiedTransactionSettlementDTO.php @@ -4,6 +4,7 @@ namespace Maatify\PhpPersistence\Transaction\DTO; +use JsonSerializable; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionOutcomeEnum; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionReasonEnum; @@ -12,7 +13,7 @@ * Immutable local evidence that separates operation effects, whole-transaction * effects and PDO disposition. Later checkout actions publish a new snapshot. */ -final readonly class VerifiedTransactionSettlementDTO +final readonly class VerifiedTransactionSettlementDTO implements JsonSerializable { /** * @param ?VerifiedTransactionOutcomeEnum $operationOutcome Effect of the operation, or null before an attempt records an effect. @@ -21,8 +22,8 @@ * including while the Host transaction remains open. * @param ?VerifiedTransactionReasonEnum $checkoutReason Reason the checkout reached a terminal failure or was retired early, * or null when neither was recorded. - * @param ?ProtectedTransactionDispositionEnum $disposition Null while held, UNCHANGED for untouched cancellation, - * REUSABLE after confirmed completion and DISCARD_REQUIRED to forbid handoff. + * @param ?ProtectedTransactionDispositionEnum $disposition Null while held, Unchanged for untouched cancellation, + * Reusable after confirmed completion and DiscardRequired to forbid handoff. */ public function __construct( public ?VerifiedTransactionOutcomeEnum $operationOutcome, @@ -31,4 +32,20 @@ public function __construct( public ?VerifiedTransactionReasonEnum $checkoutReason, public ?ProtectedTransactionDispositionEnum $disposition, ) {} + + /** + * Projects the stable settlement codes and keeps unrecorded fields null. + * + * @return array{operationOutcome: ?string, operationReason: ?string, transactionOutcome: ?string, checkoutReason: ?string, disposition: ?string} + */ + public function jsonSerialize(): array + { + return [ + 'operationOutcome' => $this->operationOutcome?->settlementCode(), + 'operationReason' => $this->operationReason?->settlementCode(), + 'transactionOutcome' => $this->transactionOutcome?->settlementCode(), + 'checkoutReason' => $this->checkoutReason?->settlementCode(), + 'disposition' => $this->disposition?->settlementCode(), + ]; + } } diff --git a/src/Transaction/Enum/ProtectedTransactionDispositionEnum.php b/src/Transaction/Enum/ProtectedTransactionDispositionEnum.php index f6b720d..6cf0fd7 100644 --- a/src/Transaction/Enum/ProtectedTransactionDispositionEnum.php +++ b/src/Transaction/Enum/ProtectedTransactionDispositionEnum.php @@ -13,13 +13,23 @@ enum ProtectedTransactionDispositionEnum /** * An untouched attachment can be cancelled without a server qualification probe. */ - case UNCHANGED; + case Unchanged; /** * Released resources and the acknowledged end were confirmed on the same idle session. */ - case REUSABLE; + case Reusable; /** * The checkout fences handoff. The Host disposes of the connection and reconciles uncertain work. */ - case DISCARD_REQUIRED; + case DiscardRequired; + + /** @internal Stable code for settlement JSON. */ + public function settlementCode(): string + { + return match ($this) { + self::Unchanged => 'UNCHANGED', + self::Reusable => 'REUSABLE', + self::DiscardRequired => 'DISCARD_REQUIRED', + }; + } } diff --git a/src/Transaction/Enum/ProtectedTransactionReasonEnum.php b/src/Transaction/Enum/ProtectedTransactionReasonEnum.php index bdaa2cc..7bd7e1a 100644 --- a/src/Transaction/Enum/ProtectedTransactionReasonEnum.php +++ b/src/Transaction/Enum/ProtectedTransactionReasonEnum.php @@ -10,33 +10,51 @@ */ enum ProtectedTransactionReasonEnum { - case CANCELLED_BEFORE_QUALIFICATION; - case SERVER_QUALIFICATION_FAILED; + case CancelledBeforeQualification; + case ServerQualificationFailed; /** * The start command or its active-session confirmation failed. */ - case START_UNCONFIRMED; + case StartUnconfirmed; /** * A recognized engine signal invalidated authority to use the transaction. It does not prove rollback. */ - case TRANSACTION_LOST; + case TransactionLost; /** * The checkout could not establish safe completion of an operation or continuity before ending it. */ - case OPERATION_UNCONFIRMED; + case OperationUnconfirmed; /** * Commit was attempted, but its result was not acknowledged. */ - case COMMIT_OUTCOME_UNKNOWN; + case CommitOutcomeUnknown; /** * Commit was acknowledged before the subsequent idle-session check failed. */ - case COMMIT_CONFIRMED_CONNECTION_UNSAFE; + case CommitConfirmedConnectionUnsafe; /** * The requested rollback or its required idle-session confirmation failed. */ - case ROLLBACK_UNCONFIRMED; - case COMMITTED; - case ROLLED_BACK; - case HOST_DISCARDED; + case RollbackUnconfirmed; + case Committed; + case RolledBack; + case HostDiscarded; + + /** @internal Stable code for settlement JSON. */ + public function settlementCode(): string + { + return match ($this) { + self::CancelledBeforeQualification => 'CANCELLED_BEFORE_QUALIFICATION', + self::ServerQualificationFailed => 'SERVER_QUALIFICATION_FAILED', + self::StartUnconfirmed => 'START_UNCONFIRMED', + self::TransactionLost => 'TRANSACTION_LOST', + self::OperationUnconfirmed => 'OPERATION_UNCONFIRMED', + self::CommitOutcomeUnknown => 'COMMIT_OUTCOME_UNKNOWN', + self::CommitConfirmedConnectionUnsafe => 'COMMIT_CONFIRMED_CONNECTION_UNSAFE', + self::RollbackUnconfirmed => 'ROLLBACK_UNCONFIRMED', + self::Committed => 'COMMITTED', + self::RolledBack => 'ROLLED_BACK', + self::HostDiscarded => 'HOST_DISCARDED', + }; + } } diff --git a/src/Transaction/Enum/VerifiedTransactionOutcomeEnum.php b/src/Transaction/Enum/VerifiedTransactionOutcomeEnum.php index d7b6399..4614a66 100644 --- a/src/Transaction/Enum/VerifiedTransactionOutcomeEnum.php +++ b/src/Transaction/Enum/VerifiedTransactionOutcomeEnum.php @@ -11,20 +11,33 @@ enum VerifiedTransactionOutcomeEnum { /** The recorded operation or transaction did not start. */ - case NOT_STARTED; + case NotStarted; /** The operation was applied inside the still-open Host transaction. */ - case PENDING_HOST; + case PendingHost; /** Rollback to the operation savepoint was acknowledged, even if release later failed. */ - case LOCAL_UNDONE; + case LocalUndone; /** The commit of the whole transaction was acknowledged. */ - case COMMITTED; + case Committed; /** The rollback of the whole transaction was acknowledged. */ - case ROLLED_BACK; + case RolledBack; /** The effect could not be confirmed. Reconcile before deciding whether to repeat work. */ - case UNKNOWN; + case Unknown; + + /** @internal Stable code for settlement JSON. */ + public function settlementCode(): string + { + return match ($this) { + self::NotStarted => 'NOT_STARTED', + self::PendingHost => 'PENDING_HOST', + self::LocalUndone => 'LOCAL_UNDONE', + self::Committed => 'COMMITTED', + self::RolledBack => 'ROLLED_BACK', + self::Unknown => 'UNKNOWN', + }; + } } diff --git a/src/Transaction/Enum/VerifiedTransactionReasonEnum.php b/src/Transaction/Enum/VerifiedTransactionReasonEnum.php index b5a1ba5..d064277 100644 --- a/src/Transaction/Enum/VerifiedTransactionReasonEnum.php +++ b/src/Transaction/Enum/VerifiedTransactionReasonEnum.php @@ -12,44 +12,65 @@ enum VerifiedTransactionReasonEnum { /** The initial idle-session qualification failed before START was attempted. */ - case QUALIFICATION_FAILED; + case QualificationFailed; /** START or the active session check immediately after it could not be confirmed. */ - case START_UNCONFIRMED; + case StartUnconfirmed; /** The checkout could not confirm continued use of the qualified transaction. */ - case CONTINUITY_UNCONFIRMED; + case ContinuityUnconfirmed; /** Creating the Host operation savepoint could not be confirmed. */ - case SAVEPOINT_UNCONFIRMED; + case SavepointUnconfirmed; /** The callback threw or returned an invalid decision, and its cleanup was confirmed. */ - case CALLBACK_FAILED; + case CallbackFailed; /** A registered command latched a driver failure. */ - case COMMAND_FAILED; + case CommandFailed; /** Command cursor release could not be confirmed. */ - case CURSOR_UNCONFIRMED; + case CursorUnconfirmed; /** Rollback to the Host operation savepoint could not be confirmed. */ - case ROLLBACK_TO_UNCONFIRMED; + case RollbackToUnconfirmed; /** Savepoint release could not be confirmed. An earlier acknowledged local undo still stands. */ - case RELEASE_UNCONFIRMED; + case ReleaseUnconfirmed; /** COMMIT was attempted without a confirmed result. */ - case COMMIT_OUTCOME_UNKNOWN; + case CommitOutcomeUnknown; /** Whole-transaction ROLLBACK was attempted without a confirmed result. */ - case ROLLBACK_UNCONFIRMED; + case RollbackUnconfirmed; /** The end was acknowledged, but the idle-session check for handoff failed. */ - case HANDOFF_UNCONFIRMED; + case HandoffUnconfirmed; /** The engine signalled a recognized transaction-loss condition. */ - case TRANSACTION_LOST; + case TransactionLost; /** The Host retired a checkout before it reached a terminal disposition. */ - case HOST_DISCARDED; + case HostDiscarded; + + /** @internal Stable code for settlement JSON. */ + public function settlementCode(): string + { + return match ($this) { + self::QualificationFailed => 'QUALIFICATION_FAILED', + self::StartUnconfirmed => 'START_UNCONFIRMED', + self::ContinuityUnconfirmed => 'CONTINUITY_UNCONFIRMED', + self::SavepointUnconfirmed => 'SAVEPOINT_UNCONFIRMED', + self::CallbackFailed => 'CALLBACK_FAILED', + self::CommandFailed => 'COMMAND_FAILED', + self::CursorUnconfirmed => 'CURSOR_UNCONFIRMED', + self::RollbackToUnconfirmed => 'ROLLBACK_TO_UNCONFIRMED', + self::ReleaseUnconfirmed => 'RELEASE_UNCONFIRMED', + self::CommitOutcomeUnknown => 'COMMIT_OUTCOME_UNKNOWN', + self::RollbackUnconfirmed => 'ROLLBACK_UNCONFIRMED', + self::HandoffUnconfirmed => 'HANDOFF_UNCONFIRMED', + self::TransactionLost => 'TRANSACTION_LOST', + self::HostDiscarded => 'HOST_DISCARDED', + }; + } } diff --git a/src/Transaction/Exception/TransactionExecutionException.php b/src/Transaction/Exception/TransactionExecutionException.php index d79c80c..4d6b761 100644 --- a/src/Transaction/Exception/TransactionExecutionException.php +++ b/src/Transaction/Exception/TransactionExecutionException.php @@ -10,9 +10,10 @@ use Maatify\PhpPersistence\Exception\PhpPersistenceExceptionInterface; /** - * Thrown when a PDO transaction-control statement (BEGIN, COMMIT, SAVEPOINT, - * RELEASE SAVEPOINT, ROLLBACK TO SAVEPOINT) fails without throwing, or when a - * caller-owned transaction is no longer active where this package requires one. + * Reports a non-throwing PDO transaction-control failure, including the + * required rollback for a raw Ordering move. Also reports an unconfirmed + * owned Ordering rollback or a caller transaction that has ended at an + * operation boundary that requires it to remain active. */ final class TransactionExecutionException extends SystemMaatifyException implements PhpPersistenceExceptionInterface { diff --git a/src/Transaction/Repository/OwnedTransactionExecutor.php b/src/Transaction/Repository/OwnedTransactionExecutor.php index 6f57c92..c90be38 100644 --- a/src/Transaction/Repository/OwnedTransactionExecutor.php +++ b/src/Transaction/Repository/OwnedTransactionExecutor.php @@ -46,7 +46,7 @@ * Delays before retry 1, 2 and 3: none, uniform 0-10 ms, uniform 0-20 ms. No * transaction (and no lock) is held while waiting. * - * @internal Shared mechanism of the transaction runners; not part of the public API. + * @internal Shared owned-transaction mechanism for the transaction runners and raw Ordering. */ final readonly class OwnedTransactionExecutor { @@ -94,10 +94,11 @@ public function __construct( * @template TResult * * @param callable(): TResult $callback + * @param bool $rollBackOnFalse Require an acknowledged rollback and an idle connection before returning false. * * @return TResult */ - public function run(callable $callback): mixed + public function run(callable $callback, bool $rollBackOnFalse = false): mixed { $retry = 0; @@ -123,6 +124,14 @@ public function run(callable $callback): mixed throw $throwable; } + if ($rollBackOnFalse && $result === false) { + if (!$this->pdo->inTransaction() || !$this->rollBackToIdle()) { + throw new TransactionExecutionException('Unable to confirm rollback of the incomplete operation.'); + } + + return $result; + } + try { $committed = $this->pdo->commit(); } catch (Throwable $throwable) { @@ -207,6 +216,11 @@ private function waitBeforeRetry(int $retry): void ($this->sleep)(($this->randomDelay)(0, $ceilingMicroseconds)); } + private function rollBackToIdle(): bool + { + return $this->pdo->rollBack() && !$this->pdo->inTransaction(); + } + private function rollBackIfActive(): void { try { diff --git a/src/Transaction/Repository/PdoProtectedTransactionCheckout.php b/src/Transaction/Repository/PdoProtectedTransactionCheckout.php index b9e05eb..b015f9e 100644 --- a/src/Transaction/Repository/PdoProtectedTransactionCheckout.php +++ b/src/Transaction/Repository/PdoProtectedTransactionCheckout.php @@ -58,8 +58,8 @@ public static function attachExclusive(#[SensitiveParameter] PDO $pdo, Protected * Qualifies the idle server session under reservation, then starts a write * transaction using the Host's isolation settings. Work becomes available * after the start is confirmed on the same session. A failed qualification - * or unconfirmed start settles as DISCARD_REQUIRED with the corresponding - * SERVER_QUALIFICATION_FAILED or START_UNCONFIRMED reason. + * or unconfirmed start settles as DiscardRequired with the corresponding + * ServerQualificationFailed or StartUnconfirmed reason. * * @throws ProtectedTransactionException If the checkout is unavailable, the start was already attempted, or the session cannot be confirmed. * @throws PDOException The original driver failure, when the driver throws. @@ -70,15 +70,15 @@ public function begin(): void throw new ProtectedTransactionException('This protected checkout cannot start a transaction.'); } $this->reserve(); - $reason = Reason::SERVER_QUALIFICATION_FAILED; + $reason = Reason::ServerQualificationFailed; try { $session = $this->inspect(false); - $reason = Reason::START_UNCONFIRMED; + $reason = Reason::StartUnconfirmed; $this->control(ProtectedTransactionDriver::START); $this->inspect(true, $session); $this->session = $session; } catch (Throwable $failure) { - $this->settle(Disposition::DISCARD_REQUIRED, $reason); + $this->settle(Disposition::DiscardRequired, $reason); throw $failure; } finally { $this->busy = false; @@ -163,7 +163,7 @@ private function finishOperation(ProtectedTransactionConnection $connection, str } $info = $failure instanceof PDOException ? $failure->errorInfo : null; $lost = $this->mariaDb && ($info[0] ?? null) === 'HY000' && in_array($info[1] ?? null, [1020, '1020'], true); - $this->settle(Disposition::DISCARD_REQUIRED, $lost ? Reason::TRANSACTION_LOST : Reason::OPERATION_UNCONFIRMED); + $this->settle(Disposition::DiscardRequired, $lost ? Reason::TransactionLost : Reason::OperationUnconfirmed); if ($primary === null) { throw $failure; } @@ -171,9 +171,9 @@ private function finishOperation(ProtectedTransactionConnection $connection, str /** * Attempts to commit the active Host transaction once. Confirmed commit - * and an idle session permit handoff. COMMIT_OUTCOME_UNKNOWN covers a + * and an idle session permit handoff. CommitOutcomeUnknown covers a * commit that may have been sent without a confirmed reply. - * COMMIT_CONFIRMED_CONNECTION_UNSAFE preserves a known commit when the + * CommitConfirmedConnectionUnsafe preserves a known commit when the * subsequent session check fails. Read settlement() after an exception. * * @throws ProtectedTransactionException|PDOException If the operation is unavailable or completion cannot be confirmed. @@ -206,8 +206,8 @@ public function settlement(): ?ProtectedTransactionSettlementDTO } /** - * Hands the original PDO back once after a verified end (REUSABLE), or - * cancels an untouched checkout (UNCHANGED) without qualifying its session. + * Hands the original PDO back once after a verified end (Reusable), or + * cancels an untouched checkout (Unchanged) without qualifying its session. * Either handoff ends this checkout's authority and releases the PDO claim. * * @throws ProtectedTransactionException During a reservation, active transaction, required discard or after handoff or discard. @@ -217,9 +217,9 @@ public function returnForHost(): PDO $this->reserve(); try { if ($this->outcome === null && $this->session === null) { - $this->settle(Disposition::UNCHANGED, Reason::CANCELLED_BEFORE_QUALIFICATION); + $this->settle(Disposition::Unchanged, Reason::CancelledBeforeQualification); } - if ($this->outcome === null || $this->outcome->disposition === Disposition::DISCARD_REQUIRED) { + if ($this->outcome === null || $this->outcome->disposition === Disposition::DiscardRequired) { throw new ProtectedTransactionException('The protected connection cannot be returned.'); } @@ -235,7 +235,7 @@ public function returnForHost(): PDO /** * Retires the checkout without returning PDO or issuing explicit SQL. - * Preserves a terminal settlement, or records HOST_DISCARDED when none + * Preserves a terminal settlement, or records HostDiscarded when none * exists. Dropping the reference may trigger automatic driver rollback. * * @throws ProtectedTransactionException During a reservation or after handoff or discard. @@ -245,7 +245,7 @@ public function discardForHost(): void $this->reserve(); try { if ($this->outcome === null) { - $this->settle(Disposition::DISCARD_REQUIRED, Reason::HOST_DISCARDED); + $this->settle(Disposition::DiscardRequired, Reason::HostDiscarded); } // Dropping the last reference can trigger driver-owned cleanup. $this->pdo = null; @@ -263,16 +263,16 @@ private function finish(bool $commit): void { $session = $this->activeSession(); $this->reserve(); - $reason = Reason::OPERATION_UNCONFIRMED; + $reason = Reason::OperationUnconfirmed; try { $this->inspect(true, $session); - $reason = $commit ? Reason::COMMIT_OUTCOME_UNKNOWN : Reason::ROLLBACK_UNCONFIRMED; + $reason = $commit ? Reason::CommitOutcomeUnknown : Reason::RollbackUnconfirmed; $this->control($commit ? ProtectedTransactionDriver::COMMIT : ProtectedTransactionDriver::ROLLBACK); - $reason = $commit ? Reason::COMMIT_CONFIRMED_CONNECTION_UNSAFE : Reason::ROLLBACK_UNCONFIRMED; + $reason = $commit ? Reason::CommitConfirmedConnectionUnsafe : Reason::RollbackUnconfirmed; $this->inspect(false, $session); - $this->settle(Disposition::REUSABLE, $commit ? Reason::COMMITTED : Reason::ROLLED_BACK); + $this->settle(Disposition::Reusable, $commit ? Reason::Committed : Reason::RolledBack); } catch (Throwable $failure) { - $this->settle(Disposition::DISCARD_REQUIRED, $reason); + $this->settle(Disposition::DiscardRequired, $reason); throw $failure; } finally { $this->busy = false; diff --git a/src/Transaction/Repository/PdoSavepointTransactionRunner.php b/src/Transaction/Repository/PdoSavepointTransactionRunner.php index 6384aa0..803530a 100644 --- a/src/Transaction/Repository/PdoSavepointTransactionRunner.php +++ b/src/Transaction/Repository/PdoSavepointTransactionRunner.php @@ -49,9 +49,16 @@ public function __construct(private PDO $pdo, int $maxDeadlockRetries = 0) /** * Returns the callback result after releasing an operation-local savepoint - * in an existing caller transaction. On failure it attempts local cleanup - * and preserves the original throwable. If PDO has no active transaction, - * owns it instead and applies the configured deadlock replay policy. + * in an existing caller transaction. A callback or RELEASE failure + * keeps precedence after best-effort local cleanup. If PDO has no active + * transaction, owns it instead and applies the configured deadlock replay + * policy. A false owned BEGIN prevents the callback from running. A false + * owned COMMIT suppresses the result after best-effort rollback. + * + * A false result from owned BEGIN, owned COMMIT, SAVEPOINT or RELEASE + * raises TransactionExecutionException. The same exception is raised if + * the caller's transaction is no longer active after SAVEPOINT. Any + * callback or driver Throwable that escapes this call retains its identity. * * @template TResult * diff --git a/src/Transaction/Repository/PdoTransactionRunner.php b/src/Transaction/Repository/PdoTransactionRunner.php index 7d54822..9fe85ac 100644 --- a/src/Transaction/Repository/PdoTransactionRunner.php +++ b/src/Transaction/Repository/PdoTransactionRunner.php @@ -60,6 +60,11 @@ public function __construct(private PDO $pdo, int $maxDeadlockRetries = 0) * a savepoint or directing its outcome. Only owned work is eligible for * the configured deadlock replay. * + * A false owned BEGIN or COMMIT raises TransactionExecutionException. + * A false BEGIN prevents the callback from running. A false COMMIT + * suppresses the result after best-effort rollback. Any callback or + * driver Throwable that escapes this call retains its identity. + * * @template TResult * * @param callable(): TResult $callback diff --git a/src/Transaction/Repository/PdoVerifiedTransactionCheckout.php b/src/Transaction/Repository/PdoVerifiedTransactionCheckout.php index e97a76f..f3744f5 100644 --- a/src/Transaction/Repository/PdoVerifiedTransactionCheckout.php +++ b/src/Transaction/Repository/PdoVerifiedTransactionCheckout.php @@ -6,7 +6,7 @@ use Closure; use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandCatalog; -use Maatify\PhpPersistence\Transaction\DTO\VerifiedTransactionDecisionDTO; +use Maatify\PhpPersistence\Transaction\Command\VerifiedTransactionDecisionCommand; use Maatify\PhpPersistence\Transaction\DTO\VerifiedTransactionSettlementDTO; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum as Disposition; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionOutcomeEnum as Outcome; @@ -80,8 +80,13 @@ public static function attachExclusive( * Starts the single Owned transaction from an unused checkout. Apply * commits and Discard rolls back. The normal payload is returned after * acknowledgement of that end and confirmation of the same idle session. + * When the callback throws, acknowledged rollback and confirmation of + * the same idle session yield a rolled-back, reusable settlement. The + * original error escapes. An unconfirmed cleanup still preserves the + * callback error and publishes a discard-required settlement. Check + * settlement() before returning or discarding the PDO. * - * @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionDTO $operation + * @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionCommand $operation */ public function runOwned(Closure $operation): mixed { @@ -99,12 +104,12 @@ public function beginHost(): void { $this->requireIdle(); $this->reserve(); - $reason = Reason::QUALIFICATION_FAILED; - $transaction = Outcome::NOT_STARTED; + $reason = Reason::QualificationFailed; + $transaction = Outcome::NotStarted; try { $this->start($reason, $transaction); } catch (Throwable $failure) { - $this->settleEnd($transaction, $reason, Disposition::DISCARD_REQUIRED); + $this->settleEnd($transaction, $reason, Disposition::DiscardRequired); throw $failure; } finally { $this->busy = false; @@ -150,7 +155,7 @@ public function runRegisteredCommand(string $commandId, array $bindings = []): i return $result; } catch (Throwable $failure) { if ($receiver->failure() !== null) { - $this->settleEnd(Outcome::UNKNOWN, $this->receiverReason($receiver), Disposition::DISCARD_REQUIRED); + $this->settleEnd(Outcome::Unknown, $this->receiverReason($receiver), Disposition::DiscardRequired); } throw $failure; } finally { @@ -164,8 +169,14 @@ public function runRegisteredCommand(string $commandId, array $bindings = []): i * Apply requires acknowledged release. Discard requires acknowledged * rollback to the savepoint and release. Both require continuity before * returning the payload. The Host still decides the outer end. + * When the callback throws, its original Throwable escapes whether local + * settlement succeeds or fails. Acknowledged local undo and release with + * confirmed session continuity record a locally undone settlement and let + * the Host continue its transaction. Failed settlement records the + * DiscardRequired disposition. Check settlement() before continuing the + * transaction or reusing the connection. * - * @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionDTO $operation + * @param Closure(VerifiedTransactionCommandsInterface): VerifiedTransactionDecisionCommand $operation */ public function runInHost(Closure $operation): mixed { @@ -215,9 +226,9 @@ public function returnForHost(): PDO $this->reserve(); try { if ($this->snapshot->disposition === null && $this->session === null) { - $this->settleEnd(Outcome::NOT_STARTED, null, Disposition::UNCHANGED); + $this->settleEnd(Outcome::NotStarted, null, Disposition::Unchanged); } - if ($this->snapshot->disposition === null || $this->snapshot->disposition === Disposition::DISCARD_REQUIRED) { + if ($this->snapshot->disposition === null || $this->snapshot->disposition === Disposition::DiscardRequired) { throw new ProtectedTransactionException('The verified connection cannot be returned.'); } $pdo = $this->connection(); @@ -242,9 +253,9 @@ public function discardForHost(): void try { if ($this->snapshot->disposition === null) { $this->settleEnd( - $this->session === null ? Outcome::NOT_STARTED : Outcome::UNKNOWN, - Reason::HOST_DISCARDED, - Disposition::DISCARD_REQUIRED, + $this->session === null ? Outcome::NotStarted : Outcome::Unknown, + Reason::HostDiscarded, + Disposition::DiscardRequired, ); } $this->pdo = null; @@ -265,9 +276,9 @@ private function run(Closure $operation, bool $owned): mixed $this->reserve(); $this->attempted = true; $receiver = new ProtectedTransactionConnection($this->connection()); - $reason = Reason::CONTINUITY_UNCONFIRMED; - $transaction = $owned ? Outcome::NOT_STARTED : Outcome::UNKNOWN; - $effect = Outcome::NOT_STARTED; + $reason = Reason::ContinuityUnconfirmed; + $transaction = $owned ? Outcome::NotStarted : Outcome::Unknown; + $effect = Outcome::NotStarted; $primary = null; $payload = null; $published = false; @@ -277,13 +288,13 @@ private function run(Closure $operation, bool $owned): mixed $this->start($reason, $transaction); } else { $this->inspect(true); - $reason = Reason::SAVEPOINT_UNCONFIRMED; + $reason = Reason::SavepointUnconfirmed; $savepoint = SavepointScope::open($receiver); - $reason = Reason::CONTINUITY_UNCONFIRMED; + $reason = Reason::ContinuityUnconfirmed; $this->inspect(true); } - $effect = Outcome::UNKNOWN; + $effect = Outcome::Unknown; // Keep execution handles out of arguments exposed by exceptions inside the callback. $executor = new ProtectedTransactionCommandExecutor($receiver); $scope = new VerifiedTransactionCommandScope( @@ -320,7 +331,7 @@ function (string $commandId, array $bindings) use ($receiver, $executor): int|ar } $commit = false; if ($primary === null) { - if ($decision instanceof VerifiedTransactionDecisionDTO) { + if ($decision instanceof VerifiedTransactionDecisionCommand) { $commit = $decision->isApply; $payload = $decision->payload; } else { @@ -336,21 +347,21 @@ function (string $commandId, array $bindings) use ($receiver, $executor): int|ar $this->snapshot = new VerifiedTransactionSettlementDTO( $effect, - $primary === null ? null : Reason::CALLBACK_FAILED, + $primary === null ? null : Reason::CallbackFailed, $owned ? $transaction : null, null, - $owned ? Disposition::REUSABLE : null, + $owned ? Disposition::Reusable : null, ); $published = true; if ($owned) { $this->session = null; } } catch (Throwable $failure) { - if ($owned && ($transaction === Outcome::COMMITTED || $transaction === Outcome::ROLLED_BACK)) { + if ($owned && ($transaction === Outcome::Committed || $transaction === Outcome::RolledBack)) { $effect = $transaction; } $reason = $this->continuityReason($reason, $failure); - $this->snapshot = new VerifiedTransactionSettlementDTO($effect, $reason, $transaction, $reason, Disposition::DISCARD_REQUIRED); + $this->snapshot = new VerifiedTransactionSettlementDTO($effect, $reason, $transaction, $reason, Disposition::DiscardRequired); $published = true; $this->session = null; throw $primary ?? $failure; @@ -360,10 +371,10 @@ function (string $commandId, array $bindings) use ($receiver, $executor): int|ar // A suspended Fiber can unwind without returning or throwing to the call site. $this->snapshot = new VerifiedTransactionSettlementDTO( $effect, - Reason::CONTINUITY_UNCONFIRMED, + Reason::ContinuityUnconfirmed, $transaction, - Reason::CONTINUITY_UNCONFIRMED, - Disposition::DISCARD_REQUIRED, + Reason::ContinuityUnconfirmed, + Disposition::DiscardRequired, ); $this->session = null; } @@ -383,11 +394,11 @@ function (string $commandId, array $bindings) use ($receiver, $executor): int|ar */ private function start(Reason &$reason, Outcome &$transaction): void { - $reason = Reason::QUALIFICATION_FAILED; + $reason = Reason::QualificationFailed; $driver = new ProtectedTransactionDriver($this->connection()); $session = $driver->inspect(false, null, closeOnFetchFailure: true); - $reason = Reason::START_UNCONFIRMED; - $transaction = Outcome::UNKNOWN; + $reason = Reason::StartUnconfirmed; + $transaction = Outcome::Unknown; $driver->start(); $driver->inspect(true, $session['id'], closeOnFetchFailure: true); $this->session = $session['id']; @@ -400,19 +411,19 @@ private function start(Reason &$reason, Outcome &$transaction): void */ private function finishWindow(SavepointScope $savepoint, bool $apply, Reason &$reason, Outcome &$effect): void { - $reason = Reason::CONTINUITY_UNCONFIRMED; + $reason = Reason::ContinuityUnconfirmed; $this->inspect(true); if (!$apply) { - $reason = Reason::ROLLBACK_TO_UNCONFIRMED; + $reason = Reason::RollbackToUnconfirmed; $savepoint->rollbackStrict(); - $effect = Outcome::LOCAL_UNDONE; + $effect = Outcome::LocalUndone; } - $reason = Reason::RELEASE_UNCONFIRMED; + $reason = Reason::ReleaseUnconfirmed; $savepoint->releaseStrict(); - $reason = Reason::CONTINUITY_UNCONFIRMED; + $reason = Reason::ContinuityUnconfirmed; $this->inspect(true); if ($apply) { - $effect = Outcome::PENDING_HOST; + $effect = Outcome::PendingHost; } } @@ -425,13 +436,13 @@ private function finishHost(bool $commit): void { $this->requireActive(); $this->reserve(); - $reason = Reason::CONTINUITY_UNCONFIRMED; - $transaction = Outcome::UNKNOWN; + $reason = Reason::ContinuityUnconfirmed; + $transaction = Outcome::Unknown; try { $this->end($commit, $reason, $transaction); - $this->settleEnd($transaction, null, Disposition::REUSABLE); + $this->settleEnd($transaction, null, Disposition::Reusable); } catch (Throwable $failure) { - $this->settleEnd($transaction, $this->continuityReason($reason, $failure), Disposition::DISCARD_REQUIRED); + $this->settleEnd($transaction, $this->continuityReason($reason, $failure), Disposition::DiscardRequired); throw $failure; } finally { $this->busy = false; @@ -444,12 +455,12 @@ private function finishHost(bool $commit): void */ private function end(bool $commit, Reason &$reason, Outcome &$transaction): void { - $reason = Reason::CONTINUITY_UNCONFIRMED; + $reason = Reason::ContinuityUnconfirmed; $this->inspect(true); - $reason = $commit ? Reason::COMMIT_OUTCOME_UNKNOWN : Reason::ROLLBACK_UNCONFIRMED; + $reason = $commit ? Reason::CommitOutcomeUnknown : Reason::RollbackUnconfirmed; (new ProtectedTransactionDriver($this->connection()))->end($commit); - $transaction = $commit ? Outcome::COMMITTED : Outcome::ROLLED_BACK; - $reason = Reason::HANDOFF_UNCONFIRMED; + $transaction = $commit ? Outcome::Committed : Outcome::RolledBack; + $reason = Reason::HandoffUnconfirmed; $this->inspect(false); } @@ -466,19 +477,19 @@ private function inspect(bool $active): void private function receiverReason(ProtectedTransactionConnection $receiver): Reason { if ($this->isTransactionLoss($receiver->failure())) { - return Reason::TRANSACTION_LOST; + return Reason::TransactionLost; } if ($receiver->cursorFailure()) { - return Reason::CURSOR_UNCONFIRMED; + return Reason::CursorUnconfirmed; } - return $receiver->continuityFailure() ? Reason::CONTINUITY_UNCONFIRMED : Reason::COMMAND_FAILED; + return $receiver->continuityFailure() ? Reason::ContinuityUnconfirmed : Reason::CommandFailed; } private function continuityReason(Reason $reason, Throwable $failure): Reason { - return $reason === Reason::CONTINUITY_UNCONFIRMED && $this->isTransactionLoss($failure) - ? Reason::TRANSACTION_LOST + return $reason === Reason::ContinuityUnconfirmed && $this->isTransactionLoss($failure) + ? Reason::TransactionLost : $reason; } diff --git a/src/Transaction/Repository/ProtectedTransactionDriver.php b/src/Transaction/Repository/ProtectedTransactionDriver.php index e308efb..ee454da 100644 --- a/src/Transaction/Repository/ProtectedTransactionDriver.php +++ b/src/Transaction/Repository/ProtectedTransactionDriver.php @@ -49,6 +49,7 @@ public function inspect(bool $active, ?string $expected, bool $closeOnFetchFailu throw new ProtectedTransactionException('Unable to inspect the protected session.'); } try { + /** @var list|false $row Positional columns for session ID, autocommit and version, or false on absence or failure. */ $row = $statement->fetch(PDO::FETCH_NUM); } catch (Throwable $primary) { if ($closeOnFetchFailure) { diff --git a/src/Transaction/Repository/ProtectedTransactionStatement.php b/src/Transaction/Repository/ProtectedTransactionStatement.php index a7ac0d2..ea40f32 100644 --- a/src/Transaction/Repository/ProtectedTransactionStatement.php +++ b/src/Transaction/Repository/ProtectedTransactionStatement.php @@ -110,6 +110,10 @@ public function errorCode(): ?string return $this->driver()->errorCode(); } + /** + * Returns the driver's affected-row count while the receiver is available. + * A driver error records the first failure for settlement and is rethrown. + */ public function rowCount(): int { $statement = $this->driver(); diff --git a/src/Transaction/Repository/SavepointScope.php b/src/Transaction/Repository/SavepointScope.php index c351a09..f203a90 100644 --- a/src/Transaction/Repository/SavepointScope.php +++ b/src/Transaction/Repository/SavepointScope.php @@ -21,9 +21,9 @@ * is acknowledged. The initiating Throwable keeps precedence over * state-check and cleanup failures. * - {@see self::undoOrFail()} is for a caller that reports failure without - * throwing: ROLLBACK TO must succeed, and its failure is not swallowed; - * Ordering uses this path for a move with a zero-row target update. A - * protected receiver records cleanup failure for the checkout to settle. + * throwing. Raw Ordering requires acknowledged ROLLBACK TO and RELEASE + * before returning its zero-row result. A protected receiver records + * cleanup failure for the checkout to settle. * - {@see self::begin()} fails before any mutation when the driver reports no * active transaction right after the SAVEPOINT reply: a server-aborted * caller transaction that the caller swallowed shows up here on the @@ -117,15 +117,23 @@ public function cleanupAfterFailure(): void } /** - * For a non-throwing failed window, ROLLBACK TO must succeed. Raw PDO treats - * RELEASE as best effort. A protected receiver records a RELEASE failure - * so the checkout fences further work and suppresses a normal result. + * For a non-throwing failed window, ROLLBACK TO must succeed before + * RELEASE is attempted. Raw PDO requires RELEASE to succeed too. A + * protected receiver records a RELEASE failure so the checkout fences + * further work and suppresses a normal result. * - * @throws Throwable when ROLLBACK TO fails + * @throws Throwable when ROLLBACK TO or a raw RELEASE fails */ public function undoOrFail(): void { $this->rollbackStrict(); + + if ($this->pdo instanceof PDO) { + $this->releaseStrict(); + + return; + } + $this->tryControlStatement('RELEASE SAVEPOINT ' . $this->name); } @@ -143,6 +151,10 @@ private function executeControlStatement(string $sql): void } } + /** + * Turns a failed best-effort control command into false. A protected receiver + * keeps its recorded failure so the enclosing operation can settle it. + */ private function tryControlStatement(string $sql): bool { try { diff --git a/src/Transaction/Repository/VerifiedTransactionCommandScope.php b/src/Transaction/Repository/VerifiedTransactionCommandScope.php index 509167b..5e5e90d 100644 --- a/src/Transaction/Repository/VerifiedTransactionCommandScope.php +++ b/src/Transaction/Repository/VerifiedTransactionCommandScope.php @@ -51,13 +51,21 @@ public function close(): void private function __clone() {} - /** @return array */ + /** + * @return array + * + * @throws ProtectedTransactionException Always. Command authority is limited to the live callback and its creating context. + */ public function __serialize(): array { throw new ProtectedTransactionException('A verified transaction command scope cannot be serialized.'); } - /** @param array $data */ + /** + * @param array $data + * + * @throws ProtectedTransactionException Always. A live verified callback must provide the command scope. + */ public function __unserialize(array $data): void { throw new ProtectedTransactionException('A verified transaction command scope cannot be restored.'); diff --git a/tests/Integration/Infrastructure/IntegrationResidueShadowTest.php b/tests/Integration/Infrastructure/IntegrationResidueShadowTest.php index fd606b0..9f34451 100644 --- a/tests/Integration/Infrastructure/IntegrationResidueShadowTest.php +++ b/tests/Integration/Infrastructure/IntegrationResidueShadowTest.php @@ -4,10 +4,11 @@ namespace Maatify\PhpPersistence\Tests\Integration\Infrastructure; -use IntegrationResidueShadow; +use Maatify\PhpPersistence\Tooling\IntegrationResidueShadow; use Maatify\PhpPersistence\Tests\Integration\IntegrationTestCase; use PDO; use PDOException; +use PDOStatement; use PHPUnit\Framework\Attributes\TestWith; use SensitiveParameter; @@ -87,7 +88,9 @@ private function exerciseServerControls(bool $commit): void $readerRow = $this->ownedRow($rows, $readerProcess); $writerBinding = $this->binding($observer, $row); $readerBinding = $this->binding($observer, $readerRow); - self::assertSame('0', $this->scalar($observer, 'SELECT COUNT(*) FROM performance_schema.data_locks WHERE THREAD_ID=' . $readerBinding['thread'])); + $writerLocks = $this->controlledLocks($observer, [$writerBinding['thread']]); + self::assertContains($table, array_column($writerLocks, 'OBJECT_NAME'), 'The active writer holds a fixture lock.'); + self::assertSame([], $this->controlledLocks($observer, [$readerBinding['thread']]), 'The reader owns no locks, even while the writer holds them.'); $live = IntegrationResidueShadow::observe($observer, 'mysql', [$row, $readerRow]); self::assertSame(['LIVE', 'UNKNOWN'], array_column($live['transactions'], 'state')); @@ -104,16 +107,16 @@ private function exerciseServerControls(bool $commit): void self::assertSame('UNKNOWN', $otherActive['state']); self::assertTrue($reader->rollBack()); - // The controlled proof covers all three owned actors. On a - // shared harness service other threads can have no transaction - // event, so a global observation cannot assert the same coverage. + // The controlled proof uses the same three actors for events + // and locks. The global observer and residue gate keep their scope. $participants = [$process, $readerProcess, $contenderProcess]; $before = $this->controlledEvents($observer, $participants); - self::assertSame('0', $this->scalar($observer, 'SELECT COUNT(*) FROM performance_schema.data_locks')); + $locks = $this->controlledLocks($observer, array_column($before, 'thread')); $after = $this->controlledEvents($observer, $participants); + self::assertSame([], $locks, 'A controlled participant still owns a lock after settlement.'); // Supply the real pre-end row so timing of the cache refresh does // not decide whether the test reaches the failing residue gate. - $stale = IntegrationResidueShadow::classify([$row], $before, $after, [], [], $bindings); + $stale = IntegrationResidueShadow::classify([$row], $before, $after, $locks, [], $bindings); $this->assertOriginalGate($stale, [$row], 'STALE_CONFIRMED'); $unbound = IntegrationResidueShadow::observe($observer, 'mysql', [$row]); $this->assertOriginalGate($unbound, [$row], 'UNKNOWN'); @@ -214,8 +217,14 @@ private function binding(PDO $observer, array $row): array self::assertMatchesRegularExpression('/^[1-9][0-9]*$/', $event); // Only the fixture controls this session and its single active event. - return ['transaction' => $row['id'], 'started' => $row['started'], 'thread' => $thread, 'event' => $event, - 'endAcknowledged' => false, 'independentlyChecked' => false]; + return [ + 'transaction' => $row['id'], + 'started' => $row['started'], + 'thread' => $thread, + 'event' => $event, + 'endAcknowledged' => false, + 'independentlyChecked' => false, + ]; } /** @@ -239,8 +248,11 @@ private function controlledEvents(PDO $observer, array $participants): array self::assertContains($row['STATE'], ['COMMITTED', 'ROLLED BACK']); self::assertSame('YES', $row['INSTRUMENTED']); $events[(int) $row['PROCESSLIST_ID']] = [ - 'thread' => (string) $row['THREAD_ID'], 'instrumented' => true, - 'event' => (string) $row['EVENT_ID'], 'state' => $row['STATE'], 'end' => (string) $row['END_EVENT_ID'], + 'thread' => (string) $row['THREAD_ID'], + 'instrumented' => true, + 'event' => (string) $row['EVENT_ID'], + 'state' => $row['STATE'], + 'end' => (string) $row['END_EVENT_ID'], ]; } } finally { @@ -251,6 +263,42 @@ private function controlledEvents(PDO $observer, array $participants): array return $events; } + /** + * Samples locks for exactly the selected fixture threads. The bounded + * failure evidence identifies locks without recording row data. + * + * @param list $threads + * @return list> + */ + private function controlledLocks(PDO $observer, array $threads): array + { + self::assertNotEmpty($threads); + self::assertCount(count($threads), array_unique($threads)); + foreach ($threads as $thread) { + self::assertMatchesRegularExpression('/\A[1-9][0-9]*\z/', $thread); + } + $parameters = implode(', ', array_fill(0, count($threads), 'CAST(? AS UNSIGNED)')); + $statement = $observer->prepare( + 'SELECT THREAD_ID, ENGINE_TRANSACTION_ID, SHA2(ENGINE_LOCK_ID, 256) AS LOCK_ID_SHA256,' + . ' OBJECT_SCHEMA, OBJECT_NAME, INDEX_NAME, LOCK_TYPE, LOCK_MODE, LOCK_STATUS' + . " FROM performance_schema.data_locks WHERE THREAD_ID IN ($parameters)" + . ' ORDER BY THREAD_ID, ENGINE_LOCK_ID LIMIT 10', + ); + self::assertInstanceOf(PDOStatement::class, $statement); + try { + self::assertTrue($statement->execute($threads)); + + $locks = []; + while (($lock = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { + $locks[] = $lock; + } + + return $locks; + } finally { + self::assertTrue($statement->closeCursor()); + } + } + /** @return array{instrument: string, consumers: array} */ private function transactionEventSettings(PDO $observer): array { diff --git a/tests/Integration/Ordering/B1CheckoutLifecycle.php b/tests/Integration/Ordering/B1CheckoutLifecycle.php index 4c72ebe..142da76 100644 --- a/tests/Integration/Ordering/B1CheckoutLifecycle.php +++ b/tests/Integration/Ordering/B1CheckoutLifecycle.php @@ -35,13 +35,13 @@ public function begin(PdoProtectedTransactionCheckout $checkout): void public function commit(PdoProtectedTransactionCheckout $checkout): void { $checkout->commit(); - $this->handoff($checkout, Reason::COMMITTED); + $this->handoff($checkout, Reason::Committed); } public function rollBack(PdoProtectedTransactionCheckout $checkout): void { $checkout->rollBack(); - $this->handoff($checkout, Reason::ROLLED_BACK); + $this->handoff($checkout, Reason::RolledBack); } public function cancel(PdoProtectedTransactionCheckout $checkout): void @@ -52,8 +52,8 @@ public function cancel(PdoProtectedTransactionCheckout $checkout): void unset($this->pending[$id]); $settlement = $checkout->settlement(); Assert::assertNotNull($settlement); - Assert::assertSame(Disposition::UNCHANGED, $settlement->disposition); - Assert::assertSame(Reason::CANCELLED_BEFORE_QUALIFICATION, $settlement->reason); + Assert::assertSame(Disposition::Unchanged, $settlement->disposition); + Assert::assertSame(Reason::CancelledBeforeQualification, $settlement->reason); } public function discard(PdoProtectedTransactionCheckout $checkout): void @@ -61,7 +61,7 @@ public function discard(PdoProtectedTransactionCheckout $checkout): void $id = $this->tracked($checkout); $settlement = $checkout->settlement(); Assert::assertNotNull($settlement); - Assert::assertSame(Disposition::DISCARD_REQUIRED, $settlement->disposition); + Assert::assertSame(Disposition::DiscardRequired, $settlement->disposition); $checkout->discardForHost(); unset($this->pending[$id]); Assert::assertSame($settlement, $checkout->settlement()); @@ -80,9 +80,9 @@ public function finish(?Throwable $primary = null): void foreach ($this->pending as $id => [$checkout, $begun]) { $disposition = $checkout->settlement()?->disposition; $state = match ($disposition) { - Disposition::REUSABLE => 'reusable without handoff', - Disposition::DISCARD_REQUIRED => 'discard required without discard', - Disposition::UNCHANGED => 'cancelled without handoff', + Disposition::Reusable => 'reusable without handoff', + Disposition::DiscardRequired => 'discard required without discard', + Disposition::Unchanged => 'cancelled without handoff', null => $begun ? 'active without verified end' : 'unstarted without cancellation', }; $incomplete[] = 'checkout ' . $id . ' ' . $state; @@ -107,7 +107,7 @@ public function finish(?Throwable $primary = null): void private function emergencyRelease(PdoProtectedTransactionCheckout $checkout, bool $begun, ?Disposition $disposition): void { - if ($disposition === Disposition::DISCARD_REQUIRED) { + if ($disposition === Disposition::DiscardRequired) { $checkout->discardForHost(); return; @@ -133,7 +133,7 @@ private function handoff(PdoProtectedTransactionCheckout $checkout, Reason $reas $id = $this->tracked($checkout); $settlement = $checkout->settlement(); Assert::assertNotNull($settlement); - Assert::assertSame(Disposition::REUSABLE, $settlement->disposition); + Assert::assertSame(Disposition::Reusable, $settlement->disposition); Assert::assertSame($reason, $settlement->reason); $checkout->returnForHost(); unset($this->pending[$id]); diff --git a/tests/Integration/Ordering/OrderingIntegrationTestCase.php b/tests/Integration/Ordering/OrderingIntegrationTestCase.php index 1660cf6..e8d7efc 100644 --- a/tests/Integration/Ordering/OrderingIntegrationTestCase.php +++ b/tests/Integration/Ordering/OrderingIntegrationTestCase.php @@ -57,13 +57,13 @@ protected function createGlobalOrderingTable(PDO $pdo): string $table = 'it_ordering_global_' . bin2hex(random_bytes(6)); $pdo->exec( 'CREATE TABLE `' . $table . '` (' - . '`id` INT UNSIGNED NOT NULL AUTO_INCREMENT, ' - . '`display_order` INT NOT NULL, ' - . '`deleted_at` DATETIME NULL DEFAULT NULL, ' - . '`label` VARCHAR(191) NOT NULL, ' - . 'PRIMARY KEY (`id`), ' - . 'KEY `idx_deleted_at` (`deleted_at`)' - . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci', + . '`id` INT UNSIGNED NOT NULL AUTO_INCREMENT, ' + . '`display_order` INT NOT NULL, ' + . '`deleted_at` DATETIME NULL DEFAULT NULL, ' + . '`label` VARCHAR(191) NOT NULL, ' + . 'PRIMARY KEY (`id`), ' + . 'KEY `idx_deleted_at` (`deleted_at`)' + . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci', ); $this->orderingTables[] = $table; @@ -76,16 +76,16 @@ protected function createScopedOrderingTable(PDO $pdo): string $table = 'it_ordering_scoped_' . bin2hex(random_bytes(6)); $pdo->exec( 'CREATE TABLE `' . $table . '` (' - . '`id` INT UNSIGNED NOT NULL AUTO_INCREMENT, ' - . '`scope_key` VARCHAR(191) NULL DEFAULT NULL, ' - . '`display_order` INT NOT NULL, ' - . '`deleted_at` DATETIME NULL DEFAULT NULL, ' - . '`updated_at` DATETIME NULL DEFAULT NULL, ' - . '`label` VARCHAR(191) NOT NULL, ' - . 'PRIMARY KEY (`id`), ' - . 'KEY `idx_scope_order` (`scope_key`, `display_order`), ' - . 'KEY `idx_deleted_at` (`deleted_at`)' - . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci', + . '`id` INT UNSIGNED NOT NULL AUTO_INCREMENT, ' + . '`scope_key` VARCHAR(191) NULL DEFAULT NULL, ' + . '`display_order` INT NOT NULL, ' + . '`deleted_at` DATETIME NULL DEFAULT NULL, ' + . '`updated_at` DATETIME NULL DEFAULT NULL, ' + . '`label` VARCHAR(191) NOT NULL, ' + . 'PRIMARY KEY (`id`), ' + . 'KEY `idx_scope_order` (`scope_key`, `display_order`), ' + . 'KEY `idx_deleted_at` (`deleted_at`)' + . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci', ); $this->orderingTables[] = $table; diff --git a/tests/Integration/Ordering/ProtectedScopedOrderingManagerIntegrationTest.php b/tests/Integration/Ordering/ProtectedScopedOrderingManagerIntegrationTest.php index 7908217..2154dcb 100644 --- a/tests/Integration/Ordering/ProtectedScopedOrderingManagerIntegrationTest.php +++ b/tests/Integration/Ordering/ProtectedScopedOrderingManagerIntegrationTest.php @@ -5,6 +5,8 @@ namespace Maatify\PhpPersistence\Tests\Integration\Ordering; use Closure; +use Maatify\PhpPersistence\Ordering\Config\ScopedOrderingConfig; +use Maatify\PhpPersistence\Ordering\Exception\InvalidOrderingOperationException; use Maatify\PhpPersistence\Ordering\Exception\OrderingExecutionException; use Maatify\PhpPersistence\Ordering\Repository\ProtectedScopedOrderingManager; use Maatify\PhpPersistence\Tests\Integration\Support\PartnerProcess; @@ -101,8 +103,8 @@ public function testGuardedOrderingFencesSnapshotHazard(bool $snapshot, bool $em } } $settlement = $checkout->settlement(); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $settlement?->disposition); - self::assertSame(ProtectedTransactionReasonEnum::TRANSACTION_LOST, $settlement->reason); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement?->disposition); + self::assertSame(ProtectedTransactionReasonEnum::TransactionLost, $settlement->reason); $this->reject(static fn() => $checkout->runRegisteredCommand('write', ['id' => $hostId])); $this->reject(static fn() => $checkout->rollBack()); $this->reject(static fn() => $checkout->returnForHost()); @@ -118,12 +120,50 @@ public function testGuardedOrderingFencesSnapshotHazard(bool $snapshot, bool $em self::assertSame($settlement, $checkout->settlement()); } + public function testInvalidMoveTimestampLeavesTheActiveCheckoutAndRowsUntouched(): void + { + $initial = '2026-01-01 00:00:00'; + $first = $this->fixture->insertScoped('target', 1, 'first', null, $initial); + $second = $this->fixture->insertScoped('target', 2, 'second', null, $initial); + $table = $this->scopedTable; + $checkout = PdoProtectedTransactionCheckout::attachExclusive( + $this->delegatedConnection(self::setting('PORT'), false), + new ProtectedTransactionCommandCatalog([ + 'read' => new ProtectedTransactionCommandPlan( + "SELECT display_order, updated_at FROM `$table` WHERE id = :id", + ['id'], + 1, + ), + ]), + ); + $config = new ScopedOrderingConfig(table: $table, scopeColumn: 'scope_key', updatedAtColumn: 'updated_at'); + $manager = new ProtectedScopedOrderingManager(); + $checkout->begin(); + + $failure = $this->caughtFailure( + fn() => $manager->moveWithinScope($checkout, $config, 'target', $second, 1, '2025-02-29 00:00:00'), + ); + self::assertInstanceOf(InvalidOrderingOperationException::class, $failure); + self::assertNull($checkout->settlement()); + self::assertSame([['display_order' => 2, 'updated_at' => $initial]], $checkout->runRegisteredCommand('read', ['id' => $second])); + + $updated = '2024-02-29 23:59:59'; + self::assertTrue($manager->moveWithinScope($checkout, $config, 'target', $second, 1, $updated)); + self::assertSame([['display_order' => 1, 'updated_at' => $updated]], $checkout->runRegisteredCommand('read', ['id' => $second])); + $checkout->rollBack(); + $checkout->returnForHost(); + self::assertSame([$first => 1, $second => 2], $this->reader()->scopedOrdersById('target')); + } + public function testReleaseFailureSuppressesFalseAfterSuccessfulSavepointUndo(): void { $this->fixture->insertScoped('target', 1); $id = $this->fixture->insertScoped('target', 2); $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'RELEASE SAVEPOINT', 'ordering-release-error', + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'RELEASE SAVEPOINT', + 'ordering-release-error', ]); try { $checkout = PdoProtectedTransactionCheckout::attachExclusive( @@ -136,7 +176,7 @@ public function testReleaseFailureSuppressesFalseAfterSuccessfulSavepointUndo(): self::assertSame(1305, self::driverCode($error)); self::assertSame('TARGET UPDATE MADE EMPTY', $relay->readLine(12.0)); self::assertSame('RELEASE REPLACED AFTER UNDO', $relay->readLine(12.0)); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $checkout->settlement()?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $checkout->settlement()?->disposition); $this->reject(static fn() => $checkout->commit()); $checkout->discardForHost(); } finally { @@ -159,7 +199,7 @@ public function testDriverErrorAfterSavepointFencesCleanupAndSubsequentCommands( $table = $this->scopedTable; $this->pdo->exec( "CREATE TRIGGER `{$table}_snapshot` BEFORE UPDATE ON `$table` FOR EACH ROW " - . "SET NEW.label = (SELECT CAST(v AS CHAR) FROM `$auxiliary` WHERE id = 1 FOR UPDATE)", + . "SET NEW.label = (SELECT CAST(v AS CHAR) FROM `$auxiliary` WHERE id = 1 FOR UPDATE)", ); $catalog['snapshot'] = new ProtectedTransactionCommandPlan("SELECT v FROM `$auxiliary` WHERE id = 1", [], 1); } @@ -186,9 +226,9 @@ public function testDriverErrorAfterSavepointFencesCleanupAndSubsequentCommands( $failure = self::failureOf(fn() => $manager->moveWithinScope($checkout, $this->scopedConfig(), 'target', $second, 1)); self::assertSame(1020, self::driverCode($failure)); $settlement = $checkout->settlement(); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $settlement?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement?->disposition); self::assertSame( - $mariaDb ? ProtectedTransactionReasonEnum::TRANSACTION_LOST : ProtectedTransactionReasonEnum::OPERATION_UNCONFIRMED, + $mariaDb ? ProtectedTransactionReasonEnum::TransactionLost : ProtectedTransactionReasonEnum::OperationUnconfirmed, $settlement->reason, ); $this->reject(static fn() => $checkout->runRegisteredCommand('read')); @@ -205,7 +245,10 @@ public function testDriverErrorAfterSavepointFencesCleanupAndSubsequentCommands( public function testReleaseFailureKeepsEarlierMovementFailureAndSealsCheckout(): void { $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'RELEASE SAVEPOINT', 'ordering-release-error', + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'RELEASE SAVEPOINT', + 'ordering-release-error', ]); try { $checkout = PdoProtectedTransactionCheckout::attachExclusive( @@ -227,7 +270,7 @@ static function (ProtectedTransactionConnection $connection) use ($primary): nev ), null, PdoProtectedTransactionCheckout::class); self::assertSame($primary, $this->caughtFailure($exercise)); self::assertSame('RELEASE REPLACED AFTER UNDO', $relay->readLine(12.0)); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $checkout->settlement()?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $checkout->settlement()?->disposition); $this->reject(static fn() => $checkout->returnForHost()); $checkout->discardForHost(); } finally { @@ -241,7 +284,11 @@ public function testProtectedTailExhaustionLeavesTheHostInControlOfTheActiveTran $this->fixture->insertScoped('target', 1); $this->fixture->insertScoped('target', 2); $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'RELEASE SAVEPOINT', 'protected-tail-churn', $table, + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'RELEASE SAVEPOINT', + 'protected-tail-churn', + $table, ]); try { $pdo = $this->delegatedConnection($this->relayPort($relay), true); @@ -267,7 +314,7 @@ public function testProtectedTailExhaustionLeavesTheHostInControlOfTheActiveTran self::assertNull($checkout->settlement()); self::assertSame('0', $this->scalar($this->pdo, "SELECT COUNT(*) FROM `$table` WHERE scope_key = 'host'")); $checkout->commit(); - self::assertSame(ProtectedTransactionReasonEnum::COMMITTED, $checkout->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::Committed, $checkout->settlement()?->reason); self::assertSame('1', $this->scalar($this->pdo, "SELECT COUNT(*) FROM `$table` WHERE scope_key = 'host'")); $checkout->returnForHost(); } finally { diff --git a/tests/Integration/Ordering/ProtectedUniqueOrderingTest.php b/tests/Integration/Ordering/ProtectedUniqueOrderingTest.php index 94b4fef..a292600 100644 --- a/tests/Integration/Ordering/ProtectedUniqueOrderingTest.php +++ b/tests/Integration/Ordering/ProtectedUniqueOrderingTest.php @@ -99,11 +99,11 @@ public function testIncompleteCheckoutFailsEvenWhenEmergencyCleanupSucceeds(stri if ($missing === 'reusable without handoff') { $checkout->commit(); - self::assertSame(ProtectedTransactionDispositionEnum::REUSABLE, $checkout->settlement()?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::Reusable, $checkout->settlement()?->disposition); } elseif ($relay !== null) { self::failureOf(fn() => $this->manager->moveUniqueWithinScope($checkout, $config, null, 3, 1)); self::assertSame('SERVER OK WITHHELD', $relay->readLine(12.0)); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $checkout->settlement()?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $checkout->settlement()?->disposition); } else { self::assertNull($checkout->settlement()); } @@ -137,20 +137,23 @@ public function testAnUntouchedCheckoutIsExplicitlyCancelled(): void $checkout = $this->checkout(begin: false); $this->lifecycle->cancel($checkout); $this->lifecycle->finish(); - self::assertSame(ProtectedTransactionReasonEnum::CANCELLED_BEFORE_QUALIFICATION, $checkout->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::CancelledBeforeQualification, $checkout->settlement()?->reason); } public function testUnconfirmedBeginIsExplicitlyDiscarded(): void { $this->createProfile(false, false); $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'START TRANSACTION READ WRITE', 'after', + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'START TRANSACTION READ WRITE', + 'after', ]); try { $checkout = $this->checkout(relayPort: $this->relayPort($relay), begin: false); self::failureOf(fn() => $this->lifecycle->begin($checkout)); self::assertSame('SERVER OK WITHHELD', $relay->readLine(12.0)); - self::assertSame(ProtectedTransactionReasonEnum::START_UNCONFIRMED, $checkout->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::StartUnconfirmed, $checkout->settlement()?->reason); $this->lifecycle->discard($checkout); $this->lifecycle->finish(); } finally { @@ -166,7 +169,10 @@ public function testEmergencyRollbackFailureIsDistinguishedAndCleansOtherCheckou $this->createProfile(false, false); $this->seedFaultProfile(); $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'ROLLBACK AND NO CHAIN NO RELEASE', 'after', + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'ROLLBACK AND NO CHAIN NO RELEASE', + 'after', ]); try { $lostAck = $this->checkout(relayPort: $this->relayPort($relay)); @@ -193,8 +199,8 @@ public function testEmergencyRollbackFailureIsDistinguishedAndCleansOtherCheckou } } self::assertSame('SERVER OK WITHHELD', $relay->readLine(12.0)); - self::assertSame(ProtectedTransactionReasonEnum::ROLLBACK_UNCONFIRMED, $lostAck->settlement()?->reason); - self::assertSame(ProtectedTransactionReasonEnum::ROLLED_BACK, $other->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::RollbackUnconfirmed, $lostAck->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::RolledBack, $other->settlement()?->reason); $this->observer->exec('SET SESSION innodb_lock_wait_timeout = 4'); $this->observer->beginTransaction(); @@ -392,8 +398,8 @@ public function testLockingReadUsesCurrentStateOrFencesMariaDbStaleSnapshot(): v if ($mariaDb) { $failure = self::failureOf($allocate); self::assertSame(1020, self::driverCode($failure)); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $stale->settlement()?->disposition); - self::assertSame(ProtectedTransactionReasonEnum::TRANSACTION_LOST, $stale->settlement()->reason); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $stale->settlement()?->disposition); + self::assertSame(ProtectedTransactionReasonEnum::TransactionLost, $stale->settlement()->reason); $this->lifecycle->discard($stale); } else { self::assertSame(3, $allocate()); @@ -411,7 +417,10 @@ public function testNoOpAndAbsentTargetDoNotOpenASavepoint(): void $this->seedFaultProfile(); $config = $this->config(); $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'SAVEPOINT', 'before', + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'SAVEPOINT', + 'before', ]); try { $checkout = $this->checkout(relayPort: $this->relayPort($relay)); @@ -486,7 +495,7 @@ public function testDriverFailureAtEachDmlPhaseFencesCheckout(string $phase, boo default => 'B1 PHASE ' . $phase, }; self::assertSame($expected, $relay->readLine(12.0)); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $checkout->settlement()?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $checkout->settlement()?->disposition); try { $checkout->commit(); self::fail('A fenced checkout accepted the commit request.'); @@ -537,8 +546,8 @@ public function testUnconfirmedCursorCloseFencesRealCheckoutAndPreservesFirstThr self::assertSame($executeFailure ?? $closeFailure, $primary); $settlement = $checkout->settlement(); self::assertNotNull($settlement); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $settlement->disposition); - self::assertSame(ProtectedTransactionReasonEnum::OPERATION_UNCONFIRMED, $settlement->reason); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement->disposition); + self::assertSame(ProtectedTransactionReasonEnum::OperationUnconfirmed, $settlement->reason); foreach ([ fn() => $checkout->runRegisteredCommand('mark', ['id' => 2]), fn() => $this->manager->getNextUniquePositionForAppend($checkout, $config, null), @@ -683,7 +692,11 @@ private function fixtureConnection(string $user, #[SensitiveParameter] string $p private function relay(string $stage, string $phase): PartnerProcess { return PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'RELEASE SAVEPOINT', $stage, $phase, + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'RELEASE SAVEPOINT', + $stage, + $phase, ]); } @@ -840,8 +853,12 @@ public function testARealAnchorDeadlockFencesTheLighterTransaction(): void private function contender(UniqueOrderingConfig $config, string $pair, string $isolation): PartnerProcess { return PartnerProcess::start([ - PHP_BINARY, __DIR__ . '/UniqueOrderingContender.php', - $this->items, $this->anchor, $isolation, $pair, + PHP_BINARY, + __DIR__ . '/UniqueOrderingContender.php', + $this->items, + $this->anchor, + $isolation, + $pair, json_encode($config->schemaAttestation, JSON_THROW_ON_ERROR), ]); } diff --git a/tests/Integration/Ordering/ScopedOrderingManagerLazySavepointTest.php b/tests/Integration/Ordering/ScopedOrderingManagerLazySavepointTest.php index ddc1205..1b78809 100644 --- a/tests/Integration/Ordering/ScopedOrderingManagerLazySavepointTest.php +++ b/tests/Integration/Ordering/ScopedOrderingManagerLazySavepointTest.php @@ -25,19 +25,17 @@ * commits, fully rolls back or retries the caller's transaction. * * Ported from legacy tests/Integration/Pdo/Ordering/ScopedOrderingManagerLazySavepointTest.php - * (1f6a7aa, provenance gate recorded in the WU-8 pull request), with two differences forced by - * this project's actual database privilege level (confirmed against mysql:8.4.13: the - * Integration Compose service grants the application user `GRANT ALL PRIVILEGES` on its own - * database only, not SUPER, and binlog is ON by default): + * (1f6a7aa, provenance gate recorded in the WU-8 pull request). The original + * port adapted two cases to the application account's privileges. On MySQL + * 8.4.13, the account has privileges on its own database, and binlog is on. * * - legacy's "false after the shifts" scenario (C04) and the matching client-injected variant * (S5) both need the target write itself to report zero affected rows without throwing, which * legacy achieved with a BEFORE UPDATE trigger that rewrites NEW back to OLD; CREATE TRIGGER - * needs SUPER or `log_bin_trust_function_creators=ON`, neither available here (error - * 1419/1458). That exact wiring — moveWithinScope() calling SavepointScope::undoOrFail() when - * the target write reports zero affected rows — is instead proven in - * tests/Unit/Ordering/Repository/ScopedOrderingManagerSavepointWiringTest.php with a scripted - * PDO, the same way WU-6 characterizes the shared helper's own statement sequence. + * needs SUPER or `log_bin_trust_function_creators=ON`. The application account + * received errors 1419/1458. ScopedOrderingManagerSettlementTest uses the + * disposable fixture admin for trigger setup and the application PDO for the move. The + * Unit wiring tests still cover the shared helper's statement sequence. * - legacy's lock-wait/deadlock (C07/C10) scenarios used a second AUDIT table that a trigger on * the target update also touched, to land the failure strictly inside the savepoint window. * Without a trigger, every row the shift/target update will touch is already exclusively @@ -486,9 +484,8 @@ public function testS4OriginalExceptionWinsOverAThrowingRollbackTo(): void $faulty->rollBack(); } - // S5 ("false result never survives a failed undo") needs the target write itself to - // return rowCount()=0 without throwing, which legacy achieved with the same neutralizing - // trigger as C04; it is proven instead in ScopedOrderingManagerSavepointWiringTest (Unit). + // ScopedOrderingManagerSettlementTest covers S5 through the raw public + // manager. A fixture trigger makes the real target UPDATE affect zero rows. public function testS6ReleaseReturningFalseUndoesTheMoveAndFails(): void { diff --git a/tests/Integration/Ordering/ScopedOrderingManagerSettlementTest.php b/tests/Integration/Ordering/ScopedOrderingManagerSettlementTest.php new file mode 100644 index 0000000..3d9e875 --- /dev/null +++ b/tests/Integration/Ordering/ScopedOrderingManagerSettlementTest.php @@ -0,0 +1,174 @@ + */ + public static function settlementOutcomes(): iterable + { + yield 'owned rollback acknowledged' => [false, null, false]; + yield 'Host undo and release acknowledged' => [true, null, false]; + foreach (['ROLLBACK', 'ROLLBACK TO SAVEPOINT', 'RELEASE SAVEPOINT'] as $control) { + $hostOwns = $control !== 'ROLLBACK'; + yield "$control returns false" => [$hostOwns, $control, false]; + yield "$control throws" => [$hostOwns, $control, true]; + } + } + + #[DataProvider('settlementOutcomes')] + public function testRawZeroRowMoveRequiresConfirmedSettlement(bool $hostOwns, ?string $control, bool $throws): void + { + $observer = $this->connect(); + $table = 'it_' . bin2hex(random_bytes(6)) . '_order_settlement'; + $observer->exec("CREATE TABLE `$table` (id INT PRIMARY KEY, scope_id INT NOT NULL, position INT NOT NULL, marker INT NOT NULL DEFAULT 0, INDEX (scope_id, position)) ENGINE=InnoDB"); + $writer = null; + + try { + $observer->exec("INSERT INTO `$table` (id, scope_id, position) VALUES (1, 10, 1), (2, 10, 2), (3, 10, 3), (4, 20, 1)"); + $this->keepTargetPosition($table); + + $writer = $this->faultConnection(); + $affectedRows = []; + $observeUpdate = static function (int $count) use (&$affectedRows): void { + $affectedRows[] = $count; + }; + self::assertTrue($writer->setAttribute(PDO::ATTR_STATEMENT_CLASS, [ObservedOrderingUpdateStatement::class, [$observeUpdate]])); + if ($hostOwns) { + self::assertTrue($writer->beginTransaction()); + self::assertSame(1, $writer->exec("UPDATE `$table` SET marker = 1 WHERE id = 4")); + } + + $injected = $throws ? new PDOException('Injected Ordering settlement failure.') : null; + if ($control === 'ROLLBACK') { + $writer->failNextRollback($injected ?? false); + } elseif ($control !== null) { + $writer->failExec('/\A' . $control . ' /', $injected ?? 'false'); + } + + $result = null; + $failure = null; + $config = new ScopedOrderingConfig( + table: $table, + orderColumn: 'position', + scopeColumn: 'scope_id', + deletedAtColumn: null, + ); + try { + $result = (new ScopedOrderingManager())->moveWithinScope($writer, $config, 10, 3, 1); + } catch (PDOException|TransactionExecutionException $exception) { + $failure = $exception; + } + + self::assertSame([2, 0], $affectedRows, 'The real range shift changes two rows and the target UPDATE changes zero.'); + $active = $hostOwns || $control === 'ROLLBACK'; + $shiftsPending = $control === 'ROLLBACK' || $control === 'ROLLBACK TO SAVEPOINT'; + self::assertSame($active, $writer->inTransaction()); + self::assertSame($shiftsPending ? [2, 3, 3, 1] : [1, 2, 3, 1], $this->positions($writer, $table)); + self::assertSame([1, 2, 3, 1], $this->positions($observer, $table)); + self::assertSame($hostOwns ? '1' : '0', $this->scalar($writer, "SELECT marker FROM `$table` WHERE id = 4")); + self::assertSame('0', $this->scalar($observer, "SELECT marker FROM `$table` WHERE id = 4")); + + if ($hostOwns) { + $this->assertLocalControlSequence($writer->savepointStatements(), $control === 'ROLLBACK TO SAVEPOINT'); + } else { + self::assertSame([], $writer->savepointStatements()); + } + + if ($control === null) { + self::assertNull($failure); + self::assertFalse($result); + } else { + self::assertNull($result, 'Failed settlement cannot return the ordinary false result.'); + if ($injected !== null) { + self::assertSame($injected, $failure); + } else { + self::assertInstanceOf(TransactionExecutionException::class, $failure); + } + } + + $hostCommitsMarker = $hostOwns && !$shiftsPending; + if ($hostCommitsMarker) { + self::assertTrue($writer->commit()); + } elseif ($active) { + self::assertTrue($writer->rollBack()); + } + + self::assertFalse($writer->inTransaction()); + self::assertSame([1, 2, 3, 1], $this->positions($observer, $table)); + self::assertSame($hostCommitsMarker ? '1' : '0', $this->scalar($observer, "SELECT marker FROM `$table` WHERE id = 4")); + } finally { + try { + if ($writer?->inTransaction()) { + $writer->exec('ROLLBACK'); + } + } finally { + $writer = null; + $observer->exec("DROP TABLE IF EXISTS `$table`"); + } + } + } + + private function keepTargetPosition(string $table): void + { + // Only fixture DDL uses the privileged account. The move uses the test application account. + $admin = new PDO(self::dsn(), 'root', self::setting('ADMIN_PASSWORD'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 10]); + $admin->exec("CREATE TRIGGER `{$table}_target` BEFORE UPDATE ON `$table` FOR EACH ROW SET NEW.position = IF(OLD.id = 3, OLD.position, NEW.position)"); + } + + private function faultConnection(): FaultInjectingPdo + { + return new FaultInjectingPdo(self::dsn(), self::setting('USER'), self::setting('PASSWORD'), [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_EMULATE_PREPARES => false, + PDO::ATTR_TIMEOUT => 10, + Mysql::ATTR_FOUND_ROWS => false, + ]); + } + + private static function dsn(): string + { + return 'mysql:host=' . self::setting('HOST') . ';port=' . self::setting('PORT') . ';dbname=' . self::setting('DATABASE'); + } + + /** @return list */ + private function positions(PDO $pdo, string $table): array + { + $statement = $pdo->query("SELECT position FROM `$table` ORDER BY id"); + self::assertInstanceOf(PDOStatement::class, $statement); + + $positions = []; + foreach ($statement->fetchAll(PDO::FETCH_COLUMN) as $position) { + self::assertIsNumeric($position); + $positions[] = (int) $position; + } + + return $positions; + } + + /** @param list $statements */ + private function assertLocalControlSequence(array $statements, bool $undoFailed): void + { + self::assertCount($undoFailed ? 2 : 3, $statements); + $savepoint = $statements[0]; + self::assertMatchesRegularExpression('/\ASAVEPOINT maatify_persistence_sp_[0-9a-f]{32}\z/', $savepoint); + self::assertSame('ROLLBACK TO ' . $savepoint, $statements[1]); + if (!$undoFailed) { + self::assertSame('RELEASE ' . $savepoint, $statements[2]); + } + } +} diff --git a/tests/Integration/Ordering/ScopedOrderingTailBudgetTest.php b/tests/Integration/Ordering/ScopedOrderingTailBudgetTest.php index cecb7fa..a344ed4 100644 --- a/tests/Integration/Ordering/ScopedOrderingTailBudgetTest.php +++ b/tests/Integration/Ordering/ScopedOrderingTailBudgetTest.php @@ -260,7 +260,7 @@ private function assertScopedRead(string $sql, ?array $params): void { self::assertSame( "SELECT `display_order` FROM `{$this->scopedTable}` WHERE `scope_key` = :scope_value AND `deleted_at` IS NULL " - . 'ORDER BY `display_order` DESC, `id` DESC LIMIT 1 FOR UPDATE', + . 'ORDER BY `display_order` DESC, `id` DESC LIMIT 1 FOR UPDATE', preg_replace('/\s+/', ' ', $sql), ); self::assertSame(['scope_value' => 'budget'], $params); diff --git a/tests/Integration/Ordering/UniqueOrderingContender.php b/tests/Integration/Ordering/UniqueOrderingContender.php index a3b31b2..68f737e 100644 --- a/tests/Integration/Ordering/UniqueOrderingContender.php +++ b/tests/Integration/Ordering/UniqueOrderingContender.php @@ -41,7 +41,7 @@ ); $pdo = new PDO( 'mysql:host=' . getenv('PHP_PERSISTENCE_IT_HOST') . ';port=' . getenv('PHP_PERSISTENCE_IT_PORT') - . ';dbname=' . getenv('PHP_PERSISTENCE_IT_DATABASE'), + . ';dbname=' . getenv('PHP_PERSISTENCE_IT_DATABASE'), (string) getenv('PHP_PERSISTENCE_IT_USER'), (string) getenv('PHP_PERSISTENCE_IT_PASSWORD'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false], @@ -107,7 +107,7 @@ throw new RuntimeException('The writer crossed a locked anchor.'); } catch (PDOException $failure) { if (!in_array($failure->errorInfo[1] ?? null, [$expected, (string) $expected], true) - || $checkout->settlement()?->disposition !== ProtectedTransactionDispositionEnum::DISCARD_REQUIRED + || $checkout->settlement()?->disposition !== ProtectedTransactionDispositionEnum::DiscardRequired ) { throw $failure; } diff --git a/tests/Integration/Pagination/DynamicSortPaginationIntegrationTest.php b/tests/Integration/Pagination/DynamicSortPaginationIntegrationTest.php index a3ed238..8d69672 100644 --- a/tests/Integration/Pagination/DynamicSortPaginationIntegrationTest.php +++ b/tests/Integration/Pagination/DynamicSortPaginationIntegrationTest.php @@ -51,8 +51,12 @@ public function testJoinedGridSortsUnicodeAndNullsWithOneUniqueTailAndAnOptional ['tenant' => 1, 'active' => true], ); $config = new PaginationConfig(new SortWhitelist([ - 'label' => 'g.nullable_code', 'name' => 'g.name', 'parent' => 'p.id', 'internal_row' => 'g.id', 'row_alias' => 'g.ID', - ]), 'name', Direction::ASC, 'internal_row', Direction::DESC, 2); + 'label' => 'g.nullable_code', + 'name' => 'g.name', + 'parent' => 'p.id', + 'internal_row' => 'g.id', + 'row_alias' => 'g.ID', + ]), 'name', Direction::Asc, 'internal_row', Direction::Desc, 2); $sorts = [['key' => 'label', 'direction' => 'desc'], ['key' => 'name', 'direction' => 'asc'], ['key' => 'parent', 'direction' => 'desc']]; $paginator = new PdoPaginator(); $reader = $this->connect(); @@ -93,7 +97,7 @@ public function testJoinedGridSortsUnicodeAndNullsWithOneUniqueTailAndAnOptional } } - $tieDefault = new PaginationConfig($config->sortWhitelist, 'row_alias', Direction::DESC, 'internal_row', Direction::ASC, 2); + $tieDefault = new PaginationConfig($config->sortWhitelist, 'row_alias', Direction::Desc, 'internal_row', Direction::Asc, 2); foreach ([[], [['key' => 'row_alias', 'direction' => 'desc']]] as $requestSorts) { $result = $paginator->paginateWithDynamicSort($reader, $query, new PageRequest(), $tieDefault, $requestSorts, self::idRow(...)); self::assertSame([$nullLabel, $charlie], array_column($result->page->data, 'id')); diff --git a/tests/Integration/Pagination/HostSnapshotTestStatement.php b/tests/Integration/Pagination/HostSnapshotTestStatement.php new file mode 100644 index 0000000..a9baa5c --- /dev/null +++ b/tests/Integration/Pagination/HostSnapshotTestStatement.php @@ -0,0 +1,10 @@ +exec( 'CREATE TABLE `' . $table . '` (' - . '`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ' - . '`tenant_id` INT UNSIGNED NOT NULL, ' - . '`category` VARCHAR(32) NOT NULL, ' - . '`name` VARCHAR(128) NOT NULL, ' - . '`score` INT NOT NULL, ' - . '`is_active` TINYINT(1) NOT NULL, ' - . '`nullable_code` VARCHAR(32) NULL, ' - . '`created_at` DATETIME(6) NOT NULL, ' - . '`deleted_at` DATETIME(6) NULL, ' - . 'PRIMARY KEY (`id`), ' - . 'KEY `idx_pagination_base` (`tenant_id`, `deleted_at`, `id`), ' - . 'KEY `idx_pagination_filter` (`tenant_id`, `category`, `is_active`, `nullable_code`, `score`, `id`), ' - . 'KEY `idx_pagination_sort` (`created_at`, `id`)' - . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci', + . '`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ' + . '`tenant_id` INT UNSIGNED NOT NULL, ' + . '`category` VARCHAR(32) NOT NULL, ' + . '`name` VARCHAR(128) NOT NULL, ' + . '`score` INT NOT NULL, ' + . '`is_active` TINYINT(1) NOT NULL, ' + . '`nullable_code` VARCHAR(32) NULL, ' + . '`created_at` DATETIME(6) NOT NULL, ' + . '`deleted_at` DATETIME(6) NULL, ' + . 'PRIMARY KEY (`id`), ' + . 'KEY `idx_pagination_base` (`tenant_id`, `deleted_at`, `id`), ' + . 'KEY `idx_pagination_filter` (`tenant_id`, `category`, `is_active`, `nullable_code`, `score`, `id`), ' + . 'KEY `idx_pagination_sort` (`created_at`, `id`)' + . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci', ); $this->paginationTables[] = $table; @@ -99,9 +99,9 @@ protected function config(): PaginationConfig 'same_id' => 'id', ]), 'created_at', - SortDirectionEnum::DESC, + SortDirectionEnum::Desc, 'id', - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, 2, 1, 50, diff --git a/tests/Integration/Pagination/PdoHostSnapshotPaginatorTest.php b/tests/Integration/Pagination/PdoHostSnapshotPaginatorTest.php index c71d93a..af02655 100644 --- a/tests/Integration/Pagination/PdoHostSnapshotPaginatorTest.php +++ b/tests/Integration/Pagination/PdoHostSnapshotPaginatorTest.php @@ -56,7 +56,7 @@ public function testAttemptsRetainTheirOwnSuccessOrFailure(bool $emulated): void $broken = $lease->newAttempt($lease->authorizePage('broken', ['min' => 10], new PageRequest())); $mapper = $lease->newAttempt($lease->authorizePage('mapper', ['min' => 10], new PageRequest())); $success = $lease->newAttempt($lease->authorizePage('page', ['min' => 10], new PageRequest(2))); - self::assertSame(Stage::NEW, $broken->state()); + self::assertSame(Stage::New, $broken->state()); self::assertNull(call_user_func($broken->settlement(...))); $ignoreArgs = ini_get('zend.exception_ignore_args'); @@ -85,11 +85,15 @@ public function testAttemptsRetainTheirOwnSuccessOrFailure(bool $emulated): void } } - self::assertSame(Stage::TERMINAL, $broken->state()); - self::assertSame(Disposition::RETURNED_TO_HOST, $broken->settlement()?->disposition); - self::assertSame(Reason::READ_FAILED, $broken->settlement()->reason); - self::assertSame(Reason::READ_FAILED, $mapper->settlement()?->reason); - self::assertSame(Reason::PAGE_COMPLETED, $success->settlement()?->reason); + self::assertSame(Stage::Terminal, $broken->state()); + self::assertSame(Disposition::ReturnedToHost, $broken->settlement()?->disposition); + self::assertSame(Reason::ReadFailed, $broken->settlement()->reason); + self::assertSame(Reason::ReadFailed, $mapper->settlement()?->reason); + self::assertSame(Reason::PageCompleted, $success->settlement()?->reason); + self::assertSame([ + 'disposition' => 'RETURNED_TO_HOST', + 'reason' => 'PAGE_COMPLETED', + ], json_decode(json_encode($success->settlement(), JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)); } public function testMapperReentryCannotOverwriteTheOriginalAttemptOrFinishTheTransaction(): void @@ -117,14 +121,14 @@ public function testMapperReentryCannotOverwriteTheOriginalAttemptOrFinishTheTra $competingSameGrant = $lease->newAttempt($outer); $competingOtherGrant = $lease->newAttempt($inner); $checkReentry = static function () use ($paginator, $lease, $first, $competingSameGrant, $competingOtherGrant): void { - self::assertSame(Stage::RUNNING, $first->state()); + self::assertSame(Stage::Running, $first->state()); self::reject(fn() => $paginator->paginate($first)); self::assertNull($first->settlement()); self::reject($lease->rollBack(...)); self::reject(fn() => $paginator->paginate($competingSameGrant)); - self::assertSame(Reason::GRANT_CONSUMED, $competingSameGrant->settlement()?->reason); + self::assertSame(Reason::GrantConsumed, $competingSameGrant->settlement()?->reason); self::reject(fn() => $paginator->paginate($competingOtherGrant)); - self::assertSame(Reason::BUSY, $competingOtherGrant->settlement()?->reason); + self::assertSame(Reason::Busy, $competingOtherGrant->settlement()?->reason); }; try { $paginator->paginate($first); @@ -132,7 +136,7 @@ public function testMapperReentryCannotOverwriteTheOriginalAttemptOrFinishTheTra $checkReentry = null; } $result = $first->settlement(); - self::assertSame(Reason::PAGE_COMPLETED, $result?->reason); + self::assertSame(Reason::PageCompleted, $result?->reason); self::reject(fn() => $paginator->paginate($first)); self::assertSame($result, $first->settlement()); $paginator->paginate($lease->newAttempt($inner)); @@ -140,7 +144,7 @@ public function testMapperReentryCannotOverwriteTheOriginalAttemptOrFinishTheTra $lease->rollBack(); $lease->beginRepeatableRead(); self::reject(fn() => $paginator->paginate($stale)); - self::assertSame(Reason::STALE_CONTEXT, $stale->settlement()?->reason); + self::assertSame(Reason::StaleContext, $stale->settlement()?->reason); $lease->rollBack(); $lease->release(); } @@ -197,7 +201,7 @@ public function testFirstUseAutoloadCannotAdmitAnOldGrantToANewGeneration(): voi try { self::reject(fn() => new PdoHostSnapshotPaginator()->paginate($attempt)); self::assertTrue($changed); - self::assertSame(Reason::STALE_CONTEXT, $attempt->settlement()?->reason); + self::assertSame(Reason::StaleContext, $attempt->settlement()?->reason); } finally { spl_autoload_unregister($loader); $lease->rollBack(); @@ -227,7 +231,7 @@ public function testInvalidCountAfterCleanCursorAllowsHostToEndItsTransaction(st } catch (PaginationExecutionException $error) { self::assertSame($message, $error->getMessage()); } - self::assertSame(Reason::READ_FAILED, $attempt->settlement()?->reason); + self::assertSame(Reason::ReadFailed, $attempt->settlement()?->reason); $lease->rollBack(); $lease->release(); } @@ -252,7 +256,7 @@ public function testCardinalityErrorDoesNotEndAConfirmedHostTransaction(bool $em $attempt = $lease->newAttempt($lease->authorizePage('invalid', [], new PageRequest())); $failure = self::failureOf(fn() => new PdoHostSnapshotPaginator()->paginate($attempt)); self::assertSame(1242, self::driverCode($failure)); - self::assertSame(Reason::READ_FAILED, $attempt->settlement()?->reason); + self::assertSame(Reason::ReadFailed, $attempt->settlement()?->reason); $lease->rollBack(); $lease->release(); } @@ -277,7 +281,7 @@ public function testDataExceptionDoesNotEndAConfirmedHostTransaction(bool $emula $attempt = $lease->newAttempt($lease->authorizePage('invalid', ['bound' => PHP_INT_MAX], new PageRequest())); $failure = self::failureOf(fn() => new PdoHostSnapshotPaginator()->paginate($attempt)); self::assertSame(1690, self::driverCode($failure)); - self::assertSame(Reason::READ_FAILED, $attempt->settlement()?->reason); + self::assertSame(Reason::ReadFailed, $attempt->settlement()?->reason); $lease->rollBack(); $lease->release(); } @@ -312,11 +316,11 @@ static function (array $row): array { self::reject($source->discardForHost(...)); $observer->exec('KILL CONNECTION ' . $id); self::failureOf($reader->resume(...)); - self::assertSame(Stage::TERMINAL, $attempt->state()); + self::assertSame(Stage::Terminal, $attempt->state()); $settlement = $attempt->settlement(); self::assertNotNull($settlement); - self::assertSame(Disposition::HOST_ACTION_REQUIRED, $settlement->disposition); - self::assertSame(Reason::SCOPE_UNCONFIRMED, $settlement->reason); + self::assertSame(Disposition::HostActionRequired, $settlement->disposition); + self::assertSame(Reason::ScopeUnconfirmed, $settlement->reason); $source->discardForHost(); self::assertSame($settlement, $attempt->settlement()); } @@ -331,7 +335,7 @@ private function plan(string $table, ?Closure $mapper = null, bool $bad = false) [], ['min'], ['min'], - new PaginationConfig(new SortWhitelist(['id' => 'id']), 'id', SortDirectionEnum::ASC, 'id', SortDirectionEnum::ASC, 2, 1, 50), + new PaginationConfig(new SortWhitelist(['id' => 'id']), 'id', SortDirectionEnum::Asc, 'id', SortDirectionEnum::Asc, 2, 1, 50), $mapper ?? static fn(array $row): array => $row, ); } diff --git a/tests/Integration/Pagination/PdoHostSnapshotRetirementTest.php b/tests/Integration/Pagination/PdoHostSnapshotRetirementTest.php index b0aca2b..a6882d1 100644 --- a/tests/Integration/Pagination/PdoHostSnapshotRetirementTest.php +++ b/tests/Integration/Pagination/PdoHostSnapshotRetirementTest.php @@ -11,6 +11,7 @@ use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotCommandResultModeEnum; use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotRetirementDispositionEnum as Disposition; use Maatify\PhpPersistence\Pagination\Repository\HostSnapshotConnection; +use Maatify\PhpPersistence\Pagination\Repository\HostSnapshotRetirement; use Maatify\PhpPersistence\Pagination\Repository\PdoHostSnapshotSource; use PDO; use ReflectionProperty; @@ -30,9 +31,11 @@ public function testRetirementTransfersTheSameIdlePdoAndCannotBeReversed(): void $lease->rollBack(); $returned = $source->retireForHost(); - self::assertSame(Disposition::RETURNED_IDLE, $returned->disposition); + self::assertSame(Disposition::ReturnedIdle, $returned->disposition); self::assertSame($reference->get(), $returned->pdo); - self::assertSame(State::RETIRED, $lease->state()); + self::assertSame(HostSnapshotRetirement::class, $returned::class); + self::assertNotContains(\JsonSerializable::class, new \ReflectionClass($returned)->getInterfaceNames()); + self::assertSame(State::Retired, $lease->state()); self::assertFalse($returned->pdo->inTransaction()); self::reject($source->checkout(...)); self::reject($source->retireForHost(...)); @@ -44,13 +47,13 @@ public function testRetirementWithActiveTransactionLeavesDispositionToHost(): vo $writer = $this->connect(); $table = $this->createTable($writer); $source = PdoHostSnapshotSource::attachExclusive($this->borrowableConnection(), new HostSnapshotCatalog([], [ - 'write' => new HostSnapshotCommandPlan("INSERT INTO $table VALUES (1, 10)", [], HostSnapshotCommandResultModeEnum::AFFECTED_ROWS, effect: Effect::PRESERVES_TRANSACTION), + 'write' => new HostSnapshotCommandPlan("INSERT INTO $table VALUES (1, 10)", [], HostSnapshotCommandResultModeEnum::AffectedRows, effect: Effect::PreservesTransaction), ])); $lease = $source->checkout(); $lease->beginRepeatableRead(); $lease->runRegisteredCommand('write'); $returned = $source->retireForHost(); - self::assertSame(Disposition::RETURNED_FOR_RECONCILIATION, $returned->disposition); + self::assertSame(Disposition::ReturnedForReconciliation, $returned->disposition); self::assertTrue($returned->pdo->inTransaction()); self::assertSame('0', $this->scalar($writer, "SELECT COUNT(*) FROM $table")); $returned->pdo->exec('COMMIT AND NO CHAIN NO RELEASE'); @@ -64,7 +67,7 @@ public function testUnresolvedResourcePreventsHandoffAndOnlyTheHostDiscards(): v $pdo = $this->borrowableConnection(); $reference = WeakReference::create($pdo); $source = PdoHostSnapshotSource::attachExclusive($pdo, new HostSnapshotCatalog([], [ - 'write' => new HostSnapshotCommandPlan("INSERT INTO $table VALUES (1, 10)", [], HostSnapshotCommandResultModeEnum::AFFECTED_ROWS, effect: Effect::PRESERVES_TRANSACTION), + 'write' => new HostSnapshotCommandPlan("INSERT INTO $table VALUES (1, 10)", [], HostSnapshotCommandResultModeEnum::AffectedRows, effect: Effect::PreservesTransaction), ])); $lease = $source->checkout(); $lease->beginRepeatableRead(); @@ -79,10 +82,10 @@ public function testUnresolvedResourcePreventsHandoffAndOnlyTheHostDiscards(): v unset($pdo, $statement); self::reject($source->retireForHost(...)); - self::assertSame(State::QUARANTINED, $lease->state()); + self::assertSame(State::Quarantined, $lease->state()); self::assertInstanceOf(PDO::class, $reference->get()); $source->discardForHost(); - self::assertSame(State::RETIRED, $lease->state()); + self::assertSame(State::Retired, $lease->state()); self::assertNull($reference->get()); self::assertSame('0', $this->scalar($writer, "SELECT COUNT(*) FROM $table")); self::reject($source->checkout(...)); @@ -100,7 +103,7 @@ public function testDiscardDoesNotProbeAConnectionLostByTheServer(): void $lease->beginRepeatableRead(); $admin->exec('KILL CONNECTION ' . $sessionId); $source->discardForHost(); - self::assertSame(State::RETIRED, $lease->state()); + self::assertSame(State::Retired, $lease->state()); } } diff --git a/tests/Integration/Pagination/PdoHostSnapshotSourceTest.php b/tests/Integration/Pagination/PdoHostSnapshotSourceTest.php index 84670b3..891aba8 100644 --- a/tests/Integration/Pagination/PdoHostSnapshotSourceTest.php +++ b/tests/Integration/Pagination/PdoHostSnapshotSourceTest.php @@ -8,7 +8,6 @@ use Maatify\PhpPersistence\Pagination\Enum\HostSnapshotCheckoutStateEnum; use Maatify\PhpPersistence\Pagination\Repository\PdoHostSnapshotSource; use PDO; -use PDOStatement; use WeakReference; final class PdoHostSnapshotSourceTest extends HostSnapshotIntegrationTestCase @@ -17,18 +16,18 @@ public function testReleasedCheckoutNeverRecoversItsAuthority(): void { $source = PdoHostSnapshotSource::attachExclusive($this->borrowableConnection(), new HostSnapshotCatalog([])); $first = $source->checkout(); - self::assertSame(HostSnapshotCheckoutStateEnum::IDLE, $first->state()); + self::assertSame(HostSnapshotCheckoutStateEnum::Idle, $first->state()); self::reject($source->checkout(...)); self::reject(fn() => serialize($source)); self::reject(fn() => serialize($first)); $first->beginRepeatableRead(); $first->rollBack(); $first->release(); - self::assertSame(HostSnapshotCheckoutStateEnum::RELEASED, $first->state()); + self::assertSame(HostSnapshotCheckoutStateEnum::Released, $first->state()); $second = $source->checkout(); self::assertNotSame($first, $second); self::reject($first->release(...)); - self::assertSame(HostSnapshotCheckoutStateEnum::IDLE, $second->state()); + self::assertSame(HostSnapshotCheckoutStateEnum::Idle, $second->state()); $second->release(); } @@ -100,13 +99,10 @@ public function testActiveTransactionCannotBeReleasedAsAnIdleCheckout(): void $pdo->exec('START TRANSACTION'); try { self::reject($checkout->release(...)); - self::assertSame(HostSnapshotCheckoutStateEnum::QUARANTINED, $checkout->state()); + self::assertSame(HostSnapshotCheckoutStateEnum::Quarantined, $checkout->state()); self::reject($source->checkout(...)); } finally { $pdo->exec('ROLLBACK AND NO CHAIN NO RELEASE'); } } - } - -final class HostSnapshotTestStatement extends PDOStatement {} diff --git a/tests/Integration/Pagination/PdoHostSnapshotTransactionTest.php b/tests/Integration/Pagination/PdoHostSnapshotTransactionTest.php index b360ab2..6617566 100644 --- a/tests/Integration/Pagination/PdoHostSnapshotTransactionTest.php +++ b/tests/Integration/Pagination/PdoHostSnapshotTransactionTest.php @@ -43,14 +43,14 @@ public function testHostControlsActualRrAndExplicitCompletion(int $completion, b $pdo->exec('SET SESSION completion_type=' . $completion); $session = $this->scalar($pdo, 'SELECT CONNECTION_ID()'); $source = PdoHostSnapshotSource::attachExclusive($pdo, new HostSnapshotCatalog([], [ - 'view' => new HostSnapshotCommandPlan("SELECT v FROM $table WHERE id=:id", ['id'], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION), - 'write' => new HostSnapshotCommandPlan("INSERT INTO $table VALUES (3, :v)", ['v'], Mode::AFFECTED_ROWS, effect: Effect::PRESERVES_TRANSACTION), - 'settings' => new HostSnapshotCommandPlan('SELECT CONNECTION_ID() AS id, @@completion_type AS completion', [], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION), + 'view' => new HostSnapshotCommandPlan("SELECT v FROM $table WHERE id=:id", ['id'], Mode::BoundedRows, 1, Effect::PreservesTransaction), + 'write' => new HostSnapshotCommandPlan("INSERT INTO $table VALUES (3, :v)", ['v'], Mode::AffectedRows, effect: Effect::PreservesTransaction), + 'settings' => new HostSnapshotCommandPlan('SELECT CONNECTION_ID() AS id, @@completion_type AS completion', [], Mode::BoundedRows, 1, Effect::PreservesTransaction), ])); unset($pdo); $lease = $source->checkout(); $lease->beginRepeatableRead(); - self::assertSame(State::TRANSACTION_ACTIVE, $lease->state()); + self::assertSame(State::TransactionActive, $lease->state()); self::assertEquals([['v' => 10]], $lease->runRegisteredCommand('view', ['id' => 1])); $writer->exec("UPDATE $table SET v=20 WHERE id=1"); self::assertEquals([['v' => 10]], $lease->runRegisteredCommand('view', ['id' => 1])); @@ -61,7 +61,7 @@ public function testHostControlsActualRrAndExplicitCompletion(int $completion, b } else { $lease->rollBack(); } - self::assertSame(State::IDLE, $lease->state()); + self::assertSame(State::Idle, $lease->state()); $settings = $lease->runRegisteredCommand('settings'); self::assertIsArray($settings); self::assertIsScalar($settings[0]['id']); @@ -70,7 +70,7 @@ public function testHostControlsActualRrAndExplicitCompletion(int $completion, b self::assertSame($completion === 1 ? '1' : '0', $this->scalar($writer, "SELECT COUNT(*) FROM $table WHERE id=3")); $lease->release(); $replacement = $source->checkout(); - $replacement->beginRepeatableRead(HostSnapshotAccessModeEnum::READ_ONLY); + $replacement->beginRepeatableRead(HostSnapshotAccessModeEnum::ReadOnly); self::assertEquals([['v' => 20]], $replacement->runRegisteredCommand('view', ['id' => 1])); $replacement->rollBack(); $replacement->release(); @@ -78,7 +78,7 @@ public function testHostControlsActualRrAndExplicitCompletion(int $completion, b public function testBoundedRowsPreserveNumericDriverColumnKeys(): void { - $plan = new HostSnapshotCommandPlan('SELECT 1', [], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION); + $plan = new HostSnapshotCommandPlan('SELECT 1', [], Mode::BoundedRows, 1, Effect::PreservesTransaction); foreach ([false, true] as $emulated) { $source = PdoHostSnapshotSource::attachExclusive( $this->borrowableConnection($emulated), @@ -88,7 +88,7 @@ public function testBoundedRowsPreserveNumericDriverColumnKeys(): void $lease->beginRepeatableRead(); self::assertEquals([[1 => 1]], $lease->runRegisteredCommand('probe')); - self::assertSame(State::TRANSACTION_ACTIVE, $lease->state()); + self::assertSame(State::TransactionActive, $lease->state()); $lease->rollBack(); $lease->release(); } @@ -98,7 +98,7 @@ public function testCatalogAcceptsStringIdentifiersThatPhpNormalizesToArrayInteg { $catalog = new HostSnapshotCatalog( ['12' => $this->emptyPagePlan()], - ['34' => new HostSnapshotCommandPlan('SELECT 1 AS v', [], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION)], + ['34' => new HostSnapshotCommandPlan('SELECT 1 AS v', [], Mode::BoundedRows, 1, Effect::PreservesTransaction)], ); $source = PdoHostSnapshotSource::attachExclusive($this->borrowableConnection(), $catalog); $lease = $source->checkout(); @@ -114,7 +114,7 @@ public function testCatalogAcceptsStringIdentifiersThatPhpNormalizesToArrayInteg public function testBoundedRowsOverflowClosesTheResourceWithoutEndingTheHostTransaction(): void { $source = PdoHostSnapshotSource::attachExclusive($this->borrowableConnection(), new HostSnapshotCatalog([], [ - 'many' => new HostSnapshotCommandPlan('SELECT 1 AS v UNION ALL SELECT 2', [], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION), + 'many' => new HostSnapshotCommandPlan('SELECT 1 AS v UNION ALL SELECT 2', [], Mode::BoundedRows, 1, Effect::PreservesTransaction), ])); $lease = $source->checkout(); $lease->beginRepeatableRead(); @@ -124,7 +124,7 @@ public function testBoundedRowsOverflowClosesTheResourceWithoutEndingTheHostTran } catch (HostSnapshotPaginationException $error) { self::assertSame('The Host snapshot result exceeds its row limit.', $error->getMessage()); } - self::assertSame(State::TRANSACTION_ACTIVE, $lease->state()); + self::assertSame(State::TransactionActive, $lease->state()); $lease->rollBack(); $lease->release(); } @@ -135,7 +135,7 @@ public function testRegisteredChainInvalidatesAQueuedPageOnTheSameSession(): voi $id = $this->scalar($pdo, 'SELECT CONNECTION_ID()'); $source = PdoHostSnapshotSource::attachExclusive($pdo, new HostSnapshotCatalog( ['page' => $this->emptyPagePlan()], - ['chain' => new HostSnapshotCommandPlan('ROLLBACK AND CHAIN NO RELEASE', [], Mode::AFFECTED_ROWS)], + ['chain' => new HostSnapshotCommandPlan('ROLLBACK AND CHAIN NO RELEASE', [], Mode::AffectedRows)], )); unset($pdo); $lease = $source->checkout(); @@ -143,13 +143,13 @@ public function testRegisteredChainInvalidatesAQueuedPageOnTheSameSession(): voi $queued = $lease->newAttempt($lease->authorizePage('page', [], new PageRequest())); $lease->runRegisteredCommand('chain'); - self::assertSame(State::TRANSACTION_UNQUALIFIED, $lease->state()); + self::assertSame(State::TransactionUnqualified, $lease->state()); self::reject(fn() => new PdoHostSnapshotPaginator()->paginate($queued)); - self::assertSame(Reason::STALE_CONTEXT, $queued->settlement()?->reason); + self::assertSame(Reason::StaleContext, $queued->settlement()?->reason); self::reject(fn() => $lease->authorizePage('page', [], new PageRequest())); $lease->rollBack(); $returned = $source->retireForHost(); - self::assertSame(HostSnapshotRetirementDispositionEnum::RETURNED_FOR_RECONCILIATION, $returned->disposition); + self::assertSame(HostSnapshotRetirementDispositionEnum::ReturnedForReconciliation, $returned->disposition); self::assertSame($id, $this->scalar($returned->pdo, 'SELECT CONNECTION_ID()')); self::assertFalse($returned->pdo->inTransaction()); } @@ -160,7 +160,7 @@ public function testHostCommandFencesAQueuedPageBeforeItsCursorIsReleased(): voi { $source = PdoHostSnapshotSource::attachExclusive($this->borrowableConnection(), new HostSnapshotCatalog( ['page' => $this->emptyPagePlan()], - ['many' => new HostSnapshotCommandPlan('SELECT 1 AS v UNION ALL SELECT 2', [], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION)], + ['many' => new HostSnapshotCommandPlan('SELECT 1 AS v UNION ALL SELECT 2', [], Mode::BoundedRows, 1, Effect::PreservesTransaction)], )); $lease = $source->checkout(); $lease->beginRepeatableRead(); @@ -169,9 +169,9 @@ public function testHostCommandFencesAQueuedPageBeforeItsCursorIsReleased(): voi $paginator = new PdoHostSnapshotPaginator(); $loader = static function (string $class) use ($lease, $paginator, $queued): void { if ($class === HostSnapshotRowLimitExceededException::class) { - self::assertSame(State::BUSY, $lease->state()); + self::assertSame(State::Busy, $lease->state()); self::reject(fn() => $paginator->paginate($queued)); - self::assertSame(Reason::BUSY, $queued->settlement()?->reason); + self::assertSame(Reason::Busy, $queued->settlement()?->reason); } }; @@ -186,7 +186,7 @@ public function testHostCommandFencesAQueuedPageBeforeItsCursorIsReleased(): voi $retry = $lease->newAttempt($grant); self::assertSame([], $paginator->paginate($retry)->data); - self::assertSame(Reason::PAGE_COMPLETED, $retry->settlement()?->reason); + self::assertSame(Reason::PageCompleted, $retry->settlement()?->reason); $lease->rollBack(); $lease->release(); } @@ -199,7 +199,7 @@ public function testOverflowRemainsThePrimaryFailureIfTheSessionIsLostDuringClea $pdo = $this->borrowableConnection(); $id = (int) $this->scalar($pdo, 'SELECT CONNECTION_ID()'); $source = PdoHostSnapshotSource::attachExclusive($pdo, new HostSnapshotCatalog([], [ - 'many' => new HostSnapshotCommandPlan('SELECT 1 AS v UNION ALL SELECT 2', [], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION), + 'many' => new HostSnapshotCommandPlan('SELECT 1 AS v UNION ALL SELECT 2', [], Mode::BoundedRows, 1, Effect::PreservesTransaction), ])); unset($pdo); $lease = $source->checkout(); @@ -220,7 +220,7 @@ public function testOverflowRemainsThePrimaryFailureIfTheSessionIsLostDuringClea } finally { spl_autoload_unregister($loader); } - self::assertSame(State::QUARANTINED, $lease->state()); + self::assertSame(State::Quarantined, $lease->state()); $source->discardForHost(); } @@ -250,14 +250,14 @@ public function testInitialPendingSettingCannotBeReturnedToThePoolUnresolved(): $lease->release(); self::fail('An unresolved next-transaction setting escaped into the pool.'); } catch (HostSnapshotPaginationException) { - self::assertSame(State::QUARANTINED, $lease->state()); + self::assertSame(State::Quarantined, $lease->state()); } } public function testCommandFailureRetainsOriginalDriverErrorAndQuarantinesSource(): void { $source = PdoHostSnapshotSource::attachExclusive($this->borrowableConnection(), new HostSnapshotCatalog([], [ - 'broken' => new HostSnapshotCommandPlan('SELECT non_existing_column', [], Mode::BOUNDED_ROWS, 1, Effect::PRESERVES_TRANSACTION), + 'broken' => new HostSnapshotCommandPlan('SELECT non_existing_column', [], Mode::BoundedRows, 1, Effect::PreservesTransaction), ])); $lease = $source->checkout(); $lease->beginRepeatableRead(); @@ -273,7 +273,7 @@ public function testCommandFailureRetainsOriginalDriverErrorAndQuarantinesSource ini_set('zend.exception_ignore_args', $ignoreArgs); } } - self::assertSame(State::QUARANTINED, $lease->state()); + self::assertSame(State::Quarantined, $lease->state()); $this->expectException(HostSnapshotPaginationException::class); $lease->release(); } diff --git a/tests/Integration/Pagination/PdoSnapshotPaginatorFailureTest.php b/tests/Integration/Pagination/PdoSnapshotPaginatorFailureTest.php index b96ff28..79c6754 100644 --- a/tests/Integration/Pagination/PdoSnapshotPaginatorFailureTest.php +++ b/tests/Integration/Pagination/PdoSnapshotPaginatorFailureTest.php @@ -42,7 +42,7 @@ public function testUnchangedReturnsToTheHostWithoutPublishingAnActiveTransactio $this->config(), static fn(array $row): array => $row, ))); - self::assertSame(SnapshotConnectionDispositionEnum::UNCHANGED, $operation->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Unchanged, $operation->connectionOutcome()?->disposition); $source->settle($checkout, $operation->connectionOutcome()); self::assertFalse($source->canCheckout()); self::assertSame($reader, $source->takeReturnedConnection()); @@ -65,7 +65,7 @@ public function testExecutionOfACompletedReadDoesNotPublishPageOnHostSettlementF $escaped = self::failure(function () use ($operation, $table, $fault, $source, $checkout): PageResultDTO { $page = $operation->paginate($this->descriptor($table), new PageRequest(), $this->config(), static fn(array $row): array => $row); self::assertSame(3, $page->filtered); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $operation->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $operation->connectionOutcome()?->disposition); $source->settle($checkout, $operation->connectionOutcome(), $fault); return $page; @@ -82,14 +82,17 @@ public function testUnbufferedFetchFailureWithUnreadRowsStillAllowsConfirmedRoll $source = new SnapshotHostCheckout($reader); [$checkout, , $operation] = $source->checkout(); $primary = new RuntimeException('fetch failed with unread wire rows'); - $reader->setAttribute(PDO::ATTR_STATEMENT_CLASS, [SnapshotCursorStatement::class, [ - static fn(): bool => true, - static function (string $sql) use ($primary): void { - if (str_contains($sql, 'SELECT id, tenant_id')) { - throw $primary; - } - }, - ]]); + $reader->setAttribute(PDO::ATTR_STATEMENT_CLASS, [ + SnapshotCursorStatement::class, + ([ + static fn(): bool => true, + static function (string $sql) use ($primary): void { + if (str_contains($sql, 'SELECT id, tenant_id')) { + throw $primary; + } + }, + ]), + ]); try { self::assertSame($primary, self::failure(fn() => $operation->paginate( $this->descriptor($table), @@ -97,7 +100,7 @@ static function (string $sql) use ($primary): void { $this->config(), static fn(array $row): array => $row, ))); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $operation->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $operation->connectionOutcome()?->disposition); $source->settle($checkout, $operation->connectionOutcome()); [$next, $available] = $source->checkout(); self::assertSame($reader, $available); @@ -182,7 +185,7 @@ public function exec(string $statement): int|false self::assertSame([], $reader->controls); $outcome = $operation->connectionOutcome(); $source->settle($checkout, $outcome); - self::assertSame(SnapshotConnectionDispositionEnum::DISCARD, $outcome?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Discard, $outcome?->disposition); self::assertNull($source->takeReturnedConnection()); self::assertFalse($source->canCheckout()); } @@ -236,7 +239,7 @@ static function (array $row) use ($reader): array { }, ))); self::assertSame(['START TRANSACTION READ ONLY'], $reader->controls); - self::assertSame(SnapshotConnectionDispositionEnum::DISCARD, $operation->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Discard, $operation->connectionOutcome()?->disposition); $source->settle($checkout, $operation->connectionOutcome()); self::assertFalse($source->canCheckout()); } finally { @@ -266,7 +269,7 @@ public function testTheHostCanReuseSameSessionAfterUnbufferedMapperError(): void $outcome = $operation->connectionOutcome(); $source->settle($checkout, $outcome); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $outcome?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $outcome?->disposition); self::assertTrue($source->canCheckout()); [$next, $available] = $source->checkout(); self::assertSame($pdo, $available); @@ -300,21 +303,25 @@ public function testUnknownCursorReleaseDiscardsTheCheckout(string $needle, bool [$seed, $table] = $this->connectWithPaginationTable(); $this->insertMultiTenantDataset($seed, $table); $reader = $this->unbufferedReader(); + $readerId = (int) $this->scalar($reader, 'SELECT CONNECTION_ID()'); $closeAttempts = 0; $closeFailure = new RuntimeException('cursor close failed'); - $reader->setAttribute(PDO::ATTR_STATEMENT_CLASS, [SnapshotCursorStatement::class, [ - static function (string $sql) use ($needle, $throws, $closeFailure, &$closeAttempts): bool { - if (! str_contains($sql, $needle)) { - return true; - } - $closeAttempts++; - if ($throws) { - throw $closeFailure; - } + $reader->setAttribute(PDO::ATTR_STATEMENT_CLASS, [ + SnapshotCursorStatement::class, + ([ + static function (string $sql) use ($needle, $throws, $closeFailure, &$closeAttempts): bool { + if (! str_contains($sql, $needle)) { + return true; + } + $closeAttempts++; + if ($throws) { + throw $closeFailure; + } - return false; - }, - ]]); + return false; + }, + ]), + ]); $source = new SnapshotHostCheckout($reader); [$checkout, $pdo, $operation] = $source->checkout(); $primary = new RuntimeException('mapper stopped with unread rows'); @@ -335,11 +342,13 @@ static function (string $sql) use ($needle, $throws, $closeFailure, &$closeAttem self::assertInstanceOf(SnapshotPaginationException::class, $failure); } self::assertSame(1, $closeAttempts); - self::assertSame(SnapshotConnectionDispositionEnum::DISCARD, $outcome?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Discard, $outcome?->disposition); self::assertSame('cursor-release', $outcome->diagnostic); self::assertFalse($source->canCheckout()); } finally { - self::endFixtureTransaction($reader); + // The discarded connection may still own an unbuffered cursor. + // Tear down the owned session through the separate fixture connection. + $seed->exec('KILL CONNECTION ' . $readerId); } } @@ -371,7 +380,7 @@ public function testSqlFailureRollsBackWithoutChangingTheThrownPdoError(bool $em $failure = self::failure(fn() => $operation->paginate($invalid, new PageRequest(), $this->config(), static fn(array $row): array => $row)); self::assertInstanceOf(PDOException::class, $failure); self::assertSame(1146, $failure->errorInfo[1] ?? null); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $operation->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $operation->connectionOutcome()?->disposition); self::assertFalse($reader->inTransaction()); } finally { self::endFixtureTransaction($reader); @@ -390,7 +399,7 @@ public function testHostHandoffFailureKeepsTheCheckoutUnavailableAndPreservesThe try { $escaped = self::failure(function () use ($operation, $table, $primary, $handoff, $source, $checkout): void { $read = self::failure(fn() => $operation->paginate($this->descriptor($table), new PageRequest(), $this->config(), static fn(): never => throw $primary)); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $operation->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $operation->connectionOutcome()?->disposition); $failure = self::failure(static fn() => $source->settle($checkout, $operation->connectionOutcome(), $handoff)); self::assertSame($handoff, $failure); @@ -440,7 +449,7 @@ public function exec(string $statement): int|false $outcome = $operation->connectionOutcome(); $source->settle($checkout, $outcome); self::assertSame(1, $reader->rollbackAttempts); - self::assertSame(SnapshotConnectionDispositionEnum::DISCARD, $outcome?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Discard, $outcome?->disposition); self::assertSame('rollback', $outcome->diagnostic); self::assertFalse($source->canCheckout()); } finally { @@ -542,7 +551,7 @@ public function testHostDiscardsAfterServerAcknowledgementWasWithheld(string $co } self::assertSame($forward ? "SERVER OK WITHHELD\n" : "COMMAND NOT FORWARDED\n", fgets($pipes[1])); $outcome = $operation->connectionOutcome(); - self::assertSame(SnapshotConnectionDispositionEnum::DISCARD, $outcome?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Discard, $outcome?->disposition); self::assertSame($phase, $outcome->diagnostic); $source->settle($checkout, $outcome); self::assertFalse($source->canCheckout()); diff --git a/tests/Integration/Pagination/PdoSnapshotPaginatorTest.php b/tests/Integration/Pagination/PdoSnapshotPaginatorTest.php index 0e61d61..58eb951 100644 --- a/tests/Integration/Pagination/PdoSnapshotPaginatorTest.php +++ b/tests/Integration/Pagination/PdoSnapshotPaginatorTest.php @@ -65,7 +65,11 @@ function (int $index, string $sql) use ($operation, $writer, $table, $original, $result = $snapshot->paginate($query, $request, $config, $mapper); $outcome = $snapshot->connectionOutcome(); self::assertNotNull($outcome); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $outcome->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $outcome->disposition); + self::assertSame([ + 'disposition' => 'REUSABLE', + 'diagnostic' => null, + ], json_decode(json_encode($outcome, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)); self::assertSame($outcome, $snapshot->connectionOutcome()); self::assertTrue($mutationRan); self::assertSame(4, $result->total); @@ -118,7 +122,7 @@ public function testRejectsIneligibleConnectionWithoutManagingHostTransaction(st ); self::fail('An ineligible connection must be rejected.'); } catch (SnapshotPaginationException) { - self::assertSame(SnapshotConnectionDispositionEnum::UNCHANGED, $snapshot->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Unchanged, $snapshot->connectionOutcome()?->disposition); } self::assertSame($case === 'active', $reader->inTransaction()); if ($case === 'active') { @@ -163,7 +167,7 @@ public function testOneShotOperationPreservesOutcomeAcrossReentryAndRepeat(): vo self::assertSame(1, $page->page); self::assertCount(1, $page->data); $outcome = $snapshot->connectionOutcome(); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $outcome?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $outcome?->disposition); try { $snapshot->paginate($query, $request, $config, static fn(array $row): array => $row); self::fail('The lease must not be consumed twice.'); @@ -215,7 +219,7 @@ public function getAttribute(int $attribute): mixed } catch (SnapshotPaginationException) { // The reader never ran. The Host must discard the uncertain checkout. } - self::assertSame(SnapshotConnectionDispositionEnum::DISCARD, $snapshot->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Discard, $snapshot->connectionOutcome()?->disposition); } public function testServerAutocommitWinsOverTheCachedPdoAttributeInBothDirections(): void @@ -233,10 +237,10 @@ public function testServerAutocommitWinsOverTheCachedPdoAttributeInBothDirection $page = $snapshot->paginate($this->descriptor($table), new PageRequest(), $this->config(), static fn(array $row): array => $row); self::assertTrue($serverAutocommit); self::assertSame(3, $page->filtered); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $snapshot->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $snapshot->connectionOutcome()?->disposition); } catch (SnapshotPaginationException $failure) { self::assertFalse($serverAutocommit, $failure->getMessage()); - self::assertSame(SnapshotConnectionDispositionEnum::UNCHANGED, $snapshot->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Unchanged, $snapshot->connectionOutcome()?->disposition); } finally { self::assertFalse($reader->inTransaction()); self::assertSame(! $serverAutocommit, (bool) $reader->getAttribute(PDO::ATTR_AUTOCOMMIT)); @@ -263,6 +267,6 @@ public function testEmptyResultSkipsDataQuery(): void self::assertSame(1, $page->page); self::assertSame(0, $page->filtered); self::assertSame([], $page->data); - self::assertSame(SnapshotConnectionDispositionEnum::REUSABLE, $snapshot->connectionOutcome()?->disposition); + self::assertSame(SnapshotConnectionDispositionEnum::Reusable, $snapshot->connectionOutcome()?->disposition); } } diff --git a/tests/Integration/Pagination/StaticSortPaginationIntegrationTest.php b/tests/Integration/Pagination/StaticSortPaginationIntegrationTest.php index a5950a6..c612677 100644 --- a/tests/Integration/Pagination/StaticSortPaginationIntegrationTest.php +++ b/tests/Integration/Pagination/StaticSortPaginationIntegrationTest.php @@ -132,8 +132,8 @@ public function testI18nLikeGridPreservesLongUnicodeOrderAndHostHintWhenQualifie ); $sorts = ['key_part' => 'k.name', 'language_code' => 'lc.language_code']; $plan = new StaticSortPlan(self::paginationConfig($sorts, 'key_part', 'language_code'), [ - 'key_part' => [['identifier' => 'lc.language_code', 'direction' => Direction::ASC]], - 'language_code' => [['identifier' => 'k.name', 'direction' => Direction::ASC]], + 'key_part' => [['identifier' => 'lc.language_code', 'direction' => Direction::Asc]], + 'language_code' => [['identifier' => 'k.name', 'direction' => Direction::Asc]], ]); $paginator = new PdoPaginator(); foreach ([ @@ -169,7 +169,7 @@ public function testI18nLikeGridPreservesLongUnicodeOrderAndHostHintWhenQualifie $expected = $paginator->paginate($pdo, $query, $request, $legacy, $mapper); $actual = $paginator->paginateWithStaticSort($pdo, $query, $request, $plan, $mapper); self::assertSame($expected->toArray(), $actual->toArray()); - self::assertSame([8, 8, $primary, $descending ? Direction::DESC : Direction::ASC], [$actual->total, $actual->filtered, $actual->sortBy, $actual->sortDirection]); + self::assertSame([8, 8, $primary, $descending ? Direction::Desc : Direction::Asc], [$actual->total, $actual->filtered, $actual->sortBy, $actual->sortDirection]); self::assertSame(array_slice($sql, -6, 3), array_slice($sql, -3)); self::assertStringNotContainsString('SET_VAR', $sql[count($sql) - 2]); self::assertSame($hinted ? 1 : 0, substr_count($sql[count($sql) - 1], 'SET_VAR(max_sort_length=2048)')); @@ -213,6 +213,6 @@ public function testMapperFailureLeavesHostTransactionAndCursorUsable(bool $buff /** @param non-empty-array $sorts */ private static function paginationConfig(array $sorts, string $primary, string $tie): PaginationConfig { - return new PaginationConfig(new SortWhitelist($sorts), $primary, Direction::ASC, $tie, Direction::ASC, 2); + return new PaginationConfig(new SortWhitelist($sorts), $primary, Direction::Asc, $tie, Direction::Asc, 2); } } diff --git a/tests/Integration/Support/FaultInjectingPdo.php b/tests/Integration/Support/FaultInjectingPdo.php index 7d1c284..b04bf7c 100644 --- a/tests/Integration/Support/FaultInjectingPdo.php +++ b/tests/Integration/Support/FaultInjectingPdo.php @@ -22,7 +22,7 @@ final class FaultInjectingPdo extends PDO /** @var list */ public array $executed = []; - /** @var list */ + /** @var list */ private array $execFaults = []; /** @var list */ @@ -30,8 +30,8 @@ final class FaultInjectingPdo extends PDO private PDOException|false|null $rollbackFault = null; - /** @param 'false'|'throw' $mode */ - public function failExec(string $regex, string $mode): void + /** @param PDOException|'false'|'throw' $mode */ + public function failExec(string $regex, PDOException|string $mode): void { $this->execFaults[] = ['regex' => $regex, 'mode' => $mode]; } @@ -67,6 +67,10 @@ public function exec(string $statement): int|false return false; } + if ($fault['mode'] instanceof PDOException) { + throw $fault['mode']; + } + throw new PDOException('Injected control statement failure.'); } } diff --git a/tests/Integration/Support/ObservedOrderingUpdateStatement.php b/tests/Integration/Support/ObservedOrderingUpdateStatement.php new file mode 100644 index 0000000..52a6e6b --- /dev/null +++ b/tests/Integration/Support/ObservedOrderingUpdateStatement.php @@ -0,0 +1,26 @@ +|null $params */ + public function execute(?array $params = null): bool + { + $executed = parent::execute($params); + if ($executed && str_starts_with($this->queryString, 'UPDATE ')) { + ($this->observe)(parent::rowCount()); + } + + return $executed; + } +} diff --git a/tests/Integration/Support/PartnerProcess.php b/tests/Integration/Support/PartnerProcess.php index a3fe7fc..5ac88f5 100644 --- a/tests/Integration/Support/PartnerProcess.php +++ b/tests/Integration/Support/PartnerProcess.php @@ -228,7 +228,7 @@ public function stop(): void if (!$this->waitForExit(self::TERMINATE_GRACE_SECONDS)) { $failure = sprintf( 'Test partner pid %d is still running %.1f s after SIGKILL (SIGTERM delivery %s, SIGKILL delivery %s); ' - . 'proc_close() is not called because it would block, so the child is leaked and must be killed manually; %s', + . 'proc_close() is not called because it would block, so the child is leaked and must be killed manually; %s', $this->pid, self::TERMINATE_GRACE_SECONDS, $termSent ? 'ok' : 'failed', diff --git a/tests/Integration/Support/SnapshotEndResponseProxy.php b/tests/Integration/Support/SnapshotEndResponseProxy.php index 97da9d2..83994bd 100644 --- a/tests/Integration/Support/SnapshotEndResponseProxy.php +++ b/tests/Integration/Support/SnapshotEndResponseProxy.php @@ -58,8 +58,16 @@ function writePacketBytes($socket, string $bytes): void 'ROLLBACK TO SAVEPOINT maatify_wub22_proof', 'RELEASE SAVEPOINT maatify_wub22_proof', ], true) || !in_array($stage, [ - 'after', 'before', 'after-ack', 'ordering-release-error', 'ordering-1020', - 'observe-ordering-1020', 'protected-tail-churn', 'prequalification-no-sql', 'b1-invalid-statement', 'b1-empty-update', + 'after', + 'before', + 'after-ack', + 'ordering-release-error', + 'ordering-1020', + 'observe-ordering-1020', + 'protected-tail-churn', + 'prequalification-no-sql', + 'b1-invalid-statement', + 'b1-empty-update', ], true) || ($b1Fault && !in_array($fixtureTable, $b1Phases, true)) || ($stage === 'protected-tail-churn' && preg_match('/\Ait_ordering_scoped_[0-9a-f]{12}\z/', $fixtureTable) !== 1) diff --git a/tests/Integration/Transaction/DeadlockIntegrationTestCase.php b/tests/Integration/Transaction/DeadlockIntegrationTestCase.php index c05d658..7504c8f 100644 --- a/tests/Integration/Transaction/DeadlockIntegrationTestCase.php +++ b/tests/Integration/Transaction/DeadlockIntegrationTestCase.php @@ -175,10 +175,10 @@ private function createPayloadTable(PDO $pdo): string $name = 'it_' . bin2hex(random_bytes(6)) . '_deadlock'; $pdo->exec( 'CREATE TABLE `' . $name . '` (' - . '`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ' - . '`payload` VARCHAR(128) NOT NULL, ' - . 'PRIMARY KEY (`id`)' - . ') ENGINE=InnoDB', + . '`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ' + . '`payload` VARCHAR(128) NOT NULL, ' + . 'PRIMARY KEY (`id`)' + . ') ENGINE=InnoDB', ); return $name; diff --git a/tests/Integration/Transaction/PdoProtectedTransactionCheckoutTest.php b/tests/Integration/Transaction/PdoProtectedTransactionCheckoutTest.php index 0442422..35242a8 100644 --- a/tests/Integration/Transaction/PdoProtectedTransactionCheckoutTest.php +++ b/tests/Integration/Transaction/PdoProtectedTransactionCheckoutTest.php @@ -17,6 +17,7 @@ use Error; use PDO; use Pdo\Mysql; +use PDOException; use PDOStatement; use PHPUnit\Framework\Attributes\DataProvider; use WeakReference; @@ -32,7 +33,7 @@ public function testAnUnqualifiedCheckoutReturnsUnchangedAndCannotBeReused(): vo $this->reject(static fn() => PdoProtectedTransactionCheckout::attachExclusive($pdo, $catalog)); $this->reject(static fn() => $checkout->commit()); self::assertSame($pdo, $checkout->returnForHost()); - self::assertSame(ProtectedTransactionDispositionEnum::UNCHANGED, $checkout->settlement()?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::Unchanged, $checkout->settlement()?->disposition); $this->reject(static fn() => $checkout->begin()); $this->reject(static fn() => $checkout->returnForHost()); $new = PdoProtectedTransactionCheckout::attachExclusive($pdo, $catalog); @@ -42,8 +43,10 @@ public function testAnUnqualifiedCheckoutReturnsUnchangedAndCannotBeReused(): vo public function testAttachmentFailedWorkAndEarlyCancellationSendNoSql(): void { $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', - 'START TRANSACTION READ WRITE', 'prequalification-no-sql', + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'START TRANSACTION READ WRITE', + 'prequalification-no-sql', ]); try { $ready = $relay->readLine(12.0); @@ -64,7 +67,7 @@ public function testAttachmentFailedWorkAndEarlyCancellationSendNoSql(): void $this->reject(static fn() => $checkout->runRegisteredCommand('read')); $this->reject(static fn() => $checkout->rollBack()); $returned = $checkout->returnForHost(); - self::assertSame(ProtectedTransactionReasonEnum::CANCELLED_BEFORE_QUALIFICATION, $checkout->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::CancelledBeforeQualification, $checkout->settlement()?->reason); unset($returned); self::assertSame('NO SQL BEFORE HANDOFF', $relay->readLine(12.0)); } finally { @@ -83,7 +86,11 @@ public function testHostChoosesTransactionEndAndReceivesSameConnection(): void $checkout->rollBack(); self::assertFalse($pdo->inTransaction()); $settlement = $checkout->settlement(); - self::assertSame(ProtectedTransactionDispositionEnum::REUSABLE, $settlement?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::Reusable, $settlement?->disposition); + self::assertSame([ + 'disposition' => 'REUSABLE', + 'reason' => 'ROLLED_BACK', + ], json_decode(json_encode($settlement, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)); self::assertSame($pdo, $checkout->returnForHost()); self::assertSame($settlement, $checkout->settlement()); } @@ -96,8 +103,8 @@ public function testFailedServerQualificationFencesEvenAnUnstartedCheckout(): vo self::assertUnsettled($checkout); $this->reject(static fn() => $checkout->begin()); $settlement = $checkout->settlement(); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $settlement?->disposition); - self::assertSame(ProtectedTransactionReasonEnum::SERVER_QUALIFICATION_FAILED, $settlement->reason); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement?->disposition); + self::assertSame(ProtectedTransactionReasonEnum::ServerQualificationFailed, $settlement->reason); $this->reject(static fn() => $checkout->returnForHost()); $this->reject(static fn() => $checkout->rollBack()); $checkout->discardForHost(); @@ -148,7 +155,7 @@ public function testHostWritesRemainUncommittedUntilExplicitCommit(): void self::assertSame([], $this->values($observer, $table)); $checkout->commit(); self::assertSame([10], $this->values($observer, $table)); - self::assertSame(ProtectedTransactionReasonEnum::COMMITTED, $checkout->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::Committed, $checkout->settlement()?->reason); $checkout->returnForHost(); } @@ -187,7 +194,7 @@ public function testRowBoundFailureClosesTheResultAndPreservesTheHostTransaction self::assertSame([['v' => 10]], $checkout->runRegisteredCommand('read')); self::assertSame([], $this->values($observer, $table)); $checkout->commit(); - self::assertSame(ProtectedTransactionReasonEnum::COMMITTED, $checkout->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::Committed, $checkout->settlement()?->reason); self::assertSame([10], $this->values($observer, $table)); $checkout->returnForHost(); } @@ -195,9 +202,9 @@ public function testRowBoundFailureClosesTheResultAndPreservesTheHostTransaction /** @return iterable */ public static function completionLossModes(): iterable { - yield 'commit acknowledgement lost' => [true, 'after', 'SERVER OK WITHHELD', ProtectedTransactionReasonEnum::COMMIT_OUTCOME_UNKNOWN]; - yield 'lost after commit acknowledgement' => [true, 'after-ack', 'SERVER OK FORWARDED', ProtectedTransactionReasonEnum::COMMIT_CONFIRMED_CONNECTION_UNSAFE]; - yield 'rollback acknowledgement lost' => [false, 'after', 'SERVER OK WITHHELD', ProtectedTransactionReasonEnum::ROLLBACK_UNCONFIRMED]; + yield 'commit acknowledgement lost' => [true, 'after', 'SERVER OK WITHHELD', ProtectedTransactionReasonEnum::CommitOutcomeUnknown]; + yield 'lost after commit acknowledgement' => [true, 'after-ack', 'SERVER OK FORWARDED', ProtectedTransactionReasonEnum::CommitConfirmedConnectionUnsafe]; + yield 'rollback acknowledgement lost' => [false, 'after', 'SERVER OK WITHHELD', ProtectedTransactionReasonEnum::RollbackUnconfirmed]; } #[DataProvider('completionLossModes')] @@ -280,7 +287,7 @@ public function testStatementFailurePreservesOriginalDriverErrorAndFencesFurther ini_set('zend.exception_ignore_args', $previousIni); } } - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $checkout->settlement()?->disposition); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $checkout->settlement()?->disposition); $this->reject(static fn() => $checkout->runRegisteredCommand('read')); $this->reject(static fn() => $checkout->commit()); $checkout->discardForHost(); @@ -324,10 +331,10 @@ public function testRejectedAttachmentHidesPdoFromTheExceptionArguments(): void /** @return iterable */ public static function completionSettings(): iterable { - yield 'CHAIN with commit' => [1, true, ProtectedTransactionReasonEnum::COMMITTED]; - yield 'CHAIN with rollback' => [1, false, ProtectedTransactionReasonEnum::ROLLED_BACK]; - yield 'RELEASE with commit' => [2, true, ProtectedTransactionReasonEnum::COMMITTED]; - yield 'RELEASE with rollback' => [2, false, ProtectedTransactionReasonEnum::ROLLED_BACK]; + yield 'CHAIN with commit' => [1, true, ProtectedTransactionReasonEnum::Committed]; + yield 'CHAIN with rollback' => [1, false, ProtectedTransactionReasonEnum::RolledBack]; + yield 'RELEASE with commit' => [2, true, ProtectedTransactionReasonEnum::Committed]; + yield 'RELEASE with rollback' => [2, false, ProtectedTransactionReasonEnum::RolledBack]; } #[DataProvider('completionSettings')] @@ -356,22 +363,42 @@ public function testLockTimeoutFencesWithoutReplayingTheRegisteredCommand(): voi $owner = $this->connect(); $table = $this->createTable($owner); $owner->exec("INSERT INTO `$table` (id, v) VALUES (1, 10)"); + $delegatedSessionId = null; $owner->beginTransaction(); try { $owner->exec("UPDATE `$table` SET v = 20 WHERE id = 1"); $pdo = $this->delegatedConnection(); $pdo->exec('SET SESSION innodb_lock_wait_timeout = 1'); + $delegatedSessionId = (int) $this->scalar($pdo, 'SELECT CONNECTION_ID()'); $checkout = PdoProtectedTransactionCheckout::attachExclusive($pdo, new ProtectedTransactionCommandCatalog([ 'write' => new ProtectedTransactionCommandPlan("UPDATE `$table` SET v = 30 WHERE id = 1", []), ])); unset($pdo); $checkout->begin(); self::assertSame(1205, self::driverCode(self::failureOf(static fn() => $checkout->runRegisteredCommand('write')))); - self::assertSame(ProtectedTransactionReasonEnum::OPERATION_UNCONFIRMED, $checkout->settlement()?->reason); + $settlement = $checkout->settlement(); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement?->disposition); + self::assertSame(ProtectedTransactionReasonEnum::OperationUnconfirmed, $settlement->reason); $this->reject(static fn() => $checkout->runRegisteredCommand('write')); $checkout->discardForHost(); + self::assertSame($settlement, $checkout->settlement()); + $this->reject(static fn() => $checkout->discardForHost()); } finally { - $owner->rollBack(); + try { + $owner->rollBack(); + } finally { + if ($delegatedSessionId !== null) { + // Release the fixture session if it outlives the checkout discard. + try { + $owner->exec('KILL CONNECTION ' . $delegatedSessionId); + } catch (PDOException $failure) { + // PDO may already have closed the session on discard. + if (self::driverCode($failure) !== 1094) { + throw $failure; + } + } + } + } } self::assertSame([10], $this->values($owner, $table)); } @@ -406,7 +433,10 @@ public function testOnceReservedTheHostCannotRunAnotherOperationOrRetainTheDrive public function testUnacknowledgedStartCannotBecomeAnActiveCheckout(): void { $relay = PartnerProcess::start([ - PHP_BINARY, dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', 'START TRANSACTION READ WRITE', 'after', + PHP_BINARY, + dirname(__DIR__) . '/Support/SnapshotEndResponseProxy.php', + 'START TRANSACTION READ WRITE', + 'after', ]); try { $ready = $relay->readLine(12.0); @@ -423,7 +453,7 @@ public function testUnacknowledgedStartCannotBecomeAnActiveCheckout(): void unset($pdo); self::failureOf(static fn() => $checkout->begin()); self::assertSame('SERVER OK WITHHELD', $relay->readLine(12.0)); - self::assertSame(ProtectedTransactionReasonEnum::START_UNCONFIRMED, $checkout->settlement()?->reason); + self::assertSame(ProtectedTransactionReasonEnum::StartUnconfirmed, $checkout->settlement()?->reason); $this->reject(static fn() => $checkout->commit()); $this->reject(static fn() => $checkout->returnForHost()); $checkout->discardForHost(); diff --git a/tests/Integration/Transaction/ProtectedTransactionDeadlockIntegrationTest.php b/tests/Integration/Transaction/ProtectedTransactionDeadlockIntegrationTest.php index cb37136..3cf5f78 100644 --- a/tests/Integration/Transaction/ProtectedTransactionDeadlockIntegrationTest.php +++ b/tests/Integration/Transaction/ProtectedTransactionDeadlockIntegrationTest.php @@ -28,8 +28,8 @@ public function testARealDeadlockFencesTheCheckoutWithoutReplay(): void }); self::assertSame(1213, self::driverCode($failure)); $settlement = $checkout->settlement(); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $settlement?->disposition); - self::assertSame(ProtectedTransactionReasonEnum::OPERATION_UNCONFIRMED, $settlement->reason); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement?->disposition); + self::assertSame(ProtectedTransactionReasonEnum::OperationUnconfirmed, $settlement->reason); self::assertNotEmpty($this->partnerReports()); $this->expectException(ProtectedTransactionException::class); $checkout->runRegisteredCommand('lock', ['id' => 1]); diff --git a/tests/Integration/Transaction/TransactionOutcomeIntegrationTest.php b/tests/Integration/Transaction/TransactionOutcomeIntegrationTest.php index c753c2c..d3f115c 100644 --- a/tests/Integration/Transaction/TransactionOutcomeIntegrationTest.php +++ b/tests/Integration/Transaction/TransactionOutcomeIntegrationTest.php @@ -118,7 +118,7 @@ public static function releaseOutcomes(): iterable } #[DataProvider('releaseOutcomes')] - public function testRawUndoCanReturnWithTheSavepointReleasedOrStillLive(bool $releaseSucceeds): void + public function testRawUndoRequiresBothRollbackAndReleaseAcknowledgements(bool $releaseSucceeds): void { $observer = $this->connect(); $table = $this->createTable($observer); @@ -133,7 +133,13 @@ public function testRawUndoCanReturnWithTheSavepointReleasedOrStillLive(bool $re $scope = SavepointScope::begin($host); $host->exec("INSERT INTO `$table` (id, v) VALUES (2, 20)"); - $scope->undoOrFail(); + if ($releaseSucceeds) { + $scope->undoOrFail(); + } else { + $thrown = $this->captureThrowable(static fn() => $scope->undoOrFail()); + self::assertInstanceOf(PDOException::class, $thrown); + self::assertSame('Injected control statement failure.', $thrown->getMessage()); + } self::assertTrue($host->inTransaction()); self::assertSame([10], $this->values($host, $table)); diff --git a/tests/Integration/Transaction/VerifiedTransactionDeadlockIntegrationTest.php b/tests/Integration/Transaction/VerifiedTransactionDeadlockIntegrationTest.php index abb115a..c91078e 100644 --- a/tests/Integration/Transaction/VerifiedTransactionDeadlockIntegrationTest.php +++ b/tests/Integration/Transaction/VerifiedTransactionDeadlockIntegrationTest.php @@ -6,7 +6,7 @@ use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandCatalog; use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandPlan; -use Maatify\PhpPersistence\Transaction\DTO\VerifiedTransactionDecisionDTO; +use Maatify\PhpPersistence\Transaction\Command\VerifiedTransactionDecisionCommand; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionOutcomeEnum; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionReasonEnum; @@ -35,12 +35,12 @@ public function testRealVictimNeverReplaysAndCannotHandBackTheConnection(bool $o ])); $attempts = 0; $seen = null; - $operation = function (VerifiedTransactionCommandsInterface $scope) use (&$attempts, &$seen): VerifiedTransactionDecisionDTO { + $operation = function (VerifiedTransactionCommandsInterface $scope) use (&$attempts, &$seen): VerifiedTransactionDecisionCommand { ++$attempts; $seen = $this->provokeDeadlockUsing(static function (int $id) use ($scope): void { $scope->runRegisteredCommand('lock', ['id' => $id]); }); - return VerifiedTransactionDecisionDTO::discard(); + return VerifiedTransactionDecisionCommand::discard(); }; try { if (!$owned) { @@ -51,10 +51,10 @@ public function testRealVictimNeverReplaysAndCannotHandBackTheConnection(bool $o self::assertSame(1213, self::driverCode($caught)); self::assertSame(1, $attempts); $settlement = $checkout->settlement(); - self::assertSame(VerifiedTransactionOutcomeEnum::UNKNOWN, $settlement->operationOutcome); - self::assertSame(VerifiedTransactionOutcomeEnum::UNKNOWN, $settlement->transactionOutcome); - self::assertSame(VerifiedTransactionReasonEnum::TRANSACTION_LOST, $settlement->checkoutReason); - self::assertSame(ProtectedTransactionDispositionEnum::DISCARD_REQUIRED, $settlement->disposition); + self::assertSame(VerifiedTransactionOutcomeEnum::Unknown, $settlement->operationOutcome); + self::assertSame(VerifiedTransactionOutcomeEnum::Unknown, $settlement->transactionOutcome); + self::assertSame(VerifiedTransactionReasonEnum::TransactionLost, $settlement->checkoutReason); + self::assertSame(ProtectedTransactionDispositionEnum::DiscardRequired, $settlement->disposition); $this->expectException(ProtectedTransactionException::class); $checkout->returnForHost(); } finally { diff --git a/tests/Integration/Transaction/VerifiedTransactionIntegrationTest.php b/tests/Integration/Transaction/VerifiedTransactionIntegrationTest.php index b84b50e..df83200 100644 --- a/tests/Integration/Transaction/VerifiedTransactionIntegrationTest.php +++ b/tests/Integration/Transaction/VerifiedTransactionIntegrationTest.php @@ -11,7 +11,7 @@ use Maatify\PhpPersistence\Tests\Integration\Support\PartnerProcess; use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandCatalog as Catalog; use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandPlan as Plan; -use Maatify\PhpPersistence\Transaction\DTO\VerifiedTransactionDecisionDTO as Decision; +use Maatify\PhpPersistence\Transaction\Command\VerifiedTransactionDecisionCommand as Decision; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum as Disposition; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionOutcomeEnum as Outcome; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionReasonEnum as Reason; @@ -70,12 +70,12 @@ public function testObservedEffectsAndSnapshotHistory(bool $owned, bool $apply, self::assertNull($operation->operationReason); self::assertNull($initial->operationOutcome); if ($owned) { - self::assertSame($apply ? Outcome::COMMITTED : Outcome::ROLLED_BACK, $operation->operationOutcome); + self::assertSame($apply ? Outcome::Committed : Outcome::RolledBack, $operation->operationOutcome); self::assertSame($operation->operationOutcome, $operation->transactionOutcome); self::assertSame($apply ? [20] : [], $this->values($observer, $table)); } else { $pending = $apply ? [10, 20] : [10]; - self::assertSame($apply ? Outcome::PENDING_HOST : Outcome::LOCAL_UNDONE, $operation->operationOutcome); + self::assertSame($apply ? Outcome::PendingHost : Outcome::LocalUndone, $operation->operationOutcome); self::assertNull($operation->transactionOutcome); self::assertNull($operation->disposition); self::assertSame(array_map(static fn(int $value): array => ['v' => $value], $pending), $checkout->runRegisteredCommand('visible')); @@ -86,7 +86,7 @@ public function testObservedEffectsAndSnapshotHistory(bool $owned, bool $apply, self::assertNull($operation->transactionOutcome); } $terminal = $checkout->settlement(); - self::assertSame(Disposition::REUSABLE, $terminal->disposition); + self::assertSame(Disposition::Reusable, $terminal->disposition); self::assertSame($pdo, $checkout->returnForHost()); $this->reject($checkout->returnForHost(...)); self::assertSame($terminal, $checkout->settlement()); @@ -110,8 +110,8 @@ public function testCleanCallbackFailurePreservesIdentityAndUndo(bool $owned): v $primary = new LogicException('application failure'); $caught = self::raised(fn() => $this->runMode($checkout, $owned, self::throwingWork($primary))); self::assertSame($primary, $caught); - self::assertSame(Reason::CALLBACK_FAILED, $checkout->settlement()->operationReason); - self::assertSame($owned ? Outcome::ROLLED_BACK : Outcome::LOCAL_UNDONE, $checkout->settlement()->operationOutcome); + self::assertSame(Reason::CallbackFailed, $checkout->settlement()->operationReason); + self::assertSame($owned ? Outcome::RolledBack : Outcome::LocalUndone, $checkout->settlement()->operationOutcome); if (!$owned) { self::assertSame([['v' => 10]], $checkout->runRegisteredCommand('visible')); $checkout->commit(); @@ -164,9 +164,9 @@ public function testCaughtCommandFailureDoesNotExposeLiveExecutionHandles(bool $ } $operation = $checkout->settlement(); - self::assertSame($owned ? Outcome::ROLLED_BACK : Outcome::LOCAL_UNDONE, $operation->operationOutcome); + self::assertSame($owned ? Outcome::RolledBack : Outcome::LocalUndone, $operation->operationOutcome); self::assertNull($operation->operationReason); - self::assertSame($owned ? Disposition::REUSABLE : null, $operation->disposition); + self::assertSame($owned ? Disposition::Reusable : null, $operation->disposition); self::assertSame([], $this->values($observer, $table)); if (!$owned) { self::assertSame([['v' => 10]], $checkout->runRegisteredCommand('visible')); @@ -221,10 +221,10 @@ public function testDriverFailureFencesButDoesNotReplaceEscapingApplicationError try { $caught = self::raised(fn() => $this->runMode($checkout, $owned, $work)); self::assertSame($afterDriver === 'throw' ? $primary : $driver, $caught); - self::assertSame(Outcome::UNKNOWN, $checkout->settlement()->operationOutcome); - self::assertSame(Outcome::UNKNOWN, $checkout->settlement()->transactionOutcome); - self::assertSame(Reason::COMMAND_FAILED, $checkout->settlement()->operationReason); - $this->fenced($checkout, Reason::COMMAND_FAILED); + self::assertSame(Outcome::Unknown, $checkout->settlement()->operationOutcome); + self::assertSame(Outcome::Unknown, $checkout->settlement()->transactionOutcome); + self::assertSame(Reason::CommandFailed, $checkout->settlement()->operationReason); + $this->fenced($checkout, Reason::CommandFailed); self::assertSame($questionsAfterFailure + 1, $this->questions($pdo)); } finally { ini_set('zend.exception_ignore_args', $previous); @@ -240,9 +240,9 @@ public function testDriverFailureFencesButDoesNotReplaceEscapingApplicationError /** @return iterable */ public static function cleanupFaults(): iterable { - yield 'Owned rollback' => [true, 'ROLLBACK AND NO CHAIN NO RELEASE', Reason::ROLLBACK_UNCONFIRMED, Outcome::UNKNOWN]; - yield 'Host undo' => [false, 'ROLLBACK TO SAVEPOINT', Reason::ROLLBACK_TO_UNCONFIRMED, Outcome::UNKNOWN]; - yield 'Host release after undo' => [false, 'RELEASE SAVEPOINT', Reason::RELEASE_UNCONFIRMED, Outcome::LOCAL_UNDONE]; + yield 'Owned rollback' => [true, 'ROLLBACK AND NO CHAIN NO RELEASE', Reason::RollbackUnconfirmed, Outcome::Unknown]; + yield 'Host undo' => [false, 'ROLLBACK TO SAVEPOINT', Reason::RollbackToUnconfirmed, Outcome::Unknown]; + yield 'Host release after undo' => [false, 'RELEASE SAVEPOINT', Reason::ReleaseUnconfirmed, Outcome::LocalUndone]; } #[DataProvider('cleanupFaults')] @@ -298,11 +298,12 @@ public function testEndAcknowledgementIsIndependentOfHandoff(bool $owned, bool $ } self::assertNoExecutionHandlesInTrace($failure); self::assertSame(self::relayEvidence($stage), $relay->readLine(12.0)); - $reason = $stage === 'after-ack' ? Reason::HANDOFF_UNCONFIRMED - : ($commit ? Reason::COMMIT_OUTCOME_UNKNOWN : Reason::ROLLBACK_UNCONFIRMED); - $outcome = $stage === 'after-ack' ? ($commit ? Outcome::COMMITTED : Outcome::ROLLED_BACK) : Outcome::UNKNOWN; + $reason = $stage === 'after-ack' + ? Reason::HandoffUnconfirmed + : ($commit ? Reason::CommitOutcomeUnknown : Reason::RollbackUnconfirmed); + $outcome = $stage === 'after-ack' ? ($commit ? Outcome::Committed : Outcome::RolledBack) : Outcome::Unknown; self::assertSame($outcome, $checkout->settlement()->transactionOutcome); - self::assertSame($owned ? $outcome : Outcome::PENDING_HOST, $checkout->settlement()->operationOutcome); + self::assertSame($owned ? $outcome : Outcome::PendingHost, $checkout->settlement()->operationOutcome); self::assertSame($owned ? $reason : null, $checkout->settlement()->operationReason); $this->fenced($checkout, $reason); self::assertSame($commit && $stage !== 'before' ? ($owned ? [20] : [10, 20]) : [], $this->values($observer, $table)); @@ -317,15 +318,15 @@ public function testEndAcknowledgementIsIndependentOfHandoff(bool $owned, bool $ public static function windowFaults(): iterable { foreach ([ - 'SAVEPOINT' => [Reason::SAVEPOINT_UNCONFIRMED, Outcome::NOT_STARTED], - 'ROLLBACK TO SAVEPOINT' => [Reason::ROLLBACK_TO_UNCONFIRMED, Outcome::UNKNOWN], - 'RELEASE SAVEPOINT' => [Reason::RELEASE_UNCONFIRMED, Outcome::LOCAL_UNDONE], + 'SAVEPOINT' => [Reason::SavepointUnconfirmed, Outcome::NotStarted], + 'ROLLBACK TO SAVEPOINT' => [Reason::RollbackToUnconfirmed, Outcome::Unknown], + 'RELEASE SAVEPOINT' => [Reason::ReleaseUnconfirmed, Outcome::LocalUndone], ] as $target => [$reason, $operation]) { foreach (['before', 'after', 'after-ack'] as $stage) { if ($stage === 'after-ack' && $target === 'ROLLBACK TO SAVEPOINT') { - $after = [Reason::RELEASE_UNCONFIRMED, Outcome::LOCAL_UNDONE]; + $after = [Reason::ReleaseUnconfirmed, Outcome::LocalUndone]; } elseif ($stage === 'after-ack') { - $after = [Reason::CONTINUITY_UNCONFIRMED, $operation]; + $after = [Reason::ContinuityUnconfirmed, $operation]; } else { $after = [$reason, $operation]; } @@ -346,7 +347,7 @@ public function testWindowControlFaultSuppressesDiscard(string $target, string $ self::assertSame(self::relayEvidence($stage), $relay->readLine(12.0)); self::assertSame($operation, $checkout->settlement()->operationOutcome); self::assertSame($reason, $checkout->settlement()->operationReason); - self::assertSame(Outcome::UNKNOWN, $checkout->settlement()->transactionOutcome); + self::assertSame(Outcome::Unknown, $checkout->settlement()->transactionOutcome); $this->fenced($checkout, $reason); self::assertSame([], $this->values($observer, $table)); $checkout->discardForHost(); @@ -365,7 +366,7 @@ public function testClaimsAreSharedAcrossBothCheckoutsAndRetirementIsSticky(): v $checkout = Checkout::attachExclusive($pdo, $catalog); $this->reject(fn() => ProtectedCheckout::attachExclusive($pdo, $catalog)); self::assertSame($pdo, $checkout->returnForHost()); - self::assertSame(Disposition::UNCHANGED, $checkout->settlement()->disposition); + self::assertSame(Disposition::Unchanged, $checkout->settlement()->disposition); $abandoned = Checkout::attachExclusive($pdo, $catalog); unset($abandoned); $this->reject(fn() => ProtectedCheckout::attachExclusive($pdo, $catalog)); @@ -392,10 +393,10 @@ public function testUnconfirmedStartNeverAdmitsWork(bool $owned, string $stage): $attempt = $owned ? fn() => $checkout->runOwned(static fn(): never => self::fail('Unexpected callback.')) : $checkout->beginHost(...); self::failureOf($attempt); self::assertSame(self::relayEvidence($stage), $relay->readLine(12.0)); - self::assertSame($owned ? Outcome::NOT_STARTED : null, $checkout->settlement()->operationOutcome); - self::assertSame($owned ? Reason::START_UNCONFIRMED : null, $checkout->settlement()->operationReason); - self::assertSame(Outcome::UNKNOWN, $checkout->settlement()->transactionOutcome); - $this->fenced($checkout, Reason::START_UNCONFIRMED); + self::assertSame($owned ? Outcome::NotStarted : null, $checkout->settlement()->operationOutcome); + self::assertSame($owned ? Reason::StartUnconfirmed : null, $checkout->settlement()->operationReason); + self::assertSame(Outcome::Unknown, $checkout->settlement()->transactionOutcome); + $this->fenced($checkout, Reason::StartUnconfirmed); $checkout->discardForHost(); } finally { $relay->stop(); @@ -443,9 +444,9 @@ public function testFirstServerProbeRejectsAnOutOfContractActiveTransaction(): v $pdo->exec('START TRANSACTION'); try { $this->reject(fn() => $checkout->runOwned(static fn(): never => self::fail('Unexpected callback.'))); - self::assertSame(Outcome::NOT_STARTED, $checkout->settlement()->operationOutcome); - self::assertSame(Outcome::NOT_STARTED, $checkout->settlement()->transactionOutcome); - $this->fenced($checkout, Reason::QUALIFICATION_FAILED); + self::assertSame(Outcome::NotStarted, $checkout->settlement()->operationOutcome); + self::assertSame(Outcome::NotStarted, $checkout->settlement()->transactionOutcome); + $this->fenced($checkout, Reason::QualificationFailed); self::assertTrue($pdo->inTransaction()); $checkout->discardForHost(); } finally { @@ -504,14 +505,14 @@ public function testFiberContextReentryAndScopeRetirement(bool $owned, bool $aba unset($fiber); gc_collect_cycles(); self::assertNull($weak->get()); - $this->fenced($checkout, Reason::CONTINUITY_UNCONFIRMED); + $this->fenced($checkout, Reason::ContinuityUnconfirmed); $checkout->discardForHost(); $pdo->rollBack(); self::assertSame([], $this->values($observer, $table)); } else { $fiber->resume(); self::assertNull($fiber->getReturn()); - self::assertSame($owned ? Outcome::ROLLED_BACK : Outcome::LOCAL_UNDONE, $checkout->settlement()->operationOutcome); + self::assertSame($owned ? Outcome::RolledBack : Outcome::LocalUndone, $checkout->settlement()->operationOutcome); if (!$owned) { $this->reject(fn() => $checkout->runInHost(self::work(true))); $checkout->commit(); @@ -534,8 +535,8 @@ public function testUnbufferedOverflowClosesTheCursorBeforeVerifiedLocalUndo(): $scope->runRegisteredCommand('limited'); return Decision::apply(); })); - self::assertSame(Outcome::LOCAL_UNDONE, $checkout->settlement()->operationOutcome); - self::assertSame(Reason::CALLBACK_FAILED, $checkout->settlement()->operationReason); + self::assertSame(Outcome::LocalUndone, $checkout->settlement()->operationOutcome); + self::assertSame(Reason::CallbackFailed, $checkout->settlement()->operationReason); self::assertNull($checkout->settlement()->disposition); $checkout->commit(); self::assertSame([10], $this->values($observer, $table)); @@ -573,7 +574,7 @@ public function testRawAliasReplacementIsAnExplicitNegativeControl(bool $during) return Decision::discard(); })); self::assertSame(1305, self::driverCode($failure)); - $this->fenced($checkout, Reason::ROLLBACK_TO_UNCONFIRMED); + $this->fenced($checkout, Reason::RollbackToUnconfirmed); self::assertSame([], $this->values($observer, $table)); $checkout->discardForHost(); } finally { @@ -623,8 +624,8 @@ public function testMariaDbSnapshotLossFencesAndMySqlControlRetainsHostOwnership self::assertNotInstanceOf(\PDOStatement::class, $arg); } } - $this->fenced($checkout, Reason::TRANSACTION_LOST); - self::assertSame(Outcome::UNKNOWN, $checkout->settlement()->transactionOutcome); + $this->fenced($checkout, Reason::TransactionLost); + self::assertSame(Outcome::Unknown, $checkout->settlement()->transactionOutcome); self::assertSame([10, 21], $this->values($observer, $table)); $checkout->discardForHost(); } finally { @@ -639,13 +640,17 @@ private function fixture(): array { $observer = $this->connect(); $table = $this->createTable($observer, 'verified'); - return [$observer, $table, new Catalog([ - 'insert' => new Plan("INSERT INTO $table (id, v) VALUES (:id, :value)", ['id', 'value']), - 'read' => new Plan("SELECT v FROM $table WHERE id = :id", ['id'], 1), - 'visible' => new Plan("SELECT v FROM $table ORDER BY id", [], 2), - 'limited' => new Plan("SELECT v FROM $table ORDER BY id", [], 1), - 'update' => new Plan("UPDATE $table SET v = :value WHERE id = :id", ['id', 'value']), - ])]; + return [ + $observer, + $table, + new Catalog([ + 'insert' => new Plan("INSERT INTO $table (id, v) VALUES (:id, :value)", ['id', 'value']), + 'read' => new Plan("SELECT v FROM $table WHERE id = :id", ['id'], 1), + 'visible' => new Plan("SELECT v FROM $table ORDER BY id", [], 2), + 'limited' => new Plan("SELECT v FROM $table ORDER BY id", [], 1), + 'update' => new Plan("UPDATE $table SET v = :value WHERE id = :id", ['id', 'value']), + ]), + ]; } private function beginWithMarker(Checkout $checkout): void @@ -681,7 +686,7 @@ private static function throwingWork(Throwable $primary): Closure private function fenced(Checkout $checkout, Reason $reason): void { self::assertSame($reason, $checkout->settlement()->checkoutReason); - self::assertSame(Disposition::DISCARD_REQUIRED, $checkout->settlement()->disposition); + self::assertSame(Disposition::DiscardRequired, $checkout->settlement()->disposition); $snapshot = $checkout->settlement(); $this->reject($checkout->returnForHost(...)); $this->reject($checkout->commit(...)); diff --git a/tests/Regression/DatabaseWorkSupervisionTest.php b/tests/Regression/DatabaseWorkSupervisionTest.php index db032ed..d626e58 100644 --- a/tests/Regression/DatabaseWorkSupervisionTest.php +++ b/tests/Regression/DatabaseWorkSupervisionTest.php @@ -18,7 +18,9 @@ public function testNormalWorkPreservesOutputAndExitStatus(): void { foreach ([0, 7] as $expected) { [$status, $out, $error] = execute(databaseWorkCommand([ - PHP_BINARY, '-r', 'fwrite(STDOUT, "worker output\n"); fwrite(STDERR, "worker error\n"); exit((int) $argv[1]);', + PHP_BINARY, + '-r', + 'fwrite(STDOUT, "worker output\n"); fwrite(STDERR, "worker error\n"); exit((int) $argv[1]);', (string) $expected, ], 5), timeoutSeconds: 8); @@ -97,7 +99,11 @@ public function testInterruptionPreservesFailureAndCleansOwnedWork(): void PHP_CODE; try { [$status, $out, $error] = execute([ - PHP_BINARY, '-r', $launcher, dirname(__DIR__, 2) . '/scripts/integration-support.php', $path, + PHP_BINARY, + '-r', + $launcher, + dirname(__DIR__, 2) . '/scripts/integration-support.php', + $path, ], timeoutSeconds: 10); self::assertSame(130, $status, $out . $error); self::assertStringContainsString('DB-WORK FAILURE: interrupted', $error); diff --git a/tests/Regression/DependencyAuditCommandTest.php b/tests/Regression/DependencyAuditCommandTest.php new file mode 100644 index 0000000..235f6e9 --- /dev/null +++ b/tests/Regression/DependencyAuditCommandTest.php @@ -0,0 +1,139 @@ +, int, string, bool}> */ + public static function outcomes(): iterable + { + yield 'valid policy and permitted abandonment blocking' => ['normal', [], 0, '', true]; + yield 'resolution blocking disabled' => ['normal', ['COMPOSER_POLICY_ADVISORIES_BLOCK' => '0'], 1, 'COMPOSER_POLICY_ADVISORIES_BLOCK', false]; + yield 'legacy blocking override' => ['normal', ['COMPOSER_NO_SECURITY_BLOCKING' => '1'], 1, 'COMPOSER_NO_SECURITY_BLOCKING', false]; + yield 'abandonment report only' => ['normal', ['COMPOSER_AUDIT_ABANDONED' => 'report'], 1, 'COMPOSER_AUDIT_ABANDONED', false]; + yield 'development dependencies excluded' => ['normal', ['COMPOSER_NO_DEV' => '1'], 1, 'COMPOSER_NO_DEV', false]; + yield 'network disabled' => ['normal', ['COMPOSER_DISABLE_NETWORK' => '1'], 1, 'COMPOSER_DISABLE_NETWORK', false]; + yield 'alternate manifest' => ['normal', ['COMPOSER' => 'alternate.json'], 1, 'COMPOSER', false]; + yield 'arguments cannot reach Composer' => ['arguments', [], 2, 'Usage', false]; + yield 'unsupported Composer' => ['old version', [], 1, 'Composer 2.10.0', false]; + yield 'effective weakened malware policy' => ['malware', [], 1, 'malware.audit', false]; + yield 'merged advisory ignore' => ['ignore', [], 1, 'advisories.ignore-severity', false]; + yield 'legacy fail-open network handling' => ['unreachable', [], 1, 'unreachable source', false]; + yield 'external repository mirror' => ['mirror', [], 1, 'default Packagist advisory source', false]; + yield 'insecure transport' => ['tls', [], 1, 'secure HTTPS', false]; + yield 'missing lock stops the audit' => ['missing lock', [], 1, 'composer update', false]; + yield 'stale lock stops the audit' => ['stale lock', [], 2, 'stale', false]; + yield 'audit failure propagated' => ['audit failure', [], 3, 'failed', true]; + } + + /** @param array $environment */ + #[DataProvider('outcomes')] + public function testEffectivePolicyAndAuditStatus( + string $case, + array $environment, + int $exit, + string $error, + bool $auditRuns, + ): void { + $root = dirname(__DIR__, 2); + $directory = sys_get_temp_dir() . '/pp-dependency-audit-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($directory . '/scripts/Tooling', 0700, true)); + try { + foreach (['dependency-audit.php', 'integration-support.php', 'Tooling/autoload.php'] as $file) { + self::assertTrue(copy($root . '/scripts/' . $file, $directory . '/scripts/' . $file)); + } + if ($case !== 'missing lock') { + self::assertTrue(touch($directory . '/composer.lock')); + } + self::assertNotFalse(file_put_contents($directory . '/composer', self::COMPOSER_FIXTURE)); + self::assertTrue(chmod($directory . '/composer', 0700)); + $command = [ + 'env', + '-i', + 'PATH=' . $directory . PATH_SEPARATOR . (getenv('PATH') ?: '/usr/bin:/bin'), + 'FIXTURE_CASE=' . $case, + 'COMPOSER_POLICY_ABANDONED_BLOCK=0', + ]; + foreach ($environment as $name => $value) { + $command[] = $name . '=' . $value; + } + $command[] = PHP_BINARY; + $command[] = $directory . '/scripts/dependency-audit.php'; + if ($case === 'arguments') { + $command[] = '--ignore-severity=high'; + } + [$status, $output, $stderr] = execute($command, [], $root); + self::assertSame($exit, $status, $output . $stderr); + if ($error !== '') { + self::assertStringContainsString($error, $stderr); + } + self::assertSame($auditRuns, is_file($directory . '/audit-ran')); + } finally { + [$cleanup] = execute(['rm', '-rf', '--', $directory]); + self::assertSame(0, $cleanup); + } + } + + private const COMPOSER_FIXTURE = <<<'PHP' + #!/usr/bin/env php + true, 'audit' => 'fail']; + if ($case === 'ignore') { + $advisories['ignore-severity'] = ['high']; + } + echo json_encode([ + 'advisories' => $advisories, + 'malware' => ['block' => true, 'audit' => $case === 'malware' ? 'report' : 'fail', 'block-scope' => 'all'], + 'abandoned' => ['audit' => 'fail', 'block' => false], + ]); + exit(0); + case ['config', 'audit']: + echo json_encode(['ignore-unreachable' => $case === 'unreachable']); + exit(0); + case ['config', 'repositories']: + echo json_encode(['packagist.org' => [ + 'type' => 'composer', + 'url' => $case === 'mirror' ? 'https://mirror.example' : 'https://repo.packagist.org', + ]]); + exit(0); + case ['config', 'disable-tls']: + echo json_encode($case === 'tls'); + exit(0); + case ['config', 'secure-http']: + echo 'true'; + exit(0); + case ['validate', '--strict', '--no-check-publish', '--check-lock']: + if ($case === 'stale lock') { + fwrite(STDERR, "lock is stale\n"); + exit(2); + } + exit(0); + case ['audit', '--locked', '--abandoned=fail']: + touch('audit-ran'); + if ($case === 'audit failure') { + fwrite(STDERR, "audit failed\n"); + exit(3); + } + exit(0); + } + exit(64); + PHP; +} diff --git a/tests/Regression/Exception/OrderingExceptionContractTest.php b/tests/Regression/Exception/OrderingExceptionContractTest.php index 7eda978..48409d0 100644 --- a/tests/Regression/Exception/OrderingExceptionContractTest.php +++ b/tests/Regression/Exception/OrderingExceptionContractTest.php @@ -88,9 +88,9 @@ public function testNoLegacyOrderingTransactionExceptionOrDeprecatedMarkerIsCarr } /** - * Ordering depends on Transaction only (Issue #16 §1): the manager carries no own savepoint - * helper and reuses the Transaction-owned SavepointScope (DEC-011 item 2), not a redesigned - * duplicate under Ordering. + * Ordering depends on Transaction only (Issue #16 §1). It shares the + * Transaction-owned SavepointScope (DEC-011 item 2) and the owned + * executor used by the public transaction runners (DEC-034). */ public function testOrderingHasNoOwnSavepointHelperAndDoesNotReviveTheInternalOperationSavepoint(): void { @@ -102,7 +102,7 @@ public function testOrderingHasNoOwnSavepointHelperAndDoesNotReviveTheInternalOp $operationsSource = file_get_contents($operationsFile); self::assertIsString($operationsSource); self::assertStringContainsString('Maatify\\PhpPersistence\\Transaction\\Repository\\SavepointScope', $operationsSource); - self::assertStringContainsString('Maatify\\PhpPersistence\\Transaction\\Repository\\PdoTransactionRunner', $operationsSource); + self::assertStringContainsString('Maatify\\PhpPersistence\\Transaction\\Repository\\OwnedTransactionExecutor', $operationsSource); } public function testInvalidOrderingConfigurationExceptionRepresentativeTrigger(): void diff --git a/tests/Regression/Exception/PaginationExceptionContractTest.php b/tests/Regression/Exception/PaginationExceptionContractTest.php index 3c6e467..f270330 100644 --- a/tests/Regression/Exception/PaginationExceptionContractTest.php +++ b/tests/Regression/Exception/PaginationExceptionContractTest.php @@ -92,6 +92,6 @@ public function testRepresentativeExecutionTrigger(): void { $this->expectException(PaginationExecutionException::class); - new PageResultDTO([], 0, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::ASC); + new PageResultDTO([], 0, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::Asc); } } diff --git a/tests/Regression/Ordering/OrderingPublicApiRegressionTest.php b/tests/Regression/Ordering/OrderingPublicApiRegressionTest.php index d568af3..d82b2c3 100644 --- a/tests/Regression/Ordering/OrderingPublicApiRegressionTest.php +++ b/tests/Regression/Ordering/OrderingPublicApiRegressionTest.php @@ -105,10 +105,18 @@ public function testProtectedB1NamedCallsAreAdditive(): void $id = ['id', 'int', false, false, null]; $newOrder = ['newOrder', 'int', false, false, null]; self::assertMethod($manager, 'getNextPositionForUpdate', [ - $host, $legacy, ['scopeValue', 'int|string', true, true, null], ['maxTailReads', 'int', false, true, 64], + $host, + $legacy, + ['scopeValue', 'int|string', true, true, null], + ['maxTailReads', 'int', false, true, 64], ], 'int'); self::assertMethod($manager, 'moveWithinScope', [ - $host, $legacy, $legacyScope, $id, $newOrder, ['updatedAtValue', 'string', true, true, null], + $host, + $legacy, + $legacyScope, + $id, + $newOrder, + ['updatedAtValue', 'string', true, true, null], ], 'bool'); $config = new ReflectionClass(UniqueOrderingConfig::class); @@ -129,7 +137,11 @@ public function testProtectedB1NamedCallsAreAdditive(): void self::assertMethod($manager, 'getNextUniquePositionForAppend', [$host, $b1, $scope], 'int'); self::assertMethod($manager, 'moveUniqueWithinScope', [$host, $b1, $scope, $id, $newOrder], 'bool'); self::assertMethod($manager, 'deleteUniqueWithinScope', [ - $host, $b1, $scope, $id, ['deleteCommandId', 'string', false, false, null], + $host, + $b1, + $scope, + $id, + ['deleteCommandId', 'string', false, false, null], ], 'bool'); } diff --git a/tests/Regression/Pagination/PaginationPublicApiRegressionTest.php b/tests/Regression/Pagination/PaginationPublicApiRegressionTest.php index 9348df1..073844b 100644 --- a/tests/Regression/Pagination/PaginationPublicApiRegressionTest.php +++ b/tests/Regression/Pagination/PaginationPublicApiRegressionTest.php @@ -14,6 +14,7 @@ use Maatify\PhpPersistence\Pagination\ValueObject\SortWhitelist; use PHPUnit\Framework\TestCase; use ReflectionClass; +use ReflectionEnum; use ReflectionIntersectionType; use ReflectionNamedType; use ReflectionParameter; @@ -21,8 +22,8 @@ use ReflectionUnionType; /** - * Reflects over the approved public Pagination contract of CONTRACT_MATRIX.md §3.3/§6.4/§6.9. - * Golden fixtures for this inventory were captured from legacy `main` (1f6a7aa) before this + * Reflects over the approved public Pagination contract, including DEC-036's + * sort direction cases. Golden fixtures for this inventory were captured from legacy `main` (1f6a7aa) before this * capability's first implementation, per the DEC-007 provenance gate. */ final class PaginationPublicApiRegressionTest extends TestCase @@ -46,10 +47,26 @@ public function testApprovedNamespacesTypesAndModifiers(): void } self::assertSame('Maatify\PhpPersistence\Pagination\Enum', (new ReflectionClass(SortDirectionEnum::class))->getNamespaceName()); - self::assertSame(['ASC' => 'ASC', 'DESC' => 'DESC'], array_column(SortDirectionEnum::cases(), 'value', 'name')); + self::assertSame(['Asc' => 'ASC', 'Desc' => 'DESC'], array_column(SortDirectionEnum::cases(), 'value', 'name')); self::assertSame(['cases', 'from', 'tryFrom'], array_map(static fn(\ReflectionMethod $method): string => $method->getName(), (new ReflectionClass(SortDirectionEnum::class))->getMethods())); } + /** Captures the DEC-036 limits of the published sort direction aliases. */ + public function testPublishedSortExpressionsRemainCompatible(): void + { + $reflection = new ReflectionEnum(SortDirectionEnum::class); + + self::assertSame(SortDirectionEnum::Asc, SortDirectionEnum::ASC); + self::assertSame(SortDirectionEnum::Desc, SortDirectionEnum::DESC); + self::assertSame(SortDirectionEnum::Asc, SortDirectionEnum::from('ASC')); + self::assertSame(SortDirectionEnum::Desc, SortDirectionEnum::tryFrom('DESC')); + self::assertFalse($reflection->hasCase('ASC')); + self::assertFalse($reflection->hasCase('DESC')); + self::assertStringContainsString(':Asc"', serialize(SortDirectionEnum::ASC)); + self::assertStringContainsString(':Desc"', serialize(SortDirectionEnum::DESC)); + self::assertSame(SortDirectionEnum::Asc, unserialize(serialize(SortDirectionEnum::ASC))); + } + public function testConstructorContractsAndPromotedProperties(): void { self::assertConstructor(PageRequest::class, [ @@ -101,7 +118,7 @@ public function testPublicMethodsAndResultEnvelope(): void self::assertMethod(PageResultDTO::class, 'jsonSerialize', [], 'array'); self::assertContains(JsonSerializable::class, class_implements(PageResultDTO::class)); - $result = new PageResultDTO([], 1, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::ASC); + $result = new PageResultDTO([], 1, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::Asc); self::assertSame(['data', 'pagination'], array_keys($result->toArray())); self::assertSame(['page', 'per_page', 'total', 'filtered', 'total_pages', 'has_next', 'has_previous', 'sort_by', 'sort_direction'], array_keys($result->toArray()['pagination'])); self::assertArrayNotHasKey('offset', $result->toArray()['pagination']); diff --git a/tests/Regression/Pagination/PaginationSqlContractRegressionTest.php b/tests/Regression/Pagination/PaginationSqlContractRegressionTest.php index 51626b6..61c4084 100644 --- a/tests/Regression/Pagination/PaginationSqlContractRegressionTest.php +++ b/tests/Regression/Pagination/PaginationSqlContractRegressionTest.php @@ -116,9 +116,9 @@ private function config(bool $duplicate = false): PaginationConfig return new PaginationConfig( new SortWhitelist(['created_at' => $duplicate ? 'id' : 'created_at', 'id' => 'id']), 'created_at', - SortDirectionEnum::DESC, + SortDirectionEnum::Desc, 'id', - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, 2, 1, 50, diff --git a/tests/Regression/PerCodingStyleDeltaCheckTest.php b/tests/Regression/PerCodingStyleDeltaCheckTest.php index 4d66ecc..b03fc06 100644 --- a/tests/Regression/PerCodingStyleDeltaCheckTest.php +++ b/tests/Regression/PerCodingStyleDeltaCheckTest.php @@ -16,26 +16,42 @@ final class PerCodingStyleDeltaCheckTest extends TestCase /** * @return array{int, string} exit status and standard error output */ - private static function check(string $source): array + private static function check(string $source, string $filename = 'Suit.php'): array { - $file = tempnam(sys_get_temp_dir(), 'percs'); - self::assertIsString($file); - file_put_contents($file, " ['pipe', 'w'], 2 => ['pipe', 'w']], - $pipes, - ); + $directory = sys_get_temp_dir() . '/percs-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($directory, 0700)); + $file = $directory . '/' . $filename; + + try { + file_put_contents($file, " ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); self::assertIsResource($process); - stream_get_contents($pipes[1]); + $output = (string) stream_get_contents($pipes[1]); $errors = (string) stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); - $status = proc_close($process); - unlink($file); - return [$status, $errors]; + return [proc_close($process), $output, $errors]; } /** @@ -51,6 +67,63 @@ public static function accepted(): array 'multi-line array with bracket on the assignment line' => ["\$e = [\n 1,\n];\n"], 'single-line array as argument' => ["foo([1, 2]);\n"], 'index access on the next line is not an array' => ["\$x = \$list\n ['key'];\n"], + 'nested call and array items are separate constructs' => [ + "\$x = [\n call(1, 2),\n [3, 4],\n];\n", + ], + 'nested multiline list matches the normative array example' => [ + "\$x = [\n 'outer',\n [\n 'nested',\n 'array',\n ],\n];\n", + ], + 'nested ternary indentation follows its own condition' => [ + "\$x = \$outer\n ? (\$inner\n ? 'yes'\n : 'no')\n : 'fallback';\n", + ], + 'multiline condition does not increase the ternary continuation indentation' => [ + "\$x = \$left\n || \$right\n ? 'yes'\n : 'no';\n", + ], + 'ternary with a multiline operand keeps its inline operators' => [ + "\$x = \$condition ? compute([\n 1,\n 2,\n]) : null;\n", + ], + 'split ternary places both operators at the start of continuation lines' => [ + "\$x = \$condition\n ? fn(): ?int => 5\n : null;\n", + ], + 'split ternary allows comments on separate lines' => [ + "\$x = \$condition\n /* when available */\n ? 'yes'\n // fallback\n : 'no';\n", + ], + 'short ternary and coalescing chains align their own continuations' => [ + "\$a = \$left\n ?: \$middle\n ?: \$right;\n\$b = \$left\n ?? \$middle\n ?? \$right;\n", + ], + 'direct and parenthesized logical control conditions share their own indentation' => [ + "if (\n \$a\n && (\n \$b\n || \$c\n )\n) {\n report();\n}\n", + ], + 'nested named argument uses its own indentation' => [ + "report(\n value: (\$a\n + \$b)\n ?? \$fallback,\n);\n", + ], + 'nested call argument does not take indentation from the control keyword' => [ + "if (\n test(\n \$a\n && \$b,\n )\n && \$c\n) {\n report();\n}\n", + ], + 'inline operator before multiline groups stays inline' => [ + "\$value = \$left + compute(\n 1,\n 2,\n) * (\n \$right\n);\n", + ], + 'unary signs following return, assignments, and a statement block' => [ + "if (\$a) {\n \$a = -\$a;\n}\n+ \$a;\nreturn -(+\$a);\n", + ], + 'expression closing braces and class literals can finish an operand' => [ + "\$x = match (1) {\n default => 1,\n}\n + 2;\n\$klass = SomeClass::class\n ?? 'fallback';\n", + ], + 'dynamic variables can finish an operand' => [ + "\$value = \${\$name}\n + 2;\n", + ], + 'types and references do not act as bitwise operators' => [ + "function &sample(\n (First&Second)|Third \$arg,\n ?int &\$ref,\n): First|Second {\n \$target = &\$ref;\n\n return \$target;\n}\n", + ], + 'split types retain their declaration syntax' => [ + "function sample(\n (First&Second)\n |Third \$arg,\n): First\n |Second {\n return \$arg;\n}\n", + ], + 'quoted operators and comments do not act as executable operators' => [ + "\$text = 'first\n?? second\n+ third\n?: fourth';\n// + \$right\n/* \$left\n& \$right */\n", + ], + 'low precedence logical operators can share a continuation level' => [ + "\$result = \$first\n and \$second\n or \$third;\n", + ], 'switch ending every case with a terminator' => [ "switch (\$a) {\n case 1:\n return 1;\n case 2:\n case 3:\n \$b = 2;\n break;\n default:\n throw new Exception('x');\n}\n", ], @@ -70,11 +143,20 @@ public static function accepted(): array "switch (\$a) {\n case 1:\n \$b = 1; /* Deliberate fall-through */\n default:\n break;\n}\n", ], 'enum whose method declares an anonymous class with a protected method' => [ - "enum Suit\n{\n case Hearts;\n\n public function f(): object\n {\n return new class {\n protected function g(): void {}\n };\n }\n}\n", + "namespace Fixture;\n\nenum Suit\n{\n case Hearts;\n\n public function f(): object\n {\n return new class {\n protected function g(): void {}\n };\n }\n}\n", + ], + 'PascalCase enum and uppercase constant' => [ + "namespace Fixture;\n\nenum Suit\n{\n case DarkBlue;\n\n private const DEFAULT_COLOR = self::DarkBlue;\n}\n", + ], + 'named class and methods with magic and anonymous methods' => [ + "namespace Fixture;\n\nfinal class Suit\n{\n public function __construct() {}\n\n public function makeColor(): object\n {\n return new class {\n public function colorCode(): int\n {\n return 1;\n }\n };\n }\n}\n", + ], + 'global helper function and embedded fixture are not method declarations' => [ + "function helper_name(): string\n{\n return 'enum Test { case BAD_STYLE; }';\n}\n", ], 'ternary inside a case label' => ["switch (\$a) {\n case \$b ? 1 : 2:\n break;\n}\n"], 'enum with private constant and method' => [ - "enum Suit: string\n{\n case Hearts = 'H';\n\n private const X = 1;\n\n private function f(): void {}\n}\n", + "namespace Fixture;\n\nenum Suit: string\n{\n case Hearts = 'H';\n\n private const X = 1;\n\n private function f(): void {}\n}\n", ], ]; } @@ -99,6 +181,86 @@ public static function violations(): array 'closure empty body without space before brace' => ["\$a = function (): void{};\n", 'empty body must be written'], 'standalone array bracket as argument' => ["foo(\n [\n 1,\n ],\n);\n", 'opening bracket of a multi-line array'], 'standalone array bracket after assignment' => ["\$a =\n [\n 1,\n ];\n", 'opening bracket of a multi-line array'], + 'multi-line array contains two values on the same line' => [ + "return [\n 1, 2,\n 3,\n];\n", + 'each value of a multi-line array must start on a separate line', + ], + 'two values share a line across a multiline array operand' => [ + "\$x = [\n call(\n 1,\n ), 2,\n];\n", + 'each value of a multi-line array must start on a separate line', + ], + 'split ternary packs both operators onto one line' => [ + "\$x = \$condition\n ? 'result' : 'fallback';\n", + 'a split ternary must put each operator on its own continuation line', + ], + 'split ternary keeps the first operator inline' => [ + "\$x = \$condition ? 'result'\n : 'fallback';\n", + 'a split ternary must put each operator on its own continuation line', + ], + 'multi-line array opens on the first item line' => [ + "return ['first',\n 'second',\n];\n", + 'the first value of a multi-line array must start on the line after its opening bracket', + ], + 'multi-line array closes on the last item line' => [ + "return [\n 'first',\n 'second',];\n", + 'the closing bracket of a multi-line array must start on the line after its last value', + ], + 'split ternary starts its middle operand after the operator line' => [ + "\$x = \$condition\n ?\n 'yes'\n : 'no';\n", + 'a split ternary must put each operator on its own continuation line', + ], + 'inline comment before the question mark' => [ + "\$x = \$condition\n /* when available */ ? 'yes'\n : 'no';\n", + 'a split ternary must put each operator on its own continuation line', + ], + 'inline comment before the colon' => [ + "\$x = \$condition\n ? 'yes'\n /* fallback */ : 'no';\n", + 'a split ternary must put each operator on its own continuation line', + ], + 'multiline comment can start a line with an operator lookalike' => [ + "\$x = \$condition\n /* The example contains\n ? inside the comment. */ ? 'yes'\n : 'no';\n", + 'a split ternary must put each operator on its own continuation line', + ], + 'overindented binary continuation' => [ + "\$x = \$left\n + \$right;\n", + 'each split operator continuation must be indented once (+)', + ], + 'nested arithmetic continuation follows its own operand' => [ + "\$x = \$first\n ?: (\$left\n * \$right);\n", + 'each split operator continuation must be indented once (*)', + ], + 'binary addition remains binary after a match brace' => [ + "\$x = match (1) {\n default => 1,\n}\n+ 2;\n", + 'each split operator continuation must be indented once (+)', + ], + 'binary subtraction remains binary after a closure brace' => [ + "\$x = function () {}\n- 2;\n", + 'each split operator continuation must be indented once (-)', + ], + 'binary addition remains binary after a dynamic variable brace' => [ + "\$value = \${\$name}\n+ 2;\n", + 'each split operator continuation must be indented once (+)', + ], + 'operator after a comment does not start the continuation' => [ + "\$x = \$left\n /* comment */ + \$right;\n", + 'a split operator must start its operand line (+)', + ], + 'logical control continuation needs indentation from the keyword' => [ + "if (\n \$a\n&& \$b\n) {\n report();\n}\n", + 'each split operator continuation must be indented once (&&)', + ], + 'split ternary continuations are unindented' => [ + "\$x = \$condition\n? 'yes'\n: 'no';\n", + 'each split ternary continuation must be indented once from its condition', + ], + 'split ternary continuations have different indentation' => [ + "\$x = \$condition\n ? 'yes'\n : 'no';\n", + 'each split ternary continuation must be indented once from its condition', + ], + 'nested ternary continuations need their own indentation' => [ + "\$x = \$outer\n ? (\$inner\n ? 'yes'\n : 'no')\n : 'fallback';\n", + 'each split ternary continuation must be indented once from its condition', + ], 'case body in braces' => ["switch (\$a) {\n case 1: {\n break;\n }\n}\n", 'must not be wrapped in braces'], 'last case without terminator' => ["switch (\$a) {\n case 1:\n \$b = 1;\n}\n", 'must end with a terminating statement'], 'middle case without terminator' => ["switch (\$a) {\n case 1:\n \$b = 1;\n case 2:\n break;\n}\n", 'must end with a terminating statement'], @@ -119,13 +281,45 @@ public static function violations(): array "switch (\$a) {\n case 1:\n \$b = 1;\n // set b\n case 2:\n break;\n}\n", 'must end with a terminating statement', ], - 'enum with protected constant' => ["enum Suit\n{\n case Hearts;\n\n protected const X = 1;\n}\n", 'private instead of protected'], + 'enum with protected constant' => ["namespace Fixture;\n\nenum Suit\n{\n case Hearts;\n\n protected const X = 1;\n}\n", 'private instead of protected'], 'enum with protected method next to an anonymous class' => [ - "enum Suit\n{\n case Hearts;\n\n protected function f(): object\n {\n return new class {};\n }\n}\n", + "namespace Fixture;\n\nenum Suit\n{\n case Hearts;\n\n protected function f(): object\n {\n return new class {};\n }\n}\n", 'private instead of protected', ], + 'enum case with underscores' => [ + "namespace Fixture;\n\nenum Suit\n{\n case DARK_BLUE;\n}\n", + 'enum case names must use PascalCase', + ], + 'enum case in uppercase' => [ + "namespace Fixture;\n\nenum Suit\n{\n case BLUE;\n}\n", + 'enum case names must use PascalCase', + ], + 'snake case method' => [ + "namespace Fixture;\n\nfinal class Suit\n{\n public function color_code(): void {}\n}\n", + 'method names must use camelCase', + ], + 'snake case method in an anonymous class with constructor arguments' => [ + "\$v = new class(1) {\n public function __construct(int \$n) {}\n\n public function color_code(): void {}\n};\n", + 'method names must use camelCase', + ], + 'named global class' => [ + "final class Suit {}\n", + 'require a formal namespace', + ], + 'class declared in the explicit global namespace' => [ + "namespace {\n final class Suit {}\n}\n", + 'require a formal namespace', + ], + 'a declaration in the wrong file' => [ + "namespace Fixture;\n\nfinal class Color {}\n", + 'must match its filename', + ], + 'two named declarations' => [ + "namespace Fixture;\n\nfinal class Suit {}\n\nfinal class Color {}\n", + 'must be in its own file', + ], 'switch with alternative syntax' => ["switch (\$a):\n case 1:\n break;\nendswitch;\n", 'alternative syntax'], - 'enum with protected member' => ["enum Suit\n{\n case Hearts;\n\n protected function f(): void {}\n}\n", 'private instead of protected'], + 'enum with protected member' => ["namespace Fixture;\n\nenum Suit\n{\n case Hearts;\n\n protected function f(): void {}\n}\n", 'private instead of protected'], 'anonymous class attribute on the new line' => ["\$o = new #[Foo] class {};\n", 'start on the line after new'], 'anonymous class attribute not indented' => ["\$o = new\n#[Foo]\nclass {};\n", 'indented once'], 'anonymous class declaration not on a new line' => ["\$o = new\n #[Foo] class {};\n", 'starts on a new line'], @@ -141,6 +335,74 @@ public function testViolationIsReported(string $source, string $message): void self::assertStringContainsString($message, $errors); } + /** @return iterable */ + public static function binaryOperators(): iterable + { + foreach ([ + '**', + '*', + '/', + '%', + '+', + '-', + '<', + '<=', + '>', + '>=', + '==', + '!=', + '===', + '!==', + '<>', + '<=>', + '=', + '+=', + '-=', + '*=', + '**=', + '/=', + '.=', + '%=', + '&=', + '|=', + '^=', + '<<=', + '>>=', + '??=', + '<<', + '>>', + '&', + '^', + '|', + '&&', + '||', + 'and', + 'xor', + 'or', + '.', + 'instanceof', + '??', + '?:', + ] as $operator) { + yield $operator => [$operator]; + } + } + + #[DataProvider('binaryOperators')] + public function testBinaryOperatorsEnforceContinuationPlacement(string $operator): void + { + [$valid, $validErrors] = self::check("\$result = \$left\n $operator \$right;\n"); + self::assertSame(0, $valid, $validErrors); + + [$unindented, $indentationErrors] = self::check("\$result = \$left\n$operator \$right;\n"); + self::assertSame(1, $unindented); + self::assertStringContainsString("each split operator continuation must be indented once ($operator)", $indentationErrors); + + [$trailing, $placementErrors] = self::check("\$result = \$left $operator\n \$right;\n"); + self::assertSame(1, $trailing); + self::assertStringContainsString("a split operator must start its operand line ($operator)", $placementErrors); + } + /** * @return array source and the message expected on PHP 8.5 or later */ @@ -149,6 +411,38 @@ public static function pipeViolations(): array return [ 'no space around the operator' => ["\$a = \$b|>trim(...);\n", 'needs a space before and after'], 'operator at the end of the line' => ["\$a = \$b |>\n trim(...);\n", 'each line starts with the operator'], + 'first operator is inline in a later split chain' => [ + "\$a = \$b |> trim(...)\n |> strtoupper(...);\n", + 'each line starts with the operator', + ], + 'two operators share a line in a split chain' => [ + "\$a = \$b\n |> trim(...) |> strtoupper(...);\n", + 'each line starts with the operator', + ], + 'multiple inline operators on different lines form a split chain' => [ + "\$result = \$source |> makeCallable(\n \$argument,\n) |> trim(...);\n", + 'each line starts with the operator', + ], + 'single-line comment comes before a pipe on the continuation line' => [ + "\$a = \$b\n /* stage */ |> trim(...);\n", + 'each line starts with the operator', + ], + 'multiline comment ends before a pipe on the same line' => [ + "\$a = \$b /* stage\n ends here */ |> trim(...);\n", + 'each line starts with the operator', + ], + 'multiline comment separates the pipe from its right operand' => [ + "\$a = \$b\n |> /* stage\n ends here */ trim(...);\n", + 'each line starts with the operator', + ], + 'pipe is overindented after a method continuation' => [ + "\$a = \$provider\n ->value()\n |> trim(...);\n", + 'must be indented once', + ], + 'pipe is overindented after a concatenation continuation' => [ + "\$a = \$b\n . ' suffix'\n |> trim(...);\n", + 'must be indented once', + ], 'continuation line not indented' => ["\$a = \$b\n|> trim(...);\n", 'must be indented'], ]; } @@ -168,15 +462,54 @@ public function testPipeOperatorViolations(string $source, string $message): voi self::assertStringContainsString('pipe operator requires a PHP version', $errors); } - public function testConformingPipeChainPassesOnPhp85AndIsRefusedOnEarlierVersions(): void + /** @return array */ + public static function conformingPipes(): array { - [$status, $errors] = self::check("\$a = \$b\n |> trim(...)\n |> strtoupper(...);\n\$c = \$d |> trim(...);\n"); + return [ + 'inline and split chains' => [ + "\$a = \$b\n |> trim(...)\n |> strtoupper(...);\n\$c = \$d |> trim(...);\n", + ], + 'different arguments and null-coalescing branches are independent' => [ + "pair(\n \$first |> trim(...),\n \$second\n |> trim(...)\n |> strtoupper(...),\n);\n" + . "\$value = \$first |> trim(...)\n ?? \$second\n |> trim(...)\n |> strtoupper(...);\n", + ], + 'pipe follows a comment on its own line and can carry a comment after it' => [ + "\$a = \$b\n /* stage */\n |> /* prepare */ trim(...);\n", + ], + 'pipe after a method continuation is indented from the start' => [ + "\$a = \$provider\n ->value()\n |> trim(...);\n", + ], + 'pipe after a concatenation continuation is indented from the start' => [ + "\$a = \$b\n . ' suffix'\n |> trim(...);\n", + ], + 'inline operator before a multiline right operand' => [ + "\$a = \$b |> makeCallable(\n 'source',\n);\n", + ], + 'inline operator after a multiline left operand' => [ + "\$a = fetch(\n \$argument,\n) |> trim(...);\n", + ], + 'nested named argument does not change the outer pipe indentation' => [ + "\$a = pair(\n first: \$input\n |> trim(...),\n second: \$other |> trim(...),\n)\n |> strtoupper(...);\n", + ], + 'comparison operator starts a higher precedence pipe expression' => [ + "\$ok = \$first\n === \$other\n |> trim(...);\n", + ], + 'ternary branches have separate chains' => [ + "\$value = \$condition\n ? \$first |> trim(...)\n : \$second\n |> trim(...)\n |> strtoupper(...);\n", + ], + ]; + } + #[DataProvider('conformingPipes')] + public function testConformingPipeChainsPass(string $source): void + { + [$status, $errors] = self::check($source); if (PHP_VERSION_ID >= 80500) { self::assertSame(0, $status, $errors); return; } + self::assertSame(1, $status); self::assertStringContainsString('pipe operator requires a PHP version', $errors); } @@ -190,23 +523,14 @@ public function testConformingAnonymousClassWithAttributesPasses(): void public function testDefaultScopeCoversConfigurationAndScriptFiles(): void { - $process = proc_open( - [PHP_BINARY, dirname(__DIR__, 2) . '/scripts/check-per-cs-3-1.php'], - [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], - $pipes, - ); - self::assertIsResource($process); - $output = (string) stream_get_contents($pipes[1]); - $errors = (string) stream_get_contents($pipes[2]); - fclose($pipes[1]); - fclose($pipes[2]); + [$status, $output, $errors] = self::runVerifier(dirname(__DIR__, 2) . '/scripts/check-per-cs-3-1.php'); - self::assertSame(0, proc_close($process), $errors); + self::assertSame(0, $status, $errors); $scanned = (int) preg_replace('/^.*check: (\d+) files.*$/s', '$1', $output); self::assertGreaterThan(0, $scanned, $output); $expected = 0; $root = dirname(__DIR__, 2); - $skipped = ['vendor', '.git', 'docs', 'node_modules', '.phpunit.cache', '.phpstan']; + $skipped = ['vendor', '.git', 'node_modules', '.phpunit.cache', '.phpstan']; $filter = new \RecursiveCallbackFilterIterator( new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS), static fn(\SplFileInfo $entry): bool => !($entry->isDir() && in_array($entry->getFilename(), $skipped, true)), @@ -220,4 +544,35 @@ public function testDefaultScopeCoversConfigurationAndScriptFiles(): void self::assertSame($expected, $scanned); self::assertFileExists($root . '/.php-cs-fixer.php'); } + + public function testDefaultScopeChecksHandwrittenPhpInDocs(): void + { + $root = sys_get_temp_dir() . '/percs-docs-' . bin2hex(random_bytes(8)); + $script = $root . '/scripts/check-per-cs-3-1.php'; + $example = $root . '/docs/examples/DocumentationProbe.php'; + + self::assertTrue(mkdir($root . '/scripts', 0700, true)); + self::assertTrue(mkdir($root . '/docs/examples', 0700, true)); + self::assertTrue(copy(dirname(__DIR__, 2) . '/scripts/check-per-cs-3-1.php', $script)); + try { + $source = " hash_file('sha256', $repo . '/README.md'), 'observedSha256' => hash('sha256', 'altered'), ], $records['CONTENT']['changedFiles']['README.md']); - self::assertSame([[ - 'pathSha256' => hash('sha256', self::EXTRA_PATH), - 'observedSha256' => hash('sha256', 'extra'), - ]], $records['CONTENT']['unexpectedFiles']); + self::assertSame([ + [ + 'pathSha256' => hash('sha256', self::EXTRA_PATH), + 'observedSha256' => hash('sha256', 'extra'), + ], + ], $records['CONTENT']['unexpectedFiles']); } else { self::assertIsArray($records['CONTENT']['matchingFiles']); self::assertCount(count($files), $records['CONTENT']['matchingFiles']); diff --git a/tests/Regression/SettlementJsonContractTest.php b/tests/Regression/SettlementJsonContractTest.php new file mode 100644 index 0000000..eea12a8 --- /dev/null +++ b/tests/Regression/SettlementJsonContractTest.php @@ -0,0 +1,155 @@ + new SnapshotConnectionOutcomeDTO($case, 'qualified stage'), + ConnectionDisposition::cases(), + ); + self::assertSame( + '[{"disposition":"UNCHANGED","diagnostic":"qualified stage"},{"disposition":"REUSABLE","diagnostic":"qualified stage"},{"disposition":"DISCARD","diagnostic":"qualified stage"}]', + json_encode($outcomes, JSON_THROW_ON_ERROR), + ); + self::assertSame( + '{"disposition":"REUSABLE","diagnostic":null}', + json_encode(new SnapshotConnectionOutcomeDTO(ConnectionDisposition::Reusable, null), JSON_THROW_ON_ERROR), + ); + } + + public function testHostSnapshotSettlementPreservesDispositionAndReasonCodes(): void + { + self::assertSame( + ['NOT_ACCEPTED', 'RETURNED_TO_HOST', 'HOST_ACTION_REQUIRED'], + array_map( + static fn(PageDisposition $case): string => (new HostSnapshotPageSettlementDTO($case, PageReason::PageCompleted))->jsonSerialize()['disposition'], + PageDisposition::cases(), + ), + ); + $expectedReasons = [ + 'SOURCE_UNAVAILABLE', + 'STALE_CONTEXT', + 'GRANT_CONSUMED', + 'BUSY', + 'PAGE_COMPLETED', + 'READ_FAILED', + 'RESOURCE_RELEASE_UNCONFIRMED', + 'SCOPE_UNCONFIRMED', + 'SETTLEMENT_UNCONFIRMED', + ]; + self::assertSame( + $expectedReasons, + array_map( + static fn(PageReason $case): string => (new HostSnapshotPageSettlementDTO(PageDisposition::ReturnedToHost, $case))->jsonSerialize()['reason'], + PageReason::cases(), + ), + ); + self::assertSame( + '{"disposition":"RETURNED_TO_HOST","reason":"PAGE_COMPLETED"}', + json_encode(new HostSnapshotPageSettlementDTO(PageDisposition::ReturnedToHost, PageReason::PageCompleted), JSON_THROW_ON_ERROR), + ); + } + + public function testProtectedSettlementPreservesDispositionAndReasonCodes(): void + { + self::assertSame( + ['UNCHANGED', 'REUSABLE', 'DISCARD_REQUIRED'], + array_map( + static fn(ProtectedDisposition $case): string => (new ProtectedTransactionSettlementDTO($case, ProtectedReason::Committed))->jsonSerialize()['disposition'], + ProtectedDisposition::cases(), + ), + ); + $expectedReasons = [ + 'CANCELLED_BEFORE_QUALIFICATION', + 'SERVER_QUALIFICATION_FAILED', + 'START_UNCONFIRMED', + 'TRANSACTION_LOST', + 'OPERATION_UNCONFIRMED', + 'COMMIT_OUTCOME_UNKNOWN', + 'COMMIT_CONFIRMED_CONNECTION_UNSAFE', + 'ROLLBACK_UNCONFIRMED', + 'COMMITTED', + 'ROLLED_BACK', + 'HOST_DISCARDED', + ]; + self::assertSame( + $expectedReasons, + array_map( + static fn(ProtectedReason $case): string => (new ProtectedTransactionSettlementDTO(ProtectedDisposition::Reusable, $case))->jsonSerialize()['reason'], + ProtectedReason::cases(), + ), + ); + self::assertSame( + '{"disposition":"DISCARD_REQUIRED","reason":"COMMIT_CONFIRMED_CONNECTION_UNSAFE"}', + json_encode(new ProtectedTransactionSettlementDTO(ProtectedDisposition::DiscardRequired, ProtectedReason::CommitConfirmedConnectionUnsafe), JSON_THROW_ON_ERROR), + ); + } + + public function testVerifiedSettlementPreservesOutcomeReasonAndNullableFields(): void + { + self::assertSame( + ['NOT_STARTED', 'PENDING_HOST', 'LOCAL_UNDONE', 'COMMITTED', 'ROLLED_BACK', 'UNKNOWN'], + array_map( + static fn(VerifiedOutcome $case): ?string => (new VerifiedTransactionSettlementDTO($case, null, null, null, null))->jsonSerialize()['operationOutcome'], + VerifiedOutcome::cases(), + ), + ); + $expectedReasons = [ + 'QUALIFICATION_FAILED', + 'START_UNCONFIRMED', + 'CONTINUITY_UNCONFIRMED', + 'SAVEPOINT_UNCONFIRMED', + 'CALLBACK_FAILED', + 'COMMAND_FAILED', + 'CURSOR_UNCONFIRMED', + 'ROLLBACK_TO_UNCONFIRMED', + 'RELEASE_UNCONFIRMED', + 'COMMIT_OUTCOME_UNKNOWN', + 'ROLLBACK_UNCONFIRMED', + 'HANDOFF_UNCONFIRMED', + 'TRANSACTION_LOST', + 'HOST_DISCARDED', + ]; + self::assertSame( + $expectedReasons, + array_map( + static fn(VerifiedReason $case): ?string => (new VerifiedTransactionSettlementDTO(null, $case, null, null, null))->jsonSerialize()['operationReason'], + VerifiedReason::cases(), + ), + ); + $settlement = new VerifiedTransactionSettlementDTO( + VerifiedOutcome::LocalUndone, + VerifiedReason::CallbackFailed, + VerifiedOutcome::Unknown, + VerifiedReason::HandoffUnconfirmed, + ProtectedDisposition::DiscardRequired, + ); + self::assertSame( + '{"operationOutcome":"LOCAL_UNDONE","operationReason":"CALLBACK_FAILED","transactionOutcome":"UNKNOWN","checkoutReason":"HANDOFF_UNCONFIRMED","disposition":"DISCARD_REQUIRED"}', + json_encode($settlement, JSON_THROW_ON_ERROR), + ); + self::assertSame( + '{"operationOutcome":null,"operationReason":null,"transactionOutcome":null,"checkoutReason":null,"disposition":null}', + json_encode(new VerifiedTransactionSettlementDTO(null, null, null, null, null), JSON_THROW_ON_ERROR), + ); + } +} diff --git a/tests/Regression/VerifiedTransactionPublicApiTest.php b/tests/Regression/VerifiedTransactionPublicApiTest.php index de84e47..b5dce61 100644 --- a/tests/Regression/VerifiedTransactionPublicApiTest.php +++ b/tests/Regression/VerifiedTransactionPublicApiTest.php @@ -6,7 +6,7 @@ use Closure; use Maatify\PhpPersistence\Transaction\Criteria\ProtectedTransactionCommandCatalog; -use Maatify\PhpPersistence\Transaction\DTO\VerifiedTransactionDecisionDTO as Decision; +use Maatify\PhpPersistence\Transaction\Command\VerifiedTransactionDecisionCommand as Decision; use Maatify\PhpPersistence\Transaction\DTO\VerifiedTransactionSettlementDTO as Settlement; use Maatify\PhpPersistence\Transaction\Enum\ProtectedTransactionDispositionEnum as Disposition; use Maatify\PhpPersistence\Transaction\Enum\VerifiedTransactionOutcomeEnum as Outcome; @@ -87,6 +87,7 @@ public function testDecisionAndSettlementAreImmutableValues(): void self::assertFalse(Decision::discard(false)->isApply); self::assertFalse(Decision::discard(false)->payload); self::assertNull(Decision::discard()->payload); + self::assertNotContains(\JsonSerializable::class, $decision->getInterfaceNames()); $settlement = new ReflectionClass(Settlement::class); self::assertTrue($settlement->isFinal() && $settlement->isReadOnly()); @@ -102,14 +103,38 @@ public function testDecisionAndSettlementAreImmutableValues(): void array_map(static fn(\ReflectionParameter $p): string => (string) $p->getType(), $parameters), )); self::assertSame( - ['NOT_STARTED', 'PENDING_HOST', 'LOCAL_UNDONE', 'COMMITTED', 'ROLLED_BACK', 'UNKNOWN'], + ['NotStarted', 'PendingHost', 'LocalUndone', 'Committed', 'RolledBack', 'Unknown'], array_column(Outcome::cases(), 'name'), ); self::assertSame([ - 'QUALIFICATION_FAILED', 'START_UNCONFIRMED', 'CONTINUITY_UNCONFIRMED', 'SAVEPOINT_UNCONFIRMED', - 'CALLBACK_FAILED', 'COMMAND_FAILED', 'CURSOR_UNCONFIRMED', 'ROLLBACK_TO_UNCONFIRMED', - 'RELEASE_UNCONFIRMED', 'COMMIT_OUTCOME_UNKNOWN', 'ROLLBACK_UNCONFIRMED', 'HANDOFF_UNCONFIRMED', - 'TRANSACTION_LOST', 'HOST_DISCARDED', + 'QualificationFailed', + 'StartUnconfirmed', + 'ContinuityUnconfirmed', + 'SavepointUnconfirmed', + 'CallbackFailed', + 'CommandFailed', + 'CursorUnconfirmed', + 'RollbackToUnconfirmed', + 'ReleaseUnconfirmed', + 'CommitOutcomeUnknown', + 'RollbackUnconfirmed', + 'HandoffUnconfirmed', + 'TransactionLost', + 'HostDiscarded', ], array_column(Reason::cases(), 'name')); } + + public function testSettlementJsonPreservesPropertiesAsStableCodesOrNull(): void + { + $settlement = new Settlement(Outcome::LocalUndone, Reason::CallbackFailed, Outcome::Unknown, null, Disposition::DiscardRequired); + + self::assertSame(Outcome::LocalUndone, $settlement->operationOutcome); + self::assertSame([ + 'operationOutcome' => 'LOCAL_UNDONE', + 'operationReason' => 'CALLBACK_FAILED', + 'transactionOutcome' => 'UNKNOWN', + 'checkoutReason' => null, + 'disposition' => 'DISCARD_REQUIRED', + ], json_decode(json_encode($settlement, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)); + } } diff --git a/tests/Support/Ordering/LazySavepointSchema.php b/tests/Support/Ordering/LazySavepointSchema.php index 1cfae2b..14b7193 100644 --- a/tests/Support/Ordering/LazySavepointSchema.php +++ b/tests/Support/Ordering/LazySavepointSchema.php @@ -62,26 +62,26 @@ public function initialize(): void foreach ([$this->plain => '', $this->unique => ', UNIQUE KEY `u_updated` (`updated_at`)'] as $table => $extra) { $this->pdo->exec( 'CREATE TABLE `' . $table . '` (' - . ' `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,' + . ' `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,' // DEFAULT 0 only matters for the filler rows the DeadlockPartner INSERT adds // (see `payload` above); every row this test suite seeds sets it explicitly. - . ' `display_order` INT NOT NULL DEFAULT 0,' - . ' `deleted_at` DATETIME NULL DEFAULT NULL,' - . ' `updated_at` DATETIME NULL DEFAULT NULL,' + . ' `display_order` INT NOT NULL DEFAULT 0,' + . ' `deleted_at` DATETIME NULL DEFAULT NULL,' + . ' `updated_at` DATETIME NULL DEFAULT NULL,' // `payload` carries no ordering meaning; it exists only so the generic // tests/Integration/Support/DeadlockPartner.php filler INSERT (used by // ScopedOrderingManagerLazySavepointTest's genuine-deadlock test) can make // itself heavy against this exact table without a dedicated partner script. - . ' `payload` VARCHAR(32) NULL DEFAULT NULL,' - . ' `label` VARCHAR(191) NOT NULL DEFAULT \'\',' - . ' PRIMARY KEY (`id`)' . $extra - . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4', + . ' `payload` VARCHAR(32) NULL DEFAULT NULL,' + . ' `label` VARCHAR(191) NOT NULL DEFAULT \'\',' + . ' PRIMARY KEY (`id`)' . $extra + . ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4', ); for ($i = 1; $i <= 5; $i++) { $this->pdo->exec( 'INSERT INTO `' . $table . '` (`display_order`, `updated_at`, `label`)' - . " VALUES ({$i}, '2026-01-0{$i} 00:00:00', 'row {$i}')", + . " VALUES ({$i}, '2026-01-0{$i} 00:00:00', 'row {$i}')", ); } } diff --git a/tests/Support/Ordering/OrderingFailureInjector.php b/tests/Support/Ordering/OrderingFailureInjector.php index d4db33d..9341d72 100644 --- a/tests/Support/Ordering/OrderingFailureInjector.php +++ b/tests/Support/Ordering/OrderingFailureInjector.php @@ -55,7 +55,7 @@ public function createTargetUpdateFailure(string $table, int $targetId, int $for $constraint = 'chk_fail_' . $table; $result = $this->pdo->exec( 'ALTER TABLE `' . $table . '` ADD CONSTRAINT `' . $constraint . '`' - . ' CHECK (`label` <> \'' . $marker . '\' OR `display_order` <> ' . $forbiddenOrder . ')', + . ' CHECK (`label` <> \'' . $marker . '\' OR `display_order` <> ' . $forbiddenOrder . ')', ); if ($result === false) { diff --git a/tests/Support/Ordering/OrderingScriptedPdo.php b/tests/Support/Ordering/OrderingScriptedPdo.php index aaca129..7c74e33 100644 --- a/tests/Support/Ordering/OrderingScriptedPdo.php +++ b/tests/Support/Ordering/OrderingScriptedPdo.php @@ -6,6 +6,7 @@ use LogicException; use PDO; +use PDOException; use PDOStatement; /** @@ -14,25 +15,33 @@ * current-order SELECT, shift UPDATE, target UPDATE), and a transaction-active flag that starts * at $participating and flips with beginTransaction()/commit()/rollBack() so the double can * script both the participating and the owned path. Control statements (SAVEPOINT/RELEASE/ - * ROLLBACK TO) go through exec(), tracked and always reported successful: the shared - * SavepointScope's own control-statement failure precedence is already characterized in - * isolation by tests/Unit/Transaction/Repository/SavepointScopeTest.php (WU-6); this double - * exists only to prove which SavepointScope method moveWithinScope() calls for a given - * target-write outcome. + * ROLLBACK TO) go through exec(). The double records transaction changes + * and can return a scripted failure or throw at either cleanup boundary. */ final class OrderingScriptedPdo extends PDO { /** @var list */ public array $executedControlStatements = []; - /** @var list */ + public int $beginCalls = 0; + public int $commitCalls = 0; + public int $rollbackCalls = 0; + + /** @var list */ private array $prepareQueue; private bool $active; - /** @param list $prepareQueue */ - public function __construct(array $prepareQueue, bool $participating = true) - { + /** + * @param list $prepareQueue + * @param list $controlResults + */ + public function __construct( + array $prepareQueue, + bool $participating = true, + private bool|PDOException $rollbackResult = true, + private array $controlResults = [], + ) { $this->prepareQueue = $prepareQueue; $this->active = $participating; } @@ -44,6 +53,7 @@ public function inTransaction(): bool public function beginTransaction(): bool { + $this->beginCalls++; $this->active = true; return true; @@ -51,6 +61,7 @@ public function beginTransaction(): bool public function commit(): bool { + $this->commitCalls++; $this->active = false; return true; @@ -58,9 +69,15 @@ public function commit(): bool public function rollBack(): bool { - $this->active = false; + $this->rollbackCalls++; + if ($this->rollbackResult instanceof PDOException) { + throw $this->rollbackResult; + } + if ($this->rollbackResult) { + $this->active = false; + } - return true; + return $this->rollbackResult; } /** @param array $options */ @@ -75,10 +92,14 @@ public function prepare(string $query, array $options = []): PDOStatement return array_shift($this->prepareQueue); } - public function exec(string $statement): int + public function exec(string $statement): int|false { $this->executedControlStatements[] = $statement; + $result = array_shift($this->controlResults) ?? 0; + if ($result instanceof PDOException) { + throw $result; + } - return 0; + return $result; } } diff --git a/tests/Support/Pagination/PaginationFixture.php b/tests/Support/Pagination/PaginationFixture.php index c5be3af..980af1f 100644 --- a/tests/Support/Pagination/PaginationFixture.php +++ b/tests/Support/Pagination/PaginationFixture.php @@ -22,8 +22,8 @@ public function insertItem( ): int { $statement = $this->pdo->prepare( 'INSERT INTO `' . $this->table . '` ' - . '(`tenant_id`, `category`, `name`, `score`, `is_active`, `nullable_code`, `created_at`, `deleted_at`) ' - . 'VALUES (:tenant_id, :category, :name, :score, :is_active, :nullable_code, :created_at, :deleted_at)', + . '(`tenant_id`, `category`, `name`, `score`, `is_active`, `nullable_code`, `created_at`, `deleted_at`) ' + . 'VALUES (:tenant_id, :category, :name, :score, :is_active, :nullable_code, :created_at, :deleted_at)', ); $statement->bindValue(':tenant_id', $tenantId, PDO::PARAM_INT); diff --git a/tests/Support/Pagination/ScriptedPdoStatement.php b/tests/Support/Pagination/ScriptedPdoStatement.php index 383e312..0c523d9 100644 --- a/tests/Support/Pagination/ScriptedPdoStatement.php +++ b/tests/Support/Pagination/ScriptedPdoStatement.php @@ -9,6 +9,12 @@ use PDOStatement; use Throwable; +/** + * Records PDO statement calls and feeds scripted outcomes to pagination tests. + * A fetch consumes one queue entry. Supply false explicitly to end the result, + * or a throwable to simulate a driver error. An exhausted queue raises + * LogicException because the fixture did not account for the fetch. + */ final class ScriptedPdoStatement extends PDOStatement { /** @var list */ diff --git a/tests/Support/Pagination/SnapshotHostCheckout.php b/tests/Support/Pagination/SnapshotHostCheckout.php index ab8e3ff..ddee72c 100644 --- a/tests/Support/Pagination/SnapshotHostCheckout.php +++ b/tests/Support/Pagination/SnapshotHostCheckout.php @@ -65,9 +65,9 @@ public function settle(int $checkout, ?SnapshotConnectionOutcomeDTO $outcome, ?T if ($failure !== null) { throw $failure; } - if ($outcome?->disposition === SnapshotConnectionDispositionEnum::REUSABLE) { + if ($outcome?->disposition === SnapshotConnectionDispositionEnum::Reusable) { $this->available = $pdo; - } elseif ($outcome?->disposition === SnapshotConnectionDispositionEnum::UNCHANGED) { + } elseif ($outcome?->disposition === SnapshotConnectionDispositionEnum::Unchanged) { $this->returnedToHost = $pdo; } } diff --git a/tests/Unit/Infrastructure/IntegrationResidueShadowTest.php b/tests/Unit/Infrastructure/IntegrationResidueShadowTest.php index ceb4be2..8d798ca 100644 --- a/tests/Unit/Infrastructure/IntegrationResidueShadowTest.php +++ b/tests/Unit/Infrastructure/IntegrationResidueShadowTest.php @@ -4,7 +4,7 @@ namespace Maatify\PhpPersistence\Tests\Unit\Infrastructure; -use IntegrationResidueShadow; +use Maatify\PhpPersistence\Tooling\IntegrationResidueShadow; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -35,8 +35,14 @@ private static function event(string $state = 'ACTIVE', string $event = '5', str /** @return Binding */ private static function binding(bool $ended): array { - return ['transaction' => '81', 'started' => self::row()['started'], 'thread' => '22', 'event' => '5', - 'endAcknowledged' => $ended, 'independentlyChecked' => $ended]; + return [ + 'transaction' => '81', + 'started' => self::row()['started'], + 'thread' => '22', + 'event' => '5', + 'endAcknowledged' => $ended, + 'independentlyChecked' => $ended, + ]; } public function testMatchingWriterLockAndStableActiveEventProveLive(): void diff --git a/tests/Unit/Ordering/Repository/ScopedOrderingManagerExecutionFailureTest.php b/tests/Unit/Ordering/Repository/ScopedOrderingManagerExecutionFailureTest.php index 1717e43..2463a69 100644 --- a/tests/Unit/Ordering/Repository/ScopedOrderingManagerExecutionFailureTest.php +++ b/tests/Unit/Ordering/Repository/ScopedOrderingManagerExecutionFailureTest.php @@ -110,7 +110,7 @@ public function testMoveRejectsUnrepresentableStoredOrderBeforeMutation(): void $statement->expects(self::once())->method('fetchColumn')->with(1)->willReturn(PHP_INT_MAX . '0'); $statement->expects(self::once())->method('closeCursor')->willReturn(true); $pdo = $this->createMock(PDO::class); - $pdo->method('inTransaction')->willReturn(false, false, true); + $pdo->method('inTransaction')->willReturn(false, true); $pdo->expects(self::once())->method('beginTransaction')->willReturn(true); $pdo->expects(self::once())->method('prepare')->willReturn($statement); $pdo->expects(self::once())->method('rollBack')->willReturn(true); @@ -252,7 +252,7 @@ public function testScopeFetchFailureClosesCursorBeforeRollbackAndPreservesOrigi }); $pdo = $this->createMock(PDO::class); - $pdo->method('inTransaction')->willReturn(false, false, true); + $pdo->method('inTransaction')->willReturn(false, true); $pdo->expects(self::once())->method('beginTransaction')->willReturn(true); $pdo->expects(self::never())->method('commit'); $pdo->expects(self::once())->method('prepare')->willReturn($scopeRead); @@ -305,7 +305,7 @@ public function testFailedWritePreventsCommitAndRollsBack( return 0; }); } else { - $pdo->method('inTransaction')->willReturn(false, false, true); + $pdo->method('inTransaction')->willReturn(false, true); $pdo->expects(self::once())->method('beginTransaction')->willReturn(true); $pdo->expects(self::once())->method('rollBack')->willReturn(true); $pdo->expects(self::never())->method('exec'); diff --git a/tests/Unit/Ordering/Repository/ScopedOrderingManagerSavepointWiringTest.php b/tests/Unit/Ordering/Repository/ScopedOrderingManagerSavepointWiringTest.php index 7970a8a..63d0608 100644 --- a/tests/Unit/Ordering/Repository/ScopedOrderingManagerSavepointWiringTest.php +++ b/tests/Unit/Ordering/Repository/ScopedOrderingManagerSavepointWiringTest.php @@ -8,23 +8,188 @@ use Maatify\PhpPersistence\Ordering\Repository\ScopedOrderingManager; use Maatify\PhpPersistence\Tests\Support\Ordering\OrderingScriptedPdo; use Maatify\PhpPersistence\Tests\Support\Ordering\OrderingScriptedStatement; +use Maatify\PhpPersistence\Transaction\Exception\TransactionExecutionException; +use PDO; +use PDOException; +use PDOStatement; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; /** - * Proves, with a scripted PDO, which {@see \Maatify\PhpPersistence\Transaction\Repository\SavepointScope} - * method moveWithinScope() calls for a given target-write outcome inside a caller-owned (participating) - * transaction: releaseOrUndo() on success, undoOrFail() when the target write reports zero affected rows - * after a real range shift (B-04). The helper's own control-statement failure precedence - * (SAVEPOINT/RELEASE/ROLLBACK TO false-or-throwing) is already characterized in isolation by - * tests/Unit/Transaction/Repository/SavepointScopeTest.php (WU-6, DEC-011 item 2); this test exists only - * because the "false after a real shift" outcome cannot be reproduced on a real connection without a - * database privilege this project's Integration environment does not grant a CREATE TRIGGER (confirmed - * against mysql:8.4.13: error 1419/1458) — see ScopedOrderingManagerLazySavepointTest (Integration) for - * the real-server scenarios (C06, C13, C14, S1-S7, the nested-runner case and a genuine deadlock) that - * remain provable there. + * Exercises raw moveWithinScope() with scripted PDO to verify owned rollback + * and Host savepoint control sequences. Returning false requires confirmed + * settlement. A cleanup failure preserves the original Throwable. + * + * SavepointScopeTest covers the shared savepoint helper in isolation. + * ScopedOrderingManagerSettlementTest exercises the public operation on + * InnoDB. It uses the disposable admin for trigger setup only, then runs the + * real shift and zero-row target UPDATE through the application PDO. It + * verifies affected rows, Host ownership, and pending versus committed data. */ final class ScopedOrderingManagerSavepointWiringTest extends TestCase { + /** @return iterable */ + public static function settlementFailures(): iterable + { + yield 'false' => [false]; + yield 'throws' => [new PDOException('Cleanup failed.')]; + } + + /** @return iterable */ + public static function hostSettlementFailures(): iterable + { + foreach (self::settlementFailures() as $name => [$failure]) { + yield "rollback to $name" => ['ROLLBACK TO SAVEPOINT', $failure]; + yield "release $name" => ['RELEASE SAVEPOINT', $failure]; + } + } + + #[DataProvider('settlementFailures')] + public function testOwnedRejectedMoveExposesRollbackFailure(PDOException|false $failure): void + { + $pdo = new OrderingScriptedPdo($this->moveStatements(new OrderingScriptedStatement()), participating: false, rollbackResult: $failure); + try { + (new ScopedOrderingManager())->moveWithinScope($pdo, new ScopedOrderingConfig(table: 'items'), null, 5, 2); + self::fail('A failed rollback must not return a normal result.'); + } catch (PDOException|TransactionExecutionException $error) { + if ($failure === false) { + self::assertInstanceOf(TransactionExecutionException::class, $error); + } else { + self::assertSame($failure, $error); + } + } + + self::assertSame(1, $pdo->beginCalls); + self::assertSame(0, $pdo->commitCalls); + self::assertSame(1, $pdo->rollbackCalls); + self::assertTrue($pdo->inTransaction()); + } + + public function testOwnedMissingTargetWithoutAnActiveTransactionCannotConfirmRollback(): void + { + $pdo = $this->createMock(PDO::class); + $pdo->method('inTransaction')->willReturn(false); + $pdo->expects(self::once())->method('beginTransaction')->willReturn(true); + $pdo->expects(self::never())->method('commit'); + $pdo->expects(self::never())->method('rollBack'); + $pdo->method('prepare')->willReturnOnConsecutiveCalls( + new OrderingScriptedStatement(fetchColumnQueue: [3, false]), + new OrderingScriptedStatement(fetchColumnQueue: [false]), + ); + + $this->expectException(TransactionExecutionException::class); + + (new ScopedOrderingManager())->moveWithinScope($pdo, new ScopedOrderingConfig(table: 'items'), null, 5, 2); + } + + public function testRollbackAcknowledgementWithAnActiveOwnedConnectionDoesNotReturnFalse(): void + { + $active = false; + $pdo = $this->createMock(PDO::class); + $pdo->method('inTransaction')->willReturnCallback(static function () use (&$active): bool { + return $active; + }); + $pdo->expects(self::once())->method('beginTransaction')->willReturnCallback(static function () use (&$active): bool { + $active = true; + + return true; + }); + $pdo->expects(self::never())->method('commit'); + $pdo->expects(self::once())->method('rollBack')->willReturn(true); + $pdo->method('prepare')->willReturnOnConsecutiveCalls( + new OrderingScriptedStatement(fetchColumnQueue: [3, false]), + new OrderingScriptedStatement(fetchColumnQueue: [false]), + ); + + $this->expectException(TransactionExecutionException::class); + + (new ScopedOrderingManager())->moveWithinScope($pdo, new ScopedOrderingConfig(table: 'items'), null, 5, 2); + } + + #[DataProvider('hostSettlementFailures')] + public function testHostRejectedMoveExposesLocalSettlementFailure(string $control, PDOException|false $failure): void + { + $failsRelease = $control === 'RELEASE SAVEPOINT'; + $results = $failsRelease ? [0, 0, $failure] : [0, $failure]; + $pdo = new OrderingScriptedPdo($this->moveStatements(new OrderingScriptedStatement()), controlResults: $results); + try { + (new ScopedOrderingManager())->moveWithinScope($pdo, new ScopedOrderingConfig(table: 'items'), null, 5, 2); + self::fail('A failed local settlement must not return a normal result.'); + } catch (PDOException|TransactionExecutionException $error) { + if ($failure === false) { + self::assertInstanceOf(TransactionExecutionException::class, $error); + } else { + self::assertSame($failure, $error); + } + } + + self::assertSame(0, $pdo->beginCalls + $pdo->commitCalls + $pdo->rollbackCalls); + self::assertTrue($pdo->inTransaction()); + self::assertCount($failsRelease ? 3 : 2, $pdo->executedControlStatements); + self::assertStringStartsWith('SAVEPOINT ', $pdo->executedControlStatements[0]); + self::assertStringStartsWith('ROLLBACK TO SAVEPOINT ', $pdo->executedControlStatements[1]); + if ($failsRelease) { + self::assertStringStartsWith('RELEASE SAVEPOINT ', $pdo->executedControlStatements[2]); + } + } + + #[DataProvider('settlementFailures')] + public function testOwnedMoveKeepsThePrimaryErrorWhenRollbackFails(PDOException|false $failure): void + { + $primary = new PDOException('Target write failed.'); + $target = $this->createMock(PDOStatement::class); + $target->expects(self::once())->method('execute')->willThrowException($primary); + $target->method('closeCursor')->willReturn(true); + $pdo = new OrderingScriptedPdo($this->moveStatements($target), participating: false, rollbackResult: $failure); + + $this->expectExceptionObject($primary); + try { + (new ScopedOrderingManager())->moveWithinScope($pdo, new ScopedOrderingConfig(table: 'items'), null, 5, 2); + } catch (PDOException $error) { + self::assertSame($primary, $error); + + throw $error; + } finally { + self::assertSame(1, $pdo->rollbackCalls); + self::assertSame(0, $pdo->commitCalls); + } + } + + #[DataProvider('hostSettlementFailures')] + public function testHostMoveKeepsThePrimaryErrorWhenLocalSettlementFails(string $control, PDOException|false $failure): void + { + $primary = new PDOException('Target write failed.'); + $target = $this->createMock(PDOStatement::class); + $target->expects(self::once())->method('execute')->willThrowException($primary); + $target->method('closeCursor')->willReturn(true); + $failsRelease = $control === 'RELEASE SAVEPOINT'; + $pdo = new OrderingScriptedPdo($this->moveStatements($target), controlResults: $failsRelease ? [0, 0, $failure] : [0, $failure]); + + $this->expectExceptionObject($primary); + try { + (new ScopedOrderingManager())->moveWithinScope($pdo, new ScopedOrderingConfig(table: 'items'), null, 5, 2); + } catch (PDOException $error) { + self::assertSame($primary, $error); + + throw $error; + } finally { + self::assertSame(0, $pdo->beginCalls + $pdo->commitCalls + $pdo->rollbackCalls); + self::assertTrue($pdo->inTransaction()); + self::assertCount($failsRelease ? 3 : 2, $pdo->executedControlStatements); + } + } + + /** @return list */ + private function moveStatements(PDOStatement $target): array + { + return [ + new OrderingScriptedStatement(fetchColumnQueue: [3, false]), + new OrderingScriptedStatement(fetchColumnQueue: [5]), + new OrderingScriptedStatement(), + $target, + ]; + } + public function testSuccessfulTargetWriteCallsReleaseOrUndo(): void { $pdo = new OrderingScriptedPdo([ diff --git a/tests/Unit/Ordering/Repository/ScopedOrderingManagerTimestampTest.php b/tests/Unit/Ordering/Repository/ScopedOrderingManagerTimestampTest.php new file mode 100644 index 0000000..f217831 --- /dev/null +++ b/tests/Unit/Ordering/Repository/ScopedOrderingManagerTimestampTest.php @@ -0,0 +1,90 @@ + */ + public static function invalidTimestamps(): iterable + { + yield 'value without a configured column' => [null, '2024-02-29 00:00:00']; + yield 'missing value' => ['updated_at', null]; + yield 'empty value' => ['updated_at', '']; + yield 'zero year' => ['updated_at', '0000-01-01 00:00:00']; + yield 'invalid calendar day' => ['updated_at', '2025-02-29 00:00:00']; + yield 'invalid calendar month' => ['updated_at', '2026-13-01 00:00:00']; + yield 'invalid clock hour' => ['updated_at', '2026-01-01 24:00:00']; + yield 'invalid clock minute' => ['updated_at', '2026-01-01 23:60:00']; + yield 'invalid clock second' => ['updated_at', '2026-01-01 23:59:60']; + yield 'empty fraction' => ['updated_at', '2026-01-01 00:00:00.']; + yield 'more than six fractional digits' => ['updated_at', '2026-01-01 00:00:00.1234567']; + yield 'date only' => ['updated_at', '2026-01-01']; + yield 'relative expression' => ['updated_at', 'tomorrow']; + yield 'ISO separator' => ['updated_at', '2026-01-01T00:00:00']; + yield 'zone offset' => ['updated_at', '2026-01-01 00:00:00+00:00']; + yield 'exponent' => ['updated_at', '2026-01-01 00:00:00.1e2']; + yield 'trailing newline' => ['updated_at', "2026-01-01 00:00:00\n"]; + } + + /** @param non-empty-string|null $column */ + #[DataProvider('invalidTimestamps')] + public function testInvalidTimestampIsRejectedBeforeUsingPdo(?string $column, ?string $value): void + { + $pdo = $this->createMock(PDO::class); + $pdo->expects(self::never())->method('inTransaction'); + $pdo->expects(self::never())->method('beginTransaction'); + $pdo->expects(self::never())->method('prepare'); + $pdo->expects(self::never())->method('exec'); + + $this->expectException(InvalidOrderingOperationException::class); + (new ScopedOrderingManager())->moveWithinScope( + $pdo, + new ScopedOrderingConfig(table: 'items', updatedAtColumn: $column), + null, + 5, + 2, + $value, + ); + } + + /** @return iterable */ + public static function validTimestamps(): iterable + { + yield 'midnight on a leap day' => ['2024-02-29 00:00:00']; + yield 'one fractional digit' => ['2026-01-01 00:00:00.1']; + yield 'six fractional digits and upper clock boundary' => ['2026-12-31 23:59:59.012300']; + } + + #[DataProvider('validTimestamps')] + public function testValidTimestampReachesTargetUpdateWithoutNormalization(string $value): void + { + $target = new OrderingScriptedStatement(rowCount: 1); + $pdo = new OrderingScriptedPdo([ + new OrderingScriptedStatement(fetchColumnQueue: [3, false]), + new OrderingScriptedStatement(fetchColumnQueue: [3]), + new OrderingScriptedStatement(), + $target, + ]); + + self::assertTrue((new ScopedOrderingManager())->moveWithinScope( + $pdo, + new ScopedOrderingConfig(table: 'items', updatedAtColumn: 'updated_at'), + null, + 5, + 2, + $value, + )); + self::assertSame($value, $target->executedWith[0]['updated_at_value']); + } +} diff --git a/tests/Unit/Ordering/UniqueOrderingConfigTest.php b/tests/Unit/Ordering/UniqueOrderingConfigTest.php index 6644fa1..0e4241e 100644 --- a/tests/Unit/Ordering/UniqueOrderingConfigTest.php +++ b/tests/Unit/Ordering/UniqueOrderingConfigTest.php @@ -33,14 +33,28 @@ public static function ineligibleProfiles(): iterable yield 'row bound exceeds position limit' => [$global, 'app.anchor', 'id', 1, 20, 21]; yield 'soft delete' => [new ScopedOrderingConfig('app.items'), 'app.anchor', 'id', 1, 20, 10]; yield 'updated timestamp' => [ - new ScopedOrderingConfig('app.items', deletedAtColumn: null, updatedAtColumn: 'updated_at'), 'app.anchor', 'id', 1, 20, 10, + new ScopedOrderingConfig('app.items', deletedAtColumn: null, updatedAtColumn: 'updated_at'), + 'app.anchor', + 'id', + 1, + 20, + 10, ]; yield 'nullable scope' => [ new ScopedOrderingConfig('app.items', scopeColumn: 'scope_id', deletedAtColumn: null, nullableScope: true), - 'app.anchor', 'id', null, 20, 10, + 'app.anchor', + 'id', + null, + 20, + 10, ]; yield 'column roles overlap' => [ - new ScopedOrderingConfig('app.items', scopeColumn: 'ID', deletedAtColumn: null), 'app.anchor', 'id', null, 20, 10, + new ScopedOrderingConfig('app.items', scopeColumn: 'ID', deletedAtColumn: null), + 'app.anchor', + 'id', + null, + 20, + 10, ]; } diff --git a/tests/Unit/Pagination/DynamicSortPaginationTest.php b/tests/Unit/Pagination/DynamicSortPaginationTest.php index e78b971..4922383 100644 --- a/tests/Unit/Pagination/DynamicSortPaginationTest.php +++ b/tests/Unit/Pagination/DynamicSortPaginationTest.php @@ -59,28 +59,41 @@ public static function successfulOrders(): iterable { yield 'empty request' => [[], false, '`o`.`status` DESC, `o`.`id` ASC', [self::sort('status', 'DESC'), self::sort(null, 'ASC')]]; yield 'one term, hidden appended tie even when selection enabled' => [ - [self::sort('score', 'aSc')], true, '`o`.`score` ASC, `o`.`id` ASC', [self::sort('score', 'ASC'), self::sort(null, 'ASC')], + [self::sort('score', 'aSc')], + true, + '`o`.`score` ASC, `o`.`id` ASC', + [self::sort('score', 'ASC'), self::sort(null, 'ASC')], ]; yield 'two mixed terms' => [ - [self::sort('score', 'desc'), self::sort('status', 'ASC')], false, '`o`.`score` DESC, `o`.`status` ASC, `o`.`id` ASC', + [self::sort('score', 'desc'), self::sort('status', 'ASC')], + false, + '`o`.`score` DESC, `o`.`status` ASC, `o`.`id` ASC', [self::sort('score', 'DESC'), self::sort('status', 'ASC'), self::sort(null, 'ASC')], ]; yield 'three reversed priority and mixed terms' => [ - [self::sort('name', 'desc'), self::sort('status', 'asc'), self::sort('score', 'desc')], false, + [self::sort('name', 'desc'), self::sort('status', 'asc'), self::sort('score', 'desc')], + false, '`o`.`name` DESC, `o`.`status` ASC, `o`.`score` DESC, `o`.`id` ASC', [self::sort('name', 'DESC'), self::sort('status', 'ASC'), self::sort('score', 'DESC'), self::sort(null, 'ASC')], ]; yield 'canonical tie selected alone' => [[self::sort('internal_id', 'dEsC')], true, '`o`.`id` DESC', [self::sort('internal_id', 'DESC')]]; yield 'canonical tie selected last' => [ - [self::sort('score', 'desc'), self::sort('internal_id', 'ASC')], true, '`o`.`score` DESC, `o`.`id` ASC', + [self::sort('score', 'desc'), self::sort('internal_id', 'ASC')], + true, + '`o`.`score` DESC, `o`.`id` ASC', [self::sort('score', 'DESC'), self::sort('internal_id', 'ASC')], ]; yield 'case-folded column alias to tie allowed last under default policy' => [ - [self::sort('status', 'asc'), self::sort('alternate_id', 'desc')], false, '`o`.`status` ASC, `o`.`ID` DESC', + [self::sort('status', 'asc'), self::sort('alternate_id', 'desc')], + false, + '`o`.`status` ASC, `o`.`ID` DESC', [self::sort('status', 'ASC'), self::sort('alternate_id', 'DESC')], ]; yield 'case-folded column alias to tie selected alone with policy enabled' => [ - [self::sort('alternate_id', 'desc')], true, '`o`.`ID` DESC', [self::sort('alternate_id', 'DESC')], + [self::sort('alternate_id', 'desc')], + true, + '`o`.`ID` DESC', + [self::sort('alternate_id', 'DESC')], ]; } @@ -137,7 +150,7 @@ public function testLegacyGoldenAliasWorksInDefaultAndExplicitDynamicSort(): voi [new SortWhitelist(['id' => 'id']), 'id', []], [new SortWhitelist(['recent' => 'o.ID', 'id' => 'o.id']), 'recent', []], ] as [$whitelist, $key, $terms]) { - $config = new PaginationConfig($whitelist, $key, Direction::DESC, 'id', Direction::ASC); + $config = new PaginationConfig($whitelist, $key, Direction::Desc, 'id', Direction::Asc); $pdo = new ScriptedPdo([ScriptedPdoStatement::count(1), ScriptedPdoStatement::count(1), ScriptedPdoStatement::data([['id' => 7]])]); $result = (new PdoPaginator())->paginateWithDynamicSort($pdo, self::query(), new PageRequest(), $config, $terms, self::row(...)); $identifier = $key === 'recent' ? '`o`.`ID`' : '`id`'; @@ -150,7 +163,7 @@ public function testLegacyGoldenAliasWorksInDefaultAndExplicitDynamicSort(): voi public function testLexicallyDifferentQualifierPathsStayDistinct(): void { - $config = new PaginationConfig(new SortWhitelist(['plain' => 'id', 'tie' => 'a.id', 'joined' => 'b.id']), 'plain', Direction::DESC, 'tie', Direction::ASC); + $config = new PaginationConfig(new SortWhitelist(['plain' => 'id', 'tie' => 'a.id', 'joined' => 'b.id']), 'plain', Direction::Desc, 'tie', Direction::Asc); $pdo = new ScriptedPdo([ScriptedPdoStatement::count(1), ScriptedPdoStatement::count(1), ScriptedPdoStatement::data([['id' => 7]])]); (new PdoPaginator())->paginateWithDynamicSort($pdo, self::query(), new PageRequest(), $config, [self::sort('plain', 'DESC'), self::sort('joined', 'ASC')], self::row(...)); self::assertSame(self::dataSql('`id` DESC, `b`.`id` ASC, `a`.`id` ASC'), $pdo->preparedSql[2]); @@ -166,9 +179,17 @@ public function testEmptyAndOvershootRetainResolvedSortAndHideTheTie(): void self::assertSame(['TOTAL :total_tenant', 'FILTERED :filtered_tenant'], $pdo->preparedSql); self::assertSame([ - 'data' => [], 'pagination' => [ - 'page' => 1, 'per_page' => 200, 'total' => 5, 'filtered' => 0, 'total_pages' => 0, - 'has_next' => false, 'has_previous' => false, 'sort_by' => 'score', 'sort_direction' => 'DESC', + 'data' => [], + 'pagination' => [ + 'page' => 1, + 'per_page' => 200, + 'total' => 5, + 'filtered' => 0, + 'total_pages' => 0, + 'has_next' => false, + 'has_previous' => false, + 'sort_by' => 'score', + 'sort_direction' => 'DESC', 'selected_sorts' => [self::sort('score', 'DESC'), self::sort('status', 'ASC')], 'effective_sorts' => [self::sort('score', 'DESC'), self::sort('status', 'ASC'), self::sort(null, 'ASC')], ], @@ -198,7 +219,7 @@ public static function rejectedRequests(): iterable yield 'missing key' => [[['direction' => 'ASC']], $request, false]; yield 'extra field' => [[$valid + ['extra' => 'drop']], $request, false]; yield 'numeric key' => [[['key' => 3, 'direction' => 'ASC']], $request, false]; - yield 'enum direction' => [[['key' => 'status', 'direction' => Direction::ASC]], $request, false]; + yield 'enum direction' => [[['key' => 'status', 'direction' => Direction::Asc]], $request, false]; yield 'invalid direction' => [[self::sort('status', 'ascending')], $request, false]; yield 'leading direction whitespace' => [[self::sort('status', ' ASC')], $request, false]; yield 'direction trailing LF' => [[self::sort('status', "DESC\n")], $request, false]; @@ -234,7 +255,7 @@ public function testRejectsInvalidRequestBeforePreparingAnything(array $sorts, P public function testQualifierCaseConflictAndConfigurationPrecedenceBeforeSql(): void { $pdo = new ScriptedPdo([]); - $config = new PaginationConfig(new SortWhitelist(['first' => 'O.iD', 'tie' => 'o.id']), 'first', Direction::DESC, 'tie', Direction::ASC); + $config = new PaginationConfig(new SortWhitelist(['first' => 'O.iD', 'tie' => 'o.id']), 'first', Direction::Desc, 'tie', Direction::Asc); $this->expectException(InvalidPaginationConfigurationException::class); try { (new PdoPaginator())->paginateWithDynamicSort($pdo, self::query(), new PageRequest(sortBy: 'conflict'), $config, [null], self::row(...)); @@ -247,7 +268,7 @@ public function testQualifierCaseConflictAndConfigurationPrecedenceBeforeSql(): public function testRequestedQualifierConflictFailsBeforeSql(bool $tieConflict): void { $pdo = new ScriptedPdo([]); - $config = new PaginationConfig(new SortWhitelist(['a' => 'db.O.Score', 'b' => 'db.o.score', 't' => $tieConflict ? 'db.o.score' : 'db.o.id', 'default' => 'db.o.date']), 'default', Direction::DESC, 't', Direction::ASC); + $config = new PaginationConfig(new SortWhitelist(['a' => 'db.O.Score', 'b' => 'db.o.score', 't' => $tieConflict ? 'db.o.score' : 'db.o.id', 'default' => 'db.o.date']), 'default', Direction::Desc, 't', Direction::Asc); $sorts = [self::sort('a', 'ASC')]; if (! $tieConflict) { $sorts[] = self::sort('b', 'ASC'); @@ -275,9 +296,9 @@ public function testQualifierConflictTakesPrecedenceOverTiePosition(array $keys) $config = new PaginationConfig( new SortWhitelist(['name' => 'o.name', 'tie' => 'o.id', 'alias' => 'O.id']), 'name', - Direction::ASC, + Direction::Asc, 'tie', - Direction::ASC, + Direction::Asc, ); $sorts = array_map(static fn(string $key): array => self::sort($key, 'ASC'), $keys); @@ -299,7 +320,7 @@ public static function qualifierConflictOrders(): iterable public function testDtoFactoryRejectsUnrelatedPageBeforePublishingMetadata(): void { $sort = ResolvedDynamicSort::resolve(self::config(), new PageRequest(), [self::sort('score', 'ASC')], false); - foreach ([['status', Direction::ASC], ['score', Direction::DESC]] as [$key, $direction]) { + foreach ([['status', Direction::Asc], ['score', Direction::Desc]] as [$key, $direction]) { try { MultiSortPageResultDTO::fromResolved(new PageResultDTO([], 1, 2, 0, 0, 0, false, false, $key, $direction), $sort); self::fail('Expected an inconsistent result to be rejected.'); @@ -398,9 +419,13 @@ public static function throwableSources(): iterable private static function config(): PaginationConfig { return new PaginationConfig(new SortWhitelist([ - 'status' => 'o.status', 'state_alias' => 'o.STATUS', 'score' => 'o.score', 'name' => 'o.name', - 'internal_id' => 'o.id', 'alternate_id' => 'o.ID', - ]), 'status', Direction::DESC, 'internal_id', Direction::ASC, 2); + 'status' => 'o.status', + 'state_alias' => 'o.STATUS', + 'score' => 'o.score', + 'name' => 'o.name', + 'internal_id' => 'o.id', + 'alternate_id' => 'o.ID', + ]), 'status', Direction::Desc, 'internal_id', Direction::Asc, 2); } private static function query(): PdoPaginationQueryDescriptor diff --git a/tests/Unit/Pagination/PageResultDTOTest.php b/tests/Unit/Pagination/PageResultDTOTest.php index c9dfd3c..9ed6599 100644 --- a/tests/Unit/Pagination/PageResultDTOTest.php +++ b/tests/Unit/Pagination/PageResultDTOTest.php @@ -36,7 +36,7 @@ public function jsonSerialize(): array } }; - $result = new PageResultDTO([['id' => 1], $object], 1, 20, 30, 22, 2, true, false, 'created_at', SortDirectionEnum::DESC); + $result = new PageResultDTO([['id' => 1], $object], 1, 20, 30, 22, 2, true, false, 'created_at', SortDirectionEnum::Desc); $array = $result->toArray(); self::assertSame($array, $result->jsonSerialize()); @@ -52,13 +52,13 @@ public function testRejectsTerminalLineFeedInDirectSortKey(): void $this->expectException(PaginationExecutionException::class); $this->expectExceptionMessage('Invalid pagination result state.'); - new PageResultDTO([], 1, 20, 0, 0, 0, false, false, "id\n", SortDirectionEnum::ASC); + new PageResultDTO([], 1, 20, 0, 0, 0, false, false, "id\n", SortDirectionEnum::Asc); } public function testPreservesValidDirectSortKeysInSerialization(): void { foreach (['id', '_id2'] as $key) { - $result = new PageResultDTO([], 1, 20, 0, 0, 0, false, false, $key, SortDirectionEnum::ASC); + $result = new PageResultDTO([], 1, 20, 0, 0, 0, false, false, $key, SortDirectionEnum::Asc); $array = $result->toArray(); self::assertSame($key, $array['pagination']['sort_by']); @@ -70,7 +70,7 @@ public function testPreservesValidDirectSortKeysInSerialization(): void #[DataProvider('validResults')] public function testValidResultMatrix(array $data, int $page, int $perPage, int $total, int $filtered, int $totalPages, bool $hasNext, bool $hasPrevious): void { - $result = new PageResultDTO($data, $page, $perPage, $total, $filtered, $totalPages, $hasNext, $hasPrevious, 'id', SortDirectionEnum::ASC); + $result = new PageResultDTO($data, $page, $perPage, $total, $filtered, $totalPages, $hasNext, $hasPrevious, 'id', SortDirectionEnum::Asc); self::assertSame($page, $result->page); self::assertSame($data, $result->data); @@ -97,21 +97,21 @@ public function testInvariantRejection(array $arguments): void /** @return iterable}> */ public static function invalidResults(): iterable { - yield 'associative outer data' => [[['x' => []], 1, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'scalar item' => [[[1], 1, 20, 1, 1, 1, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'page below one' => [[[], 0, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'per page below one' => [[[], 1, 0, 0, 0, 0, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'negative total' => [[[], 1, 20, -1, 0, 0, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'negative filtered' => [[[], 1, 20, 0, -1, 0, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'negative pages' => [[[], 1, 20, 0, 0, -1, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'data exceeds per page' => [[[[], []], 1, 1, 2, 2, 2, true, false, 'id', SortDirectionEnum::ASC]]; - yield 'bad sort key' => [[[], 1, 20, 0, 0, 0, false, false, 'bad-key', SortDirectionEnum::ASC]]; - yield 'bad total pages' => [[[], 1, 20, 20, 20, 2, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'zero filtered non-empty data' => [[[['id' => 1]], 1, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'zero filtered page not one' => [[[], 2, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'zero filtered has next' => [[[], 1, 20, 0, 0, 0, true, false, 'id', SortDirectionEnum::ASC]]; - yield 'bad has next' => [[[], 1, 20, 50, 50, 3, false, false, 'id', SortDirectionEnum::ASC]]; - yield 'bad has previous' => [[[], 1, 20, 50, 50, 3, true, true, 'id', SortDirectionEnum::ASC]]; + yield 'associative outer data' => [[['x' => []], 1, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'scalar item' => [[[1], 1, 20, 1, 1, 1, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'page below one' => [[[], 0, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'per page below one' => [[[], 1, 0, 0, 0, 0, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'negative total' => [[[], 1, 20, -1, 0, 0, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'negative filtered' => [[[], 1, 20, 0, -1, 0, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'negative pages' => [[[], 1, 20, 0, 0, -1, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'data exceeds per page' => [[[[], []], 1, 1, 2, 2, 2, true, false, 'id', SortDirectionEnum::Asc]]; + yield 'bad sort key' => [[[], 1, 20, 0, 0, 0, false, false, 'bad-key', SortDirectionEnum::Asc]]; + yield 'bad total pages' => [[[], 1, 20, 20, 20, 2, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'zero filtered non-empty data' => [[[['id' => 1]], 1, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'zero filtered page not one' => [[[], 2, 20, 0, 0, 0, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'zero filtered has next' => [[[], 1, 20, 0, 0, 0, true, false, 'id', SortDirectionEnum::Asc]]; + yield 'bad has next' => [[[], 1, 20, 50, 50, 3, false, false, 'id', SortDirectionEnum::Asc]]; + yield 'bad has previous' => [[[], 1, 20, 50, 50, 3, true, true, 'id', SortDirectionEnum::Asc]]; } /** diff --git a/tests/Unit/Pagination/PaginationConfigTest.php b/tests/Unit/Pagination/PaginationConfigTest.php index 562d918..dfb5629 100644 --- a/tests/Unit/Pagination/PaginationConfigTest.php +++ b/tests/Unit/Pagination/PaginationConfigTest.php @@ -21,13 +21,13 @@ public function testValidConfigDefaultsAndCustom(): void 'alias' => 'id', ]); - $default = new PaginationConfig($whitelist, 'created_at', SortDirectionEnum::DESC, 'id', SortDirectionEnum::ASC); + $default = new PaginationConfig($whitelist, 'created_at', SortDirectionEnum::Desc, 'id', SortDirectionEnum::Asc); self::assertSame(20, $default->defaultPerPage); self::assertSame(1, $default->minPerPage); self::assertSame(200, $default->maxPerPage); - $custom = new PaginationConfig($whitelist, 'alias', SortDirectionEnum::ASC, 'id', SortDirectionEnum::DESC, 10, 2, 50); + $custom = new PaginationConfig($whitelist, 'alias', SortDirectionEnum::Asc, 'id', SortDirectionEnum::Desc, 10, 2, 50); self::assertSame(10, $custom->defaultPerPage); self::assertSame(2, $custom->minPerPage); @@ -42,9 +42,9 @@ public function testInvalidConfig(string $default, string $tie, int $defaultPerP new PaginationConfig( new SortWhitelist(['id' => 'id', 'created_at' => 'created_at']), $default, - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, $tie, - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, $defaultPerPage, $minPerPage, $maxPerPage, diff --git a/tests/Unit/Pagination/PdoPaginatorExecutionTest.php b/tests/Unit/Pagination/PdoPaginatorExecutionTest.php index 939ec5a..9fdf476 100644 --- a/tests/Unit/Pagination/PdoPaginatorExecutionTest.php +++ b/tests/Unit/Pagination/PdoPaginatorExecutionTest.php @@ -19,7 +19,7 @@ final class PdoPaginatorExecutionTest extends TestCase { private function config(bool $dup = false): PaginationConfig { - return new PaginationConfig(new SortWhitelist(['id' => 'id', 'created_at' => $dup ? 'id' : 'created_at']), 'created_at', SortDirectionEnum::DESC, 'id', SortDirectionEnum::ASC); + return new PaginationConfig(new SortWhitelist(['id' => 'id', 'created_at' => $dup ? 'id' : 'created_at']), 'created_at', SortDirectionEnum::Desc, 'id', SortDirectionEnum::Asc); } public function testOrderSeparateMapsTypedBindingsAndFinalSql(): void @@ -30,10 +30,14 @@ public function testOrderSeparateMapsTypedBindingsAndFinalSql(): void $pdo = new ScriptedPdo([$total, $filtered, $data]); $q = new PdoPaginationQueryDescriptor('TOTAL', ['total_tenant' => 1], 'FILTERED', ['filtered_category' => 'books'], 'DATA', ['data_active' => true, 'none' => null]); $r = (new PdoPaginator())->paginate($pdo, $q, new PageRequest(2, 2, 'created_at', 'desc'), $this->config(), fn(array $row): array => $row); - self::assertSame(['TOTAL', 'FILTERED', 'DATA + self::assertSame([ + 'TOTAL', + 'FILTERED', + 'DATA ORDER BY `created_at` DESC, `id` ASC LIMIT :__pagination_limit -OFFSET :__pagination_offset'], $pdo->preparedSql); +OFFSET :__pagination_offset', + ], $pdo->preparedSql); self::assertSame(':total_tenant', $total->bindCalls[0]['parameter']); self::assertSame(PDO::PARAM_INT, $total->bindCalls[0]['type']); self::assertSame(':filtered_category', $filtered->bindCalls[0]['parameter']); diff --git a/tests/Unit/Pagination/PdoPaginatorFailureTest.php b/tests/Unit/Pagination/PdoPaginatorFailureTest.php index 4a51797..18d1ee5 100644 --- a/tests/Unit/Pagination/PdoPaginatorFailureTest.php +++ b/tests/Unit/Pagination/PdoPaginatorFailureTest.php @@ -313,7 +313,7 @@ private function queryWithoutParams(): PdoPaginationQueryDescriptor private function config(): PaginationConfig { - return new PaginationConfig(new SortWhitelist(['id' => 'id']), 'id', SortDirectionEnum::ASC, 'id', SortDirectionEnum::ASC); + return new PaginationConfig(new SortWhitelist(['id' => 'id']), 'id', SortDirectionEnum::Asc, 'id', SortDirectionEnum::Asc); } private function successfulPdo(): ScriptedPdo diff --git a/tests/Unit/Pagination/PdoPaginatorNormalizationTest.php b/tests/Unit/Pagination/PdoPaginatorNormalizationTest.php index 1ea1b4d..a63e874 100644 --- a/tests/Unit/Pagination/PdoPaginatorNormalizationTest.php +++ b/tests/Unit/Pagination/PdoPaginatorNormalizationTest.php @@ -152,9 +152,9 @@ private function config(int $defaultPerPage, int $minPerPage, int $maxPerPage): return new PaginationConfig( new SortWhitelist(['id' => 'id', 'created_at' => 'created_at']), 'created_at', - SortDirectionEnum::DESC, + SortDirectionEnum::Desc, 'id', - SortDirectionEnum::ASC, + SortDirectionEnum::Asc, $defaultPerPage, $minPerPage, $maxPerPage, diff --git a/tests/Unit/Pagination/StaticSortPaginationTest.php b/tests/Unit/Pagination/StaticSortPaginationTest.php index 5f45154..4654092 100644 --- a/tests/Unit/Pagination/StaticSortPaginationTest.php +++ b/tests/Unit/Pagination/StaticSortPaginationTest.php @@ -50,7 +50,7 @@ public function testReusablePlanProducesBoundSqlAndExistingResultEnvelope(): voi { $plan = self::plan(); $paginator = new PdoPaginator(); - foreach ([Direction::ASC, Direction::DESC] as $direction) { + foreach ([Direction::Asc, Direction::Desc] as $direction) { $total = ScriptedPdoStatement::count(10); $filtered = ScriptedPdoStatement::count(3); $data = ScriptedPdoStatement::data([['id' => 7]]); @@ -78,8 +78,15 @@ public function testReusablePlanProducesBoundSqlAndExistingResultEnvelope(): voi self::assertSame([ 'data' => [['id' => 7]], 'pagination' => [ - 'page' => 2, 'per_page' => 2, 'total' => 10, 'filtered' => 3, 'total_pages' => 2, - 'has_next' => false, 'has_previous' => true, 'sort_by' => 'business_order', 'sort_direction' => $direction->value, + 'page' => 2, + 'per_page' => 2, + 'total' => 10, + 'filtered' => 3, + 'total_pages' => 2, + 'has_next' => false, + 'has_previous' => true, + 'sort_by' => 'business_order', + 'sort_direction' => $direction->value, ], ], $page->toArray()); self::assertSame(json_encode($page->toArray(), JSON_THROW_ON_ERROR), json_encode($page, JSON_THROW_ON_ERROR)); @@ -91,9 +98,9 @@ public function testThreeTrailingTermsUseTrustedIdentifiersAndKeepPrimaryDirecti { $plan = new StaticSortPlan(self::config(), [ 'business_order' => [ - ['identifier' => 'catalog.positions.rank', 'direction' => Direction::ASC], + ['identifier' => 'catalog.positions.rank', 'direction' => Direction::Asc], ['identifier' => 'projected_rank'], - ['identifier' => 'p.id', 'direction' => Direction::DESC], + ['identifier' => 'p.id', 'direction' => Direction::Desc], ], ]); $pdo = new ScriptedPdo([ScriptedPdoStatement::count(1), ScriptedPdoStatement::count(1), ScriptedPdoStatement::data([['id' => 1]])]); @@ -102,17 +109,17 @@ public function testThreeTrailingTermsUseTrustedIdentifiersAndKeepPrimaryDirecti self::assertSame(self::dataSql('ORDER BY `p`.`scope_key` DESC, `catalog`.`positions`.`rank` ASC, `projected_rank` DESC, `p`.`id` DESC'), $pdo->preparedSql[2]); self::assertSame('business_order', $page->sortBy); - self::assertSame(Direction::DESC, $page->sortDirection); + self::assertSame(Direction::Desc, $page->sortDirection); } /** @return array */ public static function requestOrders(): array { return [ - 'unknown key retains valid direction' => ['missing', ' desc ', 'business_order', Direction::DESC, 'ORDER BY `p`.`scope_key` DESC, `p`.`position` DESC, `p`.`id` ASC'], - 'known key retains independent direction fallback' => [' id ', 'unsupported', 'id', Direction::ASC, 'ORDER BY `p`.`id` ASC'], - 'null profile de-duplicates the legacy tie' => ['id', 'DESC', 'id', Direction::DESC, 'ORDER BY `p`.`id` DESC'], - 'null profile works as the configured default' => [null, 'DESC', 'business_order', Direction::DESC, 'ORDER BY `p`.`scope_key` DESC, `p`.`id` ASC'], + 'unknown key retains valid direction' => ['missing', ' desc ', 'business_order', Direction::Desc, 'ORDER BY `p`.`scope_key` DESC, `p`.`position` DESC, `p`.`id` ASC'], + 'known key retains independent direction fallback' => [' id ', 'unsupported', 'id', Direction::Asc, 'ORDER BY `p`.`id` ASC'], + 'null profile de-duplicates the legacy tie' => ['id', 'DESC', 'id', Direction::Desc, 'ORDER BY `p`.`id` DESC'], + 'null profile works as the configured default' => [null, 'DESC', 'business_order', Direction::Desc, 'ORDER BY `p`.`scope_key` DESC, `p`.`id` ASC'], ]; } @@ -153,9 +160,16 @@ public function testEmptyPageRetainsResolvedSortWithoutDataSql(): void $page = (new PdoPaginator())->paginateWithStaticSort($pdo, self::query(), new PageRequest(99, 2, 'missing', 'DESC'), self::plan(), static fn(array $row): array => $row); self::assertSame(['TOTAL :total_tenant', 'FILTERED :filtered_tenant'], $pdo->preparedSql); - self::assertSame([[], 1, 5, 0, 0, false, false, 'business_order', Direction::DESC], [ - $page->data, $page->page, $page->total, $page->filtered, $page->totalPages, - $page->hasNext, $page->hasPrevious, $page->sortBy, $page->sortDirection, + self::assertSame([[], 1, 5, 0, 0, false, false, 'business_order', Direction::Desc], [ + $page->data, + $page->page, + $page->total, + $page->filtered, + $page->totalPages, + $page->hasNext, + $page->hasPrevious, + $page->sortBy, + $page->sortDirection, ]); } @@ -205,7 +219,7 @@ public static function invalidProfiles(): iterable yield 'not a string' => [$valid + ['other' => [['identifier' => 1]]]]; yield 'four trailing terms' => [['business_order' => [['identifier' => 'a'], ['identifier' => 'b'], ['identifier' => 'c'], ['identifier' => 'd']]]]; yield 'same path as primary with different casing' => [['business_order' => [['identifier' => 'P.SCOPE_KEY']]]]; - yield 'same path in two trailing terms' => [['business_order' => [['identifier' => 'p.position'], ['identifier' => 'p.POSITION', 'direction' => Direction::DESC]]]]; + yield 'same path in two trailing terms' => [['business_order' => [['identifier' => 'p.position'], ['identifier' => 'p.POSITION', 'direction' => Direction::Desc]]]]; foreach (['', 'p.', 'p.a.b.c', 'p.position DESC', 'p.`position`', "p.position\n"] as $identifier) { yield 'invalid identifier ' . json_encode($identifier) => [$valid + ['other' => [['identifier' => $identifier]]]]; } @@ -222,14 +236,14 @@ public function testConstructionRejectsInvalidProfiles(array $profiles): void private static function plan(): StaticSortPlan { return new StaticSortPlan(self::config(), [ - 'business_order' => [['identifier' => 'p.position'], ['identifier' => 'p.id', 'direction' => Direction::ASC]], + 'business_order' => [['identifier' => 'p.position'], ['identifier' => 'p.id', 'direction' => Direction::Asc]], 'id' => null, ]); } private static function config(): PaginationConfig { - return new PaginationConfig(new SortWhitelist(['business_order' => 'p.scope_key', 'id' => 'p.id', 'other' => 'p.other']), 'business_order', Direction::ASC, 'id', Direction::ASC, 2); + return new PaginationConfig(new SortWhitelist(['business_order' => 'p.scope_key', 'id' => 'p.id', 'other' => 'p.other']), 'business_order', Direction::Asc, 'id', Direction::Asc, 2); } private static function query(): PdoPaginationQueryDescriptor diff --git a/tests/Unit/Transaction/Repository/PdoTransactionRunnerTest.php b/tests/Unit/Transaction/Repository/PdoTransactionRunnerTest.php index b50375e..2716f31 100644 --- a/tests/Unit/Transaction/Repository/PdoTransactionRunnerTest.php +++ b/tests/Unit/Transaction/Repository/PdoTransactionRunnerTest.php @@ -8,6 +8,7 @@ use Maatify\PhpPersistence\Tests\Support\Transaction\PdoErrors; use Maatify\PhpPersistence\Tests\Support\Transaction\RetryTransactionPdo; use Maatify\PhpPersistence\Transaction\Exception\InvalidTransactionConfigurationException; +use Maatify\PhpPersistence\Transaction\Repository\PdoSavepointTransactionRunner; use Maatify\PhpPersistence\Transaction\Repository\PdoTransactionRunner; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; @@ -91,6 +92,28 @@ static function () use (&$calls): array { self::assertFalse($pdo->inTransaction()); } + /** @return iterable */ + public static function booleanCallbackResults(): iterable + { + yield 'false' => [false]; + yield 'true' => [true]; + } + + #[DataProvider('booleanCallbackResults')] + public function testBothPublicRunnersCommitOwnedWorkAndPreserveBooleanResults(bool $result): void + { + foreach ([PdoTransactionRunner::class, PdoSavepointTransactionRunner::class] as $runnerClass) { + $pdo = new RetryTransactionPdo(); + $runner = new $runnerClass($pdo); + + self::assertSame($result, $runner->run(static fn(): bool => $result)); + self::assertSame(1, $pdo->beginTransactionCalls); + self::assertSame(1, $pdo->commitCalls); + self::assertSame(0, $pdo->rollBackCalls); + self::assertFalse($pdo->inTransaction()); + } + } + #[DataProvider('configuredRetries')] public function testOwnedNonDeadlockFailureRollsBackOnceAndRethrowsExactThrowable(int $retries): void { diff --git a/tests/Unit/Transaction/Repository/SavepointScopeTest.php b/tests/Unit/Transaction/Repository/SavepointScopeTest.php index 92d6364..d2ff26d 100644 --- a/tests/Unit/Transaction/Repository/SavepointScopeTest.php +++ b/tests/Unit/Transaction/Repository/SavepointScopeTest.php @@ -162,13 +162,17 @@ public function testUndoOrFailPropagatesAThrowingRollbackTo(): void self::assertSame($failure, $this->catchThrowable(static fn() => $scope->undoOrFail())); } - public function testUndoOrFailIgnoresAFailingReleaseAfterASuccessfulRollbackTo(): void + public function testUndoOrFailPropagatesAFalseRawReleaseAfterASuccessfulRollbackTo(): void { $pdo = new SavepointTransactionPdo(transactionActive: true, execResults: [0, 0, false]); - SavepointScope::begin($pdo)->undoOrFail(); - - self::assertCount(3, $pdo->executedStatements); + $this->expectException(TransactionExecutionException::class); + try { + SavepointScope::begin($pdo)->undoOrFail(); + } finally { + self::assertSame(['SAVEPOINT SP', 'ROLLBACK TO SAVEPOINT SP', 'RELEASE SAVEPOINT SP'], $this->normalize($pdo->executedStatements)); + self::assertTrue($pdo->inTransaction()); + } } public function testBeginFailsBeforeAnyMutationWhenTheDriverReportsNoActiveTransaction(): void diff --git a/tests/evidence/CI_WORKFLOW_CONFORMANCE.md b/tests/evidence/CI_WORKFLOW_CONFORMANCE.md new file mode 100644 index 0000000..d06f584 --- /dev/null +++ b/tests/evidence/CI_WORKFLOW_CONFORMANCE.md @@ -0,0 +1,88 @@ +# CI workflow conformance evidence + +This review maps the published workflow, its local entry points and the actual +GitHub execution to the pinned CI Workflow Standard. It gives reviewers the +inputs needed to independently verify the gate, archive identities and findings. + +- Reviewed implementation: [`cf07db569a43b6afe19d93b25694bb3a5487b183`](https://github.com/Maatify-ltd/php-persistence/commit/cf07db569a43b6afe19d93b25694bb3a5487b183) + on [#108](https://github.com/Maatify-ltd/php-persistence/pull/108). +- Pinned standard: [CI Workflow 7.0.0](../../docs/php-engineering-standards/standards/packages/CI_WORKFLOW_STANDARD.md) + from `c1dbb2da062a35c45638abf2bcb2ae210140eb5d`. +- [Roadmap and release gates](https://github.com/Maatify-ltd/php-persistence/issues/65) + and [Batch 6 handoff](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7234977176). +- Baseline verdict: **REQUEST CHANGES** for local audit parity. The correction + has its own [review on #111](https://github.com/Maatify-ltd/php-persistence/pull/111) + and [exact-HEAD CI checks](https://github.com/Maatify-ltd/php-persistence/pull/111/checks). + +## Compliance and evidence + +| Standard section | Result | Evidence | +| --- | --- | --- | +| §§1–2, 2.3 | PASS | The Composer artifact owns the deterministic checks. The full run for the Batch 6 integration boundary reports 31 required successes. Stable terminal gate and distinct jobs make the failure boundary explicit. | +| §2.1 Local parity | F108-19 correction implemented | The local map provides Composer validation, unconstrained-by-lock resolution, real platform checks, strict PSR-4, syntax, whitespace, analysis, style, test/fixture orchestration, lint and per-target archive invocations. The correction uses the same dependency-audit command locally and in Compat. | +| §2.2 Consumer Verification | PASS | The workflow calls `composer test:consumer` on PHP 8.4 and 8.6, MySQL 8.4.13 and MariaDB 11.8.9. Each job uses the repository lifecycle and clean production consumers. Logs record eight lifecycles and 16 installs of the exact candidate for coexistence/differential. The terminal gate requires the jobs. See [Consumer Verification](../../docs/guides/CONSUMER_VERIFICATION.md). | +| §2.4 SHA qualification | Gate documented, pending #88 | The [handoff](../../docs/guides/RELEASE_ARTIFACT_VERIFICATION.md#release-evidence-handoff) requires actual selected `main` SHA, Full CI and target-specific RAV. The current evidence covers the review branch. | +| §2.5 Release Artifact Verification | PASS for the reviewed target | The Stable verifier runs against explicit SHA and target. The RC.2 job uses a separate tag checkout and its own verifier. The current [guide](../../docs/guides/RELEASE_ARTIFACT_VERIFICATION.md) supplies equivalent local invocations. Exact install target, undated Stable changelog allocation and the dated security/support snapshot were checked in context. | +| §2.6 Published Artifact Verification | Tool ready, Stable execution pending publication | The [verifier](../../scripts/published-artifact.php) uses a fresh external root, isolated Composer configuration, controlled preference, exact metadata and tag reference, observed install mode, inventory/hash parity and record-before-cleanup. The required mode is dist. The regression suite exercises evidence on failure. There is no applicable intentional source-only delivery decision. | +| §2.7 Immutable version | PASS for current records | RC.2 tag and Packagist dist resolve to `71dc61548e48fd053376db69149a00bc87069b70`. CI checks that identity before running its verifier. The release handoff uses the qualified SHA from the actual target boundary. | +| §§3–4, 16–17 | PASS | Full baseline for PRs into `main` and pushes to `main`, with no workflow path filter. Manual dispatch is also available. `CI gate` inspects all seven required upstream job groups and rejects any non-success. GitHub's active rules on `main` select `CI gate` only, with GitHub Actions integration ID `15368`. | +| §§5–6 | PASS | `composer validate --strict`, temporary lock during resolution, latest and lowest across each PHP minor, real `composer check-platform-reqs`, strict PSR-4. No committed lock, vendor directory or cache artifacts. | +| §§7–7.1 | PASS for CI matrix; release security evidence pending #88 | Six Compat jobs recorded stable PHP `8.4.28`, `8.5.13` and `8.6.0`. Across 29 PHP jobs the common action verified actual CLI and applicable floors. The constraint probe accepts the pinned floors, rejects adjacent lower patches and exercises the forward range without running those interpreters. Official security evidence for admitting PHP 8.6 must be recorded at release qualification as specified in [CI and Integration §3.3, PHP security patch verification](../../docs/architecture/CI_AND_INTEGRATION.md#33-php-security-patch-verification). | +| §8 | PASS | PHP syntax checks cover tracked PHP, PHPStan max checks the configured source/test/script/example paths with no suppressions, Git checks whitespace against the empty tree, full format check runs on 8.4–8.5 and required PER-CS on 8.6 under DEC-028. Unit, Regression, Integration and four smoke cells ran. Smoke ran nine examples per cell with production autoload; the bootstrap is shared support. | +| §9 | PASS on the CI baseline | Six baseline jobs used Composer 2.10.3, checked bypass environment and effective advisories/malware/abandonment policy, then audited non-interactively. The shared command below replaces those workflow steps. DEC-016 covers only the exact legacy fixture in an isolated coexistence project. See the [correction's CI checks](https://github.com/Maatify-ltd/php-persistence/pull/111/checks) for runs on #111. | +| §10 | PASS | Pinned checksum-verified actionlint 1.7.12 checks the sole tracked workflow. Local lint also passed with actionlint 1.7.12. | +| §11, §18 | PASS | Shared Compose definition, explicit seven version/digest nodes, readiness, fresh project IDs, loopback endpoint and fixture-owned teardown. Required Integration covers the endpoint versions on PHP minimum/latest. Logs show 15 cells, 60 runs of 523 tests, 60 clean residue checks and 30 verified teardowns. See [CI and Integration](../../docs/architecture/CI_AND_INTEGRATION.md) and DEC-008/013/027. | +| §§12–13 | PASS | External actions use full SHA pins. The workflow grants read-only contents, drops persisted checkout credentials and uses test-owned services. Composer/actionlint downloads are pinned and checksum-checked. Required jobs set timeouts; the concurrency policy cancels superseded PR runs and preserves protected-branch runs. | +| §§14–15 | N/A | Required checks have no dependency on restored caches or coverage artifacts. | +| §19 checklist | See [#111 review](https://github.com/Maatify-ltd/php-persistence/pull/111) | Track F108-19 acceptance on #111 and the roadmap handoff in [#65](https://github.com/Maatify-ltd/php-persistence/issues/65). Exact-`main` qualification and post-publication execution follow #88 and the release handoff. | + +## F108-19 — local dependency audit omits the CI policy preflight + +The baseline [CI workflow](https://github.com/Maatify-ltd/php-persistence/blob/cf07db569a43b6afe19d93b25694bb3a5487b183/.github/workflows/ci.yml#L117-L131) fails before +audit when the configured bypass environment is present and requires the +effective Composer advisories, malware and abandonment policy to match +specific values. The baseline [CI parity table](https://github.com/Maatify-ltd/php-persistence/blob/cf07db569a43b6afe19d93b25694bb3a5487b183/docs/architecture/CI_AND_INTEGRATION.md#1-local-and-ci-parity) +and [contribution commands](https://github.com/Maatify-ltd/php-persistence/blob/cf07db569a43b6afe19d93b25694bb3a5487b183/CONTRIBUTING.md#local-verification) give +only `composer audit --no-interaction --abandoned=fail`. The historical +checks in [Quality Tooling §6](../../docs/architecture/QUALITY_TOOLING.md#6-dependency-policy-verification-composer-2103) +print the policy and describe isolated experiments; they do not document an +equivalent fail-closed local gate. + +On the reviewed checkout with Composer 2.10.2, the documented audit exited +0 with `COMPOSER_POLICY_ADVISORIES_BLOCK=0` scoped to that invocation. The +CI preflight on the same input exited 1. The installed packages were otherwise +unchanged. This shows different local and CI acceptance semantics under +§§2.1 and 9. Close the finding by using a shared fail-closed check or an +equivalent documented local sequence and prove that the normal and weakened +configurations yield the same outcomes locally and in CI. + +### F108-19 correction on #111 + +[Local verification](../../CONTRIBUTING.md#local-verification) and the Compat +workflow run the same [dependency audit command](../../scripts/dependency-audit.php). +It rejects weakening environment values and effective Composer configuration, +validates the root lock, and runs the non-interactive audit with development +dependencies included. It rejects caller arguments and returns Composer's +nonzero audit status. The [CLI regression](../Regression/DependencyAuditCommandTest.php) +checks that preflight failures stop before the audit and verifies the exact +Composer invocation and status propagation. + +## Recheck the exact evidence + +- [CI run 46113345165](https://github.com/Maatify-ltd/php-persistence/actions/runs/46113345165) + records PR #108 HEAD `cf07db5` and base `e2cc22d`. The five job + families using merge checkout ran on `d8a08d79b6bde48337c927f28384fcdf79c90d18`. + Its tree `408d6187894e471e2c399ce5686f5b05e89b55c0` equals the reviewed + HEAD tree. Harness and Stable RAV recorded `cf07db5` directly. +- Local replay passed `actionlint .github/workflows/ci.yml`, + `composer validate --strict`, `composer check-platform-reqs`, + `composer whitespace` and `composer verify:php-constraint`. + The focused PAV evidence regression ran eight cases and 581 assertions. +- Local `composer release:verify` recorded 171 files per archive for Stable + `1.0.0` on `cf07db5` and 80 files per archive in the separate RC.2 tag + checkout. Stable Git SHA-256 + `63a1e490d8a545e7665a89221af1729fe1d6a8bf34bf989b90e375e9373829bd`, + Composer SHA-256 + `7dd83cae96b7ea206539807a36a5b9a52ee39d74183fc018b1671acd9053b27e`. +- Packagist exact-version metadata listed RC.2 and no Stable `1.0.0` at + review time. PAV for Stable remains pending publication. #88 remains HOLD. diff --git a/tests/evidence/RELEASE_PRESENTATION_CONFORMANCE.md b/tests/evidence/RELEASE_PRESENTATION_CONFORMANCE.md new file mode 100644 index 0000000..bf62f89 --- /dev/null +++ b/tests/evidence/RELEASE_PRESENTATION_CONFORMANCE.md @@ -0,0 +1,64 @@ +# Release presentation conformance evidence + +This review describes the presentation controls and actual evidence needed for an +external reviewer to verify the current Stable preparation. The implementation +reviewed is [`5565625ee710555044b830c6e7d6a93480ddcfb0`](https://github.com/Maatify-ltd/php-persistence/commit/5565625ee710555044b830c6e7d6a93480ddcfb0) +on [#108](https://github.com/Maatify-ltd/php-persistence/pull/108), with +[Library Presentation 7.0.0](../../docs/php-engineering-standards/standards/packages/LIBRARY_PRESENTATION_STANDARD.md) +and [Documentation Lifecycle 3.1.1](../../docs/php-engineering-standards/standards/governance/DOCUMENTATION_LIFECYCLE_STANDARD_AR.md) +pinned at `c1dbb2da062a35c45638abf2bcb2ae210140eb5d`. [#65](https://github.com/Maatify-ltd/php-persistence/issues/65) +tracks the findings and their disposition. + +**Reviewed baseline verdict: REQUEST CHANGES.** The release-facing facts and +the four findings below are distinct from the exact-main-SHA gates in #88. + +## Library Presentation coverage + +| Sections | Result | Evidence | +| --- | --- | --- | +| §§1–6 | PASS for scope and required files | Standalone reusable Composer artifact, licensed for authorized use. All applicable release-facing files are present. An independent local Git and Composer RAV run for Stable `1.0.0` on `5565625` passed with 171 files in each archive. | +| §§7–9 | PASS | Exact-head GitHub-rendered README HTML includes the centered header, light and dark logo sources, three badge rows, repository-local PHP and license values, and links for the artifact scope. The logo and registry download assets returned successfully. The dated RC.2 status and separate Stable target follow §§8.1.1–8.1.2. | +| §§10.1, 11–12 | PASS for presentation | The public overview links to the canonical Package Reference. The README separates three public capabilities, the manifest requirements and tested database versions; it states ownership and failure boundaries. Heading hierarchy and Author formatting were checked in the rendered README. | +| §10.2 | FAIL, F108-22 | The capability map and prerequisites are present. The nine standalone PHP examples are covered by smoke jobs. Host Snapshot B is presented as an inline, Host-dependent example and falls outside the maintained syntax and static-analysis checks. | +| §§10.3–10.4 | PASS | Root `llms.txt` has one heading, consumer/contributor boundaries, the complete canonical Public Runtime API reference, usage map, and six links resolving in the archive. | +| §§13, 22 | FAIL, F108-20 | The Code of Conduct Ecosystem badge uses the old organization. SECURITY points to another package's security instructions as authority for this library's reporting contact even though its own LICENSE supplies it. | +| §14 | PASS for current artifact presentation; first-Stable evidence pending #88 | README and SECURITY distinguish the earlier RC.2 snapshot and the unpublished Stable target. RC.2 can be resolved and installed from dist. DEC-031 covers actual Host validation on the published RC for the first Stable target. The RC.1 Harness evidence remains applicable to the recorded exception path. | +| §15 | PASS | The allocated `1.0.0` section is undated and has no release link. The RC.1 and RC.2 dates and bottom links match release history. This file contains no represented unallocated changes requiring an Unreleased section. | +| §§16–18 | PASS | CONTRIBUTING describes the actual shared dependency-audit gate and local verification. README uses the required Author formatting and final Maatify footer. | +| §19 | PASS for observed metadata | Composer and GitHub description, topics, package identity, homepage and license agree with the documented package. GitHub Releases has the two managed prereleases. No package or deployment panel was observed in the public repo view. Administrative visibility toggles were not inspected. | +| §20 | FAIL, F108-23 | The umbrella carries changes allocated to exact Stable `1.0.0`. Its title and body omit the required preparation/publication state and release-control statement, and the body omits explicit scope. | +| §20.1, §23 | Later release gates pending #88 | Exact main candidate, Full CI, Consumer Harness, RAV, Strict Lead Acceptance, Owner release authorization, then immutable tag and release, external publication, PAV and live documentation synchronization remain ordered release controls. | +| §21 | Verified within the stated review limits | Reviewed GitHub-rendered HTML, logo and badge endpoints, canonical slug and local targets. The independent check resolved 144 tracked relative links and 61 local Markdown anchors in the sampled release-facing docs; a viewport screenshot was not captured. | +| §25 | FAIL, F108-21 | LICENSE and its relative badge are correct. The short README license section does not explicitly state the requirement to obtain written authorization before use. | + +## Documentation Lifecycle coverage + +| Sections | Result | Evidence | +| --- | --- | --- | +| §§1–3 | PASS for ownership and document roles | The Package Reference owns the current public runtime contract. The architecture and decision records preserve historical context. README, guides, CHANGELOG, SECURITY and LICENSE each direct readers to the appropriate owner. | +| §§4–5.1 | PASS for published and artifact identity | The immutable artifact records exact target `1.0.0`; the RC.2 publication and support statements are dated. The exact install command is conditional on actual publication. The live state is checked in the approved distribution channel. | +| §6 | Review record | This evidence supports independent reproduction on the draft. #65 and PR review/checks carry the current verdict and subsequent corrections. | +| §7 | PASS for reviewed surfaces | Maatify identity uses `maatify.dev`. The separate outdated GitHub organization link is handled under Library Presentation §13 in F108-20. | + +## Findings and acceptance evidence + +| Finding | Evidence on the reviewed state | Required correction | +| --- | --- | --- | +| **F108-20 — Governance identity and reporting authority** | [CODE_OF_CONDUCT.md:4](https://github.com/Maatify-ltd/php-persistence/blob/5565625ee710555044b830c6e7d6a93480ddcfb0/CODE_OF_CONDUCT.md#L4) points the Ecosystem badge to `github.com/Maatify`; §13 gives the exact `Maatify-ltd` value. [SECURITY.md:19–31](https://github.com/Maatify-ltd/php-persistence/blob/5565625ee710555044b830c6e7d6a93480ddcfb0/SECURITY.md#L19-L31) uses the legacy repository's security instructions in the reporting channel paragraph. | Use the canonical Ecosystem link. Cite this package's own LICENSE for its existing private channel and retain the distinct-package scope. | +| **F108-21 — License summary misses prior written authorization** | [README.md:182–189](https://github.com/Maatify-ltd/php-persistence/blob/5565625ee710555044b830c6e7d6a93480ddcfb0/README.md#L182-L189) describes requesting a free written license. [LICENSE](../../LICENSE) and §25 require the summary to say that written authorization must be obtained before use. | Make prior written authorization explicit in the README while preserving the approved license terms, no-charge process and contact. | +| **F108-22 — Host B example bypasses syntax/static coverage** | [Usage Guide:25–34](https://github.com/Maatify-ltd/php-persistence/blob/5565625ee710555044b830c6e7d6a93480ddcfb0/docs/guides/USAGE_GUIDE.md#L25-L34) designates the [fenced PHP example](https://github.com/Maatify-ltd/php-persistence/blob/5565625ee710555044b830c6e7d6a93480ddcfb0/PHP_PERSISTENCE_PACKAGE_REFERENCE.md#L964-L977) as the Host B example. Composer syntax scans PHP files and [PHPStan](../../phpstan.neon) does not analyze this Markdown block. The installed Harness proves Host B behavior through its own fixture. | Validate the delivered Host-dependent example with the maintained syntax and static gates, retaining its explicit Host prerequisites. A validated PHP example file is one way to keep its verification attached to the delivered code. | +| **F108-23 — Stable preparation metadata in #108** | At review time the [umbrella title and body, as recorded during review](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7235660523) did not state the exact target's actual unpublished status or the Owner release-control boundary. This branch already allocates real changes under [CHANGELOG's `1.0.0` target](../../CHANGELOG.md#L7). | Reconcile the umbrella title and description with §20. Name the unpublished target, current preparatory scope and separate Owner authorization. Reference DEC-031, the actual RC.1 Harness, and zero validated real Hosts under the approved exception path. | + +## Publication and evidence boundaries + +- Packagist and GitHub show RC.1 and RC.2. A clean external Composer project + installed `maatify/php-persistence:1.0.0-rc.2` in observed `dist` mode at + `71dc61548e48fd053376db69149a00bc87069b70`. + [Packagist exact versions](https://repo.packagist.org/p2/maatify/php-persistence.json) · + [GitHub RC.2 release](https://github.com/Maatify-ltd/php-persistence/releases/tag/v1.0.0-rc.2). +- [DEC-031](../../docs/decisions/DEC-031-first-stable-real-host-exception.md) records the + exact `1.0.0` Host-only exception and [published RC.1 Harness evidence](https://github.com/Maatify-ltd/php-persistence/issues/29#issuecomment-6839437553). + The approved path calls for the final candidate verification on `main`. +- Stable `1.0.0` is a prepared target. Its local archive pass and the independent + published RC.2 install are evidence for those respective checks. Stable PAV + follows external publication. [#88](https://github.com/Maatify-ltd/php-persistence/issues/88) remains HOLD. diff --git a/tests/evidence/TESTING_CONFORMANCE.md b/tests/evidence/TESTING_CONFORMANCE.md new file mode 100644 index 0000000..bac3584 --- /dev/null +++ b/tests/evidence/TESTING_CONFORMANCE.md @@ -0,0 +1,140 @@ +# Testing conformance evidence + +This point-in-time audit covers the Testing batch in the standards conformance +review. It links the audited parent evidence and the focused F108-18 follow-up. +The package reference owns the public contracts. + +## Reviewed baseline + +- Parent review: [PR #108](https://github.com/Maatify-ltd/php-persistence/pull/108) + at [`e27c5b472b96a1f1bbe6f3bc33643073c309e13c`](https://github.com/Maatify-ltd/php-persistence/commit/e27c5b472b96a1f1bbe6f3bc33643073c309e13c). +- Reviewed tree: `39a8e723cdb6bdeeeffc6ca9dffb3a17aefd299f`. The parent PR's + synthetic merge `9d1a74d4bf2804179ef4ec999fa0fab18cf3b546` has the same tree. +- Applicable standard: [Testing 3.0.0](../../docs/php-engineering-standards/standards/testing/TESTING_STANDARD.md) + at the [adopted pin](../../docs/php-engineering-standards/STANDARDS_MANIFEST.md) + `c1dbb2da062a35c45638abf2bcb2ae210140eb5d`. +- Audit verdict: **REQUEST CHANGES** for the system-level coverage in + [F108-18](#f108-18--raw-ordering-settlement-after-a-zero-row-update). + The audit table and parent CI record apply to the reviewed parent tree. The + [focused follow-up](#f108-18--raw-ordering-settlement-after-a-zero-row-update) + records the candidate results separately. + +## Requirements and evidence on the reviewed parent + +| Testing section | Result | Evidence | +| --- | --- | --- | +| §§1, 2 — Observable behavior and mandatory protection | Partial | Public API tests run across real PDO boundaries. F108-18 identifies a specific externally observable settlement outcome that has only isolated recurrence coverage. | +| §3.1 — Unit | Pass | [PHPUnit suite definitions](../../phpunit.xml) separate Unit, Regression and Integration. The local Unit and Regression rerun completed 970 tests and 7,969 assertions. | +| §3.2 — Integration | Pass for the observed runs | [Integration entry point](../../scripts/integration.php) provisions the database and executes the Integration suite. The recorded parent CI ran it on 15 real-service jobs. | +| §3.3 — System/E2E | Partial | The coverage map below identifies public entry points, real boundaries and final observations. F108-18 concerns a missing outcome in this layer. | +| §3.4 — Consumer Verification Harness | Pass | The [harness](../../scripts/consumer-verification.php) creates separate temporary Composer roots with isolated Composer home, cache and vendor directories. It installs the candidate archive and legacy fixture as dependencies with `--no-dev`, checks installation identity and runs the scenarios through production Composer autoloading. Actual runs and observable outcomes are below. | +| §3.5 — External-provider boundary | Not applicable to this package | The [Manifest](../../docs/php-engineering-standards/STANDARDS_MANIFEST.md#resolution-summary) explains applicability. Test databases are provisioned and controlled by this repository. | +| §3.6 — Final classes and doubles | Pass | The reviewed doubles target PDO or PDOStatement boundaries. Public final classes are instantiated directly. The [development dependencies](../../composer.json) and [PHPStan configuration](../../phpstan.neon) identify the package's testing and analysis tools. | +| §4.1 — Existing behavior | Pass for reviewed workflows | The differential consumer runs, public API regression tests and real-PDO assertions protect the established contracts listed below. Compatibility with the five external consumers is tracked in [#43](https://github.com/Maatify-ltd/php-persistence/issues/43). | +| §4.2 — New observable behavior | Partial | Public workflow tests cover the changed Pagination and Transaction boundaries. F108-18 concerns the new raw Ordering exception outcome. | +| §4.3 — Critical workflows | Partial | Transaction replay and the protected Ordering writer invariants have real-contender evidence. Raw Ordering settlement after a zero-row write needs the specific system-level check in F108-18. | +| §4.4 — Integration boundaries | Partial | The observed fixtures use real databases and observable state. The isolated raw Ordering settlement check and the related real-PDO helper checks leave the F108-18 boundary uncovered. | +| §4.5 — Regression protection | Partial | [RED/GREEN sources](#regression-evidence) cover the sampled fixes. The raw Ordering recurrence case has focused Unit protection. The affected public system boundary remains open under F108-18. | +| §4.6 — Internal refactors | Pass | The [Ordering structure regression](../Regression/Exception/OrderingExceptionContractTest.php) protects shared executor usage. The surrounding public workflows ran through the real-PDO suite. | +| §4.7 — Host CI | Not applicable to this artifact | The reviewed artifact is a standalone reusable Composer package. Its package CI evidence is linked below. | +| §5 — Completion | Open | The reviewed test runs passed. The batch gate still requires the public-path coverage identified in F108-18. | + +## Public behavior coverage + +| Guarantee | Executed evidence and observable result | +| --- | --- | +| Owned Transaction commit, rollback, result and exceptions | [Transaction runner](../Integration/Transaction/PdoTransactionRunnerIntegrationTest.php), [outcomes](../Integration/Transaction/TransactionOutcomeIntegrationTest.php) and the [consumer catalog](../../harness/consumer.php). An independent connection observes committed data and distinguishes pending or rolled-back writes. | +| Caller-owned savepoints and deadlock replay | [Savepoint runner](../Integration/Transaction/PdoSavepointTransactionRunnerIntegrationTest.php) and [deadlock tests](../Integration/Transaction/DeadlockRetryIntegrationTest.php). A real contender induces InnoDB deadlocks. Tests check replay bounds, a single committed outcome, exception identity and preservation of the caller's outer work. The differential consumer also exercises both runner variants. | +| Protected and Verified Transaction | [Protected checkout](../Integration/Transaction/PdoProtectedTransactionCheckoutTest.php), [protected deadlock](../Integration/Transaction/ProtectedTransactionDeadlockIntegrationTest.php), [Verified lifecycle](../Integration/Transaction/VerifiedTransactionIntegrationTest.php) and [Verified deadlock](../Integration/Transaction/VerifiedTransactionDeadlockIntegrationTest.php). Assertions cover recovered data, settlement, no replay after fencing, failure precedence, and explicit return or discard of the connection. The consumer runs the [protected scenario](../../harness/protected-transaction-api.php) and the installed [Verified example](../../examples/verified_transaction_usage.php). | +| Offset Pagination and sort plans | [Query semantics](../Integration/Pagination/PdoPaginatorQuerySemanticsTest.php), [failure](../Integration/Pagination/PdoPaginatorFailureContractTest.php), [snapshot consistency](../Integration/Pagination/PdoPaginatorSnapshotConsistencyTest.php), [static sort](../Integration/Pagination/StaticSortPaginationIntegrationTest.php) and [dynamic sort](../Integration/Pagination/DynamicSortPaginationIntegrationTest.php). The tests check returned pages and totals, bindings, cursor/transaction ownership and concurrent committed data. The consumer compares published results and runs the installed sort examples. | +| C1, Keyset and Host Snapshot B | [C1 results](../Integration/Pagination/PdoSnapshotPaginatorTest.php) and [failure outcomes](../Integration/Pagination/PdoSnapshotPaginatorFailureTest.php), [Keyset](../Integration/Pagination/PdoKeysetPaginatorIntegrationTest.php), [Host transaction](../Integration/Pagination/PdoHostSnapshotTransactionTest.php) and [retirement](../Integration/Pagination/PdoHostSnapshotRetirementTest.php). Observable results include page continuations, mapper exception identity, session exclusion, and return or quarantine. The installed [C1 and Keyset examples](../../examples/) and the [Host Snapshot scenario](../../harness/host-snapshot-api.php) exercise the consumer side. | +| Raw and Protected Ordering | [Raw stale-snapshot moves](../Integration/Ordering/ScopedOrderingManagerMoveStaleSnapshotTest.php), [savepoint and exception paths](../Integration/Ordering/ScopedOrderingManagerLazySavepointTest.php), [MariaDB outcomes](../Integration/Ordering/ScopedOrderingManagerMariaDbSnapshotIsolationHazardTest.php) and [protected Ordering](../Integration/Ordering/ProtectedScopedOrderingManagerIntegrationTest.php). These observe committed positions, locks, rollback and fencing. The raw zero-row rejection with failed settlement is the outstanding case in F108-18. | +| Protected UNIQUE-safe Ordering B1 | [B1 system tests](../Integration/Ordering/ProtectedUniqueOrderingTest.php) cover dense append, move, delete and compact, schema eligibility, independent competing writers, rollback and a real deadlock. The installed [B1 example](../../examples/ordering_unique_usage.php) checks the consumer path. | +| Cross-capability caller ownership and serialization | The [Pagination/Ordering composition test](../Integration/Pagination/PaginationOrderingSavepointTest.php) exercises cursor release, original failure and caller-owned rollback on the same PDO. [Settlement JSON tests](../Regression/SettlementJsonContractTest.php) lock public codes and fields for the data-only projections. | + +## Executed evidence + +[Parent CI run 46101063647](https://github.com/Maatify-ltd/php-persistence/actions/runs/46101063647) +passed 31 required jobs on the reviewed head. Its logs contain 60 Integration +suite executions of 515 tests each, 60 immediate checks with zero leftover tables +and open transactions, and 30 verified teardowns. Examples Smoke executed nine +examples in each of four cells. The Consumer Verification jobs ran the two +scenarios on MySQL 8.4.13 and MariaDB 11.8.9 in two clean lifecycles each across +two PHP cells, for 16 candidate installations. The scenario sources check +production autoloading, stored state, nested savepoint isolation and an actual +deadlock retry. The [consumer evidence guide](../../docs/guides/CONSUMER_VERIFICATION.md) +describes the commands, fixture ownership, cleanup and legacy identities. + +Use these commands from a checkout of the reviewed parent with its normal +dependencies. The local single-cell Integration command is a focused run. +The linked parent CI evidence records the repeated matrix execution. + +```sh +vendor/bin/phpunit --testsuite unit,regression +php scripts/integration.php --cell=mysql-8.4.13 --fresh-runs=1 --suite-passes=1 +PP_DB_CELL=mysql-8.4.13 composer test:consumer +``` + +The [DEC-031 exception](../../docs/decisions/DEC-031-first-stable-real-host-exception.md) +applies to first-Stable real-host validation. Release qualification, including +eligibility and final-candidate evidence, is tracked under [#88](https://github.com/Maatify-ltd/php-persistence/issues/88). + +## Regression evidence + +- Raw Ordering settlement: [F108-05 compared the prior and corrected results](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7229112789). + The preserved [focused tests](../Unit/Ordering/Repository/ScopedOrderingManagerSavepointWiringTest.php) + check false/throwable controls, primary error identity and transaction + ownership. The [focused follow-up](#f108-18--raw-ordering-settlement-after-a-zero-row-update) + adds detection through the public method on a real database. +- Exit status from the syntax command: the [F108-09 before/after record](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7229920165) + captures the same missing-input condition on both heads and documents the + propagated failure and the successful case. +- Style checker: the [reproduced failure](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7232695841) + and [accepted correction](https://github.com/Maatify-ltd/php-persistence/issues/65#issuecomment-7232974255) + record the composite command and PHP 8.6 results. [Committed recurrence + cases](../Regression/PerCodingStyleDeltaCheckTest.php) cover positive and + negative placement and documentation scope. +- Published Artifact Verification tool: [CLI regression fixtures](../Regression/PublishedArtifactEvidenceTest.php) + cover evidence preserved during failure and cleanup. The actual Stable + distribution verification belongs after publication. + +## F108-18 — Raw Ordering settlement after a zero-row update + +The reviewed parent had isolated [Unit coverage](../Unit/Ordering/Repository/ScopedOrderingManagerSavepointWiringTest.php) +for the zero-row settlement path under [DEC-034](../../docs/decisions/DEC-034-raw-ordering-settlement-failures.md). +The raw Integration cases produced a primary error or a successful target +write. The savepoint helper and protected manager tests exercised different +entry points. Testing §§1, 3.3, 4.2 and 4.5 require coverage of the observable +outcome through the raw public manager. + +[ScopedOrderingManagerSettlementTest](../Integration/Ordering/ScopedOrderingManagerSettlementTest.php) +calls raw `ScopedOrderingManager::moveWithinScope()` against InnoDB. A +table-local trigger keeps the target position while allowing the preceding +range shift. The fixture uses the disposable admin connection to install the +trigger. The public call runs as the application user with native prepares +and affected-row reporting. The statement observer records the driver counts +`[2, 0]` for the shift and target UPDATE without changing their results. +Only the rollback, rollback-to-savepoint or release acknowledgement is +fault-injected in the six failure cases. + +| Case | Public result and database observation | +| --- | --- | +| Owned or Host settlement succeeds | Returns ordinary `false`. The shift is undone and the independent observer sees the original positions. | +| Owned rollback returns false or throws | Throws `TransactionExecutionException` or the exact injected PDO exception. The real shift stays pending until the fixture rolls it back. The independent observer sees unmodified positions. | +| Host rollback to savepoint returns false or throws | The corresponding error escapes, the shift and earlier Host marker remain pending, and release is skipped. The Host ends the surrounding transaction explicitly. | +| Host release returns false or throws | The corresponding error escapes after local undo. The Host retains its marker and control of the surrounding transaction. The independent observer sees the marker only after the Host commits. | + +The same new cases on historical runtime +[`9c15309`](https://github.com/Maatify-ltd/php-persistence/commit/9c15309fa18bfb25413fa65d934d999e3fca384d) +gave **RED** on MySQL 8.4.13. Four of eight cases returned ordinary `false` +after failed owned rollback or failed Host release. The controls and the +two rollback-to-savepoint failures behaved as expected on that runtime. +The failed run left zero test tables and open transactions. + +The follow-up on [Draft #110](https://github.com/Maatify-ltd/php-persistence/pull/110) +from `4caa68a` gave **GREEN** on MySQL 8.4.13 and MariaDB 11.8.9, with +eight cases and 286 assertions per engine. The runs used PHP 8.5.13 and the +repository's isolated database lifecycle. Each focused run left zero test +tables and open transactions. The supervisor verified zero owned workers and +complete Compose teardown. Full candidate CI and batch acceptance remain +separate from these focused runs.