Skip to content

[SPARK-62344][PYTHON][SQL] Add the Python Data Source API for external lookup and plan it on the driver - #60872

Open
HeartSaVioR wants to merge 1 commit into
apache:masterfrom
HeartSaVioR:SPARK-62344-python-data-source-lookup-api
Open

HeartSaVioR wants to merge 1 commit into
apache:masterfrom
HeartSaVioR:SPARK-62344-python-data-source-lookup-api

Conversation

@HeartSaVioR

@HeartSaVioR HeartSaVioR commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

What changes were proposed in this pull request?

This PR adds the Python side of the external lookup join API, and plans a lookup with a Python data source on the driver. A later PR runs the lookups on executors, so in this PR the reader factory of a Python lookup cannot create a reader yet. Everything is behind the new internal configuration spark.sql.python.externalLookup.enabled, which is false in this PR. With it off, Python data sources report the same table capabilities as before.

This PR implements SPARK-62344, part of SPARK-60031 (SPIP: External Lookup Join; see the SPIP and the dev@ discussion). It builds on the merged DSv2 connector API and lookup join of that SPIP, including SPARK-62120, which makes selectLookupPredicates return positions.

Design and decisions. The design document explains the Python API and the decisions behind it. Read it first for the whole picture, before the details of this PR.

Scope. This PR is the first of five stacked PRs that add Python Data Source support to external lookup join. Please review only this PR's own commits, listed in its first comment.

PR What it delivers
#60872 (this PR) The Python API, and planning on the driver, behind an internal configuration that is off
#60873 Execution on executors: one Python worker per reader, the request protocol, cancel and close
#60874 Streaming queries: plan reuse, the startup check, real-time mode as an opt-in; lookups on by default
#60875 Arrow results, as read() returns them
#60876 Spark Connect tests, the API reference, a tutorial section and an example

The Python API, in pyspark.sql.datasource:

  • DataSource.lookupReader(schema) returns a DataSourceLookupReader.
    • A data source that implements it and reader() serves batch reads and, with the EXTERNAL_LOOKUP hint, lookups.
    • A data source that implements it but not reader() is lookup-only: every supported stream-static join with it is a lookup join, and a batch read of it fails.
    • The supported joins are inner, left outer, left semi and left anti joins with the stream on the left. A join of another shape over a lookup side fails rather than falling back to a batch read.
  • DataSourceLookupReader mirrors the Scala API:
    • pushFilters is called only with Python filter pushdown on, as for a batch read. It receives filters with literal values, and returns the ones that the reader leaves to Spark.
    • selectLookupPredicates receives the candidates, each with a LookupParameter value. It returns the positions of the ones it selects, as a Sequence[int], and their order defines the fields of a parameter row.
    • maxParameterRowsPerRequest returns 1000 by default, Spark's own cap.
    • lookup takes and returns Python tuples.
    • close.
  • LookupParameter is the value of a candidate predicate. Candidates use the existing filter classes. Each LookupParameter equals only itself, as in Scala, so two candidates of the same shape are not equal.
  • Type hints follow the existing methods. For example, lookup is annotated as read() is.
  • Docstrings state the contract as the Scala Javadoc does, without relying on it. They cover:
    • what Spark offers and selects
    • completeness: every stored row that matches the selected predicates and the pushed filters, where extra rows are fine
    • the Python type of each parameter, where a TIMESTAMP is a naive datetime in the worker's local time, as elsewhere in PySpark
    • each error
    • when close() runs
class OffersDataSource(DataSource):
    def schema(self):
        return "user_id BIGINT, offer STRING"

    def lookupReader(self, schema):  # lookup-only: no reader()
        return OffersLookupReader()

