damccorm commented on code in PR #41616: URL: https://github.com/apache/beam/pull/41616#discussion_r4744099625
########## CHANGES.md: ########## @@ -174,6 +174,7 @@ * (Python) An unknown pipeline option is no longer given the value of a later argument that does not directly follow it, which made `Pipeline.run()` and `get_all_options(retain_unknown_options=True)` fail with `expected one argument` for flags like `--unknown_flag --job_name=foo bar` ([#22434](https://github.com/apache/beam/issues/22434)). * (Python) Fixed `WriteToJson` silently rounding floats to 10 decimal places: it now defaults pandas' `double_precision` to 15, so values such as `0.1234567890123` and `1e-11` are written correctly. Floats that need 16-17 significant digits may still be rounded ([#41102](https://github.com/apache/beam/issues/41102)). * (Java) Makes some fixes to IcebergIO's hash distribution mode, which sometimes wrote incorrect partition values. ([#41012](https://github.com/apache/beam/issues/41012)). +* (Java) Fixed the Flink runner's `MapState` and `SetState` comparing keys by `Object#equals` instead of their encoded value on heap and batch state backends (for example `byte[]` or Avro reflect POJOs), and rejecting `null` keys with `NullableCoder` ([#41616](https://github.com/apache/beam/pull/41616)). Review Comment: Looks like `CHANGES.md` and `DoFnOperatorTest.java` also picked up merge conflicts with `master`, which kept GitHub Actions from running on `035e1e38e2` — please rebase/merge `master` when you push the updates so CI can run on the migration changes. ########## runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/state/FlinkStateInternals.java: ########## @@ -1309,11 +1330,196 @@ public int hashCode() { } } + /** + * Whether keys of {@code coder} must be wrapped in {@link StructuralKey} before being stored in a + * Flink {@link org.apache.flink.api.common.state.MapState}. + * + * <p>Heap and batch keyed state backends back {@code MapState} with a Java {@link Map}, which + * compares keys by {@link Object#equals}, and both heap ({@code CopyOnWriteStateMap}) and RocksDB + * reject {@code null} keys. Coders that are {@link Coder#consistentWithEquals()} and cannot + * encode {@code null} (i.e. not {@link NullableCoder}) store raw keys directly. + */ + private static boolean usesStructuralKey(Coder<?> coder) { + return !coder.consistentWithEquals() || coder instanceof NullableCoder; + } + + private static <KeyT, ValueT> MapStateDescriptor<Object, ValueT> createMapStateDescriptor( + String stateId, + Coder<KeyT> keyCoder, + TypeSerializer<ValueT> valueSerializer, + boolean fasterCopy) { + Coder<?> stateKeyCoder = + usesStructuralKey(keyCoder) ? new StructuralKeyCoder<>(keyCoder) : keyCoder; + @SuppressWarnings("unchecked") + TypeSerializer<Object> keySerializer = + (TypeSerializer<Object>) new CoderTypeSerializer<>(stateKeyCoder, fasterCopy); + return new MapStateDescriptor<>(stateId, keySerializer, valueSerializer); + } + + /** + * Re-wraps raw {@code KeyT} entries restored from a pre-{@link StructuralKey} heap savepoint. + * + * <p>Note: {@code UnversionedTypeSerializerSnapshot.resolveSchemaCompatibility} must remain + * {@code compatibleAsIs()} rather than {@code compatibleAfterMigration()} because {@code + * RocksDBKeyedStateBackend.migrateStateValues} rejects key-serializer migration on {@code + * MapState} with {@code StateMigrationException} (RocksDB wire bytes already match), while {@code + * HeapKeyedStateBackend} deserializes snapshot entries via the old {@code restoreSerializer()} + * during {@code initializeState} and skips in-memory migration unless TTL changed. + */ + private static <KeyT, ValueT> void migrateLegacyHeapMapKeysIfNeeded( + KeyedStateBackend<FlinkKey> flinkStateBackend, + FlinkStateNamespaceKeySerializer namespaceSerializer, + MapStateDescriptor<Object, ValueT> stateDescriptor, + Coder<KeyT> keyCoder) { + if (!usesStructuralKey(keyCoder) || !(flinkStateBackend instanceof HeapKeyedStateBackend)) { Review Comment: If `state.backend.changelog.enabled` is turned on with `HashMapStateBackend`, `flinkStateBackend` is a `ChangelogKeyedStateBackend` wrapping `HeapKeyedStateBackend`, so `instanceof HeapKeyedStateBackend` will be `false` and skip migration. Unwrapping via `TestableKeyedStateBackend#getDelegatedKeyedStateBackend(true)` for the `instanceof` check (while still running the reads/writes against the outer `flinkStateBackend` so the changelog logs them) handles that cleanly (in both the `1.x` and `2.0` copies). ########## runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/state/FlinkStateInternals.java: ########## @@ -1309,11 +1330,196 @@ public int hashCode() { } } + /** + * Whether keys of {@code coder} must be wrapped in {@link StructuralKey} before being stored in a + * Flink {@link org.apache.flink.api.common.state.MapState}. + * + * <p>Heap and batch keyed state backends back {@code MapState} with a Java {@link Map}, which + * compares keys by {@link Object#equals}, and both heap ({@code CopyOnWriteStateMap}) and RocksDB + * reject {@code null} keys. Coders that are {@link Coder#consistentWithEquals()} and cannot + * encode {@code null} (i.e. not {@link NullableCoder}) store raw keys directly. + */ + private static boolean usesStructuralKey(Coder<?> coder) { + return !coder.consistentWithEquals() || coder instanceof NullableCoder; + } + + private static <KeyT, ValueT> MapStateDescriptor<Object, ValueT> createMapStateDescriptor( + String stateId, + Coder<KeyT> keyCoder, + TypeSerializer<ValueT> valueSerializer, + boolean fasterCopy) { + Coder<?> stateKeyCoder = + usesStructuralKey(keyCoder) ? new StructuralKeyCoder<>(keyCoder) : keyCoder; + @SuppressWarnings("unchecked") + TypeSerializer<Object> keySerializer = + (TypeSerializer<Object>) new CoderTypeSerializer<>(stateKeyCoder, fasterCopy); + return new MapStateDescriptor<>(stateId, keySerializer, valueSerializer); + } + + /** + * Re-wraps raw {@code KeyT} entries restored from a pre-{@link StructuralKey} heap savepoint. + * + * <p>Note: {@code UnversionedTypeSerializerSnapshot.resolveSchemaCompatibility} must remain + * {@code compatibleAsIs()} rather than {@code compatibleAfterMigration()} because {@code + * RocksDBKeyedStateBackend.migrateStateValues} rejects key-serializer migration on {@code + * MapState} with {@code StateMigrationException} (RocksDB wire bytes already match), while {@code + * HeapKeyedStateBackend} deserializes snapshot entries via the old {@code restoreSerializer()} + * during {@code initializeState} and skips in-memory migration unless TTL changed. + */ + private static <KeyT, ValueT> void migrateLegacyHeapMapKeysIfNeeded( + KeyedStateBackend<FlinkKey> flinkStateBackend, + FlinkStateNamespaceKeySerializer namespaceSerializer, + MapStateDescriptor<Object, ValueT> stateDescriptor, + Coder<KeyT> keyCoder) { + if (!usesStructuralKey(keyCoder) || !(flinkStateBackend instanceof HeapKeyedStateBackend)) { + return; + } + try { + FlinkKey previousKey = flinkStateBackend.getCurrentKey(); + try { + if (!hasLegacyRawKeys(flinkStateBackend, namespaceSerializer, stateDescriptor)) { + return; + } + List<Tuple2<FlinkKey, StateNamespace>> keysAndNamespaces; + try (Stream<Tuple2<FlinkKey, StateNamespace>> stream = + flinkStateBackend.getKeysAndNamespaces(stateDescriptor.getName())) { + keysAndNamespaces = stream.collect(Collectors.toList()); + } + for (Tuple2<FlinkKey, StateNamespace> keyAndNamespace : keysAndNamespaces) { + flinkStateBackend.setCurrentKey(keyAndNamespace.f0); + org.apache.flink.api.common.state.MapState<Object, ValueT> state = + flinkStateBackend.getPartitionedState( + keyAndNamespace.f1, namespaceSerializer, stateDescriptor); + Object firstKey = Iterables.getFirst(state.keys(), null); Review Comment: Thanks for digging into why `compatibleAfterMigration()` doesn't work here — that makes sense. One bug in the migration check (here and in `hasLegacyRawKeys` at line 1430, in both `1.x` and `2.0`): `HeapMapState` backs each `(key, namespace)` map with a `java.util.HashMap` (which allows `null` user keys; `CopyOnWriteStateMap` only rejects `null` outer keys/namespaces), and `MapSerializer` delegates directly to `CoderTypeSerializer(NullableCoder)`. So a pre-PR `HashMapStateBackend` savepoint can contain a raw `null` key — and because `HashMap` puts `null` in bucket 0, it's always the *first* key returned by `state.keys()`. `Iterables.getFirst(state.keys(), null)` conflates "empty map" with "first key is `null`", so `hasLegacyRawKeys` skips maps containing `null` (returning `false` if every restored map has a `null` key) and the loop here `continue`s past the whole `(key, namespace)` map, leaving both `null` and non-null raw keys unmigrated (silent lookup misses + NPE/`ClassCastException` on the next checkpoint). Using `Iterator<Object> it = state.keys().iterator()` and checking `it.hasNext()` fixes both places — mind updating both `1.x` and `2.0` and adding a `NullableCoder` `null`-key case to `testRestorePreStructuralKeySnapshot`? ########## runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/state/FlinkStateInternals.java: ########## @@ -1309,11 +1330,196 @@ public int hashCode() { } } + /** + * Whether keys of {@code coder} must be wrapped in {@link StructuralKey} before being stored in a + * Flink {@link org.apache.flink.api.common.state.MapState}. + * + * <p>Heap and batch keyed state backends back {@code MapState} with a Java {@link Map}, which + * compares keys by {@link Object#equals}, and both heap ({@code CopyOnWriteStateMap}) and RocksDB + * reject {@code null} keys. Coders that are {@link Coder#consistentWithEquals()} and cannot + * encode {@code null} (i.e. not {@link NullableCoder}) store raw keys directly. + */ + private static boolean usesStructuralKey(Coder<?> coder) { + return !coder.consistentWithEquals() || coder instanceof NullableCoder; + } + + private static <KeyT, ValueT> MapStateDescriptor<Object, ValueT> createMapStateDescriptor( + String stateId, + Coder<KeyT> keyCoder, + TypeSerializer<ValueT> valueSerializer, + boolean fasterCopy) { + Coder<?> stateKeyCoder = + usesStructuralKey(keyCoder) ? new StructuralKeyCoder<>(keyCoder) : keyCoder; + @SuppressWarnings("unchecked") + TypeSerializer<Object> keySerializer = + (TypeSerializer<Object>) new CoderTypeSerializer<>(stateKeyCoder, fasterCopy); + return new MapStateDescriptor<>(stateId, keySerializer, valueSerializer); + } + + /** + * Re-wraps raw {@code KeyT} entries restored from a pre-{@link StructuralKey} heap savepoint. + * + * <p>Note: {@code UnversionedTypeSerializerSnapshot.resolveSchemaCompatibility} must remain + * {@code compatibleAsIs()} rather than {@code compatibleAfterMigration()} because {@code + * RocksDBKeyedStateBackend.migrateStateValues} rejects key-serializer migration on {@code + * MapState} with {@code StateMigrationException} (RocksDB wire bytes already match), while {@code + * HeapKeyedStateBackend} deserializes snapshot entries via the old {@code restoreSerializer()} + * during {@code initializeState} and skips in-memory migration unless TTL changed. + */ + private static <KeyT, ValueT> void migrateLegacyHeapMapKeysIfNeeded( + KeyedStateBackend<FlinkKey> flinkStateBackend, + FlinkStateNamespaceKeySerializer namespaceSerializer, + MapStateDescriptor<Object, ValueT> stateDescriptor, + Coder<KeyT> keyCoder) { + if (!usesStructuralKey(keyCoder) || !(flinkStateBackend instanceof HeapKeyedStateBackend)) { + return; + } + try { + FlinkKey previousKey = flinkStateBackend.getCurrentKey(); + try { + if (!hasLegacyRawKeys(flinkStateBackend, namespaceSerializer, stateDescriptor)) { + return; + } + List<Tuple2<FlinkKey, StateNamespace>> keysAndNamespaces; + try (Stream<Tuple2<FlinkKey, StateNamespace>> stream = + flinkStateBackend.getKeysAndNamespaces(stateDescriptor.getName())) { + keysAndNamespaces = stream.collect(Collectors.toList()); + } + for (Tuple2<FlinkKey, StateNamespace> keyAndNamespace : keysAndNamespaces) { + flinkStateBackend.setCurrentKey(keyAndNamespace.f0); + org.apache.flink.api.common.state.MapState<Object, ValueT> state = + flinkStateBackend.getPartitionedState( + keyAndNamespace.f1, namespaceSerializer, stateDescriptor); + Object firstKey = Iterables.getFirst(state.keys(), null); + if (firstKey == null || firstKey instanceof StructuralKey) { + continue; + } + Map<Object, ValueT> migrated = new HashMap<>(); + for (Map.Entry<Object, ValueT> entry : state.entries()) { + @SuppressWarnings("unchecked") + KeyT rawKey = (KeyT) entry.getKey(); + migrated.put(new StructuralKey<>(keyCoder, rawKey), entry.getValue()); + } + state.clear(); + state.putAll(migrated); + } + } finally { + if (previousKey != null) { + flinkStateBackend.setCurrentKey(previousKey); + } + } + } catch (Exception e) { + throw new RuntimeException("Failed to migrate legacy heap MapState keys.", e); + } + } + + private static <ValueT> boolean hasLegacyRawKeys( + KeyedStateBackend<FlinkKey> flinkStateBackend, + FlinkStateNamespaceKeySerializer namespaceSerializer, + MapStateDescriptor<Object, ValueT> stateDescriptor) + throws Exception { + try (Stream<Tuple2<FlinkKey, StateNamespace>> stream = + flinkStateBackend.getKeysAndNamespaces(stateDescriptor.getName())) { + Iterator<Tuple2<FlinkKey, StateNamespace>> it = stream.iterator(); + while (it.hasNext()) { + Tuple2<FlinkKey, StateNamespace> keyAndNamespace = it.next(); + flinkStateBackend.setCurrentKey(keyAndNamespace.f0); + org.apache.flink.api.common.state.MapState<Object, ValueT> state = + flinkStateBackend.getPartitionedState( + keyAndNamespace.f1, namespaceSerializer, stateDescriptor); + Object firstKey = Iterables.getFirst(state.keys(), null); + if (firstKey != null) { + return !(firstKey instanceof StructuralKey); + } + } + return false; + } + } + + /** + * Wraps a key together with its {@link Coder#structuralValue} so Flink's in-memory {@code + * MapState} implementations compare keys by encoded equality (and accept {@code null} keys) while + * still retaining the original {@code KeyT} for {@code keys()} and {@code entries()}. + */ + private static final class StructuralKey<K> { + private final @Nullable K key; + private final @Nullable Object structuralValue; + + StructuralKey(Coder<K> coder, @Nullable K key) { + this.key = key; + this.structuralValue = coder.structuralValue(key); Review Comment: Optional perf suggestion: on RocksDB, `equals`/`hashCode` are never called on user keys, so calling `coder.structuralValue(key)` eagerly in the constructor double-encodes/clones every key on `get`/`put`/`remove` and re-encodes every decoded key during `keys()`/`entries()`/`read()` right before `fromStateKey` drops the wrapper. Computing `structuralValue` lazily on first `equals`/`hashCode` (cached with a `boolean` flag since `structuralValue` can be `null`) avoids that overhead on RocksDB while still running synchronously inside `HashMap.put`/`get`/`remove` on heap/batch. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
