Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/archive.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
actions: read
attestations: write
id-token: write
uses: sympress/workflows/.github/workflows/wordpress-archive.yml@177fa0d727b278d2103052ec77c102b4a4c492a0
uses: sympress/workflows/.github/workflows/wordpress-archive.yml@78d083a9a0176cf0252318b0c69fc64938a727d6
with:
artifact_attestation: false
artifact_extra_excludes: >-
Expand All @@ -39,7 +39,7 @@ jobs:

archive-check:
needs: archive
uses: sympress/workflows/.github/workflows/wordpress-archive-check.yml@177fa0d727b278d2103052ec77c102b4a4c492a0
uses: sympress/workflows/.github/workflows/wordpress-archive-check.yml@78d083a9a0176cf0252318b0c69fc64938a727d6
with:
artifact_name: ${{ needs.archive.outputs.artifact }}
secrets:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/dependency-canary.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ jobs:
permissions:
contents: read
issues: write
uses: sympress/workflows/.github/workflows/dependency-canary.yml@177fa0d727b278d2103052ec77c102b4a4c492a0
uses: sympress/workflows/.github/workflows/dependency-canary.yml@78d083a9a0176cf0252318b0c69fc64938a727d6
with:
php_version: '8.5'
4 changes: 2 additions & 2 deletions .github/workflows/qa.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ permissions:

jobs:
workflows:
uses: sympress/workflows/.github/workflows/lint-workflows.yml@177fa0d727b278d2103052ec77c102b4a4c492a0
uses: sympress/workflows/.github/workflows/lint-workflows.yml@78d083a9a0176cf0252318b0c69fc64938a727d6

qa:
uses: sympress/workflows/.github/workflows/sympress-qa.yml@177fa0d727b278d2103052ec77c102b4a4c492a0
uses: sympress/workflows/.github/workflows/sympress-qa.yml@78d083a9a0176cf0252318b0c69fc64938a727d6
with:
php_version: '8.5'
secrets:
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
where applicable.

## Unreleased

- Require explicit retirement for additional legacy adoptions without changing the canonical version; expose exact adoption diagnostics in status and reject canonical/alias version conflicts.
- Validate migration identities and plugin slugs against the 191-byte metadata storage limit before writes.
- Share advisory locks across all migration scopes in a database, configure the timeout, and verify connection/lock ownership before SQL and metadata writes.
- Continue other plugins only after typed operational failures; propagate PHP/programming errors immediately.

## 1.0.7 — 2026-10-02

- Continue other plugins after a failed migration, then return a failing aggregate CLI result.
Expand Down
5 changes: 4 additions & 1 deletion Resources/config/services.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
parameters:
migration.lock_timeout: 10

services:
_defaults:
autowire: true
Expand All @@ -15,7 +18,7 @@ services:

SymPress\WordPress\Migration\Application\MigrationSystem:
factory: ['SymPress\WordPress\Migration\Factory\MigrationServiceFactory', 'system']
arguments: ['@wpdb']
arguments: ['@wpdb', '%migration.lock_timeout%']
public: true

SymPress\WordPress\Migration\Infrastructure\MigrationTracker:
Expand Down
33 changes: 31 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,16 @@ Custom executors can implement the additive
`DeferredMigrationOperationExecutor` contract for this behavior; the original
`MigrationOperationExecutor` and `MigrationSqlExecutor` contracts remain valid
with their previous semantics. The WordPress executor implements both operation
contracts. The lock includes database, WordPress prefix and plugin scope.
contracts. All plugins, WordPress prefixes, shared ORM tables and custom metadata
tables in one database share the same advisory lock domain. Configure
`migration.lock_timeout` before bootstrap (default 10 seconds, 0–3600), or pass
`lockTimeout` to a standalone `WordPressSqlExecutor` or `MigrationSystem`.
Nested operations on the same wpdb connection reuse ownership and transaction
depth. SQL and metadata writers verify the original connection ID and
`IS_USED_LOCK()` ownership before writes. A replaced/reconnected session stops
with `MigrationOperationException`; it cannot continue under a lost lock.
The executor also checks after SQL: a reconnect inside wpdb's own automatic
query retry can already have applied SQL, so reconcile state before retrying.
DML-only operations use a transaction spanning SQL, state and history on
transactional tables. State/history writes also use a transaction after DDL.
MySQL/MariaDB DDL can commit independently and is never claimed to be atomic.
Expand Down Expand Up @@ -110,14 +119,27 @@ existing target under the operation lock, preserves that version/date, retires
only the specified legacy current-state entry and appends `adopt` history.
Historical entries remain unchanged. It runs no migration `up()` SQL and does not
claim that a newer intended schema is applied; changed schema remains pending.
If the stable identity already exists, another adoption requires explicit
`--retire-superseded`. This removes only the selected reviewed legacy record,
retains the stable version/date, and appends `retire` history with the exact
retired identity/version. It never replaces a stable record with an older
version. Review each additional old deployment separately, including records
whose versions happen to match. Different mapped legacy versions, including a
canonical-plus-alias conflict, remain blocked until explicitly reconciled.
`wp migration status` reports `Needs Adoption`, the exact binary key as Base64,
its recorded version and a `wp migration adopt` command template. Replace the
stable-key placeholder and administrator after review. Status never reports
such state as up to date, even when no ordinary migrations are pending.
Unknown/conflicting state fails. `manage_options` and explicit `--yes` are required
by the CLI before metadata is touched. The lower-level manager method is available
to trusted deployment tooling after equivalent operator authorization.