Planning on the driver:

  • Lookup support from the class. A planner worker reports whether the data source class overrides lookupReader() and reader(). It looks at the class only and creates no data source, so a data source runs its code only when it did before. PythonTable then reports EXTERNAL_LOOKUP, and drops BATCH_READ for a lookup-only source.

  • Planning a lookup. PythonScanBuilder implements SupportsExternalLookup. Its selectLookupPredicates runs a second planner worker, which:

    • creates the lookup reader
    • replays the pushed filters into it
    • selects the predicates
    • gets the request size

    It does these in the order in which Spark calls a Scala connector, calling each method once, and returns the pickled reader with its decisions. PythonScanBuilder passes the reader's positions to Spark.

  • Errors are those of a Scala connector. The existing JVM checks reject an empty selection (EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE), a repeated position (DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.DUPLICATE_SELECTED_PREDICATE) and a request size that is not positive. Python checks the rest, with the subclasses of DATA_SOURCE_INVALID_EXTERNAL_LOOKUP:

    • NULL_RESULT for None
    • the new subclass INVALID_RESULT_TYPE for a result of the wrong type, such as a selection that is not a sequence of ints or holds a bool
    • INVALID_SELECTED_PREDICATE_POSITION for a position outside the candidates; Python checks it, because a Python int can exceed the range of a Java int
    • MODIFIED_CANDIDATES for a reader that changed its list of candidates. The reader gets that list itself, not the JVM's copy, and the positions refer to the offered order. Python sends the position, and the JVM describes the candidate as it does for a Scala connector.

    So a streaming query's startup check stops on all of them.

  • A source that serves both keeps the filter and limit pushdown of its batch reads, unchanged.

    • Before the lookup is known. Spark pushes filters into a scan before it knows that the scan is a lookup. So, as for any Python batch read, the batch reader's pushFilters runs first. With limit pushdown off, that pass also plans the batch read.
    • The lookup scan. The lookup reader then receives the filters. The lookup scan reports the filters that the lookup reader pushes, and keeps no batch read.

Worth a reviewer's attention, because existing code changes:

  • The filter serialization and the filter replay of the pushdown planner worker move into shared code, on the JVM (UserDefinedPythonDataSource) and in Python (data_source_pushdown_filters.py, worker/utils.py). Batch pushdown behaves as before.

Why are the changes needed?

External lookup join lets a stream-static join look up only the keys of each micro-batch. Today only Scala and Java connectors can serve it. Python data sources are a common way to reach key-value stores, databases and web services, and this is the first step to let them serve lookups.

Does this PR introduce any user-facing change?

Yes. There are new public Python classes and methods in pyspark.sql.datasource, and a new error subclass, DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.INVALID_RESULT_TYPE. Queries are unchanged: the internal configuration spark.sql.python.externalLookup.enabled is off.

How was this patch tested?

  • Python: PythonDataSourceLookupPlanningTests (new) runs the planner workers without a session. It checks:
    • lookup support found on the class
    • every candidate shape
    • the selected positions, including sequences other than lists and positions out of range
    • a changed list of candidates
    • filters pushed before the selection, and the pushdown configuration
    • the request size
    • the checks of what the reader returns
  • Scala: PythonDataSourceExternalLookupSuite (new) plans lookup-only and dual sources, with and without the hint. It also checks:
    • the capabilities with the configuration off
    • lookup support found without creating the data source
    • batch pushdown of a dual source
    • the positions and their order
    • invalid selections, with each error above
    • request sizes
    • pushed lookup-side filters
  • Mutation checks: each new test was also run against a deliberate fault in the code it covers, and fails on it.

Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Opus 5.5

This pull request and its description were written by Isaac.

…l lookup and plan it on the driver

This adds the Python side of the external lookup join API, and plans a lookup with a Python
data source on the driver. Running the lookups on executors comes in a follow-up, so the
reader factory of a Python lookup cannot create a reader yet. All of it is behind the new
internal flag spark.sql.python.externalLookup.enabled, which is false by default. With the flag
off, Python data sources report the same table capabilities as before, so nothing changes.

Python API, in pyspark.sql.datasource:
- DataSource.lookupReader(schema) returns a DataSourceLookupReader. A data source that
  implements it and reader() serves batch reads and, with the EXTERNAL_LOOKUP hint, lookups. A
  data source that implements it but not reader() is lookup-only.
