Repository navigation
Spark 4.2: Implement SupportsReportOrdering DSv2 API - #16750
anuragmantri wants to merge 1 commit into
Conversation
|
This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions. |
|
This is not stale. |
|
This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions. |
a417b12 to
9223faa
Compare
|
@RussellSpitzer @dramaticlly - This plumbing PR is ready for review. I rebased the reader changes. |
dramaticlly
left a comment
There was a problem hiding this comment.
thanks @anuragmantri , did my first pass
| List<SortField> sortFields = sortOrder.fields(); | ||
| for (int i = 0; i < sortFields.size(); i++) { | ||
| SortField sortField = sortFields.get(i); | ||
| if (!TypeUtil.ancestorFields(schema, sortField.sourceId()).isEmpty()) { |
There was a problem hiding this comment.
I think some of the logic can combine with Merging reader, such as nested field, #14948 (comment) and UUID/float/double, I think we can extract and combine
There was a problem hiding this comment.
Extracted isUuid and isFloatingPoint into SparkOrderingUtil and used them in MergingSortedRowDataReader.validateSortKeys. I kept the nested check separate on purpose. The reader accepts a nested sort key when it is projected, and the util refuses every nested key.
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| class SortOrderAnalyzer { |
There was a problem hiding this comment.
All methods are static here, not sure if Analyzer is the best class name here, maybe SparkOrderingUtil if we need to expose package local methods ?
There was a problem hiding this comment.
Renamed to SparkOrderingUtil.
|
|
||
| private SortOrderAnalyzer() {} | ||
|
|
||
| static int reportablePrefixLength(Table table, Schema projection) { |
There was a problem hiding this comment.
sugg: I would pass sort order and schema directly to avoid pass table, it shall also help with mock in UT.
There was a problem hiding this comment.
Done. reportablePrefixLength now takes the sort order, the table schema and the projection, so the unit tests no longer mock Table.
|
|
||
| @Override | ||
| public synchronized SortOrder[] outputOrdering() { | ||
| taskGroups(); |
There was a problem hiding this comment.
sugg: is there a way to ensure we can observe them in spark UI, like with orderedBy=... in description() or anywhere
There was a problem hiding this comment.
Added orderedBy= next to groupedBy= in the descriptions of SparkBatchQueryScan, SparkCopyOnWriteScan and SparkIncrementalAppendScan, with tests for both the reported and not reported cases.
| } | ||
|
|
||
| private List<ScanTaskGroup<T>> planGroupedTaskGroups() { | ||
| if (reportedOrdering == null) { |
There was a problem hiding this comment.
I would invert the condition here to return early when reportOrdering is not null, the reason is that the default of NO_ORDERING is more robust to transient planFiles runtime problems (network etc).
There was a problem hiding this comment.
Restructured so planGroupedTaskGroups returns early when reportedOrdering is set, and reportedOrdering is only assigned once the decision completes. A failure while planning now leaves it undecided instead of cached as no ordering. Let me know if you meant something different by the default being more robust.
| Types.StructType.of(Types.NestedField.required(6, "key", Types.IntegerType.get())))); | ||
|
|
||
| private static final SortOrder SORT_ORDER = SortOrder.builderFor(SCHEMA).asc("id").build(); | ||
| private static final int SORT_ORDER_ID = 1; |
There was a problem hiding this comment.
or SORT_ORDER.orderId()
There was a problem hiding this comment.
Done, it now uses SORT_ORDER.orderId().
| SparkPartitioningAwareScan<?> scan = buildScan(tableIdent, options, null); | ||
| assertThat(scan.outputOrdering()).isEmpty(); | ||
| // partition A has 3 files and partition B has 2, each planned separately at split size 1 | ||
| assertThat(scan.taskGroups()).hasSize(5); |
There was a problem hiding this comment.
can we derive 5 from newScan().planFiles()?
There was a problem hiding this comment.
The expected count is now computed from the planned files.
| } | ||
|
|
||
| @TestTemplate | ||
| void copyOnWriteMergeIsCorrect() { |
There was a problem hiding this comment.
do we have merge-on-read counter part?
There was a problem hiding this comment.
Added merge-on-read MERGE and DELETE tests next to the copy-on-write MERGE test. Each one also checks that ordering is reported for the table before running the DML.
| private void setSortOrder(TableIdentifier ident, String... columns) { | ||
| ReplaceSortOrder sortOrder = validationCatalog.loadTable(ident).replaceSortOrder(); | ||
| for (String column : columns) { | ||
| sortOrder = sortOrder.asc(column); |
There was a problem hiding this comment.
shall we also cover desc. or with null first/last?
There was a problem hiding this comment.
Added tests for descending, nulls first and nulls last. A mismatched null order test checks that the sort is kept and the results are still correct.
| | spark.sql.iceberg.check-nullability | true | Validate that the write schema's nullability matches the table's nullability | | ||
| | spark.sql.iceberg.check-ordering | true | Validates the write schema column order matches the table schema order | | ||
| | spark.sql.iceberg.planning.preserve-data-grouping | false | When true, co-locate scan tasks for the same partition in the same read split, used in Storage Partitioned Joins | | ||
| | spark.sql.iceberg.planning.preserve-data-ordering | false | When true, report the table sort order to Spark so it can skip sorts. Requires `preserve-data-grouping` and applies only to partitioned tables. Ignored when `spark.sql.sources.v2.bucketing.allowCompatibleTransforms.enabled` or `spark.sql.sources.v2.bucketing.allowJoinKeysSubsetOfPartitionKeys.enabled` is true. Each partition is read by a single task, and vectorized reads are disabled when a task reads more than one file | |
There was a problem hiding this comment.
I don't feel we want to put too much configuration details/limits here. It can always be in javadoc or example unit test, it can simply state its purpose. Also want to ensure this meant for all spark version, what do you think?
There was a problem hiding this comment.
Trimmed both rows to their purpose. This is meant for all Spark versions. It starts with 4.1 and the other versions will follow in ports, so the rows carry no version note. I also dropped the read option for the max files setting, so only the session setting is documented.
9223faa to
994b54f
Compare
anuragmantri
left a comment
There was a problem hiding this comment.
Thanks @dramaticlly for the thorough first pass. I addressed all of the comments. Ready for another pass.
| List<SortField> sortFields = sortOrder.fields(); | ||
| for (int i = 0; i < sortFields.size(); i++) { | ||
| SortField sortField = sortFields.get(i); | ||
| if (!TypeUtil.ancestorFields(schema, sortField.sourceId()).isEmpty()) { |
There was a problem hiding this comment.
Extracted isUuid and isFloatingPoint into SparkOrderingUtil and used them in MergingSortedRowDataReader.validateSortKeys. I kept the nested check separate on purpose. The reader accepts a nested sort key when it is projected, and the util refuses every nested key.
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| class SortOrderAnalyzer { |
There was a problem hiding this comment.
Renamed to SparkOrderingUtil.
|
|
||
| private SortOrderAnalyzer() {} | ||
|
|
||
| static int reportablePrefixLength(Table table, Schema projection) { |
There was a problem hiding this comment.
Done. reportablePrefixLength now takes the sort order, the table schema and the projection, so the unit tests no longer mock Table.
|
|
||
| @Override | ||
| public synchronized SortOrder[] outputOrdering() { | ||
| taskGroups(); |
There was a problem hiding this comment.
Added orderedBy= next to groupedBy= in the descriptions of SparkBatchQueryScan, SparkCopyOnWriteScan and SparkIncrementalAppendScan, with tests for both the reported and not reported cases.
| } | ||
|
|
||
| private List<ScanTaskGroup<T>> planGroupedTaskGroups() { | ||
| if (reportedOrdering == null) { |
There was a problem hiding this comment.
Restructured so planGroupedTaskGroups returns early when reportedOrdering is set, and reportedOrdering is only assigned once the decision completes. A failure while planning now leaves it undecided instead of cached as no ordering. Let me know if you meant something different by the default being more robust.
| Types.StructType.of(Types.NestedField.required(6, "key", Types.IntegerType.get())))); | ||
|
|
||
| private static final SortOrder SORT_ORDER = SortOrder.builderFor(SCHEMA).asc("id").build(); | ||
| private static final int SORT_ORDER_ID = 1; |
There was a problem hiding this comment.
Done, it now uses SORT_ORDER.orderId().
| SparkPartitioningAwareScan<?> scan = buildScan(tableIdent, options, null); | ||
| assertThat(scan.outputOrdering()).isEmpty(); | ||
| // partition A has 3 files and partition B has 2, each planned separately at split size 1 | ||
| assertThat(scan.taskGroups()).hasSize(5); |
There was a problem hiding this comment.
The expected count is now computed from the planned files.
| } | ||
|
|
||
| @TestTemplate | ||
| void copyOnWriteMergeIsCorrect() { |
There was a problem hiding this comment.
Added merge-on-read MERGE and DELETE tests next to the copy-on-write MERGE test. Each one also checks that ordering is reported for the table before running the DML.
| private void setSortOrder(TableIdentifier ident, String... columns) { | ||
| ReplaceSortOrder sortOrder = validationCatalog.loadTable(ident).replaceSortOrder(); | ||
| for (String column : columns) { | ||
| sortOrder = sortOrder.asc(column); |
There was a problem hiding this comment.
Added tests for descending, nulls first and nulls last. A mismatched null order test checks that the sort is kept and the results are still correct.
| | spark.sql.iceberg.check-nullability | true | Validate that the write schema's nullability matches the table's nullability | | ||
| | spark.sql.iceberg.check-ordering | true | Validates the write schema column order matches the table schema order | | ||
| | spark.sql.iceberg.planning.preserve-data-grouping | false | When true, co-locate scan tasks for the same partition in the same read split, used in Storage Partitioned Joins | | ||
| | spark.sql.iceberg.planning.preserve-data-ordering | false | When true, report the table sort order to Spark so it can skip sorts. Requires `preserve-data-grouping` and applies only to partitioned tables. Ignored when `spark.sql.sources.v2.bucketing.allowCompatibleTransforms.enabled` or `spark.sql.sources.v2.bucketing.allowJoinKeysSubsetOfPartitionKeys.enabled` is true. Each partition is read by a single task, and vectorized reads are disabled when a task reads more than one file | |
There was a problem hiding this comment.
Trimmed both rows to their purpose. This is meant for all Spark versions. It starts with 4.1 and the other versions will follow in ports, so the rows carry no version note. I also dropped the read option for the max files setting, so only the session setting is documented.
dramaticlly
left a comment
There was a problem hiding this comment.
thanks @anuragmantri. Might worth considering a new core class to simplify the plumbing, other wise looks good to me.
| private final int scanHashCode; | ||
| private final boolean cacheDeleteFilesOnExecutors; | ||
| private final boolean orderingEnabled; | ||
| private final boolean anyTaskNeedsMerging; |
There was a problem hiding this comment.
I think there's a lot of plumbing involved to pass down the ordering flag which essentially depends on the state of ScanTaskGroup, I am wondering if worth a new org.apache.iceberg.OrderedTaskGroup in core module ? then needsMerging is implied to instance check of OrderedTaskGroup and at least 2 tasks?
it shall
- reduce the new flag here
- drop the change in SparkChangelogScan
- drop the change in SparkScan
- new constructor in SparkRowReaderFactory and remain stateless
There was a problem hiding this comment.
Good idea. I added OrderedScanTaskGroup, a package-private subclass of BaseScanTaskGroup in the Spark source package. When the scan reports an ordering it wraps its task groups in it, including the re-plan after runtime filtering, and needsMerging checks the type and the task count. That removed the flag from SparkBatch, the hook in SparkScan, the SparkChangelogScan change and the new SparkRowReaderFactory constructor.
I kept it out of core because only the Spark reader uses it, and a core class would be public API to carry across every engine.
| Type.TypeID resultType = sortField.transform().getResultType(field.type()).typeId(); | ||
| Preconditions.checkArgument( | ||
| resultType != Type.TypeID.UUID, | ||
| !SparkOrderingUtil.isUuid(sortField, field), |
There was a problem hiding this comment.
note this will make reader no longer standalone, especially for backport like #18492
There was a problem hiding this comment.
Good catch. I moved isUuid and isFloatingPoint into MergingSortedRowDataReader, and SparkOrderingUtil now calls them there. The reader no longer depends on anything this PR adds, so it can still be backported on its own, and the checks stay shared.
| : planBinPackedTaskGroups(); | ||
| } | ||
|
|
||
| int prefixLength = sortOrderPrefixLength(); |
There was a problem hiding this comment.
nit: I think we can add a variable for table().sortOrder() here, pass to sortOrderPrefixLength and also used twice below.
There was a problem hiding this comment.
Done. reportableOrdering reads it once and passes it to sortOrderPrefixLength.
|
|
||
| @TestTemplate | ||
| void copyOnWriteMergeIsCorrect() { | ||
| assertMergeIsCorrect("copy-on-write"); |
There was a problem hiding this comment.
let's use org.apache.iceberg.RowLevelOperationMode.COPY_ON_WRITE, same for MOR below
There was a problem hiding this comment.
Done, the tests pass RowLevelOperationMode.COPY_ON_WRITE and MERGE_ON_READ now.
| sql( | ||
| "ALTER TABLE %s SET TBLPROPERTIES ('%s' = '%s', '%s' = '%s', '%s' = '%s')", | ||
| tableName, | ||
| TableProperties.DELETE_MODE, | ||
| mode, | ||
| TableProperties.UPDATE_MODE, | ||
| mode, | ||
| TableProperties.MERGE_MODE, | ||
| mode); | ||
| } |
There was a problem hiding this comment.
| sql( | |
| "ALTER TABLE %s SET TBLPROPERTIES ('%s' = '%s', '%s' = '%s', '%s' = '%s')", | |
| tableName, | |
| TableProperties.DELETE_MODE, | |
| mode, | |
| TableProperties.UPDATE_MODE, | |
| mode, | |
| TableProperties.MERGE_MODE, | |
| mode); | |
| } | |
| sql( | |
| "ALTER TABLE %s SET TBLPROPERTIES (%s)", | |
| tablePropsAsString( | |
| ImmutableMap.of( | |
| TableProperties.DELETE_MODE, modeName, | |
| TableProperties.UPDATE_MODE, modeName, | |
| TableProperties.MERGE_MODE, modeName)) | |
| ); |
There was a problem hiding this comment.
Done, setRowLevelMode uses tablePropsAsString now.
| expected.set(sql(formattedQuery)); | ||
| }); | ||
|
|
||
| assertThat(actual.get()).containsExactlyInAnyOrderElementsOf(expected.get()); |
There was a problem hiding this comment.
can reuse assertResultUnchanged?
There was a problem hiding this comment.
Done. It only asserts the plans now and calls assertResultUnchanged for the rows.
994b54f to
28a7c84
Compare
28a7c84 to
70ef905
Compare
anuragmantri
left a comment
There was a problem hiding this comment.
Thanks for the review @dramaticlly. I also moved the PR from Spark 4.1 to 4.2 since we forward ported the reader.
The one behavior difference in 4.2 is planning. Spark 4.1 and below drops a reported ordering whenever it combines several splits of one partition, so 4.1 needs one task per partition. Spark 4.2's GroupPartitionsExec keeps it with a k-way merge when spark.sql.sources.v2.bucketing.preserveOrderingOnCoalesce.enabled is on (SPARK-55715), and otherwise keeps only the ordering on the partition keys. So in Iceberg, we can safely use normal bin packing (same as main today).
| private final int scanHashCode; | ||
| private final boolean cacheDeleteFilesOnExecutors; | ||
| private final boolean orderingEnabled; | ||
| private final boolean anyTaskNeedsMerging; |
There was a problem hiding this comment.
Good idea. I added OrderedScanTaskGroup, a package-private subclass of BaseScanTaskGroup in the Spark source package. When the scan reports an ordering it wraps its task groups in it, including the re-plan after runtime filtering, and needsMerging checks the type and the task count. That removed the flag from SparkBatch, the hook in SparkScan, the SparkChangelogScan change and the new SparkRowReaderFactory constructor.
I kept it out of core because only the Spark reader uses it, and a core class would be public API to carry across every engine.
| Type.TypeID resultType = sortField.transform().getResultType(field.type()).typeId(); | ||
| Preconditions.checkArgument( | ||
| resultType != Type.TypeID.UUID, | ||
| !SparkOrderingUtil.isUuid(sortField, field), |
There was a problem hiding this comment.
Good catch. I moved isUuid and isFloatingPoint into MergingSortedRowDataReader, and SparkOrderingUtil now calls them there. The reader no longer depends on anything this PR adds, so it can still be backported on its own, and the checks stay shared.
| : planBinPackedTaskGroups(); | ||
| } | ||
|
|
||
| int prefixLength = sortOrderPrefixLength(); |
There was a problem hiding this comment.
Done. reportableOrdering reads it once and passes it to sortOrderPrefixLength.
|
|
||
| @TestTemplate | ||
| void copyOnWriteMergeIsCorrect() { | ||
| assertMergeIsCorrect("copy-on-write"); |
There was a problem hiding this comment.
Done, the tests pass RowLevelOperationMode.COPY_ON_WRITE and MERGE_ON_READ now.
| sql( | ||
| "ALTER TABLE %s SET TBLPROPERTIES ('%s' = '%s', '%s' = '%s', '%s' = '%s')", | ||
| tableName, | ||
| TableProperties.DELETE_MODE, | ||
| mode, | ||
| TableProperties.UPDATE_MODE, | ||
| mode, | ||
| TableProperties.MERGE_MODE, | ||
| mode); | ||
| } |
There was a problem hiding this comment.
Done, setRowLevelMode uses tablePropsAsString now.
| expected.set(sql(formattedQuery)); | ||
| }); | ||
|
|
||
| assertThat(actual.get()).containsExactlyInAnyOrderElementsOf(expected.get()); |
There was a problem hiding this comment.
Done. It only asserts the plans now and calls assertResultUnchanged for the rows.
|
@RussellSpitzer - Could you also please take a look so we can wrap up this work? Thanks! |
Spark can skip sorts before joins, windows and sort aggregates when a scan reports its ordering. With
preserve-data-orderingandpreserve-data-groupingon, partitioned scans report the leading projected identity fields of the table sort order throughSupportsReportOrdering, and task groups with several files are read withMergingSortedRowDataReader(#14948). Planning stays bin-packed, because Spark 4.2 keeps the ordering across the splits of a partition with a k-way merge whenspark.sql.sources.v2.bucketing.preserveOrderingOnCoalesce.enabledis on. The ordering is not reported for UUID keys, floating point keys that are not last, nested keys, older sort orders, equality deletes, task groups overmax-files-per-task, or withallowCompatibleTransformsorallowJoinKeysSubsetOfPartitionKeyson. The 4.1, 4.0 and 3.5 backports follow separately.Test plan:
row_number()window, a sort-merge join and a sort aggregate run with noSortExecand match the results with ordering off, and a single-partition scan returns rows in sort order. Ascending, descending, nulls first and nulls last orders are covered.preserveOrderingOnCoalesceon.AI Disclosure