Named migration classes keep their class identity unless they declare a stable
`getMigrationKey(): string`. Anonymous migrations **require** that method;
basename/line and release-directory heuristics cannot establish unique identity.
Explicit keys must be non-empty, contain no NUL and fit 255 bytes. The ORM bridge
Explicit keys must be non-empty, contain no NUL and fit 191 bytes, matching the
metadata tables. Named-class keys, legacy aliases and plugin slugs have the same
191-byte limit, checked before writes. The ORM bridge
uses `orm-schema:<manager>`. Versions remain separate from keys. Collections are
indexed by these keys, support multiple instances of an anonymous declaration
with distinct keys, and reject overlapping keys/legacy aliases before execution.
Expand All @@ -140,6 +162,13 @@ Saving a new current version or marking it up retires mapped obsolete applied
keys in the same metadata transaction and retains append-only history. Rollback
and mark-down remove all applied aliases, so old state cannot reappear. Multiple
legacy aliases with conflicting versions require explicit reconciliation.

Expected operational state failures use `MigrationOperationException`. The
all-plugin CLI catches this type and returned failures, processes the remaining
plugins and exits unsuccessfully. PHP errors and other programming exceptions
propagate immediately; custom migration implementations should use the typed
exception only for reviewed operational failures. Exception details are omitted
from aggregate CLI diagnostics to avoid leaking SQL or credentials.
An up-to-date legacy record remains valid; `mark up` can explicitly move it to
the canonical key without executing SQL. Forward targets rescan all pending
migrations through that target in registration order, including changed earlier
Expand Down
30 changes: 21 additions & 9 deletions src/Application/MigrationLifecycle.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use SymPress\WordPress\Migration\Contract\MigrationOperationExecutor;
use SymPress\WordPress\Migration\Contract\MigrationSqlExecutor;
use SymPress\WordPress\Migration\Contract\MigrationStore;
use SymPress\WordPress\Migration\Exception\MigrationOperationException;
use SymPress\WordPress\Migration\Value\MigrationExecution;
use SymPress\WordPress\Migration\Value\MigrationKey;
use SymPress\WordPress\Migration\Value\MigrationRecord;
Expand Down Expand Up @@ -155,17 +156,13 @@ public function recordForMigration(PluginSlug $pluginSlug, MigrationContract $mi
continue;
}

if ($identity === MigrationKey::forMigration($migration)) {
return $record;
}

$records[] = $record;
}

$versions = array_unique(array_map(static fn (MigrationRecord $record): string => $record->version, $records));

if (count($versions) > 1) {
throw new \RuntimeException('Conflicting legacy migration versions; '
throw new MigrationOperationException('Conflicting legacy migration versions; '
. 'reconcile the exact mapped identities before execution.');
}

Expand All @@ -183,25 +180,40 @@ public function markMigrated(PluginSlug $pluginSlug, MigrationContract $migratio
return $this->runOperation($pluginSlug, [], fn (): bool => $this->markMigratedUnlocked($pluginSlug, $migration));
}

public function adoptLegacyMigration(PluginSlug $pluginSlug, MigrationContract $migration, string $legacyKey, string $expectedVersion): bool
public function adoptLegacyMigration(PluginSlug $pluginSlug, MigrationContract $migration, string $legacyKey, string $expectedVersion, bool $retireSuperseded = false): bool
{
$key = MigrationKey::forMigration($migration);
MigrationKey::assertStorageIdentity($legacyKey);
if (!str_contains($legacyKey, '@anonymous') || $legacyKey === $key || $expectedVersion === '') {
throw new \InvalidArgumentException(
'Adoption requires an exact anonymous legacy identity and its recorded version.',
);
}
return $this->runOperation($pluginSlug, [], function () use ($pluginSlug, $key, $legacyKey, $expectedVersion): bool {
return $this->runOperation($pluginSlug, [], function () use ($pluginSlug, $key, $legacyKey, $expectedVersion, $retireSuperseded): bool {
$legacy = $this->store->findRecord($pluginSlug->value, $legacyKey);
$current = $this->store->findRecord($pluginSlug->value, $key);
if (
$legacy === null || $legacy->version !== $expectedVersion
|| ($current !== null && $current->version !== $expectedVersion)
) {
throw new \RuntimeException(
throw new MigrationOperationException(
'Legacy state does not match the reviewed version or conflicts with the stable identity.',
);
}
if ($current !== null) {
if (!$retireSuperseded) {
throw new MigrationOperationException('Stable identity already exists; review this additional '
. 'legacy record and use --retire-superseded to retain the stable version.');
}
return $this->store->deleteRecord($pluginSlug->value, $legacyKey)
&& $this->store->appendHistory(
$this->createExecution($legacy, 'retire', $this->currentTimestamp()),
);
}
if ($retireSuperseded) {
throw new MigrationOperationException(
'--retire-superseded requires an existing adopted stable identity.',
);
}
$record = new MigrationRecord($pluginSlug->value, $key, $legacy->version, $legacy->migratedAt);
if (!$this->store->saveRecord($record) || !$this->store->deleteRecord($pluginSlug->value, $legacyKey)) {
return false;
Expand Down
21 changes: 14 additions & 7 deletions src/Application/MigrationStatusReporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ public function __construct(
* migrated: int,
* pending: int,
* executions: int,
* status: string
* status: string,
* diagnostic: string
* }>
*/
public function all(): array
Expand All @@ -45,9 +46,11 @@ public function all(): array
* migrated: int,
* pending: int,
* executions: int,
* status: string
* status: string,
* diagnostic: string
* },
* pending_migrations: list<array{class: string, name: string, version: string}>,
* legacy_issues: list<array<string, string>>,
* recent_history: list<array{
* plugin: string,
* migration: string,
Expand All @@ -68,7 +71,8 @@ public function plugin(string $pluginSlug): ?array

return [
'overview' => $this->overview($pluginSlug, $manager),
'pending_migrations' => $manager->getPendingMigrations(),
'pending_migrations' => $manager->getLegacyStateIssues() === [] ? $manager->getPendingMigrations() : [],
'legacy_issues' => $manager->getLegacyStateIssues(),
'recent_history' => array_slice($this->historyRows($manager), 0, 10),
];
}
Expand All @@ -81,22 +85,25 @@ public function plugin(string $pluginSlug): ?array
* migrated: int,
* pending: int,
* executions: int,
* status: string
* status: string,
* diagnostic: string
* }
*/
private function overview(string $pluginSlug, MigrationManager $manager): array
{
$current = $manager->getCurrentMigration();
$issues = $manager->getLegacyStateIssues();
$current = $issues === [] ? $manager->getCurrentMigration() : null;
$latest = $manager->getLatestMigration();

return [
'plugin' => $pluginSlug,
'current' => $current['version'] ?? 'none',
'latest' => $latest['version'] ?? 'none',
'migrated' => count($manager->getMigratedVersions()),
'pending' => count($manager->getPendingMigrations()),
'pending' => $issues === [] ? count($manager->getPendingMigrations()) : 0,
'executions' => count($manager->getMigrationHistory()),
'status' => $manager->isUpToDate() ? 'Up to Date' : 'Pending',
'status' => $issues !== [] ? 'Needs Adoption' : ($manager->isUpToDate() ? 'Up to Date' : 'Pending'),
'diagnostic' => implode("\n", array_column($issues, 'command')),
];
}

Expand Down
6 changes: 4 additions & 2 deletions src/Application/MigrationSystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ public function __construct(
\wpdb $database,
?MigrationTracker $tracker = null,
?MigrationManagerFactory $migrationManagerFactory = null,
int $lockTimeout = 10,
) {

$this->tracker = $tracker ?? new MigrationTracker($database);
$this->migrationManagerFactory = $migrationManagerFactory ?? new MigrationManagerFactory(
new MigrationLifecycle(
$this->getTracker(),
new WordPressSqlExecutor($database),
new WordPressSqlExecutor($database, $lockTimeout),
),
);
}
Expand All @@ -46,10 +47,11 @@ public static function bootstrap(
\wpdb $database,
?MigrationTracker $tracker = null,
?MigrationManagerFactory $migrationManagerFactory = null,
int $lockTimeout = 10,
): self {

if (self::$instance === null) {
self::$instance = new self($database, $tracker, $migrationManagerFactory);
self::$instance = new self($database, $tracker, $migrationManagerFactory, $lockTimeout);
}

return self::$instance;
Expand Down
11 changes: 10 additions & 1 deletion src/Cli/MigrationCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ public function version(array $args, array $assocArgs): void
* : Exact version already recorded for the old identity.
* --yes
* : Confirm the reviewed metadata adoption.
* [--retire-superseded]
* : Retire an additional reviewed legacy record while retaining the existing stable version.
*
* @param list<string> $args
* @param array<string, scalar|null> $assocArgs
Expand All @@ -163,7 +165,14 @@ public function adopt(array $args, array $assocArgs): void
}
$context = new MigrationCommandContext($this->registry);
$manager = $context->managerOrFail($context->requirePluginSlug($args, 'adopt'));
if (!$manager->adoptLegacyMigration($context->requireMigrationClass($args, 'adopt'), $legacy, $version)) {
if (
!$manager->adoptLegacyMigration(
$context->requireMigrationClass($args, 'adopt'),
$legacy,
$version,
isset($assocArgs['retire-superseded']),
)
) {
\WP_CLI::error('Legacy adoption failed; reconcile metadata before retrying.');
}
\WP_CLI::success('Legacy identity adopted; recorded version and existing history retained.');
Expand Down
8 changes: 6 additions & 2 deletions src/Cli/MigrationCommandExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace SymPress\WordPress\Migration\Cli;

use SymPress\WordPress\Migration\Domain\MigrationManager;
use SymPress\WordPress\Migration\Exception\MigrationOperationException;
use SymPress\WordPress\Migration\Infrastructure\WordPressSqlExecutor;
use WP_CLI;

final readonly class MigrationCommandExecutor
Expand Down Expand Up @@ -123,7 +125,9 @@ public function syncMetadataStorage(array $args): void
return;
}

if (!$this->context->tracker()->ensureTableExists()) {
$tracker = $this->context->tracker();
$executor = new WordPressSqlExecutor($this->context->database());
if (!$executor->runOperation('metadata', ['CREATE TABLE'], $tracker->ensureTableExists(...))) {
WP_CLI::error('Failed to sync metadata storage.');
}

Expand Down Expand Up @@ -184,7 +188,7 @@ private function migrateAllPlugins(): void
WP_CLI::success(sprintf('Completed migrations for "%s".', $slug));
continue;
}
} catch (\Throwable) {
} catch (MigrationOperationException) {
// Keep SQL, credentials and exception messages out of the CLI diagnostic.
}
$failed++;
Expand Down
12 changes: 11 additions & 1 deletion src/Cli/MigrationCommandReporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,16 @@ private function statusSinglePlugin(string $pluginSlug, bool $verbose, string $f
WP_CLI::log(sprintf('Pending: %d', $overview['pending']));
WP_CLI::log(sprintf('Executions: %d', $overview['executions']));

if ($report['legacy_issues'] !== []) {
WP_CLI::warning('Legacy migration state requires explicit review and adoption.');
\WP_CLI\Utils\format_items(
$format,
$report['legacy_issues'],
['legacy_base64', 'version', 'reason', 'command'],
);
return;
}

if ($verbose && $report['pending_migrations'] !== []) {
WP_CLI::log("\nPending migrations:");
\WP_CLI\Utils\format_items($format, $report['pending_migrations'], ['class', 'name', 'version']);
Expand Down Expand Up @@ -305,7 +315,7 @@ private function statusAllPlugins(string $format): void
\WP_CLI\Utils\format_items(
$format,
$rows,
['plugin', 'current', 'latest', 'migrated', 'pending', 'executions', 'status'],
['plugin', 'current', 'latest', 'migrated', 'pending', 'executions', 'status', 'diagnostic'],
);
}

Expand Down
Loading
Loading