- DataSourceLookupReader mirrors the Scala API: pushFilters, selectLookupPredicates,
  maxParameterRowsPerRequest (1000 by default, Spark's own cap), lookup and close.
  lookup takes and returns Python tuples.
- LookupParameter is the value of a candidate predicate. Candidates use the existing filter
  classes. selectLookupPredicates returns the positions of the selected candidates, whose order
  defines the fields of a parameter row, as the Scala method does since SPARK-62120.

Planning on the driver:
- A new planner worker, data_source_lookup_support.py, reports whether the data source class
  overrides lookupReader() and reader(). It looks at the class only and creates no data source,
  so a data source runs its code when it did before. Spark asks it once per registered class.
  PythonTable then reports EXTERNAL_LOOKUP, and drops BATCH_READ for a lookup-only source.
- PythonScanBuilder implements SupportsExternalLookup. selectLookupPredicates runs a new planner
  worker, plan_data_source_lookup.py, which creates the lookup reader, replays the pushed filters
  into it, selects the predicates and gets the request size, in the order in which Spark calls
  a Scala connector. It returns the pickled reader and the decisions. The existing JVM checks
  reject an empty or duplicate selection and a request size that is not positive, as for a
  Scala connector. Python checks what a Scala method's types already guarantee, a result of the
  wrong type or None, and a selected position that is not one of a candidate, which a Java int
  may not be able to hold. As the reader receives the list of candidates itself, Python also
  checks that the reader left it as offered, as the JVM checks its copy. It reports them with
  the errors of a Scala connector, DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT,
  INVALID_SELECTED_PREDICATE_POSITION and MODIFIED_CANDIDATES, and a new subclass,
  INVALID_RESULT_TYPE, so a streaming query's startup check stops on them.
- For a source that serves both, batch reads keep their filter and limit pushdown. A lookup scan
  reports the filters that the lookup reader pushes, and plans no batch read.
- PythonScan.toExternalLookup returns a PythonExternalLookup, whose reader factory captures what
  the executor side will need.

This depends on SPARK-62120 (apache#60746), which changes
SupportsExternalLookup.selectLookupPredicates to return positions.

The filter serialization and the filter replay are shared with the existing pushdown worker,
on the JVM and in Python.

Co-authored-by: Isaac <no-reply@databricks.com>
@HeartSaVioR

Copy link
Copy Markdown
Contributor Author

Note

DISCLAIMER: This comment was written by an LLM, Claude Opus 5.5 (claude-opus-5-5, 1M context), posting on behalf of @HeartSaVioR.

This PR is the first of the stack, so its diff contains only its own commit:

  • 1d4d4bbbb80 [SPARK-62344][PYTHON][SQL] Add the Python Data Source API for external lookup and plan it on the driver

Or see them all together.

This list is generated from the branch and updated after each rebase.

@spark-test spark-test left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary

This review found eight defects in the new Python lookup API and its driver-side planning, and has one question for the author. The pushdown-override check in python/pyspark/sql/worker/utils.py misjudges a reader class that subclasses both DataSourceReader and DataSourceLookupReader: with DataSourceReader listed first, its plain batch reads fail with DATA_SOURCE_PUSHDOWN_DISABLED for a pushFilters it does not implement, even with the lookup configuration off, and in either order its pushLimit is neither pushed nor rejected. The lookup planning worker calls maxParameterRowsPerRequest() and pickles the reader before Spark rejects an empty or repeated selection, so a failure there replaces the documented selection error. Three pieces of documentation misstate the contract or the code: the lookup() docstring promises distinct parameter tuples that TIMESTAMP values can break in a daylight-saving fall-back hour, the DataSourceLookupReader and DataSource.lookupReader docstrings misstate when pushFilters runs and leave out the batch reader that a source serving both has planned during lookup planning, and the lookupOnly comments of PythonScanBuilder say it builds only lookup scans. On the test side, no test plans a lookup under Python filter or limit pushdown or with a reader that cannot be pickled, and the new data_source_lookup_support worker is missing from the changed-files test registry in python/pyspark/testing/utils.py. A question about the Python form of TIMESTAMP lookup parameters follows under Decision challenges.

The review also covered the class-based detection of lookup support with the table capabilities it sets, including the unchanged capabilities while the configuration is off, and the move of the filter serialization and replay into shared code for batch pushdown, and found nothing to report in either.

Review-level concerns

  • Decision needed: The fix for the distinct-tuples promise in the DataSourceLookupReader.lookup docstring depends on the open decision about the Python form of TIMESTAMP lookup parameters: the qualification that the review suggests fits the naive local form that the PR documents, while a form that names one instant would let the promise stand as written, so the fix should follow whichever form the author settles on.

    Related:

    • lookup() promises distinct parameter tuples that TIMESTAMP values can break
    • TIMESTAMP lookup parameters as naive local datetimes, unlike the UTC-aware filter values

Findings

8 total: 0 P0, 0 P1, 4 P2, 4 P3.

Non-blocking (P2)

  • Pushdown-override check misjudges a reader class that subclasses both reader bases — python/pyspark/sql/worker/utils.py:70 — see inline.
  • Lookup planning calls maxParameterRowsPerRequest() and pickles the reader before Spark rejects the selection — python/pyspark/sql/worker/plan_data_source_lookup.py:260 — see inline.
  • lookup() promises distinct parameter tuples that TIMESTAMP values can break — python/pyspark/sql/datasource.py:1412 — see inline.
  • Lookup planning under Python filter or limit pushdown runs in no test — sql/core/src/test/scala/org/apache/spark/sql/execution/python/PythonDataSourceExternalLookupSuite.scala:417 — see inline.

Nit (P3)

  • Lookup planning docstrings misstate when pushFilters runs and omit the batch reader's calls — python/pyspark/sql/datasource.py:1160 — see inline.
  • lookupOnly comments say the builder builds only lookup scans, but it also builds micro-batch scans — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/python/PythonScanBuilder.scala:29-30 — see inline.
  • New data_source_lookup_support worker is missing from the changed-files test registry — python/pyspark/testing/utils.py:309-311 — see inline.
  • No test plans a lookup reader that cannot be pickled — python/pyspark/sql/tests/test_python_datasource.py:565 — see inline.

PR description suggestions

  • In the DataSourceLookupReader bullet, say that a lookup reader that overrides pushFilters fails planning with DATA_SOURCE_PUSHDOWN_DISABLED while spark.sql.python.filterPushdown.enabled is off, its default, as a batch reader does, so readers know that implementing pushFilters needs that configuration on.

Decision challenges

TIMESTAMP lookup parameters as naive local datetimes, unlike the UTC-aware filter values

Location: python/pyspark/sql/datasource.py:1422

During each daylight-saving fall-back hour, a lookup reader that turns a TIMESTAMP parameter back into an instant to query its store can ask for the wrong instant and silently miss matches, because the lookup contract documents a TIMESTAMP parameter as a naive datetime in the Python worker's local time zone (python/pyspark/sql/datasource.py:1422-1425). In America/Los_Angeles, the stream rows at 2023-11-05T08:30Z and 09:30Z both map to the naive 01:30, and PySpark's Arrow row conversion, value.astimezone().replace(tzinfo=None) (python/pyspark/sql/conversion.py:1432), drops the fold that tells them apart, so .timestamp() on either gives 08:30Z. For a selected ts < ? range, the reader then asks for the earlier instant and misses stored rows of the repeated hour, where naive local times are not even ordered like their instants (01:59 PDT sorts after 01:00 PST). The same reader's pushFilters receives TIMESTAMP literals as UTC-aware datetimes, because the shared filter code casts them to Variant timestamps (UserDefinedPythonDataSource.scala:631), and the Scala contract that this API mirrors passes an instant. The conversion itself comes with the executor-side PR, and no release has shipped this contract, so the form is still cheap to change.

The review leans toward UTC-aware values, because a value that names exactly one instant lets no reader silently miss a match, whatever conversion the executors use. Which form should TIMESTAMP parameters take?

  • Keep naive local datetimes with the current daylight-saving note: nothing changes, and the row at 09:30Z reaches lookup as the same naive 01:30 as the row at 08:30Z.
  • Keep naive local datetimes and document the workaround: the TIMESTAMP entry tells readers to look up both instants of a repeated local time, and the lookup reader's pushFilters docstring says that TIMESTAMP literals arrive UTC-aware. The row at 09:30Z still arrives as 01:30, and a reader that follows the docs queries both 08:30Z and 09:30Z.
  • Document UTC-aware datetimes, the form pushFilters already receives: the TIMESTAMP entry lists a UTC-aware datetime.datetime and drops its caveat, and the executor-side PR converts to it, so the row at 09:30Z arrives as a UTC-aware datetime for 09:30 and the row at 08:30Z as one for 08:30.

Generated by Omnigent on Databricks


return getattr(getattr(reader, name), "__func__", None) is not getattr(DataSourceReader, name)
base = (
DataSourceLookupReader if isinstance(reader, DataSourceLookupReader) else DataSourceReader

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking (P2): Choosing the base from the reader's type misjudges a reader class that subclasses both DataSourceReader and DataSourceLookupReader, which the public API allows, for example one key-value reader class that a data source returns from both reader() and lookupReader(). Such a reader is compared with DataSourceLookupReader's defaults on every path, including the batch checks in plan_data_source_read.py:373 and data_source_pushdown_filters.py:259. With DataSourceReader listed first, the inherited DataSourceReader.pushFilters is not that base's default, so a plain batch read fails with DATA_SOURCE_PUSHDOWN_DISABLED for a pushFilters the class never implements, whenever spark.sql.python.filterPushdown.enabled is off, its default, and whether or not the lookup configuration is on. In either order, DataSourceLookupReader has no pushLimit, so a pushLimit override counts as absent: the gate at data_source_pushdown_filters.py:272 never calls it, and with limit pushdown off it is silently ignored instead of rejected, which is the case this check exists to catch.

Suggest counting a method as overridden only when the attribute the reader resolves for it (its __func__ for a bound method, the attribute itself otherwise, such as for a staticmethod) is none of the Spark-provided defaults of that name, and having each caller check only its own role's pushdown methods: pushFilters and pushLimit for the batch paths, pushFilters alone for lookup planning.

Verification:

  • Regression: For a reader class that subclasses DataSourceReader and then DataSourceLookupReader without overriding pushFilters or pushLimit, the pushdown check of a plain batch read and the one of lookup planning both pass with filter and limit pushdown disabled, where the PR's current code raises DATA_SOURCE_PUSHDOWN_DISABLED for pushFilters.
  • Regression: For a reader class that subclasses both bases, in either order, and overrides only pushLimit, the batch pushdown check with filter pushdown enabled and limit pushdown disabled raises DATA_SOURCE_PUSHDOWN_DISABLED for pushLimit, and with limit pushdown enabled the batch pushdown worker calls pushLimit; the PR's current code does neither.
  • Compatibility: A plain DataSourceReader that overrides pushFilters or pushLimit, also with a staticmethod, is still rejected while the matching pushdown is disabled, a DataSourceLookupReader that overrides pushFilters still fails lookup planning with filter pushdown disabled, and a DataSourceLookupReader that defines a method named pushLimit still plans with pushdown disabled.

# pushdown, then the selection of the lookup predicates, then the request size.
pushed_filter_indices = push_filters(reader, filters)
selected_positions = select_lookup_predicates(reader, candidates)
max_rows = max_parameter_rows_per_request(reader)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking (P2): This runs before Spark checks the selection. select_lookup_predicates passes an empty or repeated selection on for the JVM to reject, but the JVM rejects it only after this reply, in PrepareExternalLookupJoin.selectedCandidates, while here maxParameterRowsPerRequest() runs and the reader is pickled (line 272) first. For a Scala connector, Spark rejects the selection right after selectLookupPredicates, before build(), toExternalLookup() and maxParameterRowsPerRequest() (PrepareExternalLookupJoin.scala lines 196, 261 and 293-294). So a reader that returns [] and sizes its requests from its selection, as the maxParameterRowsPerRequest warning advises, for example with 2100 // len(self.selected), raises ZeroDivisionError, which surfaces as PYTHON_DATA_SOURCE_ERROR, and one that returns None when nothing is selected gets NULL_RESULT for maxParameterRowsPerRequest(); neither query gets the documented NO_LOOKUP_PREDICATE, and a reader that cannot be pickled reports the pickler's error the same way. ExternalLookupJoinStartupCheck stops a streaming query only on the lookup error classes, which leave out PYTHON_DATA_SOURCE_ERROR, so in the exception cases the query starts and fails in its first micro-batch.

Suggest skipping maxParameterRowsPerRequest() and the pickling when the selection is empty or repeats a position, and replying with placeholders (an empty reader and a request size of 0) that nothing reads, because the JVM then rejects the selection with the error a Scala connector gets.

Verification:

  • Regression: A lookup-only Python data source whose lookup reader selects no candidate and whose maxParameterRowsPerRequest() returns None fails planning with EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE, where the PR's current code reports DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT for maxParameterRowsPerRequest(); with a maxParameterRowsPerRequest() that raises when nothing is selected, it also fails with NO_LOOKUP_PREDICATE instead of PYTHON_DATA_SOURCE_ERROR.
  • Regression: A lookup reader that selects the same position twice and whose maxParameterRowsPerRequest() returns None fails planning with DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.DUPLICATE_SELECTED_PREDICATE, where the PR's current code reports NULL_RESULT for maxParameterRowsPerRequest().
  • Behavior: For an empty selection, or one that breaks the lookup contract only by repeating a position, the lookup planning worker's reply carries the selected positions for the JVM to reject and no planned reader, and the reader's maxParameterRowsPerRequest() is not called; for a valid selection the reply is unchanged.

parameters : list of tuples
Between 1 and :meth:`maxParameterRowsPerRequest` parameter rows. Field `i` of each
tuple is the value for the candidate at the `i`-th position that
:meth:`selectLookupPredicates` returned. No two tuples are equal. Only the fields of

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking (P2): This promise does not hold for TIMESTAMP parameters. The TIMESTAMP entry ten lines below maps a value to a naive datetime in the Python worker's local time zone and notes that two instants can have the same local time. In America/Los_Angeles, TimestampType.fromInternal maps the stream rows at 2023-11-05T08:30Z and 09:30Z to datetime(2023, 11, 5, 1, 30), the second with fold=1, and Python's equality and hashing ignore fold. A reader that trusts this sentence and, for example, maps each parameter tuple to its ordinal in a dict to tag the rows it returns keeps one ordinal for the two rows, so the other stream row gets no matches: an inner join silently drops it, a left outer join null-extends it and a left anti join keeps it.

Suggest qualifying the sentence: Spark sends no two equal parameter rows, but because a TIMESTAMP arrives as a naive local datetime, the tuples of two instants in a repeated local hour, such as the one a daylight-saving change repeats, can be equal, so a reader must not rely on distinct tuples, for example as dict keys, when a selected parameter is a TIMESTAMP.

Verification:

  • Inspection: The parameters description of DataSourceLookupReader.lookup no longer promises without exception that no two tuples are equal, and states that two parameter rows whose TIMESTAMP fields fall in a repeated daylight-saving hour can arrive as equal tuples.

| if f != EqualTo(("tier",), 2):
| yield f
|""".stripMargin))
withExternalLookup(SQLConf.PYTHON_FILTER_PUSHDOWN_ENABLED.key -> "true") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Non-blocking (P2): This is the suite's only lookup planned with filter pushdown on, and it uses a source that also serves batch reads, with limit pushdown off and filters that all reach Python, so three branches the PR adds run in no test:

  • Every lookup-only test leaves filter pushdown off, so PythonScanBuilder.pushFilters returns before its lookupOnly branch (lines 86-92). Without that branch, a lookup-only source's filters, such as t.tier = 2, would go to the batch pushdown worker, which calls the unimplemented reader() and fails with PYTHON_DATA_SOURCE_ERROR.
  • With limit pushdown off, the batch pass here plans the read, so the deferredPlanning = false reset in selectLookupPredicates (PythonScanBuilder.scala:177) changes nothing. With both pushdowns on, removing it makes build() replay the batch read and fail with "pushFilters() returned a different set of supported filters" whenever the batch and lookup readers push different filters, as they do in this test.
  • The filters here all serialize, so mapping the pushed-filter indices through filterIndex (UserDefinedPythonDataSource.scala:790-791) is the identity; reading the raw index instead would report the wrong PushedFilters once a filter that Python does not receive, such as an Or, comes first.

Suggest adding a lookup-only case with filter pushdown on, a case for a source that serves both with filter and limit pushdown on, and a case with an Or ahead of tier = 2.

Verification:

  • Behavior: With Python filter pushdown enabled, a lookup join over a lookup-only source whose lookup reader pushes tier = 2 plans, and its scan reports [EqualTo(tier,2)] as PushedFilters; the test fails if PythonScanBuilder sends a lookup-only source's filters to the batch pushdown worker, which calls the unimplemented reader().
  • Behavior: With filter and limit pushdown both enabled, a hinted lookup join over a source whose batch reader pushes no filter and whose lookup reader pushes tier = 2 plans and reports [EqualTo(tier,2)]; the test fails if selectLookupPredicates keeps the deferred batch planning that build() would then replay against the lookup reader's pushed filters.
  • Behavior: A lookup scan builder that receives an Or filter ahead of tier = 2, with Python filter pushdown enabled, and plans a lookup whose reader pushes tier = 2 reports tier = 2, not the Or, as its pushed filter.


Each time Spark plans a lookup, on the driver, it creates a reader with
:meth:`DataSource.lookupReader` and calls :meth:`pushFilters`,
:meth:`selectLookupPredicates` and :meth:`maxParameterRowsPerRequest` on it, once each and

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (P3): The "once each" here does not hold for pushFilters. PythonScanBuilder.pushFilters returns before recording any filter while spark.sql.python.filterPushdown.enabled is off, its default, and push_filters skips an empty list, as the pushFilters docstring below says, so by default Spark plans a lookup without calling it, and a reader that prepares state for lookup() there plans and pickles without that state. This summary and the planning paragraph of DataSource.lookupReader (lines 291-294) also leave out that, for a data source that implements reader() too and with filter pushdown on, each lookup planning first creates the batch reader with reader(), calls its pushFilters and, with limit pushdown off, its partitions(), and then discards that plan, so a slow or failing partitions() slows or fails the lookup, at a streaming query's start and in each micro-batch.

Suggest saying that pushFilters runs at most once, only with Python filter pushdown on and a filter to push, and that maxParameterRowsPerRequest runs once after a selection that Spark accepts, which holds once the planning worker stops calling it after a rejected selection; and, in DataSource.lookupReader, that a source serving both has its batch reader created and planned, then discarded, during lookup planning when filter pushdown is on, as the DataSourceReader.pushFilters note does for the extra readers of limit pushdown.

Verification:

  • Inspection: The DataSourceLookupReader class docstring and the DataSource.lookupReader docstring state that pushFilters runs at most once and only with Python filter pushdown enabled and a filter to push, that maxParameterRowsPerRequest runs once after a selection Spark accepts, and that for a source that also implements reader() Spark plans and discards a batch reader during lookup planning when filter pushdown is enabled.

Comment on lines +29 to +30
* @param lookupOnly Whether the data source serves lookups but no batch reads, so that the
* builder only ever builds a lookup scan.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (P3): A lookup-only table still reports MICRO_BATCH_READ (PythonTable.scala:37), and PythonTable.newScanBuilder passes lookupOnly = true to every builder of such a table (PythonTable.scala:50-51), so a spark.readStream read of a lookup-only source that implements streamReader() builds its micro-batch scan from this builder through StreamingV2ScanPushDown.buildScan. Nothing breaks today, since the streaming builders of a Python table get no pushFilters call, but a later change in the stack that keys lookup-only behavior on this flag, for example in build(), would break those streaming reads while this comment says they cannot happen. What holds is that the builder never builds a batch scan; the comment in pushFilters (lines 87-88), "Spark builds only lookup scans from this builder", needs the same correction.

Suggested change
* @param lookupOnly Whether the data source serves lookups but no batch reads, so that the
* builder only ever builds a lookup scan.
* @param lookupOnly Whether the data source serves lookups but no batch reads, so that the
* builder never builds a batch scan, only lookup and micro-batch scans.

Verification:

  • Inspection: The lookupOnly parameter documentation and the comment in PythonScanBuilder.pushFilters describe a lookup-only builder as one that never builds a batch scan, without claiming that it builds only lookup scans, since it also builds the micro-batch scans of streaming reads.

Comment on lines 309 to +311
"pyspark.sql.worker.data_source_pushdown_filters": "pyspark.sql.datasource",
"pyspark.sql.worker.lookup_data_sources": "pyspark.sql.datasource",
"pyspark.sql.worker.plan_data_source_lookup": "pyspark.sql.datasource",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (P3): The PR maps its new plan_data_source_lookup worker but not the other one, pyspark.sql.worker.data_source_lookup_support, which UserDefinedPythonDataSourceLookupSupportRunner launches; it is the only pyspark.sql.worker module that the JVM names and this map lacks. As the comment above the map says, test code never imports such a script, so for a change confined to it, _is_module_relevant_to_changed_files counts only suites with an import chain to the module itself, and a suite that reaches the worker only through PythonTable.capabilities() with the lookup configuration on is skipped in PYSPARK_CHANGED_FILES mode. Nothing is skipped yet, but the stack plans to turn lookups on by default, after which every Python data source suite starts this worker.

Suggested change
"pyspark.sql.worker.data_source_pushdown_filters": "pyspark.sql.datasource",
"pyspark.sql.worker.lookup_data_sources": "pyspark.sql.datasource",
"pyspark.sql.worker.plan_data_source_lookup": "pyspark.sql.datasource",
"pyspark.sql.worker.data_source_lookup_support": "pyspark.sql.datasource",
"pyspark.sql.worker.data_source_pushdown_filters": "pyspark.sql.datasource",
"pyspark.sql.worker.lookup_data_sources": "pyspark.sql.datasource",
"pyspark.sql.worker.plan_data_source_lookup": "pyspark.sql.datasource",

Verification:

  • Inspection: Every module under pyspark.sql.worker that a JVM planner runner names as its worker module, data_source_lookup_support included, appears in PySparkBaseTestCase._ENTRY_POINT_PROXIES and maps to pyspark.sql.datasource.

_, _, _, max_rows = self._plan_lookup(SizedReader(value), candidates)
self.assertEqual(max_rows, expected)

def test_plan_lookup_validates_what_the_reader_returns(self):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (P3): Every reader in these planning tests pickles, so nothing guards the ordering that plan_data_source_lookup._main documents at lines 270-272: it pickles the planned reader before writing any other part of its reply, so that an unpicklable reader fails with the pickler's error. If a later change wrote the pushed indices, the positions or the request size first, every test would still pass, while a reader that holds, say, a threading.Lock or an open connection would make receiveFromPython read the first of those values as the reader's length and the exception marker as plan data, failing with a cryptic error instead of PYTHON_DATA_SOURCE_ERROR. The docstrings tell readers to stay picklable and to open connections lazily, so this is the mistake users are expected to make.

Suggest a case here with a reader that stores a threading.Lock in selectLookupPredicates, asserting that planning raises the serializer's PicklingError and writes nothing.

Verification:

  • Behavior: A lookup reader that stores a threading.Lock in selectLookupPredicates makes the lookup planning worker raise the PicklingError of Spark's serializer with nothing written to its reply.

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants