Skip to content

[spark] Use scalar indexes for runtime join filters - #11265

Open
YannByron wants to merge 3 commits into
apache:masterfrom
YannByron:codex/spark-runtime-scalar-index
Open

YannByron wants to merge 3 commits into
apache:masterfrom
YannByron:codex/spark-runtime-scalar-index

Conversation

@YannByron

@YannByron YannByron commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Paimon's Spark connector currently advertises only partition columns for runtime filtering. A filtered broadcast join therefore cannot use a non-partition join key's existing scalar index to narrow the probe scan.

Expose eligible single-column BTree and Bitmap keys through SupportsRuntimeV2Filtering. Accepted runtime IN predicates are combined with existing filters and replan splits at the original snapshot, retaining the reader builder used by Spark's original batch. Spark's existing dynamic pruning conditions still apply, including a selective build-side filter and a reusable broadcast exchange under the default configuration. The final join preserves multiplicity and join semantics.

The initial implementation covers latest-snapshot append-only Data Evolution scans with supported boolean, integer, character or date keys. Every eligible single-column index definition must cover the snapshot; columns also present in composite indexes are excluded so adding a runtime predicate cannot select an unverified composite path. Indexes must record their actual build schema and retain compatible field IDs and key types. This branch incorporates master through #11348 and reuses its schema validation with one shared metadata cache. Legacy/unknown build schemas, missing schema files, changed key types, stale indexes and unsafe scan shapes keep their ordinary behavior. Rebuilding an index after a type change restores eligibility. Fallback-branch reads retain their original independent snapshot selection. The configured scalar-index search mode is unchanged.

Capability discovery reads the index manifest once without scanning data manifests. Freshness checks run only after a usable scalar predicate arrives and use the scan's static partition scope. Runtime index work is bounded to 10,000 keys and 1 MiB of literal text per filter after Spark collects the keys; larger filters are ignored. Spark 3.2/3.3 retain their existing filtering behavior and explicitly provide the trait bridge used by the common scan class.

Tests

  • RuntimeScalarIndexFilterTest: 24 passed on Spark 3.5.9. Actual BTree/Bitmap broadcast joins cover planning-time and reader-side indexing, candidate row reduction, duplicate/NULL results, fixed snapshots, retained reader factories, static predicates and size limits.
  • Type-evolution regressions reproduce INT-to-BIGINT joins returning zero rows before the fix, then verify all ten matches and index reuse after rebuilding in both evaluation modes. A retained old-schema table/index builder is also tested against a newer snapshot: the actual build schema differs from the snapshot schema, so inferring the build type from that snapshot is insufficient. V1 and unknown-schema V2 fixtures reproduce the same loss in four cases on the updated master baseline and pass with the connector guard. Comment/rename compatibility, expired source snapshots, missing build schemas and one schema-file read across fields are covered.
  • Review regressions first failed and then passed: ordinary fallback reads with a newer fallback snapshot; incomplete composite indexes omitting the 11th matching row in both index-evaluation modes; incomplete BTree coverage hidden by a complete Bitmap index; repeated index-manifest reads and eager full-table freshness scans. A real FileIO spy checks one capability-time index-manifest read, no data-manifest reads, and later freshness reads limited to the statically selected partition.
  • Previous-revision Spark 3.2.4 and 3.3.4 validation reproduced NoSuchMethodError: readTable$, then ran the original SparkGenericCatalogTest.testPaimonTable against each corrected connector JAR with its code source checked. Both packaged reads passed; javap confirmed both bridges. This compatibility matrix is being revalidated by the new CI run.
  • Current-revision RepartitionLargeBlobScanTest and PostponeBucketTableTest: 50 passed. SparkPartitionMetadataAuthTest: 23 passed. Together with the runtime suite, 97 local regressions pass.
  • Current-revision clean 27-module package with Spotless and Checkstyle explicitly enabled, repository RAT licensing (7792 approved, zero unapproved), and git diff --check: passed. Independent correctness and readability reviews found no blocking issues. Cleaning the reactor removed stale shaded artifacts from the pre-master build.

