From b8335b4649a0cf0929c2822fc2cd8da1d5e1fd0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Brian=20Sch=C3=A4ffner?= Date: Fri, 2 Oct 2026 21:50:16 +0200 Subject: [PATCH 1/2] Adopt reviewed legacy migration state and isolate plugin failures --- .github/workflows/database.yml | 18 +++++- CHANGELOG.md | 6 ++ docs/architecture.md | 23 +++++++ src/Application/MigrationLifecycle.php | 27 ++++++++ src/Cli/MigrationCommand.php | 44 ++++++++++++- src/Cli/MigrationCommandExecutor.php | 32 ++++++---- src/Domain/MigrationManager.php | 17 +++++ tests/Support/TestEnvironment.php | 9 +++ tests/Unit/Cli/MigrationCommandTest.php | 64 +++++++++++++++++++ tests/Unit/Migration/MigrationManagerTest.php | 50 +++++++++++++++ 10 files changed, 276 insertions(+), 14 deletions(-) diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml index 75b786f..a9967e0 100644 --- a/.github/workflows/database.yml +++ b/.github/workflows/database.yml @@ -13,17 +13,31 @@ permissions: jobs: database: + name: Database (${{ matrix.engine }}) + strategy: + fail-fast: false + matrix: + include: + - engine: MariaDB 11.8 + image: mariadb:11.8@sha256:79d59758afc91b89b120b0a8904d637f5a3b3e1c4900f29b740d6d46c72fef68 + health: healthcheck.sh --connect --innodb_initialized + - engine: MySQL 8.4 + image: mysql:8.4@sha256:80f4933e3835f9dc4d35a28ec500d7986cb4414e6c6821c5461239cb7beb8995 + health: mysqladmin ping -h 127.0.0.1 --silent runs-on: ubuntu-24.04 timeout-minutes: 15 services: database: - image: mariadb:11.8@sha256:79d59758afc91b89b120b0a8904d637f5a3b3e1c4900f29b740d6d46c72fef68 + image: ${{ matrix.image }} env: MARIADB_ROOT_PASSWORD: sympress-database-test-only MARIADB_DATABASE: sympress_review_migration + MYSQL_ROOT_PASSWORD: sympress-database-test-only + MYSQL_DATABASE: sympress_review_migration + MYSQL_ROOT_HOST: '%' ports: ['3306:3306'] options: >- - --health-cmd="healthcheck.sh --connect --innodb_initialized" + --health-cmd="${{ matrix.health }}" --health-interval=10s --health-timeout=5s --health-retries=10 env: CI: 'true' diff --git a/CHANGELOG.md b/CHANGELOG.md index 867829b..b2071c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ 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 + +- Continue other plugins after a failed migration, then return a failing aggregate CLI result. +- Add administrator-only `wp migration adopt` for an explicitly confirmed exact legacy identity/version; retain the recorded version and append-only history without migration SQL. +- Run real database contracts against pinned MySQL 8.4 and MariaDB 11.8 services. + ## 1.0.6 — 2026-10-02 - Document the two narrowly scoped WordPress Plugin Check exceptions for the private temporary CSV-formatting stream; WordPress file-operation checks remain enabled elsewhere. diff --git a/docs/architecture.md b/docs/architecture.md index 1f2ea07..321c68c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -91,6 +91,29 @@ incomplete tests and runs on pull requests, main and the weekly schedule. ## Identity, deployment and table scoping +`wp migration migrate` with no plugin catches failures per plugin, continues the +remaining registrations and returns a nonzero aggregate result. Each individual +plugin still stops at its first failed migration; no failed migration is marked +applied. Failure diagnostics contain the plugin slug without SQL/credential data. + +An administrator can adopt one reviewed anonymous legacy record explicitly: + +```sh +wp --user= migration adopt orm-schema: \ + --legacy-base64= \ + --expected-version= --yes +``` + +Base64 transports PHP's NUL-separated identity unchanged. The target must be an +exact registered stable key. Adoption validates the recorded version and any +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. +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. diff --git a/src/Application/MigrationLifecycle.php b/src/Application/MigrationLifecycle.php index ec8362a..be7152a 100644 --- a/src/Application/MigrationLifecycle.php +++ b/src/Application/MigrationLifecycle.php @@ -183,6 +183,33 @@ 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 + { + $key = MigrationKey::forMigration($migration); + 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 { + $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( + 'Legacy state does not match the reviewed version or conflicts with the 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; + } + return $this->store->appendHistory($this->createExecution($record, 'adopt', $this->currentTimestamp())); + }); + } + private function markMigratedUnlocked(PluginSlug $pluginSlug, MigrationContract $migration): bool { $existingRecord = $this->recordForMigration($pluginSlug, $migration); diff --git a/src/Cli/MigrationCommand.php b/src/Cli/MigrationCommand.php index 4ad5866..0dbccdf 100644 --- a/src/Cli/MigrationCommand.php +++ b/src/Cli/MigrationCommand.php @@ -12,7 +12,7 @@ private MigrationCommandReporter $reporter; public function __construct( - ?MigrationRegistry $registry = null, + private ?MigrationRegistry $registry = null, ?SymfonyConsoleRunner $consoleRunner = null, ) { @@ -127,6 +127,48 @@ public function version(array $args, array $assocArgs): void $this->executor->version($args, $assocArgs); } + /** + * Adopt one reviewed legacy identity without running migration SQL. + * + * ## OPTIONS + * + * + * : Registered plugin slug. + * + * : Exact registered stable migration key. + * --legacy-base64= + * : Base64 encoded exact old identity, including binary bytes. + * --expected-version= + * : Exact version already recorded for the old identity. + * --yes + * : Confirm the reviewed metadata adoption. + * + * @param list $args + * @param array $assocArgs + */ + public function adopt(array $args, array $assocArgs): void + { + if (!function_exists('current_user_can') || !current_user_can('manage_options')) { + \WP_CLI::error('Adoption requires a loaded WordPress administrator; select one with --user.'); + } + if (($assocArgs['yes'] ?? false) !== true) { + \WP_CLI::error('Adoption requires explicit --yes confirmation after reviewing the legacy state.'); + } + $encoded = $assocArgs['legacy-base64'] ?? null; + // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Exact binary identity transport, no executable payload. + $legacy = is_string($encoded) ? base64_decode($encoded, true) : false; + $version = $assocArgs['expected-version'] ?? null; + if ($legacy === false || $legacy === '' || !is_string($version) || $version === '') { + \WP_CLI::error('Provide the exact --legacy-base64 identity and --expected-version.'); + } + $context = new MigrationCommandContext($this->registry); + $manager = $context->managerOrFail($context->requirePluginSlug($args, 'adopt')); + if (!$manager->adoptLegacyMigration($context->requireMigrationClass($args, 'adopt'), $legacy, $version)) { + \WP_CLI::error('Legacy adoption failed; reconcile metadata before retrying.'); + } + \WP_CLI::success('Legacy identity adopted; recorded version and existing history retained.'); + } + /** * Show migration status. * diff --git a/src/Cli/MigrationCommandExecutor.php b/src/Cli/MigrationCommandExecutor.php index 4193ec4..a37b7de 100644 --- a/src/Cli/MigrationCommandExecutor.php +++ b/src/Cli/MigrationCommandExecutor.php @@ -171,21 +171,31 @@ private function migrateAllPlugins(): void } $processed = 0; + $failed = 0; foreach ($managers as $slug => $manager) { - if (!$manager->hasPendingMigrations()) { - continue; - } - - $processed++; - WP_CLI::log(sprintf('Running pending migrations for "%s"...', $slug)); - - if ($manager->runMigrations()) { - WP_CLI::success(sprintf('Completed migrations for "%s".', $slug)); - continue; + try { + if (!$manager->hasPendingMigrations()) { + continue; + } + $processed++; + WP_CLI::log(sprintf('Running pending migrations for "%s"...', $slug)); + if ($manager->runMigrations()) { + WP_CLI::success(sprintf('Completed migrations for "%s".', $slug)); + continue; + } + } catch (\Throwable) { + // Keep SQL, credentials and exception messages out of the CLI diagnostic. } + $failed++; + WP_CLI::warning(sprintf('Migration failed for "%s"; reconcile its state before retrying.', $slug)); + } - WP_CLI::error(sprintf('Migration failed for "%s".', $slug)); + if ($failed > 0) { + WP_CLI::error(sprintf( + 'Migrations failed for %d plugin(s); other registered plugins were processed.', + $failed, + )); } if ($processed === 0) { diff --git a/src/Domain/MigrationManager.php b/src/Domain/MigrationManager.php index c4bcbe5..0d8ca5c 100644 --- a/src/Domain/MigrationManager.php +++ b/src/Domain/MigrationManager.php @@ -180,6 +180,23 @@ public function markMigration(string $migrationClass, string $direction): bool return false; } + public function adoptLegacyMigration(string $migrationKey, string $legacyKey, string $expectedVersion): bool + { + $migration = $this->getMigration($migrationKey); + if ($migration === null || MigrationKey::forMigration($migration) !== $migrationKey) { + throw new \InvalidArgumentException('Adoption requires the exact registered stable migration key.'); + } + foreach ($this->migrations->all() as $other) { + if ($other !== $migration && in_array($legacyKey, MigrationKey::identities($other), true)) { + throw new \InvalidArgumentException('Legacy identity already belongs to another registered migration.'); + } + } + if (!$this->lifecycle->ensureStorageIsReady()) { + return false; + } + return $this->lifecycle->adoptLegacyMigration($this->pluginSlug, $migration, $legacyKey, $expectedVersion); + } + public function needsUpdate(string $migrationClass): bool { $migration = $this->getMigration($migrationClass); diff --git a/tests/Support/TestEnvironment.php b/tests/Support/TestEnvironment.php index f7790e5..6f638b9 100644 --- a/tests/Support/TestEnvironment.php +++ b/tests/Support/TestEnvironment.php @@ -26,6 +26,7 @@ final class WordPressState public static string $currentTime = '2026-03-27 12:00:00'; public static string $environmentType = 'development'; + public static bool $administrator = false; public static function reset(): void { @@ -41,6 +42,7 @@ public static function reset(): void ]; self::$currentTime = '2026-03-27 12:00:00'; self::$environmentType = 'development'; + self::$administrator = false; } } } @@ -49,6 +51,13 @@ public static function reset(): void use SymPress\WordPress\Migration\Tests\Support\WordPressState; + if (!function_exists('current_user_can')) { + function current_user_can(string $capability): bool + { + return $capability === 'manage_options' && WordPressState::$administrator; + } + } + if (!function_exists('wp_get_environment_type')) { function wp_get_environment_type(): string { diff --git a/tests/Unit/Cli/MigrationCommandTest.php b/tests/Unit/Cli/MigrationCommandTest.php index a097594..d454e3b 100644 --- a/tests/Unit/Cli/MigrationCommandTest.php +++ b/tests/Unit/Cli/MigrationCommandTest.php @@ -54,6 +54,70 @@ public function test_run_executes_pending_migrations(): void ); } + public function testAllPluginsContinuesAfterThrownAndReturnedFailuresAndReportsFailure(): void + { + $registry = MigrationRegistry::getInstance(); + $registry->clear(); + foreach (['throws', 'returns-false'] as $slug) { + $failed = new class ($slug, $this->database) extends MigrationManager { + public function __construct(private string $mode, \wpdb $database) + { + parent::__construct(\SymPress\WordPress\Migration\Value\PluginSlug::fromString($mode), new \SymPress\WordPress\Migration\Application\MigrationLifecycle(new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($database), new \SymPress\WordPress\Migration\Infrastructure\WordPressSqlExecutor($database))); + } + public function hasPendingMigrations(): bool { return true; } + public function runMigrations(): bool + { + if ($this->mode === 'throws') { throw new \RuntimeException('credentialSentinel'); } + return false; + } + }; + $registry->set($slug, $failed); + } + $registry->set('my-plugin', $this->manager); + try { + $this->command->migrate([]); + self::fail('Aggregate failure must return a failing CLI result.'); + } catch (\RuntimeException $exception) { + self::assertStringContainsString('2 plugin(s)', $exception->getMessage()); + } + self::assertFalse($this->manager->hasPendingMigrations()); + self::assertCount(2, WordPressState::$cliCalls['warning']); + self::assertStringNotContainsString('credentialSentinel', json_encode(WordPressState::$cliCalls, JSON_THROW_ON_ERROR)); + } + + public function testAdoptionRequiresAdministratorAndExplicitConfirmationBeforeStorageMutation(): void + { + foreach ([false, true] as $administrator) { + WordPressState::$administrator = $administrator; + try { + $this->command->adopt(['my-plugin', 'stable'], []); + self::fail('Unconfirmed or unprivileged adoption accepted.'); + } catch (\RuntimeException) { + self::assertSame([], $this->manager->getMigratedVersions()); + } + } + self::assertFalse($this->database->hasTable('wp_migrations')); + } + + public function testAdministratorCanAdoptTheExactBinaryLegacyIdentityWithoutExecutingSql(): void + { + $legacy = "Migration@anonymous\0/old/release.php:40"; + $tracker = new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($this->database); + self::assertTrue($tracker->record('my-plugin', $legacy, '0.9.0')); + WordPressState::$administrator = true; + $this->command->adopt(['my-plugin', CreateCustomersTableMigration::class], [ + 'legacy-base64' => base64_encode($legacy), + 'expected-version' => '0.9.0', + 'yes' => true, + ]); + self::assertNull($tracker->getVersion('my-plugin', $legacy)); + self::assertSame('0.9.0', $tracker->getVersion('my-plugin', CreateCustomersTableMigration::class)); + self::assertFalse($this->database->hasTable('wp_customers')); + self::assertTrue($this->manager->hasPendingMigrations()); + self::assertSame('adopt', $this->manager->getMigrationHistory()[0]['direction']); + self::assertCount(1, WordPressState::$cliCalls['success']); + } + public function test_migrate_can_target_a_specific_version(): void { $this->command->migrate(['my-plugin', '1.0.0']); diff --git a/tests/Unit/Migration/MigrationManagerTest.php b/tests/Unit/Migration/MigrationManagerTest.php index 4c9a8a0..2b87806 100644 --- a/tests/Unit/Migration/MigrationManagerTest.php +++ b/tests/Unit/Migration/MigrationManagerTest.php @@ -303,6 +303,56 @@ public function testDistinctKeysFromOneDeclarationBothExecuteAndClassLookupIsAmb $manager->runMigration($first::class); } + public function testAdoptionRetainsRecordedVersionAndHistoryWithoutExecutingMigrationSql(): void + { + $legacy = "Migration@anonymous\0/old/release/SchemaMigrationFactory.php:40"; + $tracker = new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($this->database); + self::assertTrue($tracker->record('my-plugin', $legacy, 'schema:old')); + self::assertTrue($tracker->appendHistory(new \SymPress\WordPress\Migration\Value\MigrationExecution('my-plugin', $legacy, 'schema:old', 'up', '2026-09-01 12:00:00'))); + $manager = $this->createMigrationManager($this->database, [$this->identityMigration('orm-schema:default', 'schema:new')]); + self::assertTrue($manager->adoptLegacyMigration('orm-schema:default', $legacy, 'schema:old')); + self::assertNull($tracker->getVersion('my-plugin', $legacy)); + self::assertSame('schema:old', $tracker->getVersion('my-plugin', 'orm-schema:default')); + self::assertTrue($manager->hasPendingMigrations()); + self::assertSame(['adopt', 'up'], array_column($manager->getMigrationHistory(), 'direction')); + self::assertSame($legacy, $manager->getMigrationHistory()[1]['migration']); + self::assertNotContains('SELECT orm-schema:default', $this->database->executedStatements); + } + + public function testAdoptionCannotTakeAnIdentityMappedToAnotherMigration(): void + { + $legacy = "Migration@anonymous\0/old/release.php:40"; + $tracker = new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($this->database); + self::assertTrue($tracker->record('my-plugin', $legacy, 'schema:old')); + $manager = $this->createMigrationManager($this->database, [ + $this->identityMigration('orm-schema:default', 'schema:new'), + $this->identityMigration('other-schema', 'schema:old', [$legacy]), + ]); + try { + $manager->adoptLegacyMigration('orm-schema:default', $legacy, 'schema:old'); + self::fail('Identity belonging to another migration was adopted.'); + } catch (\InvalidArgumentException) { + self::assertSame('schema:old', $tracker->getVersion('my-plugin', $legacy)); + self::assertNull($tracker->getVersion('my-plugin', 'orm-schema:default')); + } + } + + public function testAdoptionRejectsChangedVersionBeforeRetiringLegacyIdentity(): void + { + $legacy = "Migration@anonymous\0/old/release.php:40"; + $tracker = new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($this->database); + self::assertTrue($tracker->record('my-plugin', $legacy, 'schema:changed')); + $manager = $this->createMigrationManager($this->database, [$this->identityMigration('orm-schema:default', 'schema:new')]); + try { + $manager->adoptLegacyMigration('orm-schema:default', $legacy, 'schema:reviewed'); + self::fail('Changed legacy version accepted.'); + } catch (\RuntimeException) { + self::assertSame('schema:changed', $tracker->getVersion('my-plugin', $legacy)); + self::assertNull($tracker->getVersion('my-plugin', 'orm-schema:default')); + self::assertSame([], $manager->getMigrationHistory()); + } + } + public function testUnknownLegacyAnonymousStateStopsBeforeAnyMigrationSql(): void { $tracker = new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($this->database); From 43820e4dc93822b167db128735a6ab89c11b52a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Brian=20Sch=C3=A4ffner?= Date: Fri, 2 Oct 2026 21:54:33 +0200 Subject: [PATCH 2/2] docs: prepare reviewed patch release notes --- CHANGELOG.md | 2 +- migration.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2071c1..60953ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ 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 +## 1.0.7 — 2026-10-02 - Continue other plugins after a failed migration, then return a failing aggregate CLI result. - Add administrator-only `wp migration adopt` for an explicitly confirmed exact legacy identity/version; retain the recorded version and append-only history without migration SQL. diff --git a/migration.php b/migration.php index 4d71e50..0f2b890 100644 --- a/migration.php +++ b/migration.php @@ -3,7 +3,7 @@ /** * Plugin Name: Database Migration System * Description: Standalone MU plugin for versioned WordPress database migrations. - * Version: 1.0.6 + * Version: 1.0.7 * Requires at least: 6.9 * Requires PHP: 8.5 * Author: Brian Schaeffner