From fbebdaa6779ad3e11c3630d2a68893752d83eb6e Mon Sep 17 00:00:00 2001 From: Artur Kyryliuk Date: Sat, 5 Dec 2026 23:12:44 +0100 Subject: [PATCH 1/2] fix(migrations): fit indexed columns to the MyISAM key limit MyISAM allows 1000 bytes per index key. The indexed VARCHAR(255) columns need 1020 in utf8mb4, and s_tasks (identifier, action) is over the limit even in utf8mb3, so installing sTask on a MyISAM site stopped with error 1071. The create then left its table behind without keys, and the next migrate skipped the existing table (hasTable) and recorded it. - Create migrations size the indexed strings so every key fits: identifier 128, scope 128, action 96, priority 16. - 2026_12_06_000000_fit_indexed_columns_to_myisam restores missing indexes on MySQL: it shortens a column only where no stored value is longer, and skips a unique key whose rows share a value; tables with all keys stay as they are. - The models refuse longer values (FitsIndexedColumns, INDEXED_LENGTHS), and the task API validates them, so a non-strict session never cuts them. - tests/myisam.php: lengths, key budget and the guard always; installs on MyISAM utf8mb4/utf8mb3 and InnoDB and the repair with STASK_TEST_MYSQL. tests/bootstrap.php maps every class of the checkout. Co-Authored-By: Claude Opus 5.5 --- .../2025_10_15_000000_create_task_tables.php | 14 +- ..._000000_create_supervisor_states_table.php | 3 +- ...6_000000_fit_indexed_columns_to_myisam.php | 158 ++++++++++ src/Controllers/sTaskController.php | 4 +- src/Models/Concerns/FitsIndexedColumns.php | 36 +++ src/Models/sSupervisorState.php | 6 + src/Models/sTaskModel.php | 6 + src/Models/sWorker.php | 6 + tests/README.md | 12 + tests/bootstrap.php | 14 +- tests/myisam.php | 290 ++++++++++++++++++ tests/run.php | 1 + 12 files changed, 535 insertions(+), 15 deletions(-) create mode 100644 database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php create mode 100644 src/Models/Concerns/FitsIndexedColumns.php create mode 100644 tests/myisam.php diff --git a/database/migrations/2025_10_15_000000_create_task_tables.php b/database/migrations/2025_10_15_000000_create_task_tables.php index c6c7337..5ac83d7 100644 --- a/database/migrations/2025_10_15_000000_create_task_tables.php +++ b/database/migrations/2025_10_15_000000_create_task_tables.php @@ -9,6 +9,10 @@ /** * Create the queue tables while retaining workers and tasks already stored by Evolution. * Permissions and groups are handled by a separate migration. + * + * Indexed strings are sized so every key fits the MyISAM limit of 1000 bytes in utf8mb4 (4 bytes a + * character): identifier 128, scope 128, action 96 (identifier + action: 896 bytes), priority 16. + * The models refuse longer values (INDEXED_LENGTHS). */ return new class extends Migration { /** Create each missing table independently so a partial installation can be repaired. */ @@ -45,8 +49,8 @@ private function createWorkersTable(): void $table->comment('Workers for sTask'); $table->id(); $table->uuid('uuid')->nullable()->unique(); - $table->string('identifier')->unique(); - $table->string('scope')->default(''); + $table->string('identifier', 128)->unique(); + $table->string('scope', 128)->default(''); $table->string('class'); $table->boolean('active')->default(false); $table->unsignedInteger('position')->default(0); @@ -71,8 +75,8 @@ private function createTasksTable(): void Schema::create('s_tasks', function (Blueprint $table) { $table->comment('Async tasks for sTask'); $table->bigIncrements('id'); - $table->string('identifier'); - $table->string('action'); + $table->string('identifier', 128); + $table->string('action', 96); $table->unsignedSmallInteger('status')->default(10); $table->text('message')->nullable(); $table->unsignedInteger('started_by')->nullable(); @@ -82,7 +86,7 @@ private function createTasksTable(): void $table->timestamp('finished_at')->nullable(); $table->integer('attempts')->default(0); $table->integer('max_attempts')->default(3); - $table->string('priority')->default('normal'); + $table->string('priority', 16)->default('normal'); $table->integer('progress')->default(0); $table->timestamps(); diff --git a/database/migrations/2026_07_16_000000_create_supervisor_states_table.php b/database/migrations/2026_07_16_000000_create_supervisor_states_table.php index abb7e57..714e37d 100644 --- a/database/migrations/2026_07_16_000000_create_supervisor_states_table.php +++ b/database/migrations/2026_07_16_000000_create_supervisor_states_table.php @@ -24,7 +24,8 @@ public function up(): void $table->comment('Live state and diagnostic cursor for sTask supervisors'); $table->bigIncrements('id'); $table->unsignedBigInteger('worker_id'); - $table->string('identifier'); + // 128: the key fits the MyISAM limit of 1000 bytes in utf8mb4, as s_workers.identifier + $table->string('identifier', 128); $table->string('supervisor_key'); $table->char('key_hash', 64)->unique(); $table->string('state', 24)->default('stopped'); diff --git a/database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php b/database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php new file mode 100644 index 0000000..8762c7b --- /dev/null +++ b/database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php @@ -0,0 +1,158 @@ + characters and how the create migrations define it. */ + private const COLUMNS = [ + 's_workers' => ['identifier' => [128, null], 'scope' => [128, '']], + 's_tasks' => ['identifier' => [128, null], 'action' => [96, null], 'priority' => [16, 'normal']], + 's_supervisor_states' => ['identifier' => [128, null]], + ]; + + /** Indexes of the create migrations: [unique?, columns]. */ + private const INDEXES = [ + 's_workers' => [ + [true, ['uuid']], [true, ['identifier']], [false, ['identifier']], + [false, ['scope']], [false, ['active']], [false, ['position']], + ], + 's_tasks' => [ + [false, ['identifier', 'action']], [false, ['status']], [false, ['started_by']], + [false, ['start_at']], [false, ['created_at']], [false, ['priority']], + ], + 's_supervisor_states' => [ + [true, ['key_hash']], [false, ['worker_id']], [false, ['identifier']], + [false, ['state']], [false, ['last_seen_at']], + ], + ]; + + public function up(): void + { + if (!in_array(DB::connection()->getDriverName(), ['mysql', 'mariadb'], true)) { + return; + } + + foreach (self::INDEXES as $table => $indexes) { + if (Schema::hasTable($table)) { + $this->repair($table, $indexes); + } + } + } + + public function down(): void + { + // the indexes belong to the tables; nothing to undo + } + + /** + * @param array}> $indexes + */ + private function repair(string $table, array $indexes): void + { + $missing = array_values(array_filter($indexes, fn (array $index): bool => !$this->hasIndex($table, $index[0], $index[1]))); + if ($missing === []) { + return; + } + + $lengths = []; + foreach (Schema::getColumns($table) as $column) { + if (preg_match('/^varchar\((\d+)\)/i', (string) ($column['type'] ?? ''), $match)) { + $lengths[$column['name']] = (int) $match[1]; + } + } + + $tooLong = []; + $shorten = []; + foreach (self::COLUMNS[$table] as $name => [$length, $default]) { + if (($lengths[$name] ?? 0) <= $length) { + continue; + } + $longest = (int) DB::table($table)->max(DB::raw('CHAR_LENGTH(' . DB::getQueryGrammar()->wrap($name) . ')')); + if ($longest > $length) { + $tooLong[] = $name; + } else { + $shorten[$name] = [$length, $default]; + } + } + + if ($shorten !== []) { + Schema::table($table, function (Blueprint $blueprint) use ($shorten): void { + foreach ($shorten as $name => [$length, $default]) { + $column = $blueprint->string($name, $length); + if ($default !== null) { + $column->default($default); + } + $column->change(); + } + }); + } + + $add = []; + foreach ($missing as [$unique, $columns]) { + if (array_intersect($columns, $tooLong) !== []) { + $this->report("{$table}: no index on " . implode(', ', $columns) . ': a stored value is longer than the key allows.'); + continue; + } + if ($unique && DB::table($table)->select($columns)->groupBy($columns)->havingRaw('COUNT(*) > 1')->exists()) { + $this->report("{$table}: no unique key on " . implode(', ', $columns) . ': rows share a value.'); + continue; + } + $add[] = [$unique, $columns]; + } + + if ($add !== []) { + Schema::table($table, function (Blueprint $blueprint) use ($add): void { + foreach ($add as [$unique, $columns]) { + $unique ? $blueprint->unique($columns) : $blueprint->index($columns); + } + }); + } + } + + /** + * Whether an index covers exactly these columns, unique where the create made it unique. s_workers + * has both a unique key and a plain index on identifier, so a unique key stands in for a plain index + * only where the create made no unique key on the same columns. + * + * @param list $columns + */ + private function hasIndex(string $table, bool $unique, array $columns): bool + { + $uniqueMayServe = !in_array([true, $columns], self::INDEXES[$table], true); + foreach (Schema::getIndexes($table) as $index) { + if ($index['primary'] || $index['columns'] !== $columns) { + continue; + } + if ($unique ? $index['unique'] : (!$index['unique'] || $uniqueMayServe)) { + return true; + } + } + + return false; + } + + private function report(string $message): void + { + try { + Log::warning('sTask migration: ' . $message); + } catch (\Throwable $exception) { + // the log is not bound in every context a migration runs in + } + } +}; diff --git a/src/Controllers/sTaskController.php b/src/Controllers/sTaskController.php index 70ef93b..bc85da6 100644 --- a/src/Controllers/sTaskController.php +++ b/src/Controllers/sTaskController.php @@ -79,8 +79,8 @@ public function create(Request $request) $this->authorizeStask(); $request->validate([ - 'identifier' => 'required|string', - 'action' => 'required|string', + 'identifier' => 'required|string|max:' . sTaskModel::INDEXED_LENGTHS['identifier'], + 'action' => 'required|string|max:' . sTaskModel::INDEXED_LENGTHS['action'], 'data' => 'array', 'priority' => 'in:low,normal,high', ]); diff --git a/src/Models/Concerns/FitsIndexedColumns.php b/src/Models/Concerns/FitsIndexedColumns.php new file mode 100644 index 0000000..3b3abcd --- /dev/null +++ b/src/Models/Concerns/FitsIndexedColumns.php @@ -0,0 +1,36 @@ + characters). + * + * @since 2.3.3 + */ +trait FitsIndexedColumns +{ + protected static function bootFitsIndexedColumns(): void + { + static::saving(static function (Model $model): void { + foreach (static::INDEXED_LENGTHS as $column => $length) { + $value = $model->getAttribute($column); + if (is_string($value) && mb_strlen($value) > $length) { + throw new InvalidArgumentException(sprintf( + '%s.%s holds at most %d characters, %d given.', + $model->getTable(), + $column, + $length, + mb_strlen($value) + )); + } + } + }); + } +} diff --git a/src/Models/sSupervisorState.php b/src/Models/sSupervisorState.php index 7339ef5..582d599 100644 --- a/src/Models/sSupervisorState.php +++ b/src/Models/sSupervisorState.php @@ -2,6 +2,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Seiger\sTask\Models\Concerns\FitsIndexedColumns; /** * Persisted live state and diagnostic deduplication cursor for one supervisor. @@ -11,6 +12,11 @@ */ class sSupervisorState extends Model { + use FitsIndexedColumns; + + /** Characters of the indexed string columns (create migration: keys within the MyISAM limit). */ + public const INDEXED_LENGTHS = ['identifier' => sWorker::INDEXED_LENGTHS['identifier']]; + /** @var string */ protected $table = 's_supervisor_states'; diff --git a/src/Models/sTaskModel.php b/src/Models/sTaskModel.php index 300b033..0c11526 100644 --- a/src/Models/sTaskModel.php +++ b/src/Models/sTaskModel.php @@ -3,6 +3,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use EvolutionCMS\Models\User; +use Seiger\sTask\Models\Concerns\FitsIndexedColumns; /** * Class sTaskModel @@ -16,6 +17,11 @@ */ class sTaskModel extends Model { + use FitsIndexedColumns; + + /** Characters of the indexed string columns (create migration: keys within the MyISAM limit). */ + public const INDEXED_LENGTHS = ['identifier' => sWorker::INDEXED_LENGTHS['identifier'], 'action' => 96, 'priority' => 16]; + // Task status constants public const TASK_STATUS_QUEUED = 10; // Task is queued for execution public const TASK_STATUS_PREPARING = 30; // Task is being prepared diff --git a/src/Models/sWorker.php b/src/Models/sWorker.php index a49f9ec..21d72c9 100644 --- a/src/Models/sWorker.php +++ b/src/Models/sWorker.php @@ -2,6 +2,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use Seiger\sTask\Models\Concerns\FitsIndexedColumns; /** * Class sWorker @@ -14,6 +15,11 @@ */ class sWorker extends Model { + use FitsIndexedColumns; + + /** Characters of the indexed string columns (create migration: keys within the MyISAM limit). */ + public const INDEXED_LENGTHS = ['identifier' => 128, 'scope' => 128]; + protected $table = 's_workers'; protected $fillable = [ diff --git a/tests/README.md b/tests/README.md index 22f52f1..ee4687b 100644 --- a/tests/README.md +++ b/tests/README.md @@ -94,3 +94,15 @@ The large fixture stores 120 tasks with approximately 1 MiB of combined Omit `--large` for the small functional fixture. Duration/memory metrics that were already placeholders remain placeholders; their zero values are not measured usage. + +## MyISAM key limit + +`tests/myisam.php` (also run by `tests/run.php`) checks that the indexed string columns of the create +migrations match the models' `INDEXED_LENGTHS`, that every key fits the MyISAM limit of 1000 bytes in +utf8mb4, and that the models refuse longer values. With a MySQL or MariaDB server it also installs on +MyISAM utf8mb4, MyISAM utf8mb3 and InnoDB, and repairs tables a failed MyISAM create left without keys; +each run uses a database of its own and drops it: + +```sh +STASK_TEST_MYSQL=user:password@host:port STASK_AUTOLOAD=/path/to/core/vendor/autoload.php php tests/myisam.php +``` diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 6e6650c..9db414a 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -26,13 +26,13 @@ function app($abstract = null, array $parameters = []) $loader = require $autoload; $loader->addPsr4('Seiger\\sTask\\', dirname(__DIR__) . '/src/', true); -foreach ($loader->getClassMap() as $class => $file) { - if (str_starts_with($class, 'Seiger\\sTask\\')) { - $localFile = dirname(__DIR__) . '/src/' - . str_replace('\\', '/', substr($class, strlen('Seiger\\sTask\\'))) . '.php'; - if (is_file($localFile)) { - $loader->addClassMap([$class => $localFile]); - } +// Every class of this checkout, including ones the site's (authoritative) class map does not know yet. +$sourceRoot = dirname(__DIR__) . '/src/'; +$sources = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourceRoot, FilesystemIterator::SKIP_DOTS)); +foreach ($sources as $source) { + if ($source->getExtension() === 'php') { + $relative = substr(str_replace('\\', '/', $source->getPathname()), strlen(str_replace('\\', '/', $sourceRoot)), -4); + $loader->addClassMap(['Seiger\\sTask\\' . str_replace('/', '\\', $relative) => $source->getPathname()]); } } if (realpath((new ReflectionClass(\Seiger\sTask\Services\SupervisorService::class))->getFileName()) diff --git a/tests/myisam.php b/tests/myisam.php new file mode 100644 index 0000000..c89bf4f --- /dev/null +++ b/tests/myisam.php @@ -0,0 +1,290 @@ +unique()") + && str_contains($createTasks, "string('scope', " . sWorker::INDEXED_LENGTHS['scope'] . ')') + && str_contains($createTasks, "string('identifier', " . sTaskModel::INDEXED_LENGTHS['identifier'] . ');') + && str_contains($createTasks, "string('action', " . sTaskModel::INDEXED_LENGTHS['action'] . ')') + && str_contains($createTasks, "string('priority', " . sTaskModel::INDEXED_LENGTHS['priority'] . ')') + && str_contains($createStates, "string('identifier', " . sSupervisorState::INDEXED_LENGTHS['identifier'] . ')'), + 'Create migrations use the indexed lengths of the models' +); +$myisamCheck( + max(sWorker::INDEXED_LENGTHS) * 4 <= 1000 + && (sTaskModel::INDEXED_LENGTHS['identifier'] + sTaskModel::INDEXED_LENGTHS['action']) * 4 <= 1000 + && sSupervisorState::INDEXED_LENGTHS['identifier'] * 4 <= 1000, + 'Every key fits the MyISAM limit in utf8mb4' +); + +/** Capsule with facades, Eloquent events and the Evolution tables the permission migration needs. */ +$bootDatabase = static function (array $connection): array { + $container = new Container(); + Container::setInstance($container); + $database = new Capsule($container); + $database->addConnection($connection); + $database->setEventDispatcher(new Dispatcher($container)); + $database->setAsGlobal(); + $database->bootEloquent(); + // models booted by an earlier fixture without a dispatcher would skip their saving listeners + \Illuminate\Database\Eloquent\Model::clearBootedModels(); + $container->instance('db', $database->getDatabaseManager()); + $container->instance('db.schema', $database->schema()); + Facade::clearResolvedInstances(); + Facade::setFacadeApplication($container); + $schema = $database->schema(); + $schema->create('permissions_groups', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name', 100); + $table->string('lang_key', 100); + $table->timestamps(); + }); + $schema->create('permissions', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('key', 100)->unique(); + $table->string('name', 100); + $table->string('lang_key', 100); + $table->unsignedInteger('group_id'); + $table->boolean('disabled'); + $table->timestamps(); + }); + $schema->create('role_permissions', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('role_id'); + $table->string('permission', 100); + $table->timestamps(); + }); + $repository = new DatabaseMigrationRepository($database->getDatabaseManager(), 'migrations'); + $repository->createRepository(); + + return [$database, $repository, new Migrator($repository, $database->getDatabaseManager(), new Filesystem())]; +}; + +$refuses = static function (callable $save): bool { + try { + $save(); + } catch (InvalidArgumentException $exception) { + return true; + } + + return false; +}; + +[$db, , $migrator] = $bootDatabase(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'evo_']); +$migrator->run([$migrationDirectory]); +$myisamCheck( + $refuses(static fn () => sWorker::query()->create(['identifier' => str_repeat('w', 129), 'class' => 'LongWorker'])) + && sWorker::query()->create(['identifier' => str_repeat('w', 128), 'class' => 'FittingWorker'])->exists, + 'A worker identifier longer than its column is refused' +); +$myisamCheck( + $refuses(static fn () => sTaskModel::query()->create(['identifier' => 'gallery', 'action' => str_repeat('a', 97)])) + && $refuses(static fn () => sTaskModel::query()->create(['identifier' => 'gallery', 'action' => 'optimize', 'priority' => str_repeat('p', 17)])) + && sTaskModel::query()->create(['identifier' => 'gallery', 'action' => str_repeat('a', 96)])->exists, + 'A task action or priority longer than its column is refused' +); +$myisamCheck( + $refuses(static fn () => sSupervisorState::query()->create(['worker_id' => 1, 'identifier' => str_repeat('s', 129), 'supervisor_key' => 'main', 'key_hash' => str_repeat('a', 64)])), + 'A supervisor identifier longer than its column is refused' +); + +$server = (string) getenv('STASK_TEST_MYSQL'); +if ($server === '' || !extension_loaded('pdo_mysql')) { + echo "SKIP MySQL key-limit checks (set STASK_TEST_MYSQL=user:password@host:port)\n"; + echo "sTask MyISAM regressions OK ({$myisamChecks} assertions)\n"; + + return; +} + +$url = parse_url('mysql://' . $server); +$mysql = [ + 'driver' => 'mysql', + 'host' => $url['host'] ?? '127.0.0.1', + 'port' => (int) ($url['port'] ?? 3306), + 'username' => urldecode($url['user'] ?? 'root'), + 'password' => urldecode($url['pass'] ?? ''), + 'prefix' => 'evo_', + 'strict' => false, +]; +$freshDatabase = static function (string $engine, string $charset, string $collation) use ($mysql, $bootDatabase): array { + $name = 'stask_myisam_' . getmypid(); + $root = new PDO('mysql:host=' . $mysql['host'] . ';port=' . $mysql['port'], $mysql['username'], $mysql['password']); + $root->exec("DROP DATABASE IF EXISTS `{$name}`"); + $root->exec("CREATE DATABASE `{$name}` CHARACTER SET {$charset} COLLATE {$collation}"); + + return $bootDatabase($mysql + ['database' => $name, 'engine' => $engine, 'charset' => $charset, 'collation' => $collation]); +}; +$dropDatabase = static function (Capsule $db): void { + $db->getConnection()->statement('DROP DATABASE IF EXISTS `' . $db->getConnection()->getDatabaseName() . '`'); + $db->getConnection()->disconnect(); +}; +/** @return array{lengths: array, indexes: list, engine: string} */ +$describe = static function (Capsule $db, string $table): array { + $schema = $db->schema(); + $lengths = []; + foreach ($schema->getColumns($table) as $column) { + if (preg_match('/^varchar\((\d+)\)/i', (string) $column['type'], $match)) { + $lengths[$column['name']] = (int) $match[1]; + } + } + $indexes = []; + foreach ($schema->getIndexes($table) as $index) { + if (!$index['primary']) { + $indexes[] = ($index['unique'] ? 'unique ' : 'index ') . implode(',', $index['columns']); + } + } + sort($indexes); + $engine = (string) $db->getConnection()->selectOne( + 'SELECT ENGINE AS engine FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + [$db->getConnection()->getTablePrefix() . $table] + )->engine; + + return ['lengths' => $lengths, 'indexes' => $indexes, 'engine' => $engine]; +}; +$fullIndexes = [ + 's_workers' => ['index active', 'index identifier', 'index position', 'index scope', 'unique identifier', 'unique uuid'], + 's_tasks' => ['index created_at', 'index identifier,action', 'index priority', 'index start_at', 'index started_by', 'index status'], + 's_supervisor_states' => ['index identifier', 'index last_seen_at', 'index state', 'index worker_id', 'unique key_hash'], +]; +$names = array_map(static fn (string $file): string => basename($file, '.php'), glob($migrationDirectory . '/*.php')); + +foreach ([['MyISAM', 'utf8mb4', 'utf8mb4_unicode_ci'], ['MyISAM', 'utf8', 'utf8_general_ci'], ['InnoDB', 'utf8mb4', 'utf8mb4_unicode_ci']] as [$engine, $charset, $collation]) { + [$db, $history, $migrator] = $freshDatabase($engine, $charset, $collation); + try { + $migrator->run([$migrationDirectory]); + $ok = $history->getRan() === $names; + foreach ($fullIndexes as $table => $indexes) { + $state = $describe($db, $table); + $ok = $ok && $state['indexes'] === $indexes && strcasecmp($state['engine'], $engine) === 0; + } + $ok = $ok && $describe($db, 's_tasks')['lengths']['action'] === 96; + $myisamCheck($ok, "Fresh install on {$engine} {$charset} creates every index"); + } finally { + $dropDatabase($db); + } +} + +// What a failed MyISAM create of 2.3.2 left: 255-character columns, no keys, migrations recorded by the next run. +$legacyTables = static function (Capsule $db): void { + $connection = $db->getConnection(); + $connection->statement("CREATE TABLE evo_s_workers (id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, uuid char(36) NULL, + identifier varchar(255) NOT NULL, scope varchar(255) NOT NULL DEFAULT '', class varchar(255) NOT NULL, active tinyint(1) NOT NULL DEFAULT 0, + position int unsigned NOT NULL DEFAULT 0, settings json NULL, hidden int unsigned NOT NULL DEFAULT 0, created_at timestamp NULL, updated_at timestamp NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4"); + $connection->statement("CREATE TABLE evo_s_tasks (id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, identifier varchar(255) NOT NULL, + action varchar(255) NOT NULL, status smallint unsigned NOT NULL DEFAULT 10, message text NULL, started_by int unsigned NULL, meta longtext NULL, + result longtext NULL, start_at timestamp NULL, finished_at timestamp NULL, attempts int NOT NULL DEFAULT 0, max_attempts int NOT NULL DEFAULT 3, + priority varchar(255) NOT NULL DEFAULT 'normal', progress int NOT NULL DEFAULT 0, created_at timestamp NULL, updated_at timestamp NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4"); + $connection->statement("CREATE TABLE evo_s_supervisor_states (id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, worker_id bigint unsigned NOT NULL, + identifier varchar(255) NOT NULL, supervisor_key varchar(255) NOT NULL, key_hash char(64) NOT NULL, state varchar(24) NOT NULL DEFAULT 'stopped', + pid bigint unsigned NULL, heartbeat_at timestamp NULL, supervisor_started_at timestamp NULL, uptime_seconds bigint unsigned NULL, message text NULL, + fingerprint char(64) NULL, last_transition_at timestamp NULL, last_seen_at timestamp NULL, repeat_count int unsigned NOT NULL DEFAULT 0, + launch_requested_at timestamp NULL, created_at timestamp NULL, updated_at timestamp NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4"); + $connection->table('s_workers')->insert(['identifier' => 'gallery', 'class' => 'GalleryWorker', 'settings' => '[]']); + $connection->table('s_tasks')->insert(['identifier' => 'gallery', 'action' => 'optimize']); +}; +$repairName = '2026_12_06_000000_fit_indexed_columns_to_myisam'; +$recordAllBut = static function (DatabaseMigrationRepository $history, string $skip) use ($names): void { + foreach ($names as $name) { + if ($name !== $skip) { + $history->log($name, 1); + } + } +}; + +[$db, $history, $migrator] = $freshDatabase('MyISAM', 'utf8mb4', 'utf8mb4_unicode_ci'); +try { + $legacyTables($db); + $recordAllBut($history, $repairName); + $migrator->run([$migrationDirectory]); + $migrator->run([$migrationDirectory]); + $ok = true; + foreach ($fullIndexes as $table => $indexes) { + $ok = $ok && $describe($db, $table)['indexes'] === $indexes; + } + $workers = $describe($db, 's_workers')['lengths']; + $tasks = $describe($db, 's_tasks')['lengths']; + $myisamCheck( + $ok && $workers['identifier'] === 128 && $workers['scope'] === 128 && $workers['class'] === 255 + && $tasks['identifier'] === 128 && $tasks['action'] === 96 && $tasks['priority'] === 16 + && $db->table('s_workers')->value('identifier') === 'gallery' && $db->table('s_tasks')->value('action') === 'optimize', + 'A table set left without keys by a failed MyISAM create gets its keys back, rows kept' + ); +} finally { + $dropDatabase($db); +} + +[$db, $history, $migrator] = $freshDatabase('MyISAM', 'utf8mb4', 'utf8mb4_unicode_ci'); +try { + $legacyTables($db); + $recordAllBut($history, $repairName); + // a duplicate worker blocks only its unique key; an over-long action keeps its column and its index out + $db->table('s_workers')->insert(['identifier' => 'gallery', 'class' => 'GalleryWorkerCopy', 'settings' => '[]']); + $db->table('s_tasks')->insert(['identifier' => 'gallery', 'action' => str_repeat('a', 120)]); + $migrator->run([$migrationDirectory]); + $workers = $describe($db, 's_workers'); + $tasks = $describe($db, 's_tasks'); + $myisamCheck( + !in_array('unique identifier', $workers['indexes'], true) && in_array('index identifier', $workers['indexes'], true) + && $workers['lengths']['identifier'] === 128 + && !in_array('index identifier,action', $tasks['indexes'], true) && in_array('index status', $tasks['indexes'], true) + && $tasks['lengths']['action'] === 255 && $tasks['lengths']['identifier'] === 128 + && $db->table('s_workers')->count() === 2 && $db->table('s_tasks')->count() === 2, + 'Duplicates and over-long values keep their rows and only block their own keys' + ); +} finally { + $dropDatabase($db); +} + +[$db, $history, $migrator] = $freshDatabase('InnoDB', 'utf8mb4', 'utf8mb4_unicode_ci'); +try { + // a 2.3.2 site on InnoDB: 255-character columns with every key, left alone + $migrator->run([$migrationDirectory]); + $db->getConnection()->statement('ALTER TABLE evo_s_tasks MODIFY action varchar(255) NOT NULL'); + $history->delete((object) ['migration' => $repairName]); + $migrator->run([$migrationDirectory]); + $myisamCheck( + $describe($db, 's_tasks')['lengths']['action'] === 255 && $describe($db, 's_tasks')['indexes'] === $fullIndexes['s_tasks'], + 'A table with all its keys is left as it is' + ); +} finally { + $dropDatabase($db); +} + +echo "sTask MyISAM regressions OK ({$myisamChecks} assertions)\n"; diff --git a/tests/run.php b/tests/run.php index 4c7fb49..165cae2 100644 --- a/tests/run.php +++ b/tests/run.php @@ -886,5 +886,6 @@ static function (SplFileInfo $file): bool { require __DIR__ . '/heartbeat.php'; require __DIR__ . '/migrations.php'; +require __DIR__ . '/myisam.php'; echo "sTask smoke OK ({$tests} assertions)\n"; From f59ae529dddc09251c58dd30879e9587e1296124 Mon Sep 17 00:00:00 2001 From: Artur Kyryliuk Date: Sat, 5 Dec 2026 23:17:54 +0100 Subject: [PATCH 2/2] fix(migrations): keep old rows saveable and column collations in the repair - FitsIndexedColumns checks only values being written, so a row stored before the limit in a 255-character column can still be updated. - The repair passes each column's own collation to the MODIFY; without it MySQL moves the column to the table default. - run.php starts myisam.php in its own process: heartbeat.php declares a stub sWorker. Co-Authored-By: Claude Opus 5.5 --- ...6_000000_fit_indexed_columns_to_myisam.php | 8 ++++++- src/Models/Concerns/FitsIndexedColumns.php | 5 +++-- tests/myisam.php | 21 +++++++++++++++++-- tests/run.php | 6 +++++- 4 files changed, 34 insertions(+), 6 deletions(-) diff --git a/database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php b/database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php index 8762c7b..9771806 100644 --- a/database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php +++ b/database/migrations/2026_12_06_000000_fit_indexed_columns_to_myisam.php @@ -71,9 +71,11 @@ private function repair(string $table, array $indexes): void } $lengths = []; + $collations = []; foreach (Schema::getColumns($table) as $column) { if (preg_match('/^varchar\((\d+)\)/i', (string) ($column['type'] ?? ''), $match)) { $lengths[$column['name']] = (int) $match[1]; + $collations[$column['name']] = $column['collation'] ?? null; } } @@ -92,9 +94,13 @@ private function repair(string $table, array $indexes): void } if ($shorten !== []) { - Schema::table($table, function (Blueprint $blueprint) use ($shorten): void { + Schema::table($table, function (Blueprint $blueprint) use ($shorten, $collations): void { foreach ($shorten as $name => [$length, $default]) { $column = $blueprint->string($name, $length); + // MODIFY without a collation would move the column to the table's default + if (!empty($collations[$name])) { + $column->collation($collations[$name]); + } if ($default !== null) { $column->default($default); } diff --git a/src/Models/Concerns/FitsIndexedColumns.php b/src/Models/Concerns/FitsIndexedColumns.php index 3b3abcd..1236312 100644 --- a/src/Models/Concerns/FitsIndexedColumns.php +++ b/src/Models/Concerns/FitsIndexedColumns.php @@ -8,7 +8,8 @@ * * The indexed string columns are sized so their keys fit the MyISAM limit of 1000 bytes in utf8mb4 * (see the create migrations). A longer value would be cut silently by a non-strict MySQL session, - * and the worker or task it names would no longer be found. + * and the worker or task it names would no longer be found. Only values being written are checked, so a + * row stored before the limit (a 255-character column left as it was) can still be updated. * * The model lists its columns in INDEXED_LENGTHS (column => characters). * @@ -21,7 +22,7 @@ protected static function bootFitsIndexedColumns(): void static::saving(static function (Model $model): void { foreach (static::INDEXED_LENGTHS as $column => $length) { $value = $model->getAttribute($column); - if (is_string($value) && mb_strlen($value) > $length) { + if ($model->isDirty($column) && is_string($value) && mb_strlen($value) > $length) { throw new InvalidArgumentException(sprintf( '%s.%s holds at most %d characters, %d given.', $model->getTable(), diff --git a/tests/myisam.php b/tests/myisam.php index c89bf4f..5582896 100644 --- a/tests/myisam.php +++ b/tests/myisam.php @@ -120,6 +120,14 @@ && sTaskModel::query()->create(['identifier' => 'gallery', 'action' => str_repeat('a', 96)])->exists, 'A task action or priority longer than its column is refused' ); +$legacyAction = str_repeat('l', 120); +$db->table('s_tasks')->insert(['identifier' => 'gallery', 'action' => $legacyAction]); +$legacyTask = sTaskModel::query()->where('action', $legacyAction)->firstOrFail(); +$legacyTask->status = sTaskModel::TASK_STATUS_FINISHED; +$myisamCheck( + $legacyTask->save() && sTaskModel::query()->whereKey($legacyTask->getKey())->value('status') == sTaskModel::TASK_STATUS_FINISHED, + 'A row stored before the limit can still be updated' +); $myisamCheck( $refuses(static fn () => sSupervisorState::query()->create(['worker_id' => 1, 'identifier' => str_repeat('s', 129), 'supervisor_key' => 'main', 'key_hash' => str_repeat('a', 64)])), 'A supervisor identifier longer than its column is refused' @@ -205,10 +213,10 @@ $legacyTables = static function (Capsule $db): void { $connection = $db->getConnection(); $connection->statement("CREATE TABLE evo_s_workers (id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, uuid char(36) NULL, - identifier varchar(255) NOT NULL, scope varchar(255) NOT NULL DEFAULT '', class varchar(255) NOT NULL, active tinyint(1) NOT NULL DEFAULT 0, + identifier varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, scope varchar(255) NOT NULL DEFAULT '', class varchar(255) NOT NULL, active tinyint(1) NOT NULL DEFAULT 0, position int unsigned NOT NULL DEFAULT 0, settings json NULL, hidden int unsigned NOT NULL DEFAULT 0, created_at timestamp NULL, updated_at timestamp NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4"); $connection->statement("CREATE TABLE evo_s_tasks (id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, identifier varchar(255) NOT NULL, - action varchar(255) NOT NULL, status smallint unsigned NOT NULL DEFAULT 10, message text NULL, started_by int unsigned NULL, meta longtext NULL, + action varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, status smallint unsigned NOT NULL DEFAULT 10, message text NULL, started_by int unsigned NULL, meta longtext NULL, result longtext NULL, start_at timestamp NULL, finished_at timestamp NULL, attempts int NOT NULL DEFAULT 0, max_attempts int NOT NULL DEFAULT 3, priority varchar(255) NOT NULL DEFAULT 'normal', progress int NOT NULL DEFAULT 0, created_at timestamp NULL, updated_at timestamp NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4"); $connection->statement("CREATE TABLE evo_s_supervisor_states (id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, worker_id bigint unsigned NOT NULL, @@ -240,6 +248,15 @@ } $workers = $describe($db, 's_workers')['lengths']; $tasks = $describe($db, 's_tasks')['lengths']; + $collation = static fn (string $table, string $column): string => (string) $db->getConnection()->selectOne( + 'SELECT COLLATION_NAME AS c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + ['evo_' . $table, $column] + )->c; + $myisamCheck( + $collation('s_tasks', 'action') === 'utf8mb4_bin' + && in_array($collation('s_workers', 'identifier'), ['utf8mb3_general_ci', 'utf8_general_ci'], true), + 'Shortened columns keep their own collation' + ); $myisamCheck( $ok && $workers['identifier'] === 128 && $workers['scope'] === 128 && $workers['class'] === 255 && $tasks['identifier'] === 128 && $tasks['action'] === 96 && $tasks['priority'] === 16 diff --git a/tests/run.php b/tests/run.php index 165cae2..c1eb5dc 100644 --- a/tests/run.php +++ b/tests/run.php @@ -886,6 +886,10 @@ static function (SplFileInfo $file): bool { require __DIR__ . '/heartbeat.php'; require __DIR__ . '/migrations.php'; -require __DIR__ . '/myisam.php'; +// own process: heartbeat.php declares a stub sWorker, and these checks need the real models +passthru(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg(__DIR__ . '/myisam.php'), $myisamExit); +if ($myisamExit !== 0) { + exit($myisamExit); +} echo "sTask smoke OK ({$tests} assertions)\n";