Packaged SQL verification used Scala 2.12 and JDK 17. The previous revision's complete GitHub CI passed, including Scala 2.12/2.13, Spark 3/4/4.2 and E2E; the new revision requires a fresh CI run. Local verification of the updated master used the official Apache snapshot repository because the configured mirror had not yet synchronized the exact vector-index dependency; no dependency version or repository configuration was changed in the PR. No performance benchmark is claimed.

The current head also passes local Scala 2.13.16 packaging of the common and Spark3-common production modules. Both Spark 3.2.4/3.3.4 replacement traits compile against that build; bytecode checks confirm their readTable$ bridges match the common scan's calls. These additional checks cover production builds and linkage, not the full SQL/test matrix. In CI run 45103876132, the first attempt passed all other jobs but licensing and Spark 3 / Scala 2.13 failed before compilation while setup-java extracted a non-gzip Temurin 8 download. The failed jobs were rerun on November 25. Both passed JDK setup on attempt 2 and are now building and testing; the rerun is not yet a passing CI result.

Expose completely covered, fresh scalar-index columns to Spark runtime
filtering and replan at a fixed snapshot with static predicates preserved.
Defer index capability discovery until runtime filtering is considered.

Co-Authored-By: Codex <noreply@anthropic.com>
AI-Model: gpt-6
Co-Authored-By: Codex <noreply@ai-tool.com>
AI-Contributed/Feature: 194/194
AI-Contributed/UT: 285/285

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using an existing scalar index for selective broadcast joins has user value. The snapshot pin also changes ordinary fallback-branch reads. I compared real Spark 3.5.9 SQL results with and without this change, on Data Evolution tables with no global indexes.

None
} else {
table match {
case fileTable: FileStoreTable if fileTable.primaryKeys().isEmpty =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Preserve fallback-branch snapshots on ordinary reads

FallbackReadFileStoreTable also implements FileStoreTable. The new readTable override pins it to main's latest snapshot even for a plain SELECT. Pinning the wrapper also rewrites the fallback branch's snapshot selection using main's commit time.

I reproduced this with a partitioned Data Evolution table (bucket=-1) and an empty fallback branch. I inserted (1,'main') on main, then (2,'fallback') on the fallback branch, and set scan.fallback-branch on main. A plain SELECT on the baseline returned both rows. The merged PR throws because the fallback's first snapshot is later than main's. With an earlier fallback snapshot present, the same query succeeds and silently omits a newer fallback-only partition. Setting global-index.enabled=false on this build restores both rows.

Keep fallback-branch reads on their existing path and add a SQL regression covering a fallback commit newer than main without any runtime filter.

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two additional findings from the Spark 3.5.9 SQL and FileIO probes.

}
if (scalarFilters.nonEmpty) {
// Keep the same builder: Spark may retain the original batch's reader factory.
readBuilder.withFilter(scalarFilters.asJava)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Keep matching rows outside the composite index actually chosen

A complete single-column index qualifies k for runtime filtering, but combining runtime IN(k) with a static predicate lets the planner choose a different, incomplete composite index. With the default FAST mode I built btree(k,c) on fact IDs 0–99, appended (100,2,10), and then built a complete btree(k). A broadcast join on k for dimension key 2 with static f.c = 10 returned 11 fact rows with dynamic pruning off and 10 with it on, silently omitting ID 100. I verified both planning-time indexing and global-index.query-in-reader.enabled=true.

Either constrain the runtime path to the validated index or enforce full coverage/fallback for the index plan actually selected.

DataEvolutionGlobalIndexRefreshPlanner
.findIndexesToRefresh(
fileTable,
snapshot,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Defer full freshness scans until Spark applies a scalar runtime predicate

Spark 3.5.9 calls filterAttributes() before deciding whether a join can produce a runtime predicate. In a real Data Evolution table with three partition manifests, BTree indexes on two projected fields, and a static filter selecting just one partition, one capability call opened the index manifest twice and each of the three data manifests twice. An ordinary inner join with an unfiltered dimension produced RuntimeFilters: [], so discovery can do this work even when no pruning is applied. At scale the extra reads fan out across the entire fact table for each candidate field. Defer the freshness checks until a usable scalar predicate arrives, share index manifest reads, and apply the static partition scope where possible.

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both Spark 3 CI lanes stop in ordinary table reads with the same Scala linkage error.

.toSet
}.toSet

override protected def readTable: Table = runtimeReadSnapshot.map(_._1).getOrElse(table)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Keep the runtime-filter trait binary compatible on Spark 3.2 and 3.3

Spark 3.2 and 3.3 each ship a connector-local trait with the same fully qualified name. The common PaimonBaseScan now forwards to the new trait method readTable$, but both local variants lack it. SparkGenericCatalogTest.testPaimonTable fails before any runtime filter is applied in Scala 2.12 CI and Scala 2.13 CI. Keep the bridge in each connector variant or keep the method dispatch in one common class, and exercise the packaged connectors in the regression.

Keep fallback snapshots on their existing path and reject runtime index
plans that can switch to unverified composite or incomplete definitions.
Defer scoped freshness scans until a scalar predicate arrives, and restore
the readTable bridge in the Spark 3.2 and 3.3 connector traits.

Co-Authored-By: Codex <noreply@anthropic.com>
AI-Model: gpt-6
Co-Authored-By: Codex <noreply@ai-tool.com>
AI-Contributed/Feature: 106/106
AI-Contributed/UT: 114/114

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The updated head passed all 14 runtime scalar index tests on the integration with current master, including the fallback and composite-index regressions. A separate Spark 3.5.9 regression returned incorrect join results after a supported schema change.

[P1] Exclude scalar indexes built for an older key type. I created a Data Evolution fact table with k INT, inserted 100 rows with keys 0–9, and built a complete B-tree on k. I then ran ALTER TABLE f ALTER COLUMN k TYPE BIGINT, which retained that index. A broadcast join with a BIGINT dimension filtered to key 2 returned the expected ten rows with dynamic pruning off and zero with it on. This happened with both planning-time evaluation and global-index.query-in-reader.enabled=true. Dropping and rebuilding the B-tree under BIGINT restored all ten rows with dynamic pruning on.

The runtime check validates field IDs, row ranges, and writes after the index source snapshot. It can still pass an INT index to the current BIGINT evaluator. Please validate the type used to build the index before pushing the runtime predicate, or invalidate the index when the indexed type changes. Add the DDL-plus-join case to the regression suite.

Integrate current master and reuse its recorded index-build schema validation.
Reject unknown build schemas for runtime filtering and share schema metadata
across index definitions. Cover type changes, retained old builders, rebuilding,
legacy metadata and compatible schema changes with real indexed joins.

Co-Authored-By: Codex <noreply@anthropic.com>
AI-Model: gpt-6
Co-Authored-By: Codex <noreply@ai-tool.com>
AI-Contributed/Feature: 15/13748
AI-Contributed/UT: 256/12239

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 24 Spark runtime-index cases passed against current master. The stale-build-schema check now covers the earlier type-evolution case.

val pinned = fileTable.copyWithoutTimeTravel(
Map(
CoreOptions.SCAN_MODE.key() -> "from-snapshot",
CoreOptions.SCAN_SNAPSHOT_ID.key() -> snapshot.id().toString).asJava)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the resolved snapshot through runtime replanning

The index coverage and freshness checks use the captured Snapshot, while readBuilder only gets scan.snapshot-id. An accepted runtime predicate clears the cached splits, and StaticFromSnapshotStartingScanner resolves that ID again. A concurrent administrative rollback followed by publication under a reused ID lets a scan without a pinned snapshot cache plan new manifests using validation from the older snapshot. This matters on an unpartitioned fact table because the new scalar runtime filter now triggers replanning there. Pass the captured snapshot through the scan path or use a per-scan snapshot cache as in #11496.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants