From 994e69fe7523ced59892508a80154e7ff106aedc Mon Sep 17 00:00:00 2001 From: Xiang Fu Date: Thu, 29 Oct 2026 00:10:36 -0700 Subject: [PATCH] Recommend schema and table config migrations by default Warn and record metrics for legacy definitions. Set cluster config controller.config.migration.auto.update.enabled=true to update both; see pinot-controller/CONFIG_MIGRATION.md. --- .../common/metadata/ZKMetadataProvider.java | 45 +- .../pinot/common/metrics/ControllerMeter.java | 7 + pinot-controller/CONFIG_MIGRATION.md | 74 +++ .../controller/BaseControllerStarter.java | 7 + .../pinot/controller/ControllerConf.java | 30 ++ .../helix/core/PinotHelixResourceManager.java | 307 ++++++++++- .../periodictask/ConfigMigrationManager.java | 323 +++++++++++ ...ollerPeriodicTaskStarterStatelessTest.java | 2 +- ...inotHelixResourceManagerStatelessTest.java | 376 +++++++++++++ ...ConfigMigrationManagerIntegrationTest.java | 210 ++++++++ .../ConfigMigrationManagerTest.java | 508 ++++++++++++++++++ .../data/manager/BaseTableDataManager.java | 5 +- .../manager/BaseTableDataManagerTest.java | 40 ++ .../MaterializedViewTaskExecutor.java | 2 +- .../mergerollup/MergeRollupTaskExecutor.java | 2 +- .../minion/tasks/purge/PurgeTaskExecutor.java | 2 +- ...RealtimeToOfflineSegmentsTaskExecutor.java | 2 +- .../RefreshSegmentTaskExecutor.java | 6 +- .../UpsertCompactionTaskExecutor.java | 5 +- .../UpsertCompactMergeTaskExecutor.java | 2 +- .../DefaultConfigMigrationRegistry.java | 46 ++ .../LegacyIngestionConfigMigrator.java | 61 +++ .../LegacyTimeFieldSchemaMigrator.java | 79 +++ .../LegacyIngestionConfigMigratorTest.java | 234 ++++++++ .../LegacyTimeFieldSchemaMigratorTest.java | 160 ++++++ .../predownload/PredownloadZKClient.java | 2 +- .../helix/HelixInstanceDataManager.java | 4 +- .../migration/ConfigMigrationRegistry.java | 145 +++++ .../migration/ConfigMigrationUtils.java | 99 ++++ .../spi/config/migration/ConfigMigrator.java | 49 ++ .../spi/config/migration/MigrationResult.java | 52 ++ .../spi/config/migration/SchemaMigrator.java | 29 + .../config/migration/TableConfigMigrator.java | 29 + .../org/apache/pinot/spi/data/Schema.java | 22 + .../ConfigMigrationRegistryTest.java | 206 +++++++ .../org/apache/pinot/spi/data/SchemaTest.java | 40 ++ 36 files changed, 3177 insertions(+), 35 deletions(-) create mode 100644 pinot-controller/CONFIG_MIGRATION.md create mode 100644 pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManager.java create mode 100644 pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerIntegrationTest.java create mode 100644 pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerTest.java create mode 100644 pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/DefaultConfigMigrationRegistry.java create mode 100644 pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigrator.java create mode 100644 pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigrator.java create mode 100644 pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigratorTest.java create mode 100644 pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigratorTest.java create mode 100644 pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistry.java create mode 100644 pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationUtils.java create mode 100644 pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrator.java create mode 100644 pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/MigrationResult.java create mode 100644 pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/SchemaMigrator.java create mode 100644 pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/TableConfigMigrator.java create mode 100644 pinot-spi/src/test/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistryTest.java diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metadata/ZKMetadataProvider.java b/pinot-common/src/main/java/org/apache/pinot/common/metadata/ZKMetadataProvider.java index 7c4ecff2bdfc..7428f1567bbf 100644 --- a/pinot-common/src/main/java/org/apache/pinot/common/metadata/ZKMetadataProvider.java +++ b/pinot-common/src/main/java/org/apache/pinot/common/metadata/ZKMetadataProvider.java @@ -495,10 +495,24 @@ public static ImmutablePair getTableConfigWithStat(ZkHelixPro @Nullable public static ImmutablePair getTableConfigWithVersion( ZkHelixPropertyStore propertyStore, String tableNameWithType) { + return getTableConfigWithVersion(propertyStore, tableNameWithType, true, true); + } + + /// @param replaceVariables Whether to replace environment variables and system properties with their actual values + /// @param applyDecorator Whether to apply the registered [TableConfigDecoratorRegistry] decorator + /// @return a pair of table config and current version from znRecord, null if table config does not exist. + /// + /// Pass {@code replaceVariables=false, applyDecorator=false} to read the config exactly as stored — needed when the + /// config will be transformed and written back (e.g. config migration), so that resolved env vars / decorations are + /// not accidentally persisted. + @Nullable + public static ImmutablePair getTableConfigWithVersion( + ZkHelixPropertyStore propertyStore, String tableNameWithType, boolean replaceVariables, + boolean applyDecorator) { Stat tableConfigStat = new Stat(); TableConfig tableConfig = toTableConfig( propertyStore.get(constructPropertyStorePathForResourceConfig(tableNameWithType), tableConfigStat, - AccessOption.PERSISTENT)); + AccessOption.PERSISTENT), replaceVariables, applyDecorator); if (tableConfig == null) { return null; } @@ -587,7 +601,7 @@ private static TableConfig toTableConfig(@Nullable ZNRecord znRecord, boolean re TableConfig tableConfig = TableConfigSerDeUtils.fromZNRecord(znRecord); TableConfig processedTableConfig = replaceVariables ? ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(tableConfig) : tableConfig; - return applyDecorator ? TableConfigDecoratorRegistry.applyDecorator(processedTableConfig) : tableConfig; + return applyDecorator ? TableConfigDecoratorRegistry.applyDecorator(processedTableConfig) : processedTableConfig; } catch (Exception e) { LOGGER.error("Caught exception while creating table config from ZNRecord: {}", znRecord.getId(), e); return null; @@ -599,6 +613,33 @@ public static void setSchema(ZkHelixPropertyStore propertyStore, Schem AccessOption.PERSISTENT); } + /// Updates an existing schema only if its stored version still matches. A nonnegative version prevents recreating + /// a schema deleted after the migration read. + public static boolean setSchema(ZkHelixPropertyStore propertyStore, Schema schema, int expectedVersion) { + Preconditions.checkArgument(expectedVersion >= 0, "Expected schema version must be nonnegative"); + try { + return propertyStore.set(constructPropertyStorePathForSchema(schema.getSchemaName()), + SchemaSerDeUtils.toZNRecord(schema), expectedVersion, AccessOption.PERSISTENT); + } catch (ZkBadVersionException e) { + return false; + } + } + + /// Reads the stored schema together with its ZK version, without changing its representation. + @Nullable + public static ImmutablePair getSchemaWithVersion(ZkHelixPropertyStore propertyStore, + String schemaName) { + try { + Stat stat = new Stat(); + ZNRecord record = + propertyStore.get(constructPropertyStorePathForSchema(schemaName), stat, AccessOption.PERSISTENT); + return record != null ? ImmutablePair.of(SchemaSerDeUtils.fromZNRecord(record), stat.getVersion()) : null; + } catch (Exception e) { + LOGGER.error("Caught exception while getting schema: {}", schemaName, e); + return null; + } + } + @Nullable public static Schema getSchema(ZkHelixPropertyStore propertyStore, String schemaName) { try { diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerMeter.java b/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerMeter.java index def5dee4b981..810651ee4df7 100644 --- a/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerMeter.java +++ b/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerMeter.java @@ -46,6 +46,13 @@ public enum ControllerMeter implements AbstractMetrics.Meter { CONTROLLER_PERIODIC_TASK_ERROR("periodicTaskError", false), CONTROLLER_TABLE_SEGMENT_UPLOAD_ERROR("TableSegmentUploadError", false), PERIODIC_TASK_ERROR("periodicTaskError", false), + // Recommendations count definitions needing an update on each scan, including warning-only scans. + CONFIG_MIGRATION_RECOMMENDED("configMigrationRecommended", false), + SCHEMA_MIGRATION_RECOMMENDED("schemaMigrationRecommended", false), + // Config migration: a table config or schema was upgraded to a newer version and persisted. + CONFIG_MIGRATION_SUCCESS("configMigrationSuccess", false), + // Config migration: a table's config/schema migration failed (validation, or lost the CAS race and will retry). + CONFIG_MIGRATION_FAILURE("configMigrationFailure", false), NUMBER_TIMES_SCHEDULE_TASKS_CALLED("tasks", true), NUMBER_TASKS_SUBMITTED("tasks", false), NUMBER_SEGMENT_UPLOAD_TIMEOUT_EXCEEDED("SegmentUploadTimeouts", true), diff --git a/pinot-controller/CONFIG_MIGRATION.md b/pinot-controller/CONFIG_MIGRATION.md new file mode 100644 index 000000000000..fd5bf27b8967 --- /dev/null +++ b/pinot-controller/CONFIG_MIGRATION.md @@ -0,0 +1,74 @@ + +# Stored table definition migration + +The controller inspects physical table configs and their shared schemas every hour. +By default it only logs warnings and records recommendations; it does not change stored definitions. + +The initial rules move legacy stream/batch ingestion properties into `ingestionConfig`, convert +schema `timeFieldSpec` to `dateTimeFieldSpecs`, and move schema-field `transformFunction` properties +into each affected table's `ingestionConfig.transformConfigs`. Existing table transforms take precedence. +Unsupported conversions are left unchanged. Modern definitions are no-ops, including ones without +migration markers. A later edit that reintroduces legacy fields is detected again. + +After all cluster components have been upgraded and rollback requirements have been reviewed, enable +updates through the cluster configuration API: + +```sh +curl -X POST 'http://localhost:9000/cluster/configs' \ + -H 'Content-Type: application/json' \ + -d '{"controller.config.migration.auto.update.enabled":"true"}' +``` + +This cluster flag controls both schema and table-config updates. Controllers pick up changes without +a restart; updates run on the next scan. Leave it unset, delete it, or set it to `false` for warning-only mode. +The scan schedule remains a controller setting: `controller.config.migration.frequencyPeriod=1h` by default, +or `-1s` to disable the scan entirely. + +For manual updates, move `tableIndexConfig.streamConfigs` into +`ingestionConfig.streamIngestionConfig.streamConfigMaps` as a one-element list. Move +`segmentsConfig.segmentPushType` and `segmentPushFrequency` into +`ingestionConfig.batchIngestionConfig.segmentIngestionType` and `segmentIngestionFrequency`. +TIME fields require an equivalent DATE_TIME format, granularity, and transform; unsupported time +conversions require manual review rather than automatic rewriting. + +For each nonempty, nonvirtual schema-field transform, add a table transform with the same `columnName` +and `transformFunction` unless that table already overrides the column. Both OFFLINE and REALTIME table +configs are checked before removing the shared schema transforms. TIME conversion transforms generated +by the preceding rule are moved the same way. Empty, virtual, and nested-child transforms are left unchanged. + +The controller validates all candidates, checks every affected table's captured version, writes changed +table configs, and removes the schema transforms in one atomic ZooKeeper transaction. A failed validation +or version conflict leaves all stored definitions unchanged. Table creation atomically advances the +schema's ZooKeeper version without changing its contents, so a new table also invalidates an in-flight +migration plan. Ingestion metadata readers fetch schema before table config to avoid combining an old +table config with a schema whose transforms have already moved. +Transforms whose behavior would change through template resolution or decorators are left on the schema. + +Recommendation meters are `CONFIG_MIGRATION_RECOMMENDED` per physical table and +`SCHEMA_MIGRATION_RECOMMENDED` per shared schema. They count recommendations on each scan, rather than +unique definitions. `CONFIG_MIGRATION_SUCCESS` counts successful writes and `CONFIG_MIGRATION_FAILURE` +counts failed validation or update attempts. Schemas are counted once across hybrid table halves per run. + +Automatic updates validate candidates and use version-checked writes. Concurrent edits/deletions and +stored fields that cannot survive a typed round trip prevent the update. Resolved environment values +are used for table validation and runtime actions; raw templates remain in storage. Schema-transform +migrations coordinate table and schema writes; other rules retain their independent update paths. diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java index 9f4320f27671..6b64b4e6641e 100644 --- a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java +++ b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java @@ -109,6 +109,7 @@ import org.apache.pinot.controller.helix.core.minion.PinotHelixTaskResourceManager; import org.apache.pinot.controller.helix.core.minion.PinotTaskManager; import org.apache.pinot.controller.helix.core.minion.TaskMetricsEmitter; +import org.apache.pinot.controller.helix.core.periodictask.ConfigMigrationManager; import org.apache.pinot.controller.helix.core.periodictask.ControllerPeriodicTask; import org.apache.pinot.controller.helix.core.realtime.PinotLLCRealtimeSegmentManager; import org.apache.pinot.controller.helix.core.realtime.SegmentCompletionConfig; @@ -150,6 +151,7 @@ import org.apache.pinot.core.util.trace.ContinuousJfrStarter; import org.apache.pinot.materializedview.consistency.MaterializedViewConsistencyManager; import org.apache.pinot.segment.local.utils.TableConfigUtils; +import org.apache.pinot.segment.local.utils.migration.DefaultConfigMigrationRegistry; import org.apache.pinot.segment.spi.partition.PartitionFunctionFactory; import org.apache.pinot.spi.config.instance.InstanceConfigValidatorRegistry; import org.apache.pinot.spi.config.table.TableConfig; @@ -227,6 +229,7 @@ public abstract class BaseControllerStarter implements ServiceStartable { protected LeadControllerManager _leadControllerManager; protected List _serviceStatusCallbackList; protected StaleInstancesCleanupTask _staleInstancesCleanupTask; + protected ConfigMigrationManager _configMigrationManager; protected TaskMetricsEmitter _taskMetricsEmitter; protected PoolingHttpClientConnectionManager _connectionManager; protected TenantRebalancer _tenantRebalancer; @@ -1141,6 +1144,10 @@ protected List setupControllerPeriodicTasks() { _staleInstancesCleanupTask = new StaleInstancesCleanupTask(_helixResourceManager, _leadControllerManager, _config, _controllerMetrics); periodicTasks.add(_staleInstancesCleanupTask); + _configMigrationManager = + new ConfigMigrationManager(_helixResourceManager, _leadControllerManager, _config, _controllerMetrics, + DefaultConfigMigrationRegistry.create()); + periodicTasks.add(_configMigrationManager); _taskMetricsEmitter = new TaskMetricsEmitter(_helixResourceManager, _helixTaskResourceManager, _leadControllerManager, _config, _controllerMetrics); diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java b/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java index 97f5630d9fe1..f2651365cfa8 100644 --- a/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java +++ b/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java @@ -149,6 +149,13 @@ public static class ControllerPeriodicTasksConf { public static final String STALE_INSTANCES_CLEANUP_TASK_INSTANCES_RETENTION_PERIOD = "controller.stale.instances.cleanup.task.minOfflineTimeBeforeDeletionPeriod"; + // Cluster config: applies to both schemas and table configs without restarting controllers. + public static final String CONFIG_MIGRATION_AUTO_UPDATE_ENABLED = "controller.config.migration.auto.update.enabled"; + public static final String CONFIG_MIGRATION_FREQUENCY_PERIOD = "controller.config.migration.frequencyPeriod"; + public static final String CONFIG_MIGRATION_INITIAL_DELAY_SECONDS = + "controller.config.migration.initialDelaySeconds"; + public static final String CONFIG_MIGRATION_CRON_EXPRESSION = "controller.config.migration.cronExpression"; + public static final String TASK_METRICS_EMITTER_FREQUENCY_PERIOD = "controller.minion.task.metrics.emitter.frequencyPeriod"; public static final String TASK_METRICS_EMITTER_CRON_EXPRESSION = @@ -326,6 +333,11 @@ public static long getRandomInitialDelayInSeconds() { public static final String DEFAULT_SEGMENT_LEVEL_VALIDATION_INTERVAL_PERIOD = "24h"; public static final String DEFAULT_SEGMENT_RELOCATOR_FREQUENCY_PERIOD = "1h"; + // Inspect stored definitions by default. Rewriting them requires explicit opt-in after upgrading all nodes, + // because the new format may not be accepted by a previous release during rollback. + public static final boolean DEFAULT_CONFIG_MIGRATION_AUTO_UPDATE_ENABLED = false; + public static final String DEFAULT_CONFIG_MIGRATION_FREQUENCY_PERIOD = "1h"; + // Realtime Consumer Monitor public static final String RT_CONSUMER_MONITOR_FREQUENCY_PERIOD = "controller.realtimeConsumerMonitor.frequencyPeriod"; @@ -1232,6 +1244,24 @@ public void setStaleInstancesCleanupTaskInstancesRetentionPeriod(String retentio setProperty(ControllerPeriodicTasksConf.STALE_INSTANCES_CLEANUP_TASK_INSTANCES_RETENTION_PERIOD, retentionPeriod); } + public int getConfigMigrationFrequencyInSeconds() { + String period = getProperty(ControllerPeriodicTasksConf.CONFIG_MIGRATION_FREQUENCY_PERIOD, + ControllerPeriodicTasksConf.DEFAULT_CONFIG_MIGRATION_FREQUENCY_PERIOD); + if (!isValidPeriodWithLogging(ControllerPeriodicTasksConf.CONFIG_MIGRATION_FREQUENCY_PERIOD, period)) { + period = ControllerPeriodicTasksConf.DEFAULT_CONFIG_MIGRATION_FREQUENCY_PERIOD; + } + return (int) convertPeriodToSeconds(period); + } + + public long getConfigMigrationInitialDelaySeconds() { + return getProperty(ControllerPeriodicTasksConf.CONFIG_MIGRATION_INITIAL_DELAY_SECONDS, + ControllerPeriodicTasksConf.getRandomInitialDelayInSeconds()); + } + + public String getConfigMigrationCronExpression() { + return getProperty(ControllerPeriodicTasksConf.CONFIG_MIGRATION_CRON_EXPRESSION); + } + public int getDefaultTableMinReplicas() { return getProperty(TABLE_MIN_REPLICAS, DEFAULT_TABLE_MIN_REPLICAS); } diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java index 6003dff825bb..4f0bb340d5f5 100644 --- a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java +++ b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java @@ -19,6 +19,7 @@ package org.apache.pinot.controller.helix.core; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; @@ -141,6 +142,8 @@ import org.apache.pinot.common.utils.ZkStarter; import org.apache.pinot.common.utils.config.AccessControlUserConfigUtils; import org.apache.pinot.common.utils.config.InstanceUtils; +import org.apache.pinot.common.utils.config.SchemaSerDeUtils; +import org.apache.pinot.common.utils.config.TableConfigSerDeUtils; import org.apache.pinot.common.utils.config.TagNameUtils; import org.apache.pinot.common.utils.config.TierConfigUtils; import org.apache.pinot.common.utils.helix.HelixHelper; @@ -177,13 +180,16 @@ import org.apache.pinot.materializedview.metadata.MaterializedViewDefinitionMetadataBuilder; import org.apache.pinot.materializedview.metadata.MaterializedViewDefinitionMetadataUtils; import org.apache.pinot.materializedview.metadata.MaterializedViewRuntimeMetadataUtils; +import org.apache.pinot.segment.local.utils.SchemaUtils; import org.apache.pinot.segment.local.utils.TableConfigUtils; import org.apache.pinot.segment.spi.SegmentMetadata; import org.apache.pinot.spi.auth.AuthProvider; +import org.apache.pinot.spi.config.ConfigUtils; import org.apache.pinot.spi.config.DatabaseConfig; import org.apache.pinot.spi.config.instance.Instance; import org.apache.pinot.spi.config.instance.InstanceConfigValidatorRegistry; import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.config.table.TableConfigValidatorRegistry; import org.apache.pinot.spi.config.table.TableStatsHumanReadable; import org.apache.pinot.spi.config.table.TableType; import org.apache.pinot.spi.config.table.TagOverrideConfig; @@ -211,6 +217,7 @@ import org.apache.pinot.spi.utils.IngestionConfigUtils; import org.apache.pinot.spi.utils.InstanceTypeUtils; import org.apache.pinot.spi.utils.JsonUtils; +import org.apache.pinot.spi.utils.TableConfigDecoratorRegistry; import org.apache.pinot.spi.utils.TimeUtils; import org.apache.pinot.spi.utils.builder.TableNameBuilder; import org.apache.pinot.spi.utils.retry.RetryPolicies; @@ -1760,6 +1767,116 @@ public void updateSchema(Schema schema, boolean reload, boolean forceTableSchema } } + /// Updates an existing schema with optimistic concurrency and refreshes its servers only after a successful write. + /// Returns false for an unchanged schema, a stale version, a deleted schema, or a rejected persistence operation. + public boolean updateSchema(Schema schema, int expectedVersion) + throws SchemaBackwardIncompatibleException { + Schema oldSchema = getSchemaForVersionedUpdate(schema.getSchemaName(), expectedVersion); + if (oldSchema == null) { + return false; + } + schema.validate(); + if (!updateSchema(schema, oldSchema, false, expectedVersion)) { + return false; + } + refreshTablesUsingSchema(schema.getSchemaName()); + return true; + } + + /// Finds every stored physical table sharing a schema, including configs that cannot currently be read or decorated. + /// Migration must validate all of these records before removing shared schema transforms. + public List getTableNamesForSchemaMigration(String schemaName) + throws TableNotFoundException { + List tableNames = new ArrayList<>(2); + for (TableType tableType : List.of(TableType.OFFLINE, TableType.REALTIME)) { + String tableName = TableNameBuilder.forType(tableType).tableNameWithType(schemaName); + if (ZKMetadataProvider.isTableConfigExists(_propertyStore, tableName)) { + tableNames.add(tableName); + } + } + if (tableNames.isEmpty()) { + throw new TableNotFoundException("Table '" + schemaName + "' not found."); + } + return tableNames; + } + + /// Atomically updates affected table configs before removing their shared schema's legacy transforms. + /// Every table version is checked, including tables whose existing overrides require no config change. + /// Stale/deleted records leave all definitions unchanged, and refreshes are sent only after the transaction succeeds. + public boolean updateSchemaAndTableConfigs(Schema schema, int expectedSchemaVersion, + Map> tableConfigs) + throws SchemaBackwardIncompatibleException, TableConfigBackwardIncompatibleException, TableNotFoundException, + IOException, KeeperException { + Schema oldSchema = getSchemaForVersionedUpdate(schema.getSchemaName(), expectedSchemaVersion); + if (oldSchema == null || !validateSchemaUpdate(schema, oldSchema, false)) { + return false; + } + ZkMultiWriteBuilder transaction = multiWriteZK(); + List effectiveConfigs = new ArrayList<>(tableConfigs.size()); + List changedConfigs = new ArrayList<>(tableConfigs.size()); + for (Map.Entry> entry : tableConfigs.entrySet()) { + String tableName = entry.getKey(); + TableConfig rawConfig = entry.getValue().getLeft(); + int expectedVersion = entry.getValue().getRight(); + Preconditions.checkArgument(expectedVersion >= 0 && tableName.equals(rawConfig.getTableName()) + && schema.getSchemaName().equals(TableNameBuilder.extractRawTableName(tableName)), + "Expected a versioned physical table using schema: %s", schema.getSchemaName()); + Pair original = + ZKMetadataProvider.getTableConfigWithVersion(_propertyStore, tableName, false, false); + if (original == null || original.getRight() != expectedVersion) { + return false; + } + TableConfig effective = TableConfigDecoratorRegistry.applyDecorator( + ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(rawConfig)); + TableConfig existingEffective = TableConfigDecoratorRegistry.applyDecorator( + ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(original.getLeft())); + TableConfigUtils.validate(effective, schema, null, existingEffective); + TableConfigValidatorRegistry.validate(effective, schema); + validateExistingTableConfig(rawConfig, effective, expectedVersion, false, true); + effectiveConfigs.add(effective); + String path = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(tableName); + transaction.check(path, expectedVersion); + if (!JsonUtils.objectToJsonNode(rawConfig).equals(JsonUtils.objectToJsonNode(original.getLeft()))) { + transaction.set(path, TableConfigSerDeUtils.toZNRecord(rawConfig), expectedVersion); + changedConfigs.add(effective); + } + } + SchemaUtils.validate(schema, effectiveConfigs, false, oldSchema); + if (!new HashSet<>(getTableNamesForSchemaMigration(schema.getSchemaName())).equals(tableConfigs.keySet())) { + return false; + } + transaction.set(ZKMetadataProvider.constructPropertyStorePathForSchema(schema.getSchemaName()), + SchemaSerDeUtils.toZNRecord(schema), expectedSchemaVersion); + try { + transaction.execute(); + } catch (KeeperException.BadVersionException | KeeperException.NoNodeException e) { + return false; + } + for (TableConfig config : changedConfigs) { + refreshExistingTableConfig(config); + } + refreshTablesUsingSchema(schema.getSchemaName()); + return true; + } + + @Nullable + private Schema getSchemaForVersionedUpdate(String schemaName, int expectedVersion) { + Preconditions.checkArgument(expectedVersion >= 0, "Expected schema version must be nonnegative"); + Pair schemaAndVersion = + ZKMetadataProvider.getSchemaWithVersion(_propertyStore, schemaName); + if (schemaAndVersion == null || schemaAndVersion.getRight() != expectedVersion) { + return null; + } + Stat stat = new Stat(); + ZNRecord stored = _propertyStore.get(ZKMetadataProvider.constructPropertyStorePathForSchema(schemaName), + stat, AccessOption.PERSISTENT); + if (stored == null || stat.getVersion() != expectedVersion + || !preservesStoredRecord(stored, SchemaSerDeUtils.toZNRecord(schemaAndVersion.getLeft()))) { + return null; + } + return schemaAndVersion.getLeft(); + } + /// Reloads all segments of the tables using the given schema. Logical table schemas are skipped because no /// segments are backed by them. private void reloadTablesUsingSchema(String schemaName) @@ -1798,11 +1915,31 @@ private void refreshTablesUsingSchema(String schemaName) { /// backward-compatible with the existing schema. private void updateSchema(Schema schema, Schema oldSchema, boolean forceTableSchemaUpdate) throws SchemaBackwardIncompatibleException { + updateSchema(schema, oldSchema, forceTableSchemaUpdate, null); + } + + private boolean updateSchema(Schema schema, Schema oldSchema, boolean forceTableSchemaUpdate, + @Nullable Integer expectedVersion) + throws SchemaBackwardIncompatibleException { + if (!validateSchemaUpdate(schema, oldSchema, forceTableSchemaUpdate)) { + return false; + } + if (expectedVersion == null) { + ZKMetadataProvider.setSchema(_propertyStore, schema); + } else if (!ZKMetadataProvider.setSchema(_propertyStore, schema, expectedVersion)) { + return false; + } + LOGGER.info("Updated schema: {}", schema.getSchemaName()); + return true; + } + + private boolean validateSchemaUpdate(Schema schema, Schema oldSchema, boolean forceTableSchemaUpdate) + throws SchemaBackwardIncompatibleException { String schemaName = schema.getSchemaName(); schema.updateBooleanFieldsIfNeeded(oldSchema); if (schema.equals(oldSchema)) { LOGGER.info("New schema: {} is the same as the existing schema, not updating it", schemaName); - return; + return false; } boolean isBackwardCompatible = schema.isBackwardCompatibleWith(oldSchema); @@ -1875,8 +2012,7 @@ private void updateSchema(Schema schema, Schema oldSchema, boolean forceTableSch throw new SchemaBackwardIncompatibleException(errorMsg.toString()); } } - ZKMetadataProvider.setSchema(_propertyStore, schema); - LOGGER.info("Updated schema: {}", schemaName); + return true; } /// Deletes the given schema. Returns `true` when schema exists, `false` when schema does not exist. @@ -2044,18 +2180,12 @@ public void addTable(TableConfig tableConfig, List streamMetadat IdealState idealState = PinotTableIdealStateBuilder.buildEmptyIdealStateFor(tableNameWithType, tableConfig.getReplication()); TableType tableType = tableConfig.getTableType(); - // Ensure that table is not created if schema is not present - if (ZKMetadataProvider.getSchema(_propertyStore, rawTableName) == null) { - throw new InvalidTableConfigException("No schema defined for table: " + tableNameWithType); - } Preconditions.checkState(tableType == TableType.OFFLINE || tableType == TableType.REALTIME, "Invalid table type: %s", tableType); // Add table config LOGGER.info("Adding table {}: Creating table config in the property store", tableNameWithType); - if (!ZKMetadataProvider.createTableConfig(_propertyStore, tableConfig)) { - throw new RuntimeException("Failed to create table config for table: " + tableNameWithType); - } + createTableConfigWithSchemaVersion(tableConfig); try { // Read table config from ZK to ensure we get consistent view across all APIs (e.g. environment variables applied, @@ -2103,6 +2233,56 @@ public void addTable(TableConfig tableConfig, List streamMetadat LOGGER.info("Adding table {}: Successfully added table", tableNameWithType); } + /// Fences schema cleanup against new physical tables by changing the schema data version in the same transaction. + /// The exact stored record is retained, including fields unknown to this controller. + @VisibleForTesting + void createTableConfigWithSchemaVersion(TableConfig tableConfig) + throws IOException { + String tableName = tableConfig.getTableName(); + String schemaPath = ZKMetadataProvider.constructPropertyStorePathForSchema( + TableNameBuilder.extractRawTableName(tableName)); + String tablePath = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(tableName); + String tableParent = tablePath.substring(0, tablePath.lastIndexOf('/')); + for (int attempt = 0; attempt < 3; attempt++) { + Stat stat = new Stat(); + ZNRecord schemaRecord = _propertyStore.get(schemaPath, stat, AccessOption.PERSISTENT); + if (schemaRecord == null) { + throw new InvalidTableConfigException("No schema defined for table: " + tableName); + } + try { + Preconditions.checkNotNull(SchemaSerDeUtils.fromZNRecord(schemaRecord)); + } catch (Exception e) { + throw new InvalidTableConfigException("Invalid schema defined for table: " + tableName, e); + } + if (!_propertyStore.exists(tableParent, AccessOption.PERSISTENT)) { + _propertyStore.create(tableParent, new ZNRecord("TABLE"), AccessOption.PERSISTENT); + } + try { + multiWriteZK().set(schemaPath, schemaRecord, stat.getVersion()) + .create(tablePath, TableConfigSerDeUtils.toZNRecord(tableConfig)).execute(); + return; + } catch (KeeperException.BadVersionException e) { + if (attempt == 2) { + throw new IOException("Schema changed while creating table: " + tableName + "; retry the request", e); + } + } catch (KeeperException.NodeExistsException e) { + throw new TableAlreadyExistsException("Table config for " + tableName + " already exists"); + } catch (KeeperException.NoNodeException e) { + if (!_propertyStore.exists(schemaPath, AccessOption.PERSISTENT)) { + throw new InvalidTableConfigException("No schema defined for table: " + tableName); + } + // AutoFallbackPropertyStore can read a schema that exists only in HELIX_PROPERTYSTORE. An identity update + // promotes its exact raw record to PROPERTYSTORE before retrying the version-fenced transaction. + if (!_propertyStore.update(schemaPath, existing -> existing, AccessOption.PERSISTENT)) { + throw new IOException("Failed to promote schema while creating table: " + tableName, e); + } + } catch (KeeperException e) { + throw new IOException("Failed to create table config for table: " + tableName, e); + } + } + throw new IOException("Schema changed while creating table: " + tableName + "; retry the request"); + } + /// Adds a logical table. /// @param logicalTableConfig The logical table config to be added /// @throws TableAlreadyExistsException If the logical table already exists @@ -2612,7 +2792,51 @@ public void setExistingTableConfig(TableConfig tableConfig, int expectedVersion) /// @throws TableConfigBackwardIncompatibleException if config changes are backward incompatible and force is false public void setExistingTableConfig(TableConfig tableConfig, int expectedVersion, boolean force) throws TableConfigBackwardIncompatibleException { + setExistingTableConfig(tableConfig, tableConfig, expectedVersion, force, false); + } + + /// Persists the raw config while using a separately resolved config for validation and runtime side effects. + /// This keeps environment-variable templates in storage without passing them to instance assignment. + public void setExistingTableConfig(TableConfig rawTableConfig, TableConfig tableConfig, int expectedVersion, + boolean force) + throws TableConfigBackwardIncompatibleException { + Preconditions.checkArgument(expectedVersion >= 0, "Expected table config version must be nonnegative"); + setExistingTableConfig(rawTableConfig, tableConfig, expectedVersion, force, true); + } + + private void setExistingTableConfig(TableConfig rawTableConfig, TableConfig tableConfig, int expectedVersion, + boolean force, boolean checkRoundTrip) + throws TableConfigBackwardIncompatibleException { + validateExistingTableConfig(rawTableConfig, tableConfig, expectedVersion, force, checkRoundTrip); + if (!ZKMetadataProvider.setTableConfig(_propertyStore, rawTableConfig, expectedVersion)) { + throw new RuntimeException( + "Failed to update table config in Zookeeper for table: " + tableConfig.getTableName() + " with" + + " expected version: " + expectedVersion); + } + refreshExistingTableConfig(tableConfig); + sendTableConfigSchemaRefreshMessage(tableConfig.getTableName()); + } + + private void validateExistingTableConfig(TableConfig rawTableConfig, TableConfig tableConfig, int expectedVersion, + boolean force, boolean checkRoundTrip) + throws TableConfigBackwardIncompatibleException { + Preconditions.checkArgument(rawTableConfig.getTableName().equals(tableConfig.getTableName()), + "Stored and effective table config names must match"); String tableNameWithType = tableConfig.getTableName(); + if (checkRoundTrip) { + Stat stat = new Stat(); + String path = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(tableNameWithType); + ZNRecord stored = _propertyStore.get(path, stat, AccessOption.PERSISTENT); + Preconditions.checkState(stored != null && stat.getVersion() == expectedVersion, + "Stored table config changed before migration: %s", tableNameWithType); + try { + Preconditions.checkState(preservesStoredRecord(stored, + TableConfigSerDeUtils.toZNRecord(TableConfigSerDeUtils.fromZNRecord(stored))), + "Automatic migration would lose stored table config fields: %s", tableNameWithType); + } catch (IOException e) { + throw new IllegalStateException("Failed to check stored table config: " + tableNameWithType, e); + } + } TableConfig existingTableConfig = getTableConfig(tableNameWithType); if (existingTableConfig != null) { List violations = TableConfigUtils.validateBackwardCompatibility(tableConfig, existingTableConfig); @@ -2630,13 +2854,10 @@ public void setExistingTableConfig(TableConfig tableConfig, int expectedVersion, } } } + } - if (!ZKMetadataProvider.setTableConfig(_propertyStore, tableConfig, expectedVersion)) { - throw new RuntimeException( - "Failed to update table config in Zookeeper for table: " + tableNameWithType + " with" + " expected version: " - + expectedVersion); - } - + private void refreshExistingTableConfig(TableConfig tableConfig) { + String tableNameWithType = tableConfig.getTableName(); // Update IdealState replication IdealState idealState = _helixAdmin.getResourceIdealState(_helixClusterName, tableNameWithType); Preconditions.checkArgument(idealState != null, @@ -2657,7 +2878,59 @@ public void setExistingTableConfig(TableConfig tableConfig, int expectedVersion, // Refresh brokers and servers so in-memory table config caches observe the update. sendTableConfigRefreshMessage(tableNameWithType); - sendTableConfigSchemaRefreshMessage(tableNameWithType); + } + + /// Automatic migration must not discard fields understood by another version or a plugin. Added defaults are + /// harmless, but every stored value (including empty containers and extra ZNRecord fields) must survive parsing. + private static boolean preservesStoredRecord(ZNRecord stored, ZNRecord roundTripped) { + return Objects.equals(stored.getId(), roundTripped.getId()) + && Arrays.equals(stored.getRawPayload(), roundTripped.getRawPayload()) + && preservesStoredJson(JsonUtils.objectToJsonNode(stored.getSimpleFields()), + JsonUtils.objectToJsonNode(roundTripped.getSimpleFields())) + && preservesStoredJson(JsonUtils.objectToJsonNode(stored.getMapFields()), + JsonUtils.objectToJsonNode(roundTripped.getMapFields())) + && preservesStoredJson(JsonUtils.objectToJsonNode(stored.getListFields()), + JsonUtils.objectToJsonNode(roundTripped.getListFields())); + } + + private static boolean preservesStoredJson(JsonNode stored, @Nullable JsonNode roundTripped) { + if (stored.equals(roundTripped)) { + return true; + } + if (roundTripped == null) { + return false; + } + if (stored.isObject()) { + if (!roundTripped.isObject()) { + return false; + } + for (Map.Entry field : stored.properties()) { + if (!preservesStoredJson(field.getValue(), roundTripped.get(field.getKey()))) { + return false; + } + } + return true; + } + if (stored.isArray()) { + if (!roundTripped.isArray() || stored.size() != roundTripped.size()) { + return false; + } + for (int i = 0; i < stored.size(); i++) { + if (!preservesStoredJson(stored.get(i), roundTripped.get(i))) { + return false; + } + } + return true; + } + if (stored.isTextual() && roundTripped.isTextual()) { + try { + return preservesStoredJson(JsonUtils.stringToJsonNode(stored.textValue()), + JsonUtils.stringToJsonNode(roundTripped.textValue())); + } catch (IOException e) { + return false; + } + } + return false; } public void deleteUser(String username) { diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManager.java b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManager.java new file mode 100644 index 000000000000..5a2cfe116ddb --- /dev/null +++ b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManager.java @@ -0,0 +1,323 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.controller.helix.core.periodictask; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import javax.annotation.Nullable; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.helix.store.zk.ZkHelixPropertyStore; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.pinot.common.metadata.ZKMetadataProvider; +import org.apache.pinot.common.metrics.ControllerMeter; +import org.apache.pinot.common.metrics.ControllerMetrics; +import org.apache.pinot.controller.ControllerConf; +import org.apache.pinot.controller.ControllerConf.ControllerPeriodicTasksConf; +import org.apache.pinot.controller.LeadControllerManager; +import org.apache.pinot.controller.helix.core.PinotHelixResourceManager; +import org.apache.pinot.segment.local.utils.SchemaUtils; +import org.apache.pinot.segment.local.utils.TableConfigUtils; +import org.apache.pinot.spi.config.ConfigUtils; +import org.apache.pinot.spi.config.migration.ConfigMigrationRegistry; +import org.apache.pinot.spi.config.migration.ConfigMigrationUtils; +import org.apache.pinot.spi.config.migration.MigrationResult; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.config.table.TableConfigValidatorRegistry; +import org.apache.pinot.spi.config.table.ingestion.IngestionConfig; +import org.apache.pinot.spi.config.table.ingestion.TransformConfig; +import org.apache.pinot.spi.data.FieldSpec; +import org.apache.pinot.spi.data.Schema; +import org.apache.pinot.spi.utils.JsonUtils; +import org.apache.pinot.spi.utils.TableConfigDecoratorRegistry; +import org.apache.pinot.spi.utils.builder.TableNameBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/// Inspects stored table definitions and recommends available schema and table-config migrations. +/// By default only warnings and recommendation meters are emitted. Explicitly enabling +/// the cluster config `controller.config.migration.auto.update.enabled` also persists validated candidates with the +/// captured ZooKeeper version and refreshes caches through the resource manager. +/// +/// Schema transforms move to all affected table configs before being removed, using one version-checked transaction. +/// Raw templates are retained for storage; a separate resolved table config is used for validation and +/// runtime side effects. Table leadership and sequential per-run processing are provided by [ControllerPeriodicTask]. +public class ConfigMigrationManager extends ControllerPeriodicTask { + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigMigrationManager.class); + public static final String TASK_NAME = ConfigMigrationManager.class.getSimpleName(); + + private final ConfigMigrationRegistry _migrationRegistry; + private volatile boolean _autoUpdateEnabled = + ControllerPeriodicTasksConf.DEFAULT_CONFIG_MIGRATION_AUTO_UPDATE_ENABLED; + + public ConfigMigrationManager(PinotHelixResourceManager helixResourceManager, + LeadControllerManager leadControllerManager, ControllerConf config, ControllerMetrics controllerMetrics, + ConfigMigrationRegistry migrationRegistry) { + super(TASK_NAME, config.getConfigMigrationFrequencyInSeconds(), config.getConfigMigrationInitialDelaySeconds(), + config.getConfigMigrationCronExpression(), helixResourceManager, leadControllerManager, controllerMetrics); + _migrationRegistry = migrationRegistry; + } + + @Override + public void onChange(Set changedConfigs, Map clusterConfigs) { + if (changedConfigs.contains(ControllerPeriodicTasksConf.CONFIG_MIGRATION_AUTO_UPDATE_ENABLED)) { + _autoUpdateEnabled = Boolean.parseBoolean(clusterConfigs.getOrDefault( + ControllerPeriodicTasksConf.CONFIG_MIGRATION_AUTO_UPDATE_ENABLED, + Boolean.toString(ControllerPeriodicTasksConf.DEFAULT_CONFIG_MIGRATION_AUTO_UPDATE_ENABLED))); + } + } + + /// Tracks shared schemas so a hybrid table's OFFLINE/REALTIME halves report and update it once per run. + public static class Context { + private final Set _processedSchemas = new HashSet<>(); + private final Set _processedTables = new HashSet<>(); + } + + @Override + protected Context preprocess(Properties periodicTaskProperties) { + return new Context(); + } + + @Override + protected void processTable(String tableNameWithType, Context context) { + if (_migrationRegistry.getCurrentTableConfigVersion() == 0 && _migrationRegistry.getCurrentSchemaVersion() == 0) { + return; + } + ZkHelixPropertyStore propertyStore = _pinotHelixResourceManager.getPropertyStore(); + String schemaName = TableNameBuilder.extractRawTableName(tableNameWithType); + ImmutablePair schemaAndVersion = + ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName); + Schema schema = schemaAndVersion != null ? schemaAndVersion.getLeft() : null; + if (_migrationRegistry.getCurrentSchemaVersion() > 0 && schemaAndVersion != null + && context._processedSchemas.add(schemaName)) { + schema = migrateSchema(schema, schemaAndVersion.getRight(), context); + } + if (_migrationRegistry.getCurrentTableConfigVersion() > 0 && context._processedTables.add(tableNameWithType)) { + migrateTableConfig(propertyStore, tableNameWithType, schema); + } + } + + private void migrateTableConfig(ZkHelixPropertyStore propertyStore, String tableNameWithType, + @Nullable Schema schema) { + try { + ImmutablePair configAndVersion = + ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableNameWithType, false, false); + if (configAndVersion == null) { + return; + } + TableConfig original = configAndVersion.getLeft(); + MigrationResult result = _migrationRegistry.migrateTableConfig(original); + if (!result.isChanged()) { + return; + } + LOGGER.warn("Table: {} has legacy configuration; recommend updating to config migration version: {}. " + + "Automatic updates enabled: {}", tableNameWithType, result.getVersion(), _autoUpdateEnabled); + _controllerMetrics.addMeteredTableValue(tableNameWithType, ControllerMeter.CONFIG_MIGRATION_RECOMMENDED, 1L); + if (schema == null) { + return; + } + TableConfig migrated = result.getConfig(); + TableConfig effective = TableConfigDecoratorRegistry.applyDecorator( + ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(migrated)); + TableConfig existingEffective = TableConfigDecoratorRegistry.applyDecorator( + ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(original)); + TableConfigUtils.validate(effective, schema, null, existingEffective); + TableConfigValidatorRegistry.validate(effective, schema); + if (!_autoUpdateEnabled) { + return; + } + _pinotHelixResourceManager.setExistingTableConfig(migrated, effective, configAndVersion.getRight(), false); + LOGGER.info("Updated table config for table: {} to migration version: {}", tableNameWithType, + result.getVersion()); + _controllerMetrics.addMeteredTableValue(tableNameWithType, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + } catch (Exception e) { + // Exception messages can contain resolved config values; report only the type, never the config payload. + LOGGER.warn("Could not complete table config migration for table: {}; will recheck next scan ({})", + tableNameWithType, e.getClass().getSimpleName()); + _controllerMetrics.addMeteredTableValue(tableNameWithType, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + } + } + + private Schema migrateSchema(Schema original, int expectedVersion, Context context) { + String schemaName = original.getSchemaName(); + try { + if (ConfigMigrationUtils.getSchemaVersion(original) > _migrationRegistry.getCurrentSchemaVersion()) { + return original; + } + MigrationResult result = _migrationRegistry.migrateSchema(original); + Schema migrated = result.getConfig(); + Map transforms = getSchemaTransforms(migrated); + if (!result.isChanged() && transforms.isEmpty()) { + return original; + } + LOGGER.warn("Schema: {} has legacy configuration; recommend updating to schema migration version: {}. " + + "Automatic updates enabled: {}", schemaName, result.getVersion(), _autoUpdateEnabled); + _controllerMetrics.addMeteredTableValue(schemaName, ControllerMeter.SCHEMA_MIGRATION_RECOMMENDED, 1L); + if (!transforms.isEmpty()) { + return migrateSchemaTransforms(original, migrated, expectedVersion, transforms, context); + } + List tableConfigs = new ArrayList<>(); + for (String tableName : _pinotHelixResourceManager.getTableNamesForSchemaMigration(schemaName)) { + TableConfig config = _pinotHelixResourceManager.getTableConfig(tableName); + if (config == null) { + throw new IllegalStateException("Table config unavailable for schema migration"); + } + tableConfigs.add(config); + } + SchemaUtils.validate(migrated, tableConfigs, false, original); + if (!_autoUpdateEnabled) { + return original; + } + if (!_pinotHelixResourceManager.updateSchema(migrated, expectedVersion)) { + _controllerMetrics.addMeteredTableValue(schemaName, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + return original; + } + LOGGER.info("Updated schema: {} to migration version: {}", schemaName, result.getVersion()); + _controllerMetrics.addMeteredTableValue(schemaName, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + return migrated; + } catch (Exception e) { + LOGGER.warn("Could not complete schema migration: {}; will recheck next scan ({})", + schemaName, e.getClass().getSimpleName()); + _controllerMetrics.addMeteredTableValue(schemaName, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + return original; + } + } + + // Read legacy schema transforms deliberately; empty and virtual transforms have different runtime semantics. + @SuppressWarnings("deprecation") + private static Map getSchemaTransforms(Schema schema) { + Map transforms = new LinkedHashMap<>(); + for (FieldSpec field : schema.getAllFieldSpecs()) { + String transform = field.getTransformFunction(); + if (!field.isVirtualColumn() && transform != null && !transform.isEmpty()) { + transforms.put(field.getName(), transform); + } + } + return transforms; + } + + // Clear deprecated schema properties only in a copy whose table replacements are committed atomically. + @SuppressWarnings("deprecation") + private Schema migrateSchemaTransforms(Schema original, Schema candidate, int expectedVersion, + Map transforms, Context context) + throws Exception { + String schemaName = original.getSchemaName(); + Schema migrated = Schema.fromString(candidate.toSingleLineJsonString()); + for (String column : transforms.keySet()) { + migrated.getFieldSpecFor(column).setTransformFunction(null); + } + ConfigMigrationUtils.setSchemaVersion(migrated, _migrationRegistry.getCurrentSchemaVersion()); + List tables = _pinotHelixResourceManager.getTableNamesForSchemaMigration(schemaName); + Map> tableConfigs = new LinkedHashMap<>(); + List effectiveConfigs = new ArrayList<>(); + Set changedTables = new HashSet<>(); + for (String tableName : tables) { + Pair stored = ZKMetadataProvider.getTableConfigWithVersion( + _pinotHelixResourceManager.getPropertyStore(), tableName, false, false); + if (stored == null || ConfigMigrationUtils.getTableConfigVersion(stored.getLeft()) + > _migrationRegistry.getCurrentTableConfigVersion()) { + throw new IllegalStateException("Table config unavailable for schema transform migration"); + } + TableConfig existing = stored.getLeft(); + TableConfig updated = JsonUtils.stringToObject( + _migrationRegistry.migrateTableConfig(existing).getConfig().toJsonString(), TableConfig.class); + addSchemaTransforms(updated, transforms); + boolean changed = !JsonUtils.objectToJsonNode(existing).equals(JsonUtils.objectToJsonNode(updated)); + if (changed) { + ConfigMigrationUtils.setTableConfigVersion(updated, _migrationRegistry.getCurrentTableConfigVersion()); + changedTables.add(tableName); + _controllerMetrics.addMeteredTableValue(tableName, ControllerMeter.CONFIG_MIGRATION_RECOMMENDED, 1L); + } + TableConfig existingEffective = TableConfigDecoratorRegistry.applyDecorator( + ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(existing)); + TableConfig effective = TableConfigDecoratorRegistry.applyDecorator( + ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(updated)); + TableConfig expectedEffective = JsonUtils.stringToObject( + _migrationRegistry.migrateTableConfig(existingEffective).getConfig().toJsonString(), TableConfig.class); + addSchemaTransforms(expectedEffective, transforms); + if (changed) { + ConfigMigrationUtils.setTableConfigVersion(expectedEffective, + _migrationRegistry.getCurrentTableConfigVersion()); + } + if (!JsonUtils.objectToJsonNode(effective).equals(JsonUtils.objectToJsonNode(expectedEffective))) { + throw new IllegalStateException("Moving schema transforms would change the effective table config"); + } + TableConfigUtils.validate(effective, migrated, null, existingEffective); + TableConfigValidatorRegistry.validate(effective, migrated); + effectiveConfigs.add(effective); + tableConfigs.put(tableName, Pair.of(updated, stored.getRight())); + } + SchemaUtils.validate(migrated, effectiveConfigs, false, original); + if (!_autoUpdateEnabled) { + context._processedTables.addAll(tables); + return original; + } + if (!new HashSet<>(_pinotHelixResourceManager.getTableNamesForSchemaMigration(schemaName)) + .equals(tableConfigs.keySet()) + || !_pinotHelixResourceManager.updateSchemaAndTableConfigs(migrated, expectedVersion, tableConfigs)) { + _controllerMetrics.addMeteredTableValue(schemaName, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + return original; + } + context._processedTables.addAll(tables); + for (String table : changedTables) { + _controllerMetrics.addMeteredTableValue(table, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + } + _controllerMetrics.addMeteredTableValue(schemaName, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + LOGGER.info("Moved schema transforms to table configs for schema: {}", schemaName); + return migrated; + } + + private static void addSchemaTransforms(TableConfig config, Map transforms) { + Map existing = getTableTransforms(config); + List updated = new ArrayList<>(); + IngestionConfig ingestion = config.getIngestionConfig(); + if (ingestion != null && ingestion.getTransformConfigs() != null) { + updated.addAll(ingestion.getTransformConfigs()); + } + for (Map.Entry transform : transforms.entrySet()) { + if (!existing.containsKey(transform.getKey())) { + updated.add(new TransformConfig(transform.getKey(), transform.getValue())); + } + } + if (updated.size() != existing.size()) { + if (ingestion == null) { + ingestion = new IngestionConfig(); + config.setIngestionConfig(ingestion); + } + ingestion.setTransformConfigs(updated); + } + } + + private static Map getTableTransforms(TableConfig config) { + Map transforms = new LinkedHashMap<>(); + IngestionConfig ingestion = config.getIngestionConfig(); + if (ingestion != null && ingestion.getTransformConfigs() != null) { + for (TransformConfig transform : ingestion.getTransformConfigs()) { + transforms.put(transform.getColumnName(), transform.getTransformFunction()); + } + } + return transforms; + } +} diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerPeriodicTaskStarterStatelessTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerPeriodicTaskStarterStatelessTest.java index 107325e7009b..73e74a7747b3 100644 --- a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerPeriodicTaskStarterStatelessTest.java +++ b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerPeriodicTaskStarterStatelessTest.java @@ -55,7 +55,7 @@ public ControllerStarter createControllerStarter() { } private class MockControllerStarter extends ControllerStarter { - private static final int NUM_PERIODIC_TASKS = 13; + private static final int NUM_PERIODIC_TASKS = 14; public MockControllerStarter() { super(); diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManagerStatelessTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManagerStatelessTest.java index 1b2f403d9ac6..54601cfe4d34 100644 --- a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManagerStatelessTest.java +++ b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManagerStatelessTest.java @@ -18,6 +18,7 @@ */ package org.apache.pinot.controller.helix.core; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.BiMap; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; @@ -40,16 +41,20 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import org.apache.commons.lang3.tuple.Pair; import org.apache.helix.AccessOption; import org.apache.helix.HelixAdmin; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; +import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.MasterSlaveSMD; +import org.apache.helix.store.zk.AutoFallbackPropertyStore; +import org.apache.helix.store.zk.ZkHelixPropertyStore; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.zkclient.exception.ZkBadVersionException; import org.apache.pinot.common.assignment.PartitionAssignmentUtils; @@ -65,9 +70,12 @@ import org.apache.pinot.common.utils.LLCSegmentName; import org.apache.pinot.common.utils.URIUtils; import org.apache.pinot.common.utils.config.InstanceUtils; +import org.apache.pinot.common.utils.config.SchemaSerDeUtils; +import org.apache.pinot.common.utils.config.TableConfigSerDeUtils; import org.apache.pinot.common.utils.config.TagNameUtils; import org.apache.pinot.common.utils.helix.HelixHelper; import org.apache.pinot.common.utils.helix.LeadControllerUtils; +import org.apache.pinot.common.utils.helix.ZkMultiWriteBuilder; import org.apache.pinot.controller.ControllerConf; import org.apache.pinot.controller.api.exception.InvalidTableConfigException; import org.apache.pinot.controller.api.resources.InstanceInfo; @@ -87,11 +95,13 @@ import org.apache.pinot.spi.config.table.TierConfig; import org.apache.pinot.spi.config.table.ingestion.BatchIngestionConfig; import org.apache.pinot.spi.config.table.ingestion.IngestionConfig; +import org.apache.pinot.spi.config.table.ingestion.TransformConfig; import org.apache.pinot.spi.config.tenant.Tenant; import org.apache.pinot.spi.config.tenant.TenantRole; import org.apache.pinot.spi.data.DateTimeFieldSpec; import org.apache.pinot.spi.data.DimensionFieldSpec; import org.apache.pinot.spi.data.FieldSpec; +import org.apache.pinot.spi.data.FieldSpec.DataType; import org.apache.pinot.spi.data.LogicalTableConfig; import org.apache.pinot.spi.data.Schema; import org.apache.pinot.spi.stream.LongMsgOffset; @@ -103,6 +113,7 @@ import org.apache.pinot.spi.utils.CommonConstants.Helix; import org.apache.pinot.spi.utils.CommonConstants.Segment; import org.apache.pinot.spi.utils.CommonConstants.Server; +import org.apache.pinot.spi.utils.JsonUtils; import org.apache.pinot.spi.utils.builder.TableConfigBuilder; import org.apache.pinot.spi.utils.builder.TableNameBuilder; import org.apache.pinot.util.TestUtils; @@ -115,11 +126,16 @@ import org.testng.annotations.Test; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.*; @@ -1192,6 +1208,366 @@ public void testAddSchemaWithOverrideRefreshesServerCaches() } } + @Test + public void testVersionedSchemaUpdatePreservesConcurrentEditsAndDeletes() + throws Exception { + String schemaName = "versionedSchemaUpdate"; + addDummySchema(schemaName); + try { + var propertyStore = _helixResourceManager.getPropertyStore(); + var original = ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName); + assertNotNull(original); + Schema migrated = createDummySchema(schemaName); + migrated.addField(new DimensionFieldSpec("migrated", DataType.STRING, true)); + PinotHelixResourceManager resourceManager = spy(_helixResourceManager); + String tableNameWithType = TableNameBuilder.OFFLINE.tableNameWithType(schemaName); + doReturn(List.of(tableNameWithType)).when(resourceManager).getExistingTableNamesWithType(schemaName, null); + doNothing().when(resourceManager).sendTableConfigSchemaRefreshMessage(tableNameWithType); + assertTrue(resourceManager.updateSchema(migrated, original.getRight())); + verify(resourceManager).sendTableConfigSchemaRefreshMessage(tableNameWithType); + var updated = ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName); + assertNotNull(updated); + assertEquals(updated.getLeft(), migrated); + assertEquals(updated.getRight().intValue(), original.getRight() + 1); + + Schema stale = createDummySchema(schemaName); + stale.addField(new DimensionFieldSpec("stale", DataType.STRING, true)); + assertFalse(resourceManager.updateSchema(stale, original.getRight())); + assertEquals(_helixResourceManager.getSchema(schemaName), migrated); + assertFalse(ZKMetadataProvider.setSchema(propertyStore, stale, original.getRight())); + assertEquals(_helixResourceManager.getSchema(schemaName), migrated); + + assertTrue(_helixResourceManager.deleteSchema(schemaName)); + assertFalse(ZKMetadataProvider.setSchema(propertyStore, migrated, updated.getRight())); + assertFalse(resourceManager.updateSchema(migrated, updated.getRight())); + assertNull(ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName)); + verify(resourceManager).sendTableConfigSchemaRefreshMessage(tableNameWithType); + } finally { + if (ZKMetadataProvider.isSchemaExists(_helixResourceManager.getPropertyStore(), schemaName)) { + deleteSchema(schemaName); + } + } + } + + @Test + public void testFailedVersionedSchemaWriteDoesNotRefresh() + throws Exception { + String schemaName = "failedSchemaMigration"; + Schema original = createDummySchema(schemaName); + Schema migrated = createDummySchema(schemaName); + migrated.addField(new DimensionFieldSpec("migrated", DataType.STRING, true)); + ZkHelixPropertyStore propertyStore = mock(); + doAnswer(invocation -> { + invocation.getArgument(1).setVersion(3); + return SchemaSerDeUtils.toZNRecord(original); + }).when(propertyStore).get(anyString(), any(Stat.class), eq(AccessOption.PERSISTENT)); + when(propertyStore.set(anyString(), any(ZNRecord.class), eq(3), eq(AccessOption.PERSISTENT))).thenReturn(false); + PinotHelixResourceManager resourceManager = spy(_helixResourceManager); + Field propertyStoreField = PinotHelixResourceManager.class.getDeclaredField("_propertyStore"); + propertyStoreField.setAccessible(true); + propertyStoreField.set(resourceManager, propertyStore); + + assertFalse(resourceManager.updateSchema(migrated, 3)); + verify(propertyStore).set(anyString(), any(ZNRecord.class), eq(3), eq(AccessOption.PERSISTENT)); + verify(propertyStore, never()).exists(anyString(), anyInt()); + verify(resourceManager, never()).sendTableConfigSchemaRefreshMessage(anyString()); + } + + @Test + @SuppressWarnings("deprecation") // Reproduce a stored schema transform before moving it into the table config. + public void testCoordinatedSchemaMigrationChecksTableVersionsAtomically() + throws Exception { + String schemaName = "coordinatedSchemaMigration"; + String tableName = TableNameBuilder.OFFLINE.tableNameWithType(schemaName); + addDummySchema(schemaName); + TableConfig originalTable = new TableConfigBuilder(TableType.OFFLINE).setTableName(schemaName) + .setBrokerTenant(BROKER_TENANT_NAME).setServerTenant(SERVER_TENANT_NAME).build(); + waitForEVToDisappear(tableName); + _helixResourceManager.addTable(originalTable); + var propertyStore = _helixResourceManager.getPropertyStore(); + String tablePath = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(tableName); + try { + Schema original = createDummySchema(schemaName); + original.getFieldSpecFor("dimA").setTransformFunction("lower(sourceDimA)"); + ZKMetadataProvider.setSchema(propertyStore, original); + var schemaAndVersion = ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName); + assertNotNull(schemaAndVersion); + Schema migrated = createDummySchema(schemaName); + TableConfig migratedTable = new TableConfig(originalTable); + IngestionConfig ingestion = new IngestionConfig(); + ingestion.setTransformConfigs(List.of(new TransformConfig("dimA", "lower(sourceDimA)"))); + migratedTable.setIngestionConfig(ingestion); + PinotHelixResourceManager resourceManager = spy(_helixResourceManager); + doNothing().when(resourceManager).sendTableConfigRefreshMessage(tableName); + doNothing().when(resourceManager).sendTableConfigSchemaRefreshMessage(tableName); + + String unreadableTableName = TableNameBuilder.REALTIME.tableNameWithType(schemaName); + String unreadableTablePath = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(unreadableTableName); + ZNRecord unreadableTable = new ZNRecord(unreadableTableName); + assertTrue(propertyStore.set(unreadableTablePath, unreadableTable, AccessOption.PERSISTENT)); + try { + var tableAndVersion = ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableName, false, false); + assertNotNull(tableAndVersion); + assertFalse(resourceManager.updateSchemaAndTableConfigs(migrated, schemaAndVersion.getRight(), + Map.of(tableName, Pair.of(migratedTable, tableAndVersion.getRight())))); + assertEquals(ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName), schemaAndVersion); + assertEquals(ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableName, false, false), + tableAndVersion); + assertEquals(propertyStore.get(unreadableTablePath, null, AccessOption.PERSISTENT), unreadableTable); + } finally { + assertTrue(propertyStore.remove(unreadableTablePath, AccessOption.PERSISTENT)); + } + + for (boolean delete : List.of(false, true)) { + assertTrue(ZKMetadataProvider.setTableConfig(propertyStore, originalTable, -1)); + var tableAndVersion = ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableName, false, false); + assertNotNull(tableAndVersion); + doAnswer(invocation -> { + ZkMultiWriteBuilder transaction = spy(_helixResourceManager.multiWriteZK()); + doAnswer(execute -> { + if (delete) { + assertTrue(propertyStore.remove(tablePath, AccessOption.PERSISTENT)); + } else { + assertTrue(ZKMetadataProvider.setTableConfig(propertyStore, originalTable, -1)); + } + return execute.callRealMethod(); + }).when(transaction).execute(); + return transaction; + }).when(resourceManager).multiWriteZK(); + + assertFalse(resourceManager.updateSchemaAndTableConfigs(migrated, schemaAndVersion.getRight(), + Map.of(tableName, Pair.of(migratedTable, tableAndVersion.getRight())))); + assertEquals(ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName), schemaAndVersion); + assertEquals(ZKMetadataProvider.getTableConfig(propertyStore, tableName, false, false), + delete ? null : originalTable); + } + assertTrue(ZKMetadataProvider.setTableConfig(propertyStore, originalTable, -1)); + var tableAndVersion = ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableName, false, false); + assertNotNull(tableAndVersion); + TableConfig counterpart = new TableConfigBuilder(TableType.REALTIME).setTableName(schemaName).build(); + String counterpartPath = + ZKMetadataProvider.constructPropertyStorePathForResourceConfig(counterpart.getTableName()); + doAnswer(invocation -> { + ZkMultiWriteBuilder transaction = spy(_helixResourceManager.multiWriteZK()); + doAnswer(execute -> { + _helixResourceManager.createTableConfigWithSchemaVersion(counterpart); + return execute.callRealMethod(); + }).when(transaction).execute(); + return transaction; + }).when(resourceManager).multiWriteZK(); + try { + assertFalse(resourceManager.updateSchemaAndTableConfigs(migrated, schemaAndVersion.getRight(), + Map.of(tableName, Pair.of(migratedTable, tableAndVersion.getRight())))); + assertEquals(ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName).getLeft(), original); + assertEquals(ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableName, false, false), + tableAndVersion); + } finally { + assertTrue(propertyStore.remove(counterpartPath, AccessOption.PERSISTENT)); + } + verify(resourceManager, never()).sendTableConfigRefreshMessage(anyString()); + verify(resourceManager, never()).sendTableConfigSchemaRefreshMessage(anyString()); + schemaAndVersion = ZKMetadataProvider.getSchemaWithVersion(propertyStore, schemaName); + assertNotNull(schemaAndVersion); + doAnswer(invocation -> _helixResourceManager.multiWriteZK()).when(resourceManager).multiWriteZK(); + assertTrue(resourceManager.updateSchemaAndTableConfigs(migrated, schemaAndVersion.getRight(), + Map.of(tableName, Pair.of(migratedTable, tableAndVersion.getRight())))); + var updatedTable = ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableName, false, false); + assertNotNull(updatedTable); + assertEquals(updatedTable.getRight().intValue(), tableAndVersion.getRight() + 1); + assertEquals(updatedTable.getLeft().getIngestionConfig().getTransformConfigs(), ingestion.getTransformConfigs()); + assertNull(_helixResourceManager.getSchema(schemaName).getFieldSpecFor("dimA").getTransformFunction()); + + Schema extended = createDummySchema(schemaName); + extended.addField(new DimensionFieldSpec("extra", DataType.STRING, true)); + assertTrue(resourceManager.updateSchemaAndTableConfigs(extended, schemaAndVersion.getRight() + 1, + Map.of(tableName, updatedTable))); + assertEquals(ZKMetadataProvider.getTableConfigWithVersion(propertyStore, tableName, false, false).getRight(), + updatedTable.getRight()); + verify(resourceManager).sendTableConfigRefreshMessage(tableName); + verify(resourceManager, times(2)).sendTableConfigSchemaRefreshMessage(tableName); + } finally { + _helixResourceManager.deleteOfflineTable(schemaName); + deleteSchema(schemaName); + } + } + + @Test + public void testTableCreationRejectsUnreadableSchema() + throws Exception { + String schemaName = "unreadableSchemaCreation"; + String schemaPath = ZKMetadataProvider.constructPropertyStorePathForSchema(schemaName); + TableConfig table = new TableConfigBuilder(TableType.OFFLINE).setTableName(schemaName).build(); + String tablePath = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(table.getTableName()); + var propertyStore = _helixResourceManager.getPropertyStore(); + ZNRecord stored = new ZNRecord(schemaName); + try { + for (String schemaJson : List.of("{", "null")) { + stored.setSimpleField("schemaJSON", schemaJson); + assertTrue(propertyStore.set(schemaPath, stored, AccessOption.PERSISTENT)); + Stat before = new Stat(); + propertyStore.get(schemaPath, before, AccessOption.PERSISTENT); + assertThrows(InvalidTableConfigException.class, + () -> _helixResourceManager.createTableConfigWithSchemaVersion(table)); + Stat after = new Stat(); + assertEquals(propertyStore.get(schemaPath, after, AccessOption.PERSISTENT), stored); + assertEquals(after.getVersion(), before.getVersion()); + assertFalse(propertyStore.exists(tablePath, AccessOption.PERSISTENT)); + } + } finally { + propertyStore.remove(tablePath, AccessOption.PERSISTENT); + propertyStore.remove(schemaPath, AccessOption.PERSISTENT); + } + } + + @Test + public void testTableCreationPromotesFallbackSchemaWithoutLosingStoredFields() + throws Exception { + String schemaName = "fallbackSchemaCreation"; + String schemaPath = ZKMetadataProvider.constructPropertyStorePathForSchema(schemaName); + String clusterRoot = "/" + _helixResourceManager.getHelixClusterName(); + String currentSchemaPath = + PropertyPathBuilder.propertyStore(_helixResourceManager.getHelixClusterName()) + schemaPath; + String legacySchemaPath = clusterRoot + "/HELIX_PROPERTYSTORE" + schemaPath; + var accessor = _helixResourceManager.getHelixZkManager().getHelixDataAccessor().getBaseDataAccessor(); + ZNRecord stored = SchemaSerDeUtils.toZNRecord(createDummySchema(schemaName)); + ObjectNode schemaJson = (ObjectNode) JsonUtils.stringToJsonNode(stored.getSimpleField("schemaJSON")); + schemaJson.put("futureSchemaSetting", "preserve"); + stored.setSimpleField("schemaJSON", schemaJson.toString()); + stored.setMapField("futureRecordSetting", Map.of("key", "preserve")); + TableConfig table = new TableConfigBuilder(TableType.OFFLINE).setTableName(schemaName).build(); + String tablePath = PropertyPathBuilder.propertyStore(_helixResourceManager.getHelixClusterName()) + + ZKMetadataProvider.constructPropertyStorePathForResourceConfig(table.getTableName()); + assertFalse(accessor.exists(currentSchemaPath, AccessOption.PERSISTENT)); + assertTrue(accessor.create(legacySchemaPath, stored, AccessOption.PERSISTENT)); + try { + AutoFallbackPropertyStore propertyStore = new AutoFallbackPropertyStore<>( + (ZkBaseDataAccessor) accessor, + PropertyPathBuilder.propertyStore(_helixResourceManager.getHelixClusterName()), + clusterRoot + "/HELIX_PROPERTYSTORE"); + PinotHelixResourceManager resourceManager = spy(_helixResourceManager); + Field propertyStoreField = PinotHelixResourceManager.class.getDeclaredField("_propertyStore"); + propertyStoreField.setAccessible(true); + propertyStoreField.set(resourceManager, propertyStore); + doAnswer(invocation -> _helixResourceManager.multiWriteZK()).when(resourceManager).multiWriteZK(); + assertNotNull(resourceManager.getSchema(schemaName)); + resourceManager.createTableConfigWithSchemaVersion(table); + ZNRecord promoted = accessor.get(currentSchemaPath, null, AccessOption.PERSISTENT); + assertNotNull(promoted); + assertEquals(promoted.getSimpleFields(), stored.getSimpleFields()); + assertEquals(promoted.getMapFields(), stored.getMapFields()); + assertNotNull(accessor.get(tablePath, null, AccessOption.PERSISTENT)); + } finally { + accessor.remove(tablePath, AccessOption.PERSISTENT); + accessor.remove(currentSchemaPath, AccessOption.PERSISTENT); + accessor.remove(legacySchemaPath, AccessOption.PERSISTENT); + } + } + + @Test + public void testTableConfigMigrationPreservesRawTemplates() + throws Exception { + String rawTableName = "rawTableConfigMigration"; + String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(rawTableName); + addDummySchema(rawTableName); + TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(rawTableName) + .setBrokerTenant(BROKER_TENANT_NAME).setServerTenant(SERVER_TENANT_NAME).build(); + waitForEVToDisappear(offlineTableName); + _helixResourceManager.addTable(tableConfig); + String previousTenant = System.getProperty("MIGRATION_SERVER_TENANT"); + System.setProperty("MIGRATION_SERVER_TENANT", SERVER_TENANT_NAME); + try { + var configAndVersion = ZKMetadataProvider.getTableConfigWithVersion( + _helixResourceManager.getPropertyStore(), offlineTableName, false, false); + assertNotNull(configAndVersion); + TableConfig rawConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(rawTableName) + .setBrokerTenant(BROKER_TENANT_NAME).setServerTenant("${MIGRATION_SERVER_TENANT}").build(); + PinotHelixResourceManager resourceManager = spy(_helixResourceManager); + doNothing().when(resourceManager).sendTableConfigRefreshMessage(offlineTableName); + doNothing().when(resourceManager).sendTableConfigSchemaRefreshMessage(offlineTableName); + resourceManager.setExistingTableConfig(rawConfig, tableConfig, configAndVersion.getRight(), false); + + TableConfig stored = ZKMetadataProvider.getTableConfig( + _helixResourceManager.getPropertyStore(), offlineTableName, false, false); + assertNotNull(stored); + assertEquals(stored.getTenantConfig().getServer(), "${MIGRATION_SERVER_TENANT}"); + verify(resourceManager).sendTableConfigRefreshMessage(offlineTableName); + verify(resourceManager).sendTableConfigSchemaRefreshMessage(offlineTableName); + } finally { + _helixResourceManager.deleteOfflineTable(rawTableName); + deleteSchema(rawTableName); + if (previousTenant == null) { + System.clearProperty("MIGRATION_SERVER_TENANT"); + } else { + System.setProperty("MIGRATION_SERVER_TENANT", previousTenant); + } + } + } + + @Test + public void testAutomaticMigrationRejectsUnknownStoredFields() + throws Exception { + String rawTableName = "unknownMigrationFields"; + String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(rawTableName); + addDummySchema(rawTableName); + TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(rawTableName) + .setBrokerTenant(BROKER_TENANT_NAME).setServerTenant(SERVER_TENANT_NAME).build(); + waitForEVToDisappear(offlineTableName); + _helixResourceManager.addTable(tableConfig); + var propertyStore = _helixResourceManager.getPropertyStore(); + String schemaPath = ZKMetadataProvider.constructPropertyStorePathForSchema(rawTableName); + String tablePath = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(offlineTableName); + PinotHelixResourceManager resourceManager = spy(_helixResourceManager); + doNothing().when(resourceManager).sendTableConfigRefreshMessage(offlineTableName); + doNothing().when(resourceManager).sendTableConfigSchemaRefreshMessage(offlineTableName); + try { + Schema original = createDummySchema(rawTableName); + Schema migrated = createDummySchema(rawTableName); + migrated.addField(new DimensionFieldSpec("migrated", DataType.STRING, true)); + for (int i = 0; i < 3; i++) { + ZNRecord storedSchema = SchemaSerDeUtils.toZNRecord(original); + ObjectNode schemaJson = (ObjectNode) JsonUtils.stringToJsonNode(storedSchema.getSimpleField("schemaJSON")); + ObjectNode field = (ObjectNode) schemaJson.get("dimensionFieldSpecs").get(0); + if (i == 0) { + field.putObject("futureOptions"); + } else if (i == 1) { + field.putArray("futureOptions"); + } else { + storedSchema.setSimpleField("futureSetting", "retained"); + storedSchema.setMapField("futureMap", Map.of()); + storedSchema.setListField("futureList", List.of()); + } + storedSchema.setSimpleField("schemaJSON", schemaJson.toString()); + assertTrue(propertyStore.set(schemaPath, storedSchema, AccessOption.PERSISTENT)); + Stat stat = new Stat(); + propertyStore.get(schemaPath, stat, AccessOption.PERSISTENT); + assertFalse(resourceManager.updateSchema(migrated, stat.getVersion())); + assertEquals(propertyStore.get(schemaPath, null, AccessOption.PERSISTENT), storedSchema); + + ZNRecord storedTable = TableConfigSerDeUtils.toZNRecord(tableConfig); + ObjectNode indexing = + (ObjectNode) JsonUtils.stringToJsonNode(storedTable.getSimpleField(TableConfig.INDEXING_CONFIG_KEY)); + if (i == 0) { + indexing.putObject("futureOptions"); + } else if (i == 1) { + indexing.putArray("futureOptions"); + } else { + storedTable.setListField("futureList", List.of()); + } + storedTable.setSimpleField(TableConfig.INDEXING_CONFIG_KEY, indexing.toString()); + assertTrue(propertyStore.set(tablePath, storedTable, AccessOption.PERSISTENT)); + propertyStore.get(tablePath, stat, AccessOption.PERSISTENT); + assertThrows(IllegalStateException.class, + () -> resourceManager.setExistingTableConfig(tableConfig, tableConfig, stat.getVersion(), false)); + assertEquals(propertyStore.get(tablePath, null, AccessOption.PERSISTENT), storedTable); + } + verify(resourceManager, never()).sendTableConfigRefreshMessage(offlineTableName); + verify(resourceManager, never()).sendTableConfigSchemaRefreshMessage(offlineTableName); + } finally { + _helixResourceManager.deleteOfflineTable(rawTableName); + deleteSchema(rawTableName); + } + } + /// Tests the code path where a subset of merged segments (from the original segmentsTo list) /// is passed to the endReplace API. /// @throws Exception diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerIntegrationTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerIntegrationTest.java new file mode 100644 index 000000000000..a434b2a19d59 --- /dev/null +++ b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerIntegrationTest.java @@ -0,0 +1,210 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.controller.helix.core.periodictask; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.apache.helix.AccessOption; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.pinot.common.metadata.ZKMetadataProvider; +import org.apache.pinot.common.metrics.ControllerMeter; +import org.apache.pinot.common.metrics.ControllerMetrics; +import org.apache.pinot.controller.ControllerConf; +import org.apache.pinot.controller.helix.ControllerTest; +import org.apache.pinot.segment.local.utils.migration.DefaultConfigMigrationRegistry; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.config.table.TableType; +import org.apache.pinot.spi.config.table.ingestion.TransformConfig; +import org.apache.pinot.spi.data.FieldSpec.DataType; +import org.apache.pinot.spi.data.Schema; +import org.apache.pinot.spi.data.TimeFieldSpec; +import org.apache.pinot.spi.data.TimeGranularitySpec; +import org.apache.pinot.spi.utils.builder.TableConfigBuilder; +import org.apache.pinot.spi.utils.builder.TableNameBuilder; +import org.apache.pinot.util.TestUtils; +import org.apache.zookeeper.data.Stat; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + + +/// Exercises warning-only and opted-in migration through the real controller resource manager and ZooKeeper store. +// Legacy APIs are deliberately used to reproduce definitions stored by older Pinot versions. +@SuppressWarnings({"deprecation", "removal"}) +@Test(groups = "stateless") +public class ConfigMigrationManagerIntegrationTest extends ControllerTest { + private static final String TABLE_NAME = "migrationDefinition"; + private static final String TABLE_NAME_WITH_TYPE = TableNameBuilder.OFFLINE.tableNameWithType(TABLE_NAME); + private static final String REPLICATION_TEMPLATE = "${pinot.migration.test.replication:1}"; + + @Override + protected void overrideControllerConf(Map properties) { + properties.put(ControllerConf.ControllerPeriodicTasksConf.CONFIG_MIGRATION_INITIAL_DELAY_SECONDS, 3600); + } + + @BeforeClass + public void setUp() + throws Exception { + startZk(); + startController(); + addFakeBrokerInstancesToAutoJoinHelixCluster(1, true); + addFakeServerInstancesToAutoJoinHelixCluster(1, true); + } + + @AfterClass(alwaysRun = true) + public void tearDown() { + stopFakeInstances(); + stopController(); + stopZk(); + } + + @Test + public void testUnreadableHybridCounterpartPreservesSchemaTransforms() + throws Exception { + String schemaName = "unreadableHybridMigration"; + String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(schemaName); + String realtimeTableName = TableNameBuilder.REALTIME.tableNameWithType(schemaName); + String realtimePath = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(realtimeTableName); + Schema originalSchema = new Schema.SchemaBuilder().setSchemaName(schemaName) + .addSingleValueDimension("country", DataType.STRING).build(); + originalSchema.getFieldSpecFor("country").setTransformFunction("lower(rawCountry)"); + ZKMetadataProvider.setSchema(_propertyStore, originalSchema); + TableConfig legacyTable = new TableConfigBuilder(TableType.OFFLINE).setTableName(schemaName) + .setSegmentPushType("APPEND").build(); + _helixResourceManager.addTable(legacyTable); + ZNRecord unreadableCounterpart = new ZNRecord(realtimeTableName); + assertTrue(_propertyStore.set(realtimePath, unreadableCounterpart, AccessOption.PERSISTENT)); + var schemaBefore = ZKMetadataProvider.getSchemaWithVersion(_propertyStore, schemaName); + ConfigMigrationManager manager = new ConfigMigrationManager(_helixResourceManager, + _controllerStarter.getLeadControllerManager(), new ControllerConf(), _controllerStarter.getControllerMetrics(), + DefaultConfigMigrationRegistry.create()); + String autoUpdateKey = ControllerConf.ControllerPeriodicTasksConf.CONFIG_MIGRATION_AUTO_UPDATE_ENABLED; + manager.onChange(Set.of(autoUpdateKey), Map.of(autoUpdateKey, "true")); + try { + manager.processTable(offlineTableName, new ConfigMigrationManager.Context()); + assertEquals(ZKMetadataProvider.getSchemaWithVersion(_propertyStore, schemaName), schemaBefore); + assertEquals(_propertyStore.get(realtimePath, null, AccessOption.PERSISTENT), unreadableCounterpart); + TableConfig migratedTable = ZKMetadataProvider.getTableConfig(_propertyStore, offlineTableName, false, false); + assertNotNull(migratedTable); + assertNull(migratedTable.getValidationConfig().getSegmentPushType()); + assertEquals(migratedTable.getIngestionConfig().getBatchIngestionConfig().getSegmentIngestionType(), "APPEND"); + assertNull(migratedTable.getIngestionConfig().getTransformConfigs()); + + assertTrue(_propertyStore.remove(realtimePath, AccessOption.PERSISTENT)); + manager.processTable(offlineTableName, new ConfigMigrationManager.Context()); + assertNull(ZKMetadataProvider.getSchema(_propertyStore, schemaName).getFieldSpecFor("country") + .getTransformFunction()); + assertEquals(ZKMetadataProvider.getTableConfig(_propertyStore, offlineTableName, false, false) + .getIngestionConfig().getTransformConfigs(), + List.of(new TransformConfig("country", "lower(rawCountry)"))); + } finally { + _propertyStore.remove(realtimePath, AccessOption.PERSISTENT); + } + } + + @Test + public void testWarningOnlyThenOptedInUpdatesBothStoredDefinitions() + throws Exception { + Schema legacySchema = new Schema.SchemaBuilder().setSchemaName(TABLE_NAME) + .addSingleValueDimension("country", DataType.STRING).build(); + legacySchema.getFieldSpecFor("country").setTransformFunction("lower(rawCountry)"); + legacySchema.addField(new TimeFieldSpec( + new TimeGranularitySpec(DataType.LONG, TimeUnit.SECONDS, "eventTimeSeconds"), + new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "eventTime"))); + // New REST submissions reject TIME; direct persistence reproduces an existing legacy schema. + ZKMetadataProvider.setSchema(_propertyStore, legacySchema); + TableConfig legacyTable = new TableConfigBuilder(TableType.OFFLINE).setTableName(TABLE_NAME) + .setTimeColumnName("eventTime").setSegmentPushType("APPEND").setSegmentPushFrequency("HOURLY").build(); + _helixResourceManager.addTable(legacyTable); + legacyTable.getValidationConfig().setReplication(REPLICATION_TEMPLATE); + assertTrue(ZKMetadataProvider.setTableConfig(_propertyStore, legacyTable, -1)); + + String tablePath = ZKMetadataProvider.constructPropertyStorePathForResourceConfig(TABLE_NAME_WITH_TYPE); + String schemaPath = ZKMetadataProvider.constructPropertyStorePathForSchema(TABLE_NAME); + Stat tableBefore = new Stat(); + Stat schemaBefore = new Stat(); + ZNRecord tableRecord = _propertyStore.get(tablePath, tableBefore, AccessOption.PERSISTENT); + ZNRecord schemaRecord = _propertyStore.get(schemaPath, schemaBefore, AccessOption.PERSISTENT); + ControllerMetrics metrics = _controllerStarter.getControllerMetrics(); + long tableRecommendations = metrics.getMeteredTableValue(TABLE_NAME_WITH_TYPE, + ControllerMeter.CONFIG_MIGRATION_RECOMMENDED).count(); + long schemaRecommendations = metrics.getMeteredTableValue(TABLE_NAME, + ControllerMeter.SCHEMA_MIGRATION_RECOMMENDED).count(); + + TestUtils.waitForCondition(() -> { + if (metrics.getMeteredTableValue(TABLE_NAME_WITH_TYPE, + ControllerMeter.CONFIG_MIGRATION_RECOMMENDED).count() > tableRecommendations + && metrics.getMeteredTableValue(TABLE_NAME, + ControllerMeter.SCHEMA_MIGRATION_RECOMMENDED).count() > schemaRecommendations) { + return true; + } + runPeriodicTask(ConfigMigrationManager.TASK_NAME, TABLE_NAME, TableType.OFFLINE); + return false; + }, 500, 10_000, "Warning-only scan did not report both definitions", null); + + Stat tableAfterWarning = new Stat(); + Stat schemaAfterWarning = new Stat(); + assertEquals(_propertyStore.get(tablePath, tableAfterWarning, AccessOption.PERSISTENT), tableRecord); + assertEquals(_propertyStore.get(schemaPath, schemaAfterWarning, AccessOption.PERSISTENT), schemaRecord); + assertEquals(tableAfterWarning.getVersion(), tableBefore.getVersion()); + assertEquals(schemaAfterWarning.getVersion(), schemaBefore.getVersion()); + updateClusterConfig(Map.of(ControllerConf.ControllerPeriodicTasksConf.CONFIG_MIGRATION_AUTO_UPDATE_ENABLED, + "true")); + TestUtils.waitForCondition(() -> { + if (ZKMetadataProvider.getTableConfigWithVersion(_propertyStore, TABLE_NAME_WITH_TYPE, false, false) + .getRight() > tableBefore.getVersion() + && ZKMetadataProvider.getSchemaWithVersion(_propertyStore, TABLE_NAME).getRight() + > schemaBefore.getVersion()) { + return true; + } + runPeriodicTask(ConfigMigrationManager.TASK_NAME, TABLE_NAME, TableType.OFFLINE); + return false; + }, 500, 10_000, "Cluster config did not enable schema and table updates without a restart", null); + + var storedTable = ZKMetadataProvider.getTableConfigWithVersion( + _propertyStore, TABLE_NAME_WITH_TYPE, false, false); + var storedSchema = ZKMetadataProvider.getSchemaWithVersion(_propertyStore, TABLE_NAME); + assertNotNull(storedTable); + assertNotNull(storedSchema); + assertEquals(storedTable.getRight().intValue(), tableBefore.getVersion() + 1); + assertEquals(storedSchema.getRight().intValue(), schemaBefore.getVersion() + 1); + assertEquals(storedTable.getLeft().getValidationConfig().getReplication(), REPLICATION_TEMPLATE); + assertNull(storedTable.getLeft().getValidationConfig().getSegmentPushType()); + assertEquals(storedTable.getLeft().getIngestionConfig().getBatchIngestionConfig().getSegmentIngestionType(), + "APPEND"); + assertEquals(storedTable.getLeft().getIngestionConfig().getBatchIngestionConfig().getSegmentIngestionFrequency(), + "HOURLY"); + assertNull(storedSchema.getLeft().getTimeFieldSpec()); + assertNotNull(storedSchema.getLeft().getDateTimeSpec("eventTime")); + assertNull(storedSchema.getLeft().getDateTimeSpec("eventTime").getTransformFunction()); + assertNull(storedSchema.getLeft().getFieldSpecFor("country").getTransformFunction()); + assertEquals(storedTable.getLeft().getIngestionConfig().getTransformConfigs().stream() + .collect(Collectors.toMap(TransformConfig::getColumnName, TransformConfig::getTransformFunction)), + Map.of("country", "lower(rawCountry)", "eventTime", "fromEpochSeconds(eventTimeSeconds)")); + assertEquals(_helixResourceManager.getTableConfig(TABLE_NAME_WITH_TYPE).getReplication(), 1); + } +} diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerTest.java new file mode 100644 index 000000000000..e8ed355fb226 --- /dev/null +++ b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/periodictask/ConfigMigrationManagerTest.java @@ -0,0 +1,508 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.controller.helix.core.periodictask; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.helix.AccessOption; +import org.apache.helix.store.zk.ZkHelixPropertyStore; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.pinot.common.metrics.ControllerMeter; +import org.apache.pinot.common.metrics.ControllerMetrics; +import org.apache.pinot.common.utils.config.SchemaSerDeUtils; +import org.apache.pinot.common.utils.config.TableConfigSerDeUtils; +import org.apache.pinot.controller.ControllerConf; +import org.apache.pinot.controller.LeadControllerManager; +import org.apache.pinot.controller.helix.core.PinotHelixResourceManager; +import org.apache.pinot.core.realtime.impl.fakestream.FakeStreamConfigUtils; +import org.apache.pinot.segment.local.utils.migration.DefaultConfigMigrationRegistry; +import org.apache.pinot.spi.config.migration.ConfigMigrationRegistry; +import org.apache.pinot.spi.config.migration.ConfigMigrationUtils; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.config.table.TableType; +import org.apache.pinot.spi.config.table.TenantConfig; +import org.apache.pinot.spi.config.table.ingestion.IngestionConfig; +import org.apache.pinot.spi.config.table.ingestion.StreamIngestionConfig; +import org.apache.pinot.spi.config.table.ingestion.TransformConfig; +import org.apache.pinot.spi.data.DateTimeFieldSpec; +import org.apache.pinot.spi.data.DimensionFieldSpec; +import org.apache.pinot.spi.data.FieldSpec.DataType; +import org.apache.pinot.spi.data.Schema; +import org.apache.pinot.spi.data.TimeGranularitySpec; +import org.apache.pinot.spi.utils.TableConfigDecoratorRegistry; +import org.apache.pinot.spi.utils.builder.TableConfigBuilder; +import org.apache.pinot.spi.utils.builder.TableNameBuilder; +import org.apache.zookeeper.data.Stat; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + + +/// Exercises reporting-only defaults, explicit writes, failure reporting, and shared-schema deduplication. +public class ConfigMigrationManagerTest { + private static final String RAW_TABLE_NAME = "myTable"; + private static final String OFFLINE_TABLE_NAME = TableNameBuilder.OFFLINE.tableNameWithType(RAW_TABLE_NAME); + private static final String REALTIME_TABLE_NAME = TableNameBuilder.REALTIME.tableNameWithType(RAW_TABLE_NAME); + private static final String CONFIG_PATH = "/CONFIGS/TABLE/" + OFFLINE_TABLE_NAME; + private static final String SCHEMA_PATH = "/SCHEMAS/" + RAW_TABLE_NAME; + private static final String AUTO_UPDATE_KEY = + ControllerConf.ControllerPeriodicTasksConf.CONFIG_MIGRATION_AUTO_UPDATE_ENABLED; + + private ZkHelixPropertyStore _propertyStore; + private PinotHelixResourceManager _resourceManager; + private ControllerMetrics _controllerMetrics; + + @SuppressWarnings("unchecked") + @BeforeMethod + public void setUp() + throws Exception { + _propertyStore = mock(ZkHelixPropertyStore.class); + _resourceManager = mock(PinotHelixResourceManager.class); + when(_resourceManager.getPropertyStore()).thenReturn(_propertyStore); + when(_resourceManager.getTableNamesForSchemaMigration(RAW_TABLE_NAME)).thenReturn(List.of()); + _controllerMetrics = mock(ControllerMetrics.class); + } + + private ConfigMigrationManager newManager(boolean autoUpdate, ConfigMigrationRegistry registry) { + ConfigMigrationManager manager = + new ConfigMigrationManager(_resourceManager, mock(LeadControllerManager.class), new ControllerConf(), + _controllerMetrics, registry); + Map clusterConfig = autoUpdate ? Map.of(AUTO_UPDATE_KEY, "true") : Map.of(); + manager.onChange(clusterConfig.keySet(), clusterConfig); + return manager; + } + + private void stubRecord(String path, ZNRecord record, int version) { + when(_propertyStore.get(eq(path), any(), eq(AccessOption.PERSISTENT))).thenAnswer(invocation -> { + Stat stat = invocation.getArgument(1); + if (stat != null) { + stat.setVersion(version); + } + return record; + }); + } + + private void stubTable(TableConfig config) + throws Exception { + stubRecord(CONFIG_PATH, TableConfigSerDeUtils.toZNRecord(config), 7); + } + + // Exercise the legacy stored format that this task recommends replacing. + @SuppressWarnings({"deprecation", "removal"}) + private static TableConfig legacyTable() { + return new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME) + .setSegmentPushType("APPEND").setSegmentPushFrequency("HOURLY").build(); + } + + // Remove the deprecated property emitted by the builder to reproduce a modern stored config. + @SuppressWarnings("deprecation") + private static TableConfig currentTable() { + TableConfig config = new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).build(); + // The builder still emits the old APPEND property by default; a modern definition does not contain it. + config.getValidationConfig().setSegmentPushType(null); + return config; + } + + private static Schema currentSchema() { + return new Schema.SchemaBuilder().setSchemaName(RAW_TABLE_NAME) + .addSingleValueDimension("d", DataType.STRING).build(); + } + + private static IngestionConfig ingestionTransforms(TransformConfig... transforms) { + IngestionConfig ingestion = new IngestionConfig(); + ingestion.setTransformConfigs(List.of(transforms)); + return ingestion; + } + + private static Map transforms(TableConfig table) { + return table.getIngestionConfig().getTransformConfigs().stream() + .collect(Collectors.toMap(TransformConfig::getColumnName, TransformConfig::getTransformFunction)); + } + + @SuppressWarnings("deprecation") // Stored schema transforms are the migration inputs. + private Schema stubSchemaTransform(TableConfig table) + throws Exception { + Schema schema = currentSchema(); + schema.getFieldSpecFor("d").setTransformFunction("lower(sourceD)"); + stubTable(table); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(schema), 3); + when(_resourceManager.getTableNamesForSchemaMigration(RAW_TABLE_NAME)) + .thenReturn(List.of(OFFLINE_TABLE_NAME)); + return schema; + } + + @SuppressWarnings("deprecation") // Stored TIME schemas remain readable and are migration inputs. + private static Schema legacySchema() { + return new Schema.SchemaBuilder().setSchemaName(RAW_TABLE_NAME) + .addTime(new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "ts"), null).build(); + } + + @Test + public void testClusterConfigControlsBothDefinitionUpdates() + throws Exception { + TableConfig table = legacyTable(); + Schema schema = legacySchema(); + String originalTable = table.toJsonString(); + String originalSchema = schema.toSingleLineJsonString(); + stubTable(table); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(schema), 3); + + ConfigMigrationManager manager = newManager(false, DefaultConfigMigrationRegistry.create()); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + + verify(_controllerMetrics) + .addMeteredTableValue(OFFLINE_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_RECOMMENDED, 1L); + verify(_controllerMetrics).addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.SCHEMA_MIGRATION_RECOMMENDED, 1L); + verify(_resourceManager, never()).setExistingTableConfig(any(), any(), anyInt(), anyBoolean()); + verify(_resourceManager, never()).updateSchema(any(), anyInt()); + verify(_propertyStore, never()).set(any(), any(), anyInt(), anyInt()); + assertEquals(table.toJsonString(), originalTable); + assertEquals(schema.toSingleLineJsonString(), originalSchema); + + when(_resourceManager.updateSchema(any(), eq(3))).thenReturn(true); + manager.onChange(Set.of(AUTO_UPDATE_KEY), Map.of(AUTO_UPDATE_KEY, "true")); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_resourceManager).setExistingTableConfig(any(), any(), eq(7), eq(false)); + verify(_resourceManager).updateSchema(any(), eq(3)); + + manager.onChange(Set.of("unrelated"), Map.of()); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_resourceManager, times(2)).setExistingTableConfig(any(), any(), eq(7), eq(false)); + verify(_resourceManager, times(2)).updateSchema(any(), eq(3)); + + manager.onChange(Set.of(AUTO_UPDATE_KEY), Map.of(AUTO_UPDATE_KEY, "false")); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_resourceManager, times(2)).setExistingTableConfig(any(), any(), eq(7), eq(false)); + verify(_resourceManager, times(2)).updateSchema(any(), eq(3)); + + manager.onChange(Set.of(AUTO_UPDATE_KEY), Map.of(AUTO_UPDATE_KEY, "true")); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + manager.onChange(Set.of(AUTO_UPDATE_KEY), Map.of()); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_resourceManager, times(3)).setExistingTableConfig(any(), any(), eq(7), eq(false)); + verify(_resourceManager, times(3)).updateSchema(any(), eq(3)); + } + + @Test + @SuppressWarnings({"deprecation", "removal"}) // Exercise a template in the legacy property being migrated. + public void testTableUpdateKeepsRawTemplateAndUsesResolvedRuntimeConfig() + throws Exception { + String property = "pinot.migration.test.pushType"; + String previous = System.setProperty(property, "APPEND"); + try (MockedStatic decorators = mockStatic(TableConfigDecoratorRegistry.class)) { + decorators.when(() -> TableConfigDecoratorRegistry.applyDecorator(any())).thenAnswer(invocation -> { + TableConfig decorated = invocation.getArgument(0); + TenantConfig tenant = decorated.getTenantConfig(); + decorated.setTenantConfig( + new TenantConfig(tenant.getBroker(), "decoratedTenant", tenant.getTagOverrideConfig())); + return decorated; + }); + TableConfig config = legacyTable(); + // Intentionally use the legacy template to verify conversion does not persist the resolved value. + config.getValidationConfig().setSegmentPushType("${" + property + "}"); + stubTable(config); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(currentSchema()), 3); + + newManager(true, DefaultConfigMigrationRegistry.create()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + + ArgumentCaptor raw = ArgumentCaptor.forClass(TableConfig.class); + ArgumentCaptor effective = ArgumentCaptor.forClass(TableConfig.class); + verify(_resourceManager).setExistingTableConfig(raw.capture(), effective.capture(), eq(7), eq(false)); + assertEquals(raw.getValue().getIngestionConfig().getBatchIngestionConfig().getSegmentIngestionType(), + "${" + property + "}"); + assertEquals(effective.getValue().getIngestionConfig().getBatchIngestionConfig().getSegmentIngestionType(), + "APPEND"); + assertEquals(effective.getValue().getTenantConfig().getServer(), "decoratedTenant"); + assertEquals(raw.getValue().getTenantConfig().getServer(), config.getTenantConfig().getServer()); + verify(_controllerMetrics).addMeteredTableValue(OFFLINE_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + } finally { + if (previous == null) { + System.clearProperty(property); + } else { + System.setProperty(property, previous); + } + } + } + + @Test + public void testModernUnmarkedDefinitionsProduceNoRecommendation() + throws Exception { + stubTable(currentTable()); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(currentSchema()), 3); + newManager(true, DefaultConfigMigrationRegistry.create()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verifyNoInteractions(_controllerMetrics); + verify(_resourceManager, never()).setExistingTableConfig(any(), any(), anyInt(), anyBoolean()); + verify(_resourceManager, never()).updateSchema(any(), anyInt()); + } + + @Test + public void testTableConflictDoesNotReportSuccess() + throws Exception { + stubTable(legacyTable()); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(currentSchema()), 3); + doThrow(new IllegalStateException("version mismatch")).when(_resourceManager) + .setExistingTableConfig(any(), any(), eq(7), eq(false)); + newManager(true, DefaultConfigMigrationRegistry.create()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_controllerMetrics) + .addMeteredTableValue(OFFLINE_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + verify(_controllerMetrics, never()) + .addMeteredTableValue(OFFLINE_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + } + + @Test + public void testSchemaConflictDoesNotReportSuccess() + throws Exception { + stubTable(currentTable()); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(legacySchema()), 3); + when(_resourceManager.updateSchema(any(), eq(3))).thenReturn(false); + newManager(true, DefaultConfigMigrationRegistry.create()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_resourceManager).updateSchema(any(), eq(3)); + verify(_controllerMetrics).addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + verify(_controllerMetrics, never()) + .addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + } + + @Test + @SuppressWarnings("deprecation") // Assert that the legacy TIME field was removed. + public void testSharedSchemaUpdatedOnce() + throws Exception { + stubTable(currentTable()); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(legacySchema()), 3); + when(_resourceManager.updateSchema(any(), eq(3))).thenReturn(true); + ConfigMigrationManager manager = newManager(true, DefaultConfigMigrationRegistry.create()); + ConfigMigrationManager.Context context = new ConfigMigrationManager.Context(); + manager.processTable(OFFLINE_TABLE_NAME, context); + manager.processTable(REALTIME_TABLE_NAME, context); + ArgumentCaptor schema = ArgumentCaptor.forClass(Schema.class); + verify(_resourceManager, times(1)).updateSchema(schema.capture(), eq(3)); + assertNull(schema.getValue().getTimeFieldSpec()); + assertEquals(schema.getValue().getDateTimeFieldSpecs().get(0).getName(), "ts"); + verify(_controllerMetrics).addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + } + + @Test + @SuppressWarnings("deprecation") // Exercise existing schema transforms and remove the builder's legacy push type. + public void testSchemaTransformsMoveToBothHybridTablesAfterOptIn() + throws Exception { + TableConfig offline = currentTable(); + offline.setIngestionConfig(ingestionTransforms(new TransformConfig("d", "trim(sourceD)"))); + Schema schema = stubSchemaTransform(offline); + schema.addField(new DimensionFieldSpec("copied", DataType.STRING, true)); + schema.getFieldSpecFor("copied").setTransformFunction("lower(sourceCopied)"); + schema.addField(new DateTimeFieldSpec("ts", DataType.LONG, + "1:MILLISECONDS:EPOCH", "1:MILLISECONDS")); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(schema), 3); + TableConfig realtime = new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME) + .setTimeColumnName("ts").build(); + realtime.getValidationConfig().setSegmentPushType(null); + IngestionConfig realtimeIngestion = ingestionTransforms(new TransformConfig("d", "upper(sourceD)")); + realtimeIngestion.setStreamIngestionConfig(new StreamIngestionConfig( + List.of(FakeStreamConfigUtils.getDefaultLowLevelStreamConfigs().getStreamConfigsMap()))); + realtime.setIngestionConfig(realtimeIngestion); + stubRecord("/CONFIGS/TABLE/" + REALTIME_TABLE_NAME, TableConfigSerDeUtils.toZNRecord(realtime), 11); + when(_resourceManager.getTableNamesForSchemaMigration(RAW_TABLE_NAME)) + .thenReturn(List.of(OFFLINE_TABLE_NAME, REALTIME_TABLE_NAME)); + String originalSchema = schema.toSingleLineJsonString(); + ConfigMigrationManager manager = newManager(false, DefaultConfigMigrationRegistry.create()); + ConfigMigrationManager.Context context = new ConfigMigrationManager.Context(); + manager.processTable(OFFLINE_TABLE_NAME, context); + manager.processTable(REALTIME_TABLE_NAME, context); + verify(_controllerMetrics) + .addMeteredTableValue(OFFLINE_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_RECOMMENDED, 1L); + verify(_controllerMetrics) + .addMeteredTableValue(REALTIME_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_RECOMMENDED, 1L); + verify(_resourceManager, never()).updateSchemaAndTableConfigs(any(), anyInt(), any()); + verify(_resourceManager, never()).updateSchema(any(), anyInt()); + verify(_resourceManager, never()).setExistingTableConfig(any(), any(), anyInt(), anyBoolean()); + + when(_resourceManager.updateSchemaAndTableConfigs(any(), eq(3), any())).thenReturn(true); + manager.onChange(Set.of(AUTO_UPDATE_KEY), Map.of(AUTO_UPDATE_KEY, "true")); + context = new ConfigMigrationManager.Context(); + manager.processTable(OFFLINE_TABLE_NAME, context); + manager.processTable(REALTIME_TABLE_NAME, context); + ArgumentCaptor migrated = ArgumentCaptor.forClass(Schema.class); + @SuppressWarnings("unchecked") + ArgumentCaptor>> tables = ArgumentCaptor.forClass(Map.class); + verify(_resourceManager).updateSchemaAndTableConfigs(migrated.capture(), eq(3), tables.capture()); + assertNull(migrated.getValue().getFieldSpecFor("d").getTransformFunction()); + assertNull(migrated.getValue().getFieldSpecFor("copied").getTransformFunction()); + assertEquals(tables.getValue().keySet(), Set.of(OFFLINE_TABLE_NAME, REALTIME_TABLE_NAME)); + assertEquals(tables.getValue().get(OFFLINE_TABLE_NAME).getRight().intValue(), 7); + assertEquals(tables.getValue().get(REALTIME_TABLE_NAME).getRight().intValue(), 11); + assertEquals(transforms(tables.getValue().get(OFFLINE_TABLE_NAME).getLeft()), + Map.of("d", "trim(sourceD)", "copied", "lower(sourceCopied)")); + assertEquals(transforms(tables.getValue().get(REALTIME_TABLE_NAME).getLeft()), + Map.of("d", "upper(sourceD)", "copied", "lower(sourceCopied)")); + for (Pair table : tables.getValue().values()) { + assertEquals(ConfigMigrationUtils.getTableConfigVersion(table.getLeft()), 1); + } + assertEquals(schema.toSingleLineJsonString(), originalSchema); + } + + @Test + public void testSchemaTransformConflictAndFailureDoNotReportSuccess() + throws Exception { + Schema schema = stubSchemaTransform(legacyTable()); + String original = schema.toSingleLineJsonString(); + when(_resourceManager.updateSchemaAndTableConfigs(any(), eq(3), any())) + .thenReturn(false).thenThrow(new IllegalStateException("version mismatch")); + ConfigMigrationManager manager = newManager(true, DefaultConfigMigrationRegistry.create()); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + manager.processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_resourceManager, times(2)).updateSchemaAndTableConfigs(any(), eq(3), any()); + verify(_resourceManager, times(2)).setExistingTableConfig(any(), any(), eq(7), eq(false)); + verify(_resourceManager, never()).updateSchema(any(), anyInt()); + verify(_controllerMetrics, times(2)) + .addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + verify(_controllerMetrics, never()) + .addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_SUCCESS, 1L); + assertEquals(schema.toSingleLineJsonString(), original); + } + + @Test + public void testUnreadableHybridTableDoesNotBlockIndependentTableMigration() + throws Exception { + Schema schema = stubSchemaTransform(legacyTable()); + String original = schema.toSingleLineJsonString(); + when(_resourceManager.getTableNamesForSchemaMigration(RAW_TABLE_NAME)) + .thenReturn(List.of(OFFLINE_TABLE_NAME, REALTIME_TABLE_NAME)); + ConfigMigrationManager manager = newManager(true, DefaultConfigMigrationRegistry.create()); + ConfigMigrationManager.Context context = new ConfigMigrationManager.Context(); + manager.processTable(OFFLINE_TABLE_NAME, context); + manager.processTable(REALTIME_TABLE_NAME, context); + verify(_resourceManager).setExistingTableConfig(any(), any(), eq(7), eq(false)); + verify(_resourceManager, never()).updateSchemaAndTableConfigs(any(), anyInt(), any()); + verify(_resourceManager, never()).updateSchema(any(), anyInt()); + verify(_controllerMetrics).addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + assertEquals(schema.toSingleLineJsonString(), original); + } + + @Test + @SuppressWarnings("deprecation") // Empty and virtual legacy transforms retain their existing behavior. + public void testEmptyAndVirtualSchemaTransformsAreUnchanged() + throws Exception { + Schema schema = currentSchema(); + schema.getFieldSpecFor("d").setTransformFunction(""); + DimensionFieldSpec virtual = new DimensionFieldSpec("virtual", DataType.STRING, true); + virtual.setVirtualColumnProvider("testProvider"); + virtual.setTransformFunction("lower(sourceVirtual)"); + schema.addField(virtual); + stubTable(currentTable()); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(schema), 3); + newManager(true, DefaultConfigMigrationRegistry.create()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_resourceManager, never()).updateSchemaAndTableConfigs(any(), anyInt(), any()); + verify(_resourceManager, never()).updateSchema(any(), anyInt()); + verifyNoInteractions(_controllerMetrics); + assertEquals(schema.getFieldSpecFor("d").getTransformFunction(), ""); + assertEquals(schema.getFieldSpecFor("virtual").getTransformFunction(), "lower(sourceVirtual)"); + } + + @DataProvider(name = "effectiveOverrides") + public Object[][] effectiveOverrides() { + return new Object[][]{{"template"}, {"schemaDestinationDecorator"}, {"unrelatedDestinationDecorator"}, + {"populatedIngestionDecorator"}}; + } + + @Test(dataProvider = "effectiveOverrides") + public void testEffectiveOverrideMismatchLeavesSchemaIntact(String override) + throws Exception { + boolean template = override.equals("template"); + boolean unrelated = override.equals("unrelatedDestinationDecorator"); + boolean populated = override.equals("populatedIngestionDecorator"); + TableConfig table = currentTable(); + if (populated) { + table.setIngestionConfig(ingestionTransforms(new TransformConfig("country", "lower(sourceCountry)"))); + } + if (template) { + table.setIngestionConfig(ingestionTransforms( + new TransformConfig("${pinot.migration.test.column:d}", "upper(sourceD)"))); + } + Schema schema = stubSchemaTransform(table); + if (unrelated || populated) { + schema.addField(new DimensionFieldSpec("country", DataType.STRING, true)); + stubRecord(SCHEMA_PATH, SchemaSerDeUtils.toZNRecord(schema), 3); + } + String original = schema.toSingleLineJsonString(); + try (MockedStatic decorators = mockStatic(TableConfigDecoratorRegistry.class)) { + decorators.when(() -> TableConfigDecoratorRegistry.applyDecorator(any())).thenAnswer(invocation -> { + TableConfig decorated = invocation.getArgument(0); + if (populated && transforms(decorated).containsKey("d")) { + decorated.setIngestionConfig(ingestionTransforms(new TransformConfig("country", "lower(sourceCountry)"), + new TransformConfig("d", "upper(sourceD)"))); + } + if (!template && decorated.getIngestionConfig() == null) { + String column = unrelated ? "country" : "d"; + String transform = unrelated ? "lower(sourceCountry)" : "upper(sourceD)"; + decorated.setIngestionConfig(ingestionTransforms(new TransformConfig(column, transform))); + } + return decorated; + }); + newManager(true, DefaultConfigMigrationRegistry.create()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + } + verify(_resourceManager, never()).updateSchemaAndTableConfigs(any(), anyInt(), any()); + verify(_resourceManager, never()).updateSchema(any(), anyInt()); + verify(_controllerMetrics).addMeteredTableValue(RAW_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_FAILURE, 1L); + assertEquals(schema.toSingleLineJsonString(), original); + } + + @Test + public void testMissingSchemaStillReportsTableRecommendation() + throws Exception { + stubTable(legacyTable()); + newManager(true, DefaultConfigMigrationRegistry.create()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verify(_controllerMetrics) + .addMeteredTableValue(OFFLINE_TABLE_NAME, ControllerMeter.CONFIG_MIGRATION_RECOMMENDED, 1L); + verify(_resourceManager, never()).setExistingTableConfig(any(), any(), anyInt(), anyBoolean()); + } + + @Test + public void testEmptyRegistryDoesNotReadStore() { + newManager(false, new ConfigMigrationRegistry()) + .processTable(OFFLINE_TABLE_NAME, new ConfigMigrationManager.Context()); + verifyNoInteractions(_propertyStore, _controllerMetrics); + } +} diff --git a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java index 2f4305810e69..b997c8fff471 100644 --- a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java +++ b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java @@ -461,10 +461,11 @@ public SegmentZKMetadata fetchZKMetadata(String segmentName) { @Override public IndexLoadingConfig fetchIndexLoadingConfig() { - TableConfig tableConfig = ZKMetadataProvider.getTableConfig(_propertyStore, _tableNameWithType); - Preconditions.checkState(tableConfig != null, "Failed to find table config for table: %s", _tableNameWithType); + // Schema first: a schema-transform migration publishes table transforms before clearing the schema. Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType); Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType); + TableConfig tableConfig = ZKMetadataProvider.getTableConfig(_propertyStore, _tableNameWithType); + Preconditions.checkState(tableConfig != null, "Failed to find table config for table: %s", _tableNameWithType); IndexLoadingConfig indexLoadingConfig = new IndexLoadingConfig(_instanceDataManagerConfig, tableConfig, schema); indexLoadingConfig.setTableDataDir(_tableDataDir); updateCachedTableConfigAndSchema(tableConfig, schema); diff --git a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java index e4b3d7f7c517..7eceaa3d6f82 100644 --- a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java +++ b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java @@ -59,6 +59,7 @@ import org.apache.pinot.segment.local.data.manager.SegmentDataManager; import org.apache.pinot.segment.local.indexsegment.immutable.EmptyIndexSegment; import org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader; +import org.apache.pinot.segment.local.recordtransformer.ExpressionTransformer; import org.apache.pinot.segment.local.segment.creator.impl.SegmentIndexCreationDriverImpl; import org.apache.pinot.segment.local.segment.index.loader.IndexLoadingConfig; import org.apache.pinot.segment.local.segment.readers.GenericRowRecordReader; @@ -85,8 +86,11 @@ import org.apache.pinot.spi.config.table.TierConfig; import org.apache.pinot.spi.config.table.TimestampConfig; import org.apache.pinot.spi.config.table.TimestampIndexGranularity; +import org.apache.pinot.spi.config.table.ingestion.IngestionConfig; +import org.apache.pinot.spi.config.table.ingestion.TransformConfig; import org.apache.pinot.spi.crypt.PinotCrypter; import org.apache.pinot.spi.crypt.PinotCrypterFactory; +import org.apache.pinot.spi.data.DimensionFieldSpec; import org.apache.pinot.spi.data.FieldSpec.DataType; import org.apache.pinot.spi.data.Schema; import org.apache.pinot.spi.data.readers.GenericRow; @@ -106,7 +110,9 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.clearInvocations; @@ -1680,6 +1686,40 @@ public void testGetCachedIndexLoadingConfigReusesSchemaAndRefreshes() { assertSame(indexed.getFieldIndexConfig("id"), manager.getCachedIndexLoadingConfig().getFieldIndexConfig("id")); } + @Test + @SuppressWarnings("deprecation") // Reproduce a stored transform moving from the schema to the table config. + public void testFetchIndexLoadingConfigDuringSchemaTransformMigration() + throws Exception { + TableConfig table = new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).build(); + Schema schema = createSchemaReuseSchema(); + DimensionFieldSpec derived = new DimensionFieldSpec("derived", DataType.STRING, true); + derived.setTransformFunction("lower(raw)"); + schema.addField(derived); + BaseTableDataManager manager = createSchemaReuseManager(table, schema); + TableConfig migratedTable = new TableConfig(table); + IngestionConfig ingestion = new IngestionConfig(); + ingestion.setTransformConfigs(List.of(new TransformConfig("derived", "lower(raw)"))); + migratedTable.setIngestionConfig(ingestion); + Schema migratedSchema = Schema.fromString(schema.toSingleLineJsonString()); + migratedSchema.getFieldSpecFor("derived").setTransformFunction(null); + AtomicBoolean migrate = new AtomicBoolean(true); + doAnswer(invocation -> { + Object record = invocation.callRealMethod(); + if (migrate.compareAndSet(true, false)) { + // Commit between the two reads, returning the first record from before migration. + ZKMetadataProvider.setTableConfig(manager._propertyStore, migratedTable); + ZKMetadataProvider.setSchema(manager._propertyStore, migratedSchema); + } + return record; + }).when(manager._propertyStore).get(anyString(), any(), anyInt()); + + IndexLoadingConfig config = manager.fetchIndexLoadingConfig(); + GenericRow row = new GenericRow(); + row.putValue("raw", "VALUE"); + new ExpressionTransformer(config.getTableConfig(), config.getSchema()).transform(row); + assertEquals(row.getValue("derived"), "value"); + } + @Test public void testGetCachedIndexLoadingConfigDerivesSegmentTier() { TableConfig table = new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).build(); diff --git a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/materializedview/MaterializedViewTaskExecutor.java b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/materializedview/MaterializedViewTaskExecutor.java index d01d7a121026..e39a6dc3b9c8 100644 --- a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/materializedview/MaterializedViewTaskExecutor.java +++ b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/materializedview/MaterializedViewTaskExecutor.java @@ -194,8 +194,8 @@ public SegmentConversionResult executeTask(PinotTaskConfig pinotTaskConfig) LOGGER.info("MaterializedViewTask for table: {}, window: [{}, {}), SQL: {}", tableName, windowStartMs, windowEndMs, definedSQL); - TableConfig tableConfig = getTableConfig(tableName); Schema schema = getSchema(tableName); + TableConfig tableConfig = getTableConfig(tableName); eventObserver.notifyProgress(pinotTaskConfig, "Executing query for MV table: " + tableName); AuthProvider authProvider = resolveAuthProvider(configs); diff --git a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/mergerollup/MergeRollupTaskExecutor.java b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/mergerollup/MergeRollupTaskExecutor.java index 5e900061da2c..7e0f9b62e9a8 100644 --- a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/mergerollup/MergeRollupTaskExecutor.java +++ b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/mergerollup/MergeRollupTaskExecutor.java @@ -66,8 +66,8 @@ protected List convert(PinotTaskConfig pinotTaskConfig, long startMillis = System.currentTimeMillis(); String tableNameWithType = configs.get(MinionConstants.TABLE_NAME_KEY); - TableConfig tableConfig = getTableConfig(tableNameWithType); Schema schema = getSchema(tableNameWithType); + TableConfig tableConfig = getTableConfig(tableNameWithType); Set dimensionsToErase = MergeRollupTaskUtils.getDimensionsToErase(configs); List customRecordTransformers = new ArrayList<>(); diff --git a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/purge/PurgeTaskExecutor.java b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/purge/PurgeTaskExecutor.java index 99e5ec3b026b..4e47b57470fe 100644 --- a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/purge/PurgeTaskExecutor.java +++ b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/purge/PurgeTaskExecutor.java @@ -51,8 +51,8 @@ protected SegmentConversionResult convert(PinotTaskConfig pinotTaskConfig, File String taskType = pinotTaskConfig.getTaskType(); SegmentPurger.RecordPurgerFactory recordPurgerFactory = MINION_CONTEXT.getRecordPurgerFactory(); - TableConfig tableConfig = getTableConfig(tableNameWithType); Schema schema = getSchema(tableNameWithType); + TableConfig tableConfig = getTableConfig(tableNameWithType); SegmentPurger.RecordPurger recordPurger = recordPurgerFactory != null ? recordPurgerFactory.getRecordPurger(pinotTaskConfig, tableConfig, schema) : null; SegmentPurger.RecordModifierFactory recordModifierFactory = MINION_CONTEXT.getRecordModifierFactory(); diff --git a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/realtimetoofflinesegments/RealtimeToOfflineSegmentsTaskExecutor.java b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/realtimetoofflinesegments/RealtimeToOfflineSegmentsTaskExecutor.java index 391a2936e661..219033a82dad 100644 --- a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/realtimetoofflinesegments/RealtimeToOfflineSegmentsTaskExecutor.java +++ b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/realtimetoofflinesegments/RealtimeToOfflineSegmentsTaskExecutor.java @@ -120,8 +120,8 @@ protected List convert(PinotTaskConfig pinotTaskConfig, String realtimeTableName = configs.get(MinionConstants.TABLE_NAME_KEY); String rawTableName = TableNameBuilder.extractRawTableName(realtimeTableName); String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(rawTableName); - TableConfig tableConfig = getTableConfig(offlineTableName); Schema schema = getSchema(offlineTableName); + TableConfig tableConfig = getTableConfig(offlineTableName); SegmentProcessorConfig.Builder segmentProcessorConfigBuilder = new SegmentProcessorConfig.Builder().setTableConfig(tableConfig).setSchema(schema); diff --git a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/refreshsegment/RefreshSegmentTaskExecutor.java b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/refreshsegment/RefreshSegmentTaskExecutor.java index 09aa4756b561..3349373686f4 100644 --- a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/refreshsegment/RefreshSegmentTaskExecutor.java +++ b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/refreshsegment/RefreshSegmentTaskExecutor.java @@ -75,8 +75,8 @@ protected SegmentConversionResult convert(PinotTaskConfig pinotTaskConfig, File LOGGER.info("Starting task: {} with configs: {}", taskType, Obfuscator.DEFAULT.toJsonString(configs)); } - TableConfig tableConfig = getTableConfig(tableNameWithType); Schema schema = getSchema(tableNameWithType); + TableConfig tableConfig = getTableConfig(tableNameWithType); IndexLoadingConfig indexLoadingConfig = new IndexLoadingConfig(tableConfig, schema); SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(indexDir); @@ -146,8 +146,8 @@ protected SegmentConversionResult convert(PinotTaskConfig pinotTaskConfig, File ImmutableSegment segment = ImmutableSegmentLoader.load(indexDir, indexLoadingConfig, false); try (PinotSegmentRecordReader recordReader = new PinotSegmentRecordReader()) { recordReader.init(segment); - SegmentGeneratorConfig config = getSegmentGeneratorConfig(workingDir, tableConfig, segmentMetadata, segmentName, - getSchema(tableNameWithType)); + SegmentGeneratorConfig config = + getSegmentGeneratorConfig(workingDir, tableConfig, segmentMetadata, segmentName, schema); SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl(); driver.init(config, recordReader); driver.build(); diff --git a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompaction/UpsertCompactionTaskExecutor.java b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompaction/UpsertCompactionTaskExecutor.java index 8539606a78c2..cbb1652566e0 100644 --- a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompaction/UpsertCompactionTaskExecutor.java +++ b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompaction/UpsertCompactionTaskExecutor.java @@ -58,6 +58,7 @@ protected SegmentConversionResult convert(PinotTaskConfig pinotTaskConfig, File long startMillis = System.currentTimeMillis(); String tableNameWithType = configs.get(MinionConstants.TABLE_NAME_KEY); + Schema schema = getSchema(tableNameWithType); TableConfig tableConfig = getTableConfig(tableNameWithType); String validDocIdsTypeStr = MinionTaskUtils.getValidDocIdsType(tableConfig.getUpsertConfig(), configs, @@ -109,8 +110,8 @@ protected SegmentConversionResult convert(PinotTaskConfig pinotTaskConfig, File int totalDocsAfterCompaction; try (CompactedPinotSegmentRecordReader compactedRecordReader = new CompactedPinotSegmentRecordReader(validDocIds)) { compactedRecordReader.init(indexDir, null, null); - SegmentGeneratorConfig config = getSegmentGeneratorConfig(workingDir, tableConfig, segmentMetadata, segmentName, - getSchema(tableNameWithType)); + SegmentGeneratorConfig config = + getSegmentGeneratorConfig(workingDir, tableConfig, segmentMetadata, segmentName, schema); SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl(); driver.init(config, compactedRecordReader); driver.build(); diff --git a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompactmerge/UpsertCompactMergeTaskExecutor.java b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompactmerge/UpsertCompactMergeTaskExecutor.java index d62a2102ecbf..65026ca5010f 100644 --- a/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompactmerge/UpsertCompactMergeTaskExecutor.java +++ b/pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/upsertcompactmerge/UpsertCompactMergeTaskExecutor.java @@ -77,8 +77,8 @@ protected List convert(PinotTaskConfig pinotTaskConfig, long startMillis = System.currentTimeMillis(); String tableNameWithType = configs.get(MinionConstants.TABLE_NAME_KEY); - TableConfig tableConfig = getTableConfig(tableNameWithType); Schema schema = getSchema(tableNameWithType); + TableConfig tableConfig = getTableConfig(tableNameWithType); SegmentProcessorConfig.Builder segmentProcessorConfigBuilder = new SegmentProcessorConfig.Builder().setTableConfig(tableConfig).setSchema(schema); diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/DefaultConfigMigrationRegistry.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/DefaultConfigMigrationRegistry.java new file mode 100644 index 000000000000..63bd49fd8d12 --- /dev/null +++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/DefaultConfigMigrationRegistry.java @@ -0,0 +1,46 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.utils.migration; + +import org.apache.pinot.spi.config.migration.ConfigMigrationRegistry; + + +/// Assembles the built-in [ConfigMigrationRegistry] with the migration chain shipped by Pinot. +/// +/// This is the single place that declares the ordered set of migrators, and therefore defines the +/// current table-config and schema migration versions. Add a new migrator to the end of the relevant +/// chain (with `fromVersion` equal to the current chain length) to introduce a new upgrade step. +/// +/// Table-config chain: +/// - v0 -> v1: [LegacyIngestionConfigMigrator] (fold deprecated ingestion fields into ingestionConfig) +/// +/// Schema chain: +/// - v0 -> v1: [LegacyTimeFieldSchemaMigrator] (replace TIME with equivalent DATE_TIME fields) +public class DefaultConfigMigrationRegistry { + private DefaultConfigMigrationRegistry() { + } + + /// Builds a fresh registry populated with the built-in migration chain. + public static ConfigMigrationRegistry create() { + ConfigMigrationRegistry registry = new ConfigMigrationRegistry(); + registry.registerTableConfigMigrator(new LegacyIngestionConfigMigrator()); + registry.registerSchemaMigrator(new LegacyTimeFieldSchemaMigrator()); + return registry; + } +} diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigrator.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigrator.java new file mode 100644 index 000000000000..9e2db2371637 --- /dev/null +++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigrator.java @@ -0,0 +1,61 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.utils.migration; + +import org.apache.pinot.segment.local.utils.TableConfigUtils; +import org.apache.pinot.spi.config.migration.TableConfigMigrator; +import org.apache.pinot.spi.config.table.TableConfig; + + +/// Migrates a [TableConfig] from migration version 0 (pre-framework) to version 1 by folding the +/// deprecated ingestion-related fields into [org.apache.pinot.spi.config.table.ingestion.IngestionConfig]: +/// +/// - `tableIndexConfig.streamConfigs` -> `ingestionConfig.streamIngestionConfig` +/// - `segmentsConfig.segmentPushType` / `segmentPushFrequency` -> `ingestionConfig.batchIngestionConfig` +/// +/// The transform delegates to [TableConfigUtils#convertFromLegacyTableConfig(TableConfig)], which +/// mutates the config in place and clears the deprecated fields. Configs that already use the +/// current ingestion shape are left effectively unchanged (the deprecated fields are simply null). +/// +/// Rolling-upgrade note: this migration **clears** the deprecated fields once folded. Current readers resolve stream +/// config via `IngestionConfigUtils`, which prefers `ingestionConfig` and treats the deprecated fields only as a +/// fallback, so a same-version reader is unaffected. However, rolling this back to a binary old enough to read the +/// deprecated fields *without* that fallback would see them missing. This is why config migration is opt-in and +/// intended to be enabled only after every node in the cluster has been upgraded. +public class LegacyIngestionConfigMigrator implements TableConfigMigrator { + + @Override + public int fromVersion() { + return 0; + } + + @Override + public TableConfig migrate(TableConfig input) { + boolean createStreamConfig = input.getIngestionConfig() == null + || input.getIngestionConfig().getStreamIngestionConfig() == null; + boolean columnMajorSegmentBuilderEnabled = input.getIndexingConfig().isColumnMajorSegmentBuilderEnabled(); + TableConfigUtils.convertFromLegacyTableConfig(input); + if (createStreamConfig && input.getIngestionConfig() != null + && input.getIngestionConfig().getStreamIngestionConfig() != null) { + input.getIngestionConfig().getStreamIngestionConfig() + .setColumnMajorSegmentBuilderEnabled(columnMajorSegmentBuilderEnabled); + } + return input; + } +} diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigrator.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigrator.java new file mode 100644 index 000000000000..7e17e98337a5 --- /dev/null +++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigrator.java @@ -0,0 +1,79 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.utils.migration; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.base.Preconditions; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.apache.pinot.spi.config.migration.SchemaMigrator; +import org.apache.pinot.spi.data.DateTimeFieldSpec; +import org.apache.pinot.spi.data.Schema; +import org.apache.pinot.spi.data.TimeFieldSpec; +import org.apache.pinot.spi.data.TimeGranularitySpec; +import org.apache.pinot.spi.utils.JsonUtils; + + +/// Replaces legacy TIME fields with equivalent DATE_TIME fields, retaining their common field attributes. +/// The existing schema conversion supplies the time format, granularity, and any required ingestion transform. +/// This stateless migrator is safe to invoke concurrently on distinct schema copies. +// Legacy TIME and transform APIs are intentionally read to migrate existing stored schemas. +@SuppressWarnings("deprecation") +public class LegacyTimeFieldSchemaMigrator implements SchemaMigrator { + @Override + public int fromVersion() { + return 0; + } + + @Override + public Schema migrate(Schema input) { + TimeFieldSpec timeFieldSpec = input.getTimeFieldSpec(); + if (timeFieldSpec == null) { + return input; + } + TimeGranularitySpec incoming = timeFieldSpec.getIncomingGranularitySpec(); + TimeGranularitySpec outgoing = timeFieldSpec.getOutgoingGranularitySpec(); + // An empty transform still selects the legacy time converter, but the helper would copy it as an identity. + Preconditions.checkState(!"".equals(timeFieldSpec.getTransformFunction()) || incoming.equals(outgoing), + "Cannot automatically migrate time field with empty conversion transform: %s", timeFieldSpec.getName()); + boolean nonUnitMillis = incoming.getTimeType() == TimeUnit.MILLISECONDS && incoming.getTimeUnitSize() != 1 + || outgoing.getTimeType() == TimeUnit.MILLISECONDS && outgoing.getTimeUnitSize() != 1; + // The conversion helper does not multiply/divide non-unit millisecond values when generating a transform. + Preconditions.checkState( + !nonUnitMillis || incoming.equals(outgoing) || timeFieldSpec.getTransformFunction() != null, + "Cannot automatically migrate time field with non-unit millisecond conversion: %s", timeFieldSpec.getName()); + DateTimeFieldSpec converted = Schema.convertToDateTimeFieldSpec(timeFieldSpec); + // Preserve all common attributes, including column identity and nullability, which the conversion helper + // predates. Replace only the TIME representation and the converted format/granularity/transform. + ObjectNode attributes = (ObjectNode) JsonUtils.objectToJsonNode(timeFieldSpec); + attributes.remove(List.of("incomingGranularitySpec", "outgoingGranularitySpec", "name", "dataType", "fieldType", + "transformFunction")); + ObjectNode field = converted.toJsonObject(); + field.setAll(attributes); + try { + converted = JsonUtils.jsonNodeToObject(field, DateTimeFieldSpec.class); + } catch (IOException e) { + throw new IllegalArgumentException("Cannot convert legacy time field: " + timeFieldSpec.getName(), e); + } + input.removeField(timeFieldSpec.getName()); + input.addField(converted); + return input; + } +} diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigratorTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigratorTest.java new file mode 100644 index 000000000000..51ec08faa706 --- /dev/null +++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyIngestionConfigMigratorTest.java @@ -0,0 +1,234 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.utils.migration; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.pinot.common.utils.config.TableConfigSerDeUtils; +import org.apache.pinot.spi.config.migration.ConfigMigrationRegistry; +import org.apache.pinot.spi.config.migration.ConfigMigrationUtils; +import org.apache.pinot.spi.config.migration.MigrationResult; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.config.table.TableType; +import org.apache.pinot.spi.config.table.ingestion.BatchIngestionConfig; +import org.apache.pinot.spi.config.table.ingestion.IngestionConfig; +import org.apache.pinot.spi.config.table.ingestion.StreamIngestionConfig; +import org.apache.pinot.spi.stream.StreamConfigProperties; +import org.apache.pinot.spi.utils.builder.TableConfigBuilder; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; +import static org.testng.Assert.assertTrue; + + +public class LegacyIngestionConfigMigratorTest { + + private static Map streamConfigs() { + Map streamConfigMap = new HashMap<>(); + streamConfigMap.put(StreamConfigProperties.STREAM_TYPE, "kafka"); + streamConfigMap.put( + StreamConfigProperties.constructStreamProperty("kafka", StreamConfigProperties.STREAM_TOPIC_NAME), "topic"); + streamConfigMap.put( + StreamConfigProperties.constructStreamProperty("kafka", StreamConfigProperties.STREAM_CONSUMER_FACTORY_CLASS), + "cf"); + streamConfigMap.put( + StreamConfigProperties.constructStreamProperty("kafka", StreamConfigProperties.STREAM_DECODER_CLASS), "dec"); + return streamConfigMap; + } + + @Test + public void testDefaultRegistryUpgradesLegacyTableConfig() { + Map streamConfigs = streamConfigs(); + TableConfig legacy = new TableConfigBuilder(TableType.REALTIME).setTableName("legacyTable") + .setSegmentPushType("APPEND") + .setSegmentPushFrequency("HOURLY") + .setStreamConfigs(streamConfigs) + .build(); + assertNull(legacy.getIngestionConfig()); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(legacy), 0); + + ConfigMigrationRegistry registry = DefaultConfigMigrationRegistry.create(); + assertEquals(registry.getCurrentTableConfigVersion(), 1); + + MigrationResult result = registry.migrateTableConfig(legacy); + assertTrue(result.isChanged()); + assertEquals(result.getVersion(), 1); + + TableConfig migrated = result.getConfig(); + // Deprecated ingestion fields are folded into ingestionConfig. + IngestionConfig ingestionConfig = migrated.getIngestionConfig(); + assertNotNull(ingestionConfig); + assertNotNull(ingestionConfig.getBatchIngestionConfig()); + assertEquals(ingestionConfig.getBatchIngestionConfig().getSegmentIngestionType(), "APPEND"); + assertNotNull(ingestionConfig.getStreamIngestionConfig()); + assertEquals(ingestionConfig.getStreamIngestionConfig().getStreamConfigMaps().get(0), streamConfigs); + // Deprecated fields are cleared and the version marker is stamped. + assertNull(migrated.getIndexingConfig().getStreamConfigs()); + assertNull(migrated.getValidationConfig().getSegmentPushType()); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(migrated), 1); + } + + @Test + public void testUpgradesDeprecatedStreamConfigsOnly() { + // A REALTIME table whose only deprecated field is tableIndexConfig.streamConfigs. + Map streamConfigs = streamConfigs(); + TableConfig legacy = new TableConfigBuilder(TableType.REALTIME).setTableName("streamOnly") + .setStreamConfigs(streamConfigs) + .build(); + + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateTableConfig(legacy); + assertTrue(result.isChanged()); + TableConfig migrated = result.getConfig(); + assertNotNull(migrated.getIngestionConfig().getStreamIngestionConfig()); + assertEquals(migrated.getIngestionConfig().getStreamIngestionConfig().getStreamConfigMaps().get(0), streamConfigs); + assertNull(migrated.getIndexingConfig().getStreamConfigs()); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(migrated), 1); + } + + @Test + public void testUpgradesDeprecatedBatchPushConfigsOnly() { + // An OFFLINE table whose only deprecated fields are the segmentsConfig batch push settings. + TableConfig legacy = new TableConfigBuilder(TableType.OFFLINE).setTableName("batchOnly") + .setSegmentPushType("REFRESH") + .setSegmentPushFrequency("DAILY") + .build(); + + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateTableConfig(legacy); + assertTrue(result.isChanged()); + TableConfig migrated = result.getConfig(); + BatchIngestionConfig batchIngestionConfig = migrated.getIngestionConfig().getBatchIngestionConfig(); + assertNotNull(batchIngestionConfig); + assertEquals(batchIngestionConfig.getSegmentIngestionType(), "REFRESH"); + assertEquals(batchIngestionConfig.getSegmentIngestionFrequency(), "DAILY"); + assertNull(migrated.getValidationConfig().getSegmentPushType()); + assertNull(migrated.getValidationConfig().getSegmentPushFrequency()); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(migrated), 1); + } + + @Test + public void testUpgradeSurvivesZkSerializationRoundTrip() + throws Exception { + // Simulate the real controller flow: an old version stored a deprecated config as a ZNRecord; the migration task + // reads it back, migrates, and the upgraded config re-serializes cleanly with the version marker persisted. + TableConfig legacy = new TableConfigBuilder(TableType.REALTIME).setTableName("roundTrip") + .setSegmentPushType("APPEND") + .setStreamConfigs(streamConfigs()) + .build(); + + // Round-trip through the ZK ZNRecord form used by ZKMetadataProvider. + TableConfig stored = TableConfigSerDeUtils.fromZNRecord(TableConfigSerDeUtils.toZNRecord(legacy)); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(stored), 0); + + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateTableConfig(stored); + assertTrue(result.isChanged()); + + // Re-serialize the migrated config (as the task persists it) and read it back: upgrade + marker both survive. + TableConfig persisted = TableConfigSerDeUtils.fromZNRecord(TableConfigSerDeUtils.toZNRecord(result.getConfig())); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(persisted), 1); + assertNotNull(persisted.getIngestionConfig().getStreamIngestionConfig()); + assertNotNull(persisted.getIngestionConfig().getBatchIngestionConfig()); + assertNull(persisted.getIndexingConfig().getStreamConfigs()); + assertNull(persisted.getValidationConfig().getSegmentPushType()); + } + + @Test + public void testExistingIngestionConfigWinsOverDeprecatedFields() { + // A v0 config that has BOTH a modern ingestionConfig.streamIngestionConfig AND deprecated streamConfigs: the + // existing modern config must win and the deprecated field must be cleared (no data loss / double-fold). + Map deprecatedStreamConfigs = streamConfigs(); + Map modernStreamConfigs = new HashMap<>(streamConfigs()); + modernStreamConfigs.put(StreamConfigProperties.STREAM_TOPIC_NAME, "modernTopic"); + + IngestionConfig ingestionConfig = new IngestionConfig(); + ingestionConfig.setStreamIngestionConfig(new StreamIngestionConfig(List.of(modernStreamConfigs))); + ingestionConfig.getStreamIngestionConfig().setColumnMajorSegmentBuilderEnabled(false); + TableConfig config = new TableConfigBuilder(TableType.REALTIME).setTableName("collision") + .setStreamConfigs(deprecatedStreamConfigs) + .setIngestionConfig(ingestionConfig) + .build(); + + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateTableConfig(config); + assertTrue(result.isChanged()); + TableConfig migrated = result.getConfig(); + // Modern config is retained; deprecated field is cleared. + assertEquals(migrated.getIngestionConfig().getStreamIngestionConfig().getStreamConfigMaps().get(0), + modernStreamConfigs); + assertNull(migrated.getIndexingConfig().getStreamConfigs()); + assertFalse(migrated.getIngestionConfig().getStreamIngestionConfig().getColumnMajorSegmentBuilderEnabled()); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(migrated), 1); + } + + @Test + public void testWarningOnlyMigrationPreservesOriginalAndColumnMajorSetting() { + TableConfig legacy = new TableConfigBuilder(TableType.REALTIME).setTableName("columnMajor") + .setStreamConfigs(streamConfigs()).build(); + legacy.getIndexingConfig().setColumnMajorSegmentBuilderEnabled(false); + + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateTableConfig(legacy); + assertTrue(result.isChanged()); + assertFalse(result.getConfig().getIngestionConfig().getStreamIngestionConfig() + .getColumnMajorSegmentBuilderEnabled()); + assertNotNull(legacy.getIndexingConfig().getStreamConfigs()); + assertNull(legacy.getIngestionConfig()); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(legacy), 0); + + MigrationResult second = + DefaultConfigMigrationRegistry.create().migrateTableConfig(result.getConfig()); + assertFalse(second.isChanged()); + assertSame(second.getConfig(), result.getConfig()); + } + + @Test + public void testModernUnmarkedTableIsNotRecommended() { + TableConfig modern = new TableConfigBuilder(TableType.OFFLINE).setTableName("modern").build(); + modern.getValidationConfig().setSegmentPushType(null); + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateTableConfig(modern); + assertFalse(result.isChanged()); + assertSame(result.getConfig(), modern); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(modern), 0); + } + + @Test + public void testLegacyFieldsReintroducedAfterMigrationAreStillDetected() { + TableConfig config = new TableConfigBuilder(TableType.REALTIME).setTableName("edited") + .setStreamConfigs(streamConfigs()).build(); + ConfigMigrationUtils.setTableConfigVersion(config, 1); + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateTableConfig(config); + assertTrue(result.isChanged()); + assertNull(result.getConfig().getIndexingConfig().getStreamConfigs()); + assertNotNull(config.getIndexingConfig().getStreamConfigs()); + } + + @Test + public void testAlreadyMigratedConfigIsNoOp() { + TableConfig config = new TableConfigBuilder(TableType.OFFLINE).setTableName("currentTable").build(); + config.getValidationConfig().setSegmentPushType(null); + ConfigMigrationUtils.setTableConfigVersion(config, 1); + + ConfigMigrationRegistry registry = DefaultConfigMigrationRegistry.create(); + MigrationResult result = registry.migrateTableConfig(config); + assertFalse(result.isChanged()); + assertEquals(result.getVersion(), 1); + } +} diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigratorTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigratorTest.java new file mode 100644 index 000000000000..c84cc7c9f052 --- /dev/null +++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/utils/migration/LegacyTimeFieldSchemaMigratorTest.java @@ -0,0 +1,160 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.utils.migration; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.apache.pinot.spi.config.migration.ConfigMigrationRegistry; +import org.apache.pinot.spi.config.migration.MigrationResult; +import org.apache.pinot.spi.data.DateTimeFieldSpec; +import org.apache.pinot.spi.data.DimensionFieldSpec; +import org.apache.pinot.spi.data.FieldSpec.DataType; +import org.apache.pinot.spi.data.FieldSpec.MaxLengthExceedStrategy; +import org.apache.pinot.spi.data.Schema; +import org.apache.pinot.spi.data.TimeFieldSpec; +import org.apache.pinot.spi.data.TimeGranularitySpec; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; +import static org.testng.Assert.assertThrows; +import static org.testng.Assert.assertTrue; + + +/// Verifies legacy TIME conversion, preservation of field attributes, and rejection of unsupported conversions. +// Intentionally exercises schemas stored with deprecated TIME fields and legacy field transforms. +@SuppressWarnings("deprecation") +public class LegacyTimeFieldSchemaMigratorTest { + @Test + public void testConvertsLegacyTimeWithoutMutatingOriginal() { + TimeFieldSpec time = new TimeFieldSpec(new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "incoming"), + new TimeGranularitySpec(DataType.LONG, TimeUnit.HOURS, "hours")); + time.setDefaultNullValue(-7L); + time.setFieldId(19); + time.setAliases(List.of("eventHours")); + time.setMetadata(Map.of("owner", "analytics")); + time.setDescription("event time"); + time.setTags(List.of("time")); + time.setNotNull(true); + time.setMaxLength(123); + time.setMaxLengthExceedStrategy(MaxLengthExceedStrategy.ERROR); + time.setAllowTrailingZeros(true); + Schema original = new Schema(); + original.setSchemaName("events"); + original.addField(new DimensionFieldSpec("country", DataType.STRING, true)); + original.addField(time); + original.setPrimaryKeyColumns(List.of("hours")); + + ConfigMigrationRegistry registry = DefaultConfigMigrationRegistry.create(); + MigrationResult result = registry.migrateSchema(original); + assertTrue(result.isChanged()); + Schema migrated = result.getConfig(); + assertEquals(migrated.getSchemaName(), "events"); + assertNull(migrated.getTimeFieldSpec()); + DateTimeFieldSpec actual = migrated.getDateTimeSpec("hours"); + assertNotNull(actual); + assertEquals(actual.getDataType(), DataType.LONG); + assertEquals(actual.getFormat(), "1:HOURS:EPOCH"); + assertEquals(actual.getGranularity(), "1:HOURS"); + assertEquals(actual.getTransformFunction(), "toEpochHours(incoming)"); + assertEquals(actual.getDefaultNullValue(), -7L); + assertEquals(actual.getFieldId(), Integer.valueOf(19)); + assertEquals(actual.getAliases(), List.of("eventHours")); + assertEquals(actual.getMetadata(), Map.of("owner", "analytics")); + assertEquals(actual.getDescription(), "event time"); + assertEquals(actual.getTags(), List.of("time")); + assertTrue(actual.isNotNull()); + assertEquals(actual.getMaxLength(), Integer.valueOf(123)); + assertEquals(actual.getMaxLengthExceedStrategy(), MaxLengthExceedStrategy.ERROR); + assertTrue(actual.isAllowTrailingZeros()); + assertEquals(migrated.getPrimaryKeyColumns(), original.getPrimaryKeyColumns()); + assertEquals(migrated.getDimensionFieldSpecs(), original.getDimensionFieldSpecs()); + assertSame(original.getTimeFieldSpec(), time); + assertEquals(original.getConfigMigrationVersion(), 0); + assertTrue(original.getDateTimeFieldSpecs().isEmpty()); + assertEquals(migrated.getConfigMigrationVersion(), 1); + assertFalse(registry.migrateSchema(migrated).isChanged()); + } + + @Test + public void testPreservesExplicitLegacyTransform() { + TimeFieldSpec time = new TimeFieldSpec(new TimeGranularitySpec(DataType.LONG, TimeUnit.HOURS, "hours")); + time.setTransformFunction("toEpochHours(timestamp)"); + Schema original = new Schema(); + original.setSchemaName("events"); + original.addField(time); + Schema migrated = DefaultConfigMigrationRegistry.create().migrateSchema(original).getConfig(); + assertEquals(migrated.getDateTimeSpec("hours").getTransformFunction(), "toEpochHours(timestamp)"); + } + + @Test + public void testModernUnmarkedSchemaIsNotRecommended() { + Schema schema = new Schema.SchemaBuilder().setSchemaName("modern") + .addDateTime("ts", DataType.LONG, "1:MILLISECONDS:EPOCH", "1:MILLISECONDS").build(); + MigrationResult result = DefaultConfigMigrationRegistry.create().migrateSchema(schema); + assertFalse(result.isChanged()); + assertSame(result.getConfig(), schema); + assertEquals(schema.getConfigMigrationVersion(), 0); + } + + @DataProvider + public Object[][] unsupportedBucketConversions() { + TimeFieldSpec emptyTransform = new TimeFieldSpec( + new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "incoming"), + new TimeGranularitySpec(DataType.LONG, TimeUnit.SECONDS, "outgoing")); + emptyTransform.setTransformFunction(""); + return new Object[][]{ + {new TimeFieldSpec(new TimeGranularitySpec(DataType.LONG, 1000, TimeUnit.MILLISECONDS, "incoming"), + new TimeGranularitySpec(DataType.LONG, TimeUnit.SECONDS, "outgoing"))}, + {new TimeFieldSpec(new TimeGranularitySpec(DataType.LONG, TimeUnit.SECONDS, "incoming"), + new TimeGranularitySpec(DataType.LONG, 1000, TimeUnit.MILLISECONDS, "outgoing"))}, + {emptyTransform} + }; + } + + @Test(dataProvider = "unsupportedBucketConversions") + public void testUnsupportedBucketConversionLeavesOriginalUntouched(TimeFieldSpec time) { + Schema schema = new Schema(); + schema.setSchemaName("nonUnitMillis"); + schema.addField(time); + assertThrows(IllegalStateException.class, () -> DefaultConfigMigrationRegistry.create().migrateSchema(schema)); + assertSame(schema.getTimeFieldSpec(), time); + assertEquals(schema.getConfigMigrationVersion(), 0); + assertTrue(schema.getDateTimeFieldSpecs().isEmpty()); + } + + @Test + public void testUnsupportedTimeConversionLeavesOriginalUntouched() { + TimeFieldSpec time = new TimeFieldSpec( + new TimeGranularitySpec(DataType.STRING, TimeUnit.DAYS, "SIMPLE_DATE_FORMAT:yyyyMMdd", "incoming"), + new TimeGranularitySpec(DataType.LONG, TimeUnit.HOURS, "hours")); + Schema schema = new Schema(); + schema.setSchemaName("unsupported"); + schema.addField(time); + assertThrows(IllegalStateException.class, () -> DefaultConfigMigrationRegistry.create().migrateSchema(schema)); + assertSame(schema.getTimeFieldSpec(), time); + assertEquals(schema.getConfigMigrationVersion(), 0); + assertTrue(schema.getDateTimeFieldSpecs().isEmpty()); + } +} diff --git a/pinot-server/src/main/java/org/apache/pinot/server/predownload/PredownloadZKClient.java b/pinot-server/src/main/java/org/apache/pinot/server/predownload/PredownloadZKClient.java index 31da2e1eee7c..9dfb2285f974 100644 --- a/pinot-server/src/main/java/org/apache/pinot/server/predownload/PredownloadZKClient.java +++ b/pinot-server/src/main/java/org/apache/pinot/server/predownload/PredownloadZKClient.java @@ -202,13 +202,13 @@ public void updateSegmentMetadata(List predownloadSegmen for (PredownloadSegmentInfo predownloadSegmentInfo : predownloadSegmentInfoList) { String tableNameWithType = predownloadSegmentInfo.getTableNameWithType(); tableInfoMap.computeIfAbsent(tableNameWithType, name -> { + Schema schema = ZKMetadataProvider.getTableSchema(propertyStore, tableNameWithType); TableConfig tableConfig = ZKMetadataProvider.getTableConfig(propertyStore, tableNameWithType); if (tableConfig == null) { LOGGER.warn("Cannot predownload segment {} because not able to get its table config from ZK", predownloadSegmentInfo.getSegmentName()); return null; } - Schema schema = ZKMetadataProvider.getTableSchema(propertyStore, tableNameWithType); return new PredownloadTableInfo(name, tableConfig, schema, instanceDataManagerConfig); }); SegmentZKMetadata segmentZKMetadata = ZKMetadataProvider.getSegmentZKMetadata(propertyStore, tableNameWithType, diff --git a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java index be395294ddf4..fc48398eb3b8 100644 --- a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java +++ b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java @@ -396,6 +396,8 @@ private TableDataManager getOrCreateTableDataManager(String tableNameWithType) { @VisibleForTesting TableDataManager createTableDataManager(String tableNameWithType) { LOGGER.info("Creating table data manager for table: {}", tableNameWithType); + Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, tableNameWithType); + Preconditions.checkState(schema != null, "Failed to find schema for table: %s", tableNameWithType); TableConfig tableConfig; Long tableDeleteTimeMs = _recentlyDeletedTables.getIfPresent(tableNameWithType); if (tableDeleteTimeMs != null) { @@ -415,8 +417,6 @@ TableDataManager createTableDataManager(String tableNameWithType) { tableConfig = ZKMetadataProvider.getTableConfig(_propertyStore, tableNameWithType); Preconditions.checkState(tableConfig != null, "Failed to find table config for table: %s", tableNameWithType); } - Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, tableNameWithType); - Preconditions.checkState(schema != null, "Failed to find schema for table: %s", tableNameWithType); TimestampIndexUtils.applyTimestampIndex(tableConfig, schema); TableDataManager tableDataManager = _tableDataManagerProvider.getTableDataManager(tableConfig, schema, _segmentReloadSemaphore, diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistry.java b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistry.java new file mode 100644 index 000000000000..bdb5a19d5fd6 --- /dev/null +++ b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistry.java @@ -0,0 +1,145 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.spi.config.migration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.base.Preconditions; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.data.Schema; +import org.apache.pinot.spi.utils.JsonUtils; + + +/// Registry of ordered [ConfigMigrator]s that upgrade stored [TableConfig] and [Schema] objects to +/// the current migration version. +/// +/// Migrators form a dense chain: the migrator at index {@code i} declares {@code fromVersion() == i} +/// and produces version {@code i + 1}. The current version is therefore the number of registered +/// migrators. [#migrateTableConfig]/[#migrateSchema] apply every idempotent migrator in order for supported +/// configs, including already-marked configs: a later user update may have reintroduced a legacy property. +/// A future-version marker prevents migration after a downgrade. [MigrationResult#isChanged()] reports an +/// actual content change, rather than the presence or absence of a marker. +/// +/// Migrators are registered once during startup (before any migration runs) and the registry is then +/// read-only, so migration itself is thread-safe across tables. Registration is guarded to enforce +/// the dense, in-order contract. +/// +/// The default no-migrator registry (current version 0) is a safe identity: every config is already +/// current and nothing is rewritten. +public class ConfigMigrationRegistry { + private final List _tableConfigMigrators = new ArrayList<>(); + private final List _schemaMigrators = new ArrayList<>(); + + /// Registers the next table-config migrator. Its [ConfigMigrator#fromVersion()] must equal the + /// current number of registered table-config migrators, keeping the chain dense and in order. + public synchronized void registerTableConfigMigrator(TableConfigMigrator migrator) { + Preconditions.checkArgument(migrator.fromVersion() == _tableConfigMigrators.size(), + "TableConfig migrator fromVersion %s does not match expected version %s (migrators must be registered in " + + "dense, ascending order)", migrator.fromVersion(), _tableConfigMigrators.size()); + _tableConfigMigrators.add(migrator); + } + + /// Registers the next schema migrator. Its [ConfigMigrator#fromVersion()] must equal the current + /// number of registered schema migrators, keeping the chain dense and in order. + public synchronized void registerSchemaMigrator(SchemaMigrator migrator) { + Preconditions.checkArgument(migrator.fromVersion() == _schemaMigrators.size(), + "Schema migrator fromVersion %s does not match expected version %s (migrators must be registered in dense, " + + "ascending order)", migrator.fromVersion(), _schemaMigrators.size()); + _schemaMigrators.add(migrator); + } + + /// The current table-config migration version, i.e. the number of registered table-config migrators. + public int getCurrentTableConfigVersion() { + return _tableConfigMigrators.size(); + } + + /// The current schema migration version, i.e. the number of registered schema migrators. + public int getCurrentSchemaVersion() { + return _schemaMigrators.size(); + } + + /// Migrates the given table config from its stored version up to [#getCurrentTableConfigVersion()]. + /// Only a substantive transformation is reported as changed and stamped with the target version. + /// A modern config without a marker is left untouched, rather than recommended for a bookkeeping-only update. + public MigrationResult migrateTableConfig(TableConfig tableConfig) { + int currentVersion = ConfigMigrationUtils.getTableConfigVersion(tableConfig); + int targetVersion = getCurrentTableConfigVersion(); + if (targetVersion == 0 || currentVersion > targetVersion) { + return new MigrationResult<>(tableConfig, targetVersion, false); + } + JsonNode original = JsonUtils.objectToJsonNode(tableConfig); + TableConfig migrated = migrate(copy(original, TableConfig.class), _tableConfigMigrators); + if (original.equals(JsonUtils.objectToJsonNode(migrated))) { + return new MigrationResult<>(tableConfig, targetVersion, false); + } + ConfigMigrationUtils.setTableConfigVersion(migrated, targetVersion); + return new MigrationResult<>(migrated, targetVersion, true); + } + + /// Migrates the given schema from its stored version up to [#getCurrentSchemaVersion()]. The + /// returned schema carries the stamped version marker only when its content changed. Migrators operate + /// on a deep copy, so recommendations cannot mutate a cached schema. + public MigrationResult migrateSchema(Schema schema) { + int currentVersion = ConfigMigrationUtils.getSchemaVersion(schema); + int targetVersion = getCurrentSchemaVersion(); + if (targetVersion == 0 || currentVersion > targetVersion) { + return new MigrationResult<>(schema, targetVersion, false); + } + JsonNode original = JsonUtils.objectToJsonNode(schema); + Schema migrated = migrate(copySchema(schema), _schemaMigrators); + if (original.equals(JsonUtils.objectToJsonNode(migrated))) { + return new MigrationResult<>(schema, targetVersion, false); + } + ConfigMigrationUtils.setSchemaVersion(migrated, targetVersion); + return new MigrationResult<>(migrated, targetVersion, true); + } + + // Legacy TIME serialization omits common FieldSpec attributes. Copy the full field before running a + // compatibility migrator, so attributes such as nullability and column identity are not lost by the copy itself. + @SuppressWarnings("deprecation") + private static Schema copySchema(Schema schema) { + ObjectNode json = schema.toJsonObject(); + if (schema.getTimeFieldSpec() != null) { + ObjectNode timeField = schema.getTimeFieldSpec().toJsonObject(); + timeField.setAll((ObjectNode) JsonUtils.objectToJsonNode(schema.getTimeFieldSpec())); + json.set("timeFieldSpec", timeField); + } + return copy(json, Schema.class); + } + + private static T copy(JsonNode json, Class type) { + try { + return JsonUtils.jsonNodeToObject(json, type); + } catch (IOException e) { + throw new IllegalArgumentException("Cannot copy config for migration", e); + } + } + + /// Reruns the ordered, idempotent chain so legacy properties reintroduced by later edits are still detected. + private static > T migrate(T config, List migrators) { + T result = config; + for (M migrator : migrators) { + result = migrator.migrate(result); + } + return result; + } +} diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationUtils.java b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationUtils.java new file mode 100644 index 000000000000..224b1b29ba09 --- /dev/null +++ b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrationUtils.java @@ -0,0 +1,99 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.spi.config.migration; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.config.table.TableCustomConfig; +import org.apache.pinot.spi.data.Schema; + + +/// Reads and stamps the migration-version marker on [TableConfig] and [Schema]. +/// +/// The marker records the highest migration version that has been applied to a stored config, so +/// future-version configs can be left untouched after a downgrade. Supported configs are still inspected for +/// legacy fields reintroduced by later user edits. +/// +/// - **TableConfig**: the marker lives under [#CONFIG_MIGRATION_VERSION_KEY] in +/// [TableCustomConfig#getCustomConfigs()]. Storing it in the free-form custom-config map avoids +/// adding a first-class SPI field and keeps mixed-version rollback safe (older controllers simply +/// preserve the unknown key). +/// - **Schema**: the marker is the dedicated {@code configMigrationVersion} field on [Schema], which +/// older readers ignore via {@code @JsonIgnoreProperties(ignoreUnknown = true)}. +/// +/// A missing or unparseable marker is treated as version {@link #INITIAL_VERSION} (0) — the state of +/// any config written before this framework existed. +public class ConfigMigrationUtils { + private ConfigMigrationUtils() { + } + + /// Reserved custom-config key under which a table config's applied migration version is stored. + /// + /// This key is **controller-managed**: it is written by the config-migration task and is visible in the table + /// config's `metadata.customConfigs` in REST responses. Operators should not set or edit it; a user-provided value + /// is updated when the config is migrated. Other custom-config entries are preserved untouched. + public static final String CONFIG_MIGRATION_VERSION_KEY = "config.migration.version"; + + /// The version assigned to configs written before the migration framework existed. + public static final int INITIAL_VERSION = 0; + + /// Returns the migration version recorded on the given table config, or {@link #INITIAL_VERSION} + /// if the marker is absent or unparseable. + public static int getTableConfigVersion(TableConfig tableConfig) { + TableCustomConfig customConfig = tableConfig.getCustomConfig(); + Map customConfigs = customConfig != null ? customConfig.getCustomConfigs() : null; + if (customConfigs == null) { + return INITIAL_VERSION; + } + return parseVersion(customConfigs.get(CONFIG_MIGRATION_VERSION_KEY)); + } + + /// Stamps the given migration version onto the table config's custom-config map in place, creating + /// the [TableCustomConfig] if necessary. Existing custom configs are preserved. + public static void setTableConfigVersion(TableConfig tableConfig, int version) { + TableCustomConfig existing = tableConfig.getCustomConfig(); + // getCustomConfig() never returns null, but the backing map may be immutable, so always copy. + Map customConfigs = + existing.getCustomConfigs() != null ? new LinkedHashMap<>(existing.getCustomConfigs()) : new LinkedHashMap<>(); + customConfigs.put(CONFIG_MIGRATION_VERSION_KEY, Integer.toString(version)); + tableConfig.setCustomConfig(new TableCustomConfig(customConfigs)); + } + + /// Returns the migration version recorded on the given schema. + public static int getSchemaVersion(Schema schema) { + return Math.max(schema.getConfigMigrationVersion(), INITIAL_VERSION); + } + + /// Stamps the given migration version onto the schema in place. + public static void setSchemaVersion(Schema schema, int version) { + schema.setConfigMigrationVersion(version); + } + + private static int parseVersion(String value) { + if (value == null) { + return INITIAL_VERSION; + } + try { + return Math.max(Integer.parseInt(value.trim()), INITIAL_VERSION); + } catch (NumberFormatException e) { + return INITIAL_VERSION; + } + } +} diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrator.java b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrator.java new file mode 100644 index 000000000000..d84695e1ee61 --- /dev/null +++ b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/ConfigMigrator.java @@ -0,0 +1,49 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.spi.config.migration; + +/// A single step in a versioned migration chain that upgrades a configuration object from one +/// migration version to the next. +/// +/// [#fromVersion()] defines the step's position in the ordered chain. The [ConfigMigrationRegistry] +/// reruns the chain for configs at any supported version, because later user updates can reintroduce +/// legacy properties without clearing the version marker. +/// +/// Implementations must be: +/// - **Idempotent**: a current-format input must remain unchanged, even after repeated execution. +/// - **Compatible with later steps**: legacy properties may already have been modernized by a previous run. +/// - **Thread-safe**: migrators are singletons registered once at startup and may be invoked +/// concurrently for different tables. +/// +/// @param the configuration type being migrated (e.g. {@code TableConfig} or {@code Schema}) +public interface ConfigMigrator { + + /// The step's position in the migration chain. Positions are dense, non-negative integers starting at 0. + /// The registry stamps the chain's target version only after a substantive transformation. + int fromVersion(); + + /// Modernizes any legacy properties owned by this step, leaving current-format input unchanged. + /// + /// Implementations may either mutate {@code input} in place and return it, or return a new + /// object. The version marker itself is stamped by the registry, not by the migrator. + /// + /// @param input config at any supported migration version + /// @return the equivalent modernized config + T migrate(T input); +} diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/MigrationResult.java b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/MigrationResult.java new file mode 100644 index 000000000000..efc47df45b30 --- /dev/null +++ b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/MigrationResult.java @@ -0,0 +1,52 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.spi.config.migration; + +/// The outcome of running the migration chain over a single config object. +/// +/// - [#getConfig()] is the (possibly upgraded) config. When [#isChanged()] is {@code false} this is +/// the same instance that was passed in. +/// - [#getVersion()] is the registry's target version. It is stamped onto [#getConfig()] only when changed. +/// - [#isChanged()] is {@code true} when the config content changed. A version-marker-only update is not +/// recommended. When {@code false}, the caller should skip the write entirely. +/// +/// @param the configuration type (e.g. {@code TableConfig} or {@code Schema}) +public class MigrationResult { + private final T _config; + private final int _version; + private final boolean _changed; + + public MigrationResult(T config, int version, boolean changed) { + _config = config; + _version = version; + _changed = changed; + } + + public T getConfig() { + return _config; + } + + public int getVersion() { + return _version; + } + + public boolean isChanged() { + return _changed; + } +} diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/SchemaMigrator.java b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/SchemaMigrator.java new file mode 100644 index 000000000000..8a0cda7b205b --- /dev/null +++ b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/SchemaMigrator.java @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.spi.config.migration; + +import org.apache.pinot.spi.data.Schema; + + +/// A [ConfigMigrator] that upgrades a [Schema] from one migration version to the next. +/// +/// Register concrete implementations with [ConfigMigrationRegistry#registerSchemaMigrator] so they +/// participate in the startup migration chain run by the controller. +public interface SchemaMigrator extends ConfigMigrator { +} diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/TableConfigMigrator.java b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/TableConfigMigrator.java new file mode 100644 index 000000000000..df68874d3d46 --- /dev/null +++ b/pinot-spi/src/main/java/org/apache/pinot/spi/config/migration/TableConfigMigrator.java @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.spi.config.migration; + +import org.apache.pinot.spi.config.table.TableConfig; + + +/// A [ConfigMigrator] that upgrades a [TableConfig] from one migration version to the next. +/// +/// Register concrete implementations with [ConfigMigrationRegistry#registerTableConfigMigrator] so +/// they participate in the startup migration chain run by the controller. +public interface TableConfigMigrator extends ConfigMigrator { +} diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java b/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java index 2d0c9bd88843..0e6588a3fd52 100644 --- a/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java +++ b/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java @@ -77,6 +77,12 @@ public final class Schema implements Serializable { @Nullable private List _tags; private boolean _enableColumnBasedNullHandling; + // Highest config-migration version applied to this schema by the controller's startup migration + // chain (see org.apache.pinot.spi.config.migration). 0 means "written before the migration + // framework existed". This is migration bookkeeping, not part of the schema's logical identity, so + // it is intentionally excluded from equals()/hashCode(). Older controllers ignore the JSON field + // via @JsonIgnoreProperties(ignoreUnknown = true), keeping rollback safe. + private int _configMigrationVersion; private final List _dimensionFieldSpecs = new ArrayList<>(); private final List _metricFieldSpecs = new ArrayList<>(); @SuppressWarnings("deprecation") @@ -208,6 +214,16 @@ public void setEnableColumnBasedNullHandling(boolean enableColumnBasedNullHandli _enableColumnBasedNullHandling = enableColumnBasedNullHandling; } + /// The highest config-migration version applied to this schema. See + /// [org.apache.pinot.spi.config.migration.ConfigMigrationUtils] for how this marker is used. + public int getConfigMigrationVersion() { + return _configMigrationVersion; + } + + public void setConfigMigrationVersion(int configMigrationVersion) { + _configMigrationVersion = configMigrationVersion; + } + @Nullable public List getPrimaryKeyColumns() { return _primaryKeyColumns; @@ -407,6 +423,7 @@ public Schema withoutVirtualColumns() { newSchema.setDescription(_description); newSchema.setTags(_tags); newSchema.setEnableColumnBasedNullHandling(isEnableColumnBasedNullHandling()); + newSchema.setConfigMigrationVersion(_configMigrationVersion); List primaryKeyColumns = getPrimaryKeyColumns(); if (primaryKeyColumns != null) { newSchema.setPrimaryKeyColumns(primaryKeyColumns.stream() @@ -531,6 +548,11 @@ public ObjectNode toJsonObject() { jsonObject.set("tags", tagsArray); } jsonObject.set("enableColumnBasedNullHandling", JsonUtils.objectToJsonNode(_enableColumnBasedNullHandling)); + // Only emit the migration marker once it has advanced past the initial version, so schemas that + // predate the migration framework keep serializing to identical JSON. + if (_configMigrationVersion != 0) { + jsonObject.put("configMigrationVersion", _configMigrationVersion); + } if (!_dimensionFieldSpecs.isEmpty()) { ArrayNode jsonArray = JsonUtils.newArrayNode(); for (DimensionFieldSpec dimensionFieldSpec : _dimensionFieldSpecs) { diff --git a/pinot-spi/src/test/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistryTest.java b/pinot-spi/src/test/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistryTest.java new file mode 100644 index 000000000000..10032a385364 --- /dev/null +++ b/pinot-spi/src/test/java/org/apache/pinot/spi/config/migration/ConfigMigrationRegistryTest.java @@ -0,0 +1,206 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.spi.config.migration; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.config.table.TableCustomConfig; +import org.apache.pinot.spi.config.table.TableType; +import org.apache.pinot.spi.data.DimensionFieldSpec; +import org.apache.pinot.spi.data.FieldSpec.DataType; +import org.apache.pinot.spi.data.Schema; +import org.apache.pinot.spi.utils.JsonUtils; +import org.apache.pinot.spi.utils.builder.TableConfigBuilder; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; +import static org.testng.Assert.assertThrows; +import static org.testng.Assert.assertTrue; + + +public class ConfigMigrationRegistryTest { + + private static TableConfig newTableConfig() { + return new TableConfigBuilder(TableType.OFFLINE).setTableName("myTable").build(); + } + + private static Schema newSchema() { + Schema schema = new Schema(); + schema.setSchemaName("myTable"); + schema.addField(new DimensionFieldSpec("d", DataType.STRING, true)); + return schema; + } + + /// A schema migrator that records the version it saw and bumps a counter in the schema description so we can assert + /// migrators run in order. + private static class RecordingSchemaMigrator implements SchemaMigrator { + private final int _fromVersion; + private final List _log; + + RecordingSchemaMigrator(int fromVersion, List log) { + _fromVersion = fromVersion; + _log = log; + } + + @Override + public int fromVersion() { + return _fromVersion; + } + + @Override + public Schema migrate(Schema input) { + _log.add(_fromVersion); + input.setDescription("migrated-" + _fromVersion); + return input; + } + } + + @Test + public void testEmptyRegistryIsIdentity() { + ConfigMigrationRegistry registry = new ConfigMigrationRegistry(); + assertEquals(registry.getCurrentTableConfigVersion(), 0); + assertEquals(registry.getCurrentSchemaVersion(), 0); + + TableConfig tableConfig = newTableConfig(); + MigrationResult result = registry.migrateTableConfig(tableConfig); + assertFalse(result.isChanged()); + assertSame(result.getConfig(), tableConfig); + assertEquals(result.getVersion(), 0); + } + + @Test + public void testMigratorsRunInOrderForSupportedStoredVersions() { + List log = new ArrayList<>(); + ConfigMigrationRegistry registry = new ConfigMigrationRegistry(); + registry.registerSchemaMigrator(new RecordingSchemaMigrator(0, log)); + registry.registerSchemaMigrator(new RecordingSchemaMigrator(1, log)); + registry.registerSchemaMigrator(new RecordingSchemaMigrator(2, log)); + assertEquals(registry.getCurrentSchemaVersion(), 3); + + // A version-0 schema runs all three migrators in order. + Schema schema = newSchema(); + MigrationResult result = registry.migrateSchema(schema); + assertTrue(result.isChanged()); + assertEquals(result.getVersion(), 3); + assertEquals(ConfigMigrationUtils.getSchemaVersion(result.getConfig()), 3); + assertEquals(log, List.of(0, 1, 2)); + assertEquals(schema.getConfigMigrationVersion(), 0); + assertNull(schema.getDescription()); + + // Supported markers are advisory: inspect every step in case a later edit reintroduced legacy properties. + log.clear(); + Schema partiallyMigrated = newSchema(); + partiallyMigrated.setConfigMigrationVersion(2); + MigrationResult result2 = registry.migrateSchema(partiallyMigrated); + assertTrue(result2.isChanged()); + assertEquals(result2.getVersion(), 3); + assertEquals(log, List.of(0, 1, 2)); + } + + @Test + public void testMarkerOnlyUpdateIsNotRecommended() { + ConfigMigrationRegistry registry = new ConfigMigrationRegistry(); + registry.registerSchemaMigrator(new SchemaMigrator() { + @Override + public int fromVersion() { + return 0; + } + + @Override + public Schema migrate(Schema input) { + return input; + } + }); + Schema schema = newSchema(); + MigrationResult result = registry.migrateSchema(schema); + assertFalse(result.isChanged()); + assertSame(result.getConfig(), schema); + assertEquals(schema.getConfigMigrationVersion(), 0); + } + + @Test + public void testAlreadyCurrentIsNoOp() { + List log = new ArrayList<>(); + ConfigMigrationRegistry registry = new ConfigMigrationRegistry(); + registry.registerSchemaMigrator(new RecordingSchemaMigrator(0, log)); + + Schema schema = newSchema(); + schema.setConfigMigrationVersion(1); + schema.setDescription("migrated-0"); + MigrationResult result = registry.migrateSchema(schema); + assertFalse(result.isChanged()); + assertSame(result.getConfig(), schema); + assertEquals(result.getVersion(), 1); + assertEquals(log, List.of(0)); + } + + @Test + public void testStoredVersionAboveCurrentIsUntouched() { + // e.g. after a controller downgrade: a config stamped at a higher version must not be "migrated" backwards. + ConfigMigrationRegistry registry = new ConfigMigrationRegistry(); + registry.registerSchemaMigrator(new RecordingSchemaMigrator(0, new ArrayList<>())); + + Schema schema = newSchema(); + schema.setConfigMigrationVersion(5); + MigrationResult result = registry.migrateSchema(schema); + assertFalse(result.isChanged()); + assertEquals(ConfigMigrationUtils.getSchemaVersion(result.getConfig()), 5); + } + + @Test + public void testRegistrationEnforcesDenseAscendingOrder() { + ConfigMigrationRegistry registry = new ConfigMigrationRegistry(); + // First migrator must declare fromVersion == 0. + assertThrows(IllegalArgumentException.class, + () -> registry.registerSchemaMigrator(new RecordingSchemaMigrator(1, new ArrayList<>()))); + + registry.registerSchemaMigrator(new RecordingSchemaMigrator(0, new ArrayList<>())); + // Next migrator must declare fromVersion == 1, not skip to 2. + assertThrows(IllegalArgumentException.class, + () -> registry.registerSchemaMigrator(new RecordingSchemaMigrator(2, new ArrayList<>()))); + } + + @Test + public void testTableConfigMarkerRoundTrip() + throws Exception { + // Start with a pre-existing user custom config that must be preserved when the marker is stamped. + TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("myTable") + .setCustomConfig(new TableCustomConfig(new HashMap<>(Map.of("userKey", "userValue")))) + .build(); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(tableConfig), 0); + + ConfigMigrationUtils.setTableConfigVersion(tableConfig, 3); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(tableConfig), 3); + // Stamping the marker preserves the user's existing custom config. + Map customConfigs = tableConfig.getCustomConfig().getCustomConfigs(); + assertEquals(customConfigs.get("userKey"), "userValue"); + assertEquals(customConfigs.get(ConfigMigrationUtils.CONFIG_MIGRATION_VERSION_KEY), "3"); + + // The marker (and the user config) survive a full JSON round-trip. + TableConfig deserialized = JsonUtils.stringToObject(tableConfig.toJsonString(), TableConfig.class); + assertEquals(ConfigMigrationUtils.getTableConfigVersion(deserialized), 3); + assertEquals(deserialized.getCustomConfig().getCustomConfigs().get("userKey"), "userValue"); + } +} diff --git a/pinot-spi/src/test/java/org/apache/pinot/spi/data/SchemaTest.java b/pinot-spi/src/test/java/org/apache/pinot/spi/data/SchemaTest.java index ce4df4a78a05..0e990eb97e04 100644 --- a/pinot-spi/src/test/java/org/apache/pinot/spi/data/SchemaTest.java +++ b/pinot-spi/src/test/java/org/apache/pinot/spi/data/SchemaTest.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; +import org.apache.pinot.spi.data.FieldSpec.DataType; import org.apache.pinot.spi.data.TimeGranularitySpec.TimeFormat; import org.apache.pinot.spi.utils.BytesUtils; import org.apache.pinot.spi.utils.CommonConstants; @@ -38,6 +39,9 @@ import org.testng.collections.Lists; import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; @SuppressWarnings("deprecation") @@ -841,4 +845,40 @@ public void schemaBuilderAddOpenStruct() { ComplexFieldSpec cfs = (ComplexFieldSpec) fs; Assert.assertEquals(cfs.getChildFieldSpec("count").getDataType(), FieldSpec.DataType.INT); } + + @Test + public void testConfigMigrationVersionMarker() + throws Exception { + Schema schema = new Schema.SchemaBuilder().setSchemaName("test") + .addSingleValueDimension("svDimension", DataType.INT) + .build(); + // Default marker is 0 and is not emitted, so schemas that predate the framework serialize unchanged. Assert via + // both toJsonObject() and the full objectToString() path (Schema uses @JsonValue, so both go through toJsonObject). + assertEquals(schema.getConfigMigrationVersion(), 0); + assertFalse(schema.toJsonObject().has("configMigrationVersion")); + assertFalse(JsonUtils.objectToString(schema).contains("configMigrationVersion")); + + schema.setConfigMigrationVersion(2); + assertTrue(schema.toJsonObject().has("configMigrationVersion")); + assertTrue(JsonUtils.objectToString(schema).contains("configMigrationVersion")); + + // The marker survives a JSON round-trip. + Schema deserialized = JsonUtils.stringToObject(JsonUtils.objectToString(schema), Schema.class); + assertEquals(deserialized.getConfigMigrationVersion(), 2); + + // Backward/forward compatibility: JSON carrying the marker plus an unknown future field still deserializes + // (older readers ignore both via @JsonIgnoreProperties(ignoreUnknown = true)). + String json = "{\"schemaName\":\"test\",\"configMigrationVersion\":4,\"someFutureField\":\"x\"," + + "\"dimensionFieldSpecs\":[{\"name\":\"svDimension\",\"dataType\":\"INT\"}]}"; + Schema fromFutureJson = JsonUtils.stringToObject(json, Schema.class); + assertEquals(fromFutureJson.getConfigMigrationVersion(), 4); + + // The marker is bookkeeping, not identity: two schemas differing only by marker are equal. + Schema other = new Schema.SchemaBuilder().setSchemaName("test") + .addSingleValueDimension("svDimension", DataType.INT) + .build(); + other.setConfigMigrationVersion(5); + assertEquals(schema, other); + assertEquals(schema.hashCode(), other.hashCode()); + } }