This is an automated email from the ASF dual-hosted git repository.

viirya pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 04f53b43 [SPARK-61422][CONNECT][INFRA] Make the generated function 
dispatch and wrappers reproducible from their generator, and check them in CI
04f53b43 is described below

commit 04f53b4377db0fae459bbd2ba4a1a9b2bba38a16
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Tue Nov 10 18:09:09 2026 -0800

    [SPARK-61422][CONNECT][INFRA] Make the generated function dispatch and 
wrappers reproducible from their generator, and check them in CI
    
    ### What changes were proposed in this pull request?
    
    `crates/pyspark-rs/src/dispatch_generated.rs` and 
`python/pyspark/sql/functions_generated.py` both say "Generated by 
scripts/gen_fn_dispatch.py - do not edit directly". This PR makes that true and 
checks it in CI. **Neither generated file changes**: the generator now 
reproduces both byte for byte.
    
    `scripts/gen_fn_dispatch.py`:
    
    - Parses `functions.rs` with a signature scanner instead of a regex. The 
regex missed every generic function (`pub fn array<C: Into<Column>>(...)`) and 
let a function that does not return a `Column` swallow the next one 
(`broadcast` -> `cume_dist`).
    - Declares every hand edit of the Rust dispatch in a table:
      - `OPTIONAL_ARG_VARIANTS`: the arm of the base picks the longer function 
by the number of arguments (`round` -> `round_scale`, `instr` -> 
`instr_with_start` / `instr_with_start_and_occurrence`, 19 bases in all); the 
longer functions have no arm of their own.
      - `HEAD_REST_ARMS`: `count_distinct`, `countDistinct` and 
`variant_delete` call `f(args[0], args[1..])`.
      - `DISPATCH_ONLY`: functions whose Python wrapper is written by hand in 
`functions.py` but that keep a dispatch arm.
      - `NOT_DISPATCHED`: functions without an arm, each with its reason (i64 
seeds, Rust closures, ...).
      - `SECTION_OVERRIDES` / `ORDER_AS`: the six arms that do not stand where 
their signature puts them. They only keep the file byte-stable.
    - Fails the generation when a function fits no rule and no table, or when a 
table entry no longer fits `functions.rs`, instead of emitting an arm that does 
not compile or dropping the function silently.
    - Derives the Python wrapper names from the dispatch arms and 
`UPSTREAM_EXTRA`, no longer from the existing `functions_generated.py`.
    - Adds `--check`, which regenerates in memory and exits 1 with a unified 
diff of each file that differs. `--write-dispatch` is removed: the dispatch is 
always generated. The script is importable and runs from any directory.
    
    New files:
    
    - `.github/workflows/generated-drift.yml` runs `--check` against the 
PySpark of the tag pinned in `scripts/check_vendored_upstream.sh`.
    - `scripts/tests/test_gen_fn_dispatch.py` covers the parser and the tables, 
and checks the Rust dispatch without a reference PySpark, so the existing 
"Tooling unit tests" step guards it too.
    
    ### Why are the changes needed?
    
    The Rust dispatch had been edited by hand, and the generator kept 
`--write-dispatch` off because regenerating would regress it; a regeneration in 
fact emitted arms that do not compile (a `Column` passed to 
`rand_with_seed(seed: i64)`). The set of Python wrappers was read back from the 
generated file itself, so a wrapper deleted from that file stayed deleted. 
Nothing compared either file with the generator, so drift was undetectable.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No. The generated files are unchanged.
    
    ### How was this patch tested?
    
    - `python scripts/gen_fn_dispatch.py --pyspark-src <spark v4.3.0>/python 
--check` reports both files as matching, and running it without `--check` 
leaves the tree unchanged.
    - After replacing `round_scale` in the `round` arm, and deleting the 
`acosh` wrapper with its `__all__` entry, `--check` exits 1 and prints both 
diffs.
    - `python3 -m unittest discover -s scripts/tests` (11 new tests), `ruff 
check scripts/`, `ruff format --check scripts/`.
    - The new workflow runs for the first time on this PR.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code
    
    Closes #498 from viirya/SPARK-61422-generated-drift.
    
    Authored-by: Liang-Chi Hsieh <[email protected]>
    Signed-off-by: Liang-Chi Hsieh <[email protected]>
---
 .github/workflows/generated-drift.yml |  64 +++
 scripts/gen_fn_dispatch.py            | 907 +++++++++++++++++++++++-----------
 scripts/tests/test_gen_fn_dispatch.py | 238 +++++++++
 3 files changed, 918 insertions(+), 291 deletions(-)

diff --git a/.github/workflows/generated-drift.yml 
b/.github/workflows/generated-drift.yml
new file mode 100644
index 00000000..22361ab5
--- /dev/null
+++ b/.github/workflows/generated-drift.yml
@@ -0,0 +1,64 @@
+#
+# 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.
+#
+
+name: Generated files drift
+
+# Guards the two files that scripts/gen_fn_dispatch.py generates
+# (crates/pyspark-rs/src/dispatch_generated.rs and
+# python/pyspark/sql/functions_generated.py): regenerates them in memory from
+# crates/spark-connect/src/functions.rs and the PySpark of the tracked Apache 
Spark
+# tag, and fails with a diff when a checked-in file differs. Catches hand 
edits to the
+# generated files, and generator or functions.rs changes that were not 
regenerated.
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
+on:
+  push:
+    branches: [master, "branch-*"]
+  pull_request:
+    branches: [master, "branch-*"]
+
+jobs:
+  generated-drift:
+    name: Generated files match scripts/gen_fn_dispatch.py
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: actions/setup-python@v5
+        with:
+          # The generator copies function bodies and signatures from the 
reference
+          # PySpark with `inspect`; keep the interpreter the one the files were
+          # generated with.
+          python-version: "3.11"
+      - name: Fetch the reference PySpark (sparse, blobless)
+        # The tracked tag is the one the vendored-drift check pins.
+        run: |
+          SPARK_TAG="$(sed -n 's/^SPARK_TAG="\(.*\)"$/\1/p' 
scripts/check_vendored_upstream.sh)"
+          test -n "${SPARK_TAG}"
+          echo "Fetching Apache Spark ${SPARK_TAG} ..."
+          git clone --quiet --depth 1 --branch "${SPARK_TAG}" 
--filter=blob:none --sparse \
+            https://github.com/apache/spark.git "${RUNNER_TEMP}/spark"
+          git -C "${RUNNER_TEMP}/spark" sparse-checkout set python/pyspark
+      - name: Install the dependencies of PySpark Connect
+        # Only so that pyspark.sql.connect.functions.builtin imports; the 
generated
+        # text does not depend on their versions.
+        run: |
+          python -m pip install --upgrade pip
+          python -m pip install 'pandas>=2.2,<3.0' pyarrow numpy grpcio 
grpcio-status googleapis-common-protos zstandard py4j
+      - name: Check the generated files
+        run: python scripts/gen_fn_dispatch.py --pyspark-src 
"${RUNNER_TEMP}/spark/python" --check
diff --git a/scripts/gen_fn_dispatch.py b/scripts/gen_fn_dispatch.py
index 6aebb909..0e6b5140 100644
--- a/scripts/gen_fn_dispatch.py
+++ b/scripts/gen_fn_dispatch.py
@@ -1,11 +1,37 @@
 #!/usr/bin/env python3
 """
-Generator for dispatch and Python wrappers for all 440 Spark SQL functions.
-Parses crates/spark-connect/src/functions.rs and generates optimized code.
+Generator for the Rust dispatch and the Python wrappers of the Spark SQL 
functions.
+
+It parses crates/spark-connect/src/functions.rs and generates
+
+  * crates/pyspark-rs/src/dispatch_generated.rs  (``call_builtin``: function 
name ->
+    call into the Rust core), and
+  * python/pyspark/sql/functions_generated.py    (the 
``pyspark.sql.functions`` wrappers;
+    needs ``--pyspark-src``).
+
+Both files are fully generated: every arm or wrapper that does not follow from 
a
+function's Rust signature is declared in one of the tables below, so 
regenerating
+reproduces the checked-in files byte for byte. ``--check`` regenerates in 
memory and
+fails with a diff when a checked-in file differs; CI runs it
+(.github/workflows/generated-drift.yml), and 
scripts/tests/test_gen_fn_dispatch.py runs
+the Rust half without a reference PySpark.
+
+Usage, from anywhere:
+
+    python scripts/gen_fn_dispatch.py --pyspark-src <spark>/python            
# write
+    python scripts/gen_fn_dispatch.py --pyspark-src <spark>/python --check    
# verify
+
+``<spark>/python`` is the python/ directory of an Apache Spark checkout at the 
tracked
+tag (SPARK_TAG of scripts/check_vendored_upstream.sh), run with an interpreter 
in which
+the dependencies of PySpark Connect (pandas, pyarrow, grpcio, ...) import. 
Without
+``--pyspark-src`` only the Rust dispatch is generated (or checked).
 """
 
+from __future__ import annotations
+
 import argparse
 import ast
+import difflib
 import dis
 import inspect
 import re
@@ -14,89 +40,119 @@ import textwrap
 import types
 from pathlib import Path
 
-_ap = argparse.ArgumentParser(description=__doc__)
-_ap.add_argument(
-    "--pyspark-src",
-    default=None,
-    help="Path to the reference PySpark package root (…/python), with the 
dependencies of "
-    "PySpark Connect importable. When given, a function whose PySpark Connect "
-    "implementation only marshals its arguments into a function call is 
generated with "
-    "that implementation's signature and body; the others carry the 
reference's parameter "
-    "names and dispatch to the Rust core. Without it, wrappers fall back to 
the historical "
-    "*args form.",
-)
-_ap.add_argument(
-    "--write-dispatch",
-    action="store_true",
-    help="Also (re)write crates/pyspark-rs/src/dispatch_generated.rs. OFF by 
default: "
-    "that file carries hand-tuned multi-arg arms (e.g. round_scale, "
-    "approx_count_distinct_rsd) this generator does not reproduce, so 
overwriting it "
-    "would regress. Only pass this when intentionally regenerating the Rust 
dispatch.",
-)
-_args = _ap.parse_args()
-
-# Optionally load the reference pyspark to mirror real function signatures, 
and its
-# PySpark Connect implementations.
-_ref_functions = None
-_ref_builtin = None
-if _args.pyspark_src:
-    sys.path.insert(0, _args.pyspark_src)
-    import pyspark.sql.connect.functions.builtin as _ref_builtin  # noqa: E402
-    import pyspark.sql.functions as _ref_functions  # noqa: E402
-
-# Read the spark-connect functions file
-functions_rs = Path("crates/spark-connect/src/functions.rs").read_text()
-
-# Extract all function definitions with their full signatures
-# Pattern: pub fn name(params) -> Column {
-pattern = r"^pub fn ([a-zA-Z0-9_#]+)\((.*?)\)\s*->\s*Column\s*\{"
-matches = re.finditer(pattern, functions_rs, re.MULTILINE | re.DOTALL)
-
-functions: dict[str, dict] = {}
-for match in matches:
-    full_name = match.group(1)
-    name = full_name.replace("r#", "")  # Remove raw string prefix like 
r#struct
-    params_str = match.group(2).strip()
-
-    # Parse parameters
-    params = []
-    if params_str:
-        # Split by comma, but handle nested angle brackets
-        param_parts = []
-        current = ""
-        depth = 0
-        for char in params_str:
-            if char == "<":
-                depth += 1
-            elif char == ">":
-                depth -= 1
-            elif char == "," and depth == 0:
-                param_parts.append(current.strip())
-                current = ""
-                continue
-            current += char
-        if current.strip():
-            param_parts.append(current.strip())
-
-        for param in param_parts:
-            # Parse each parameter: name: type
-            if ":" in param:
-                parts = param.split(":")
-                pname = parts[0].strip()
-                ptype = ":".join(parts[1:]).strip()
-                params.append({"name": pname, "type": ptype})
-
-    functions[name] = {
-        "full_name": full_name,
-        "params": params,
-        "param_count": len(params),
-    }
+REPO_ROOT = Path(__file__).resolve().parent.parent
+FUNCTIONS_RS = Path("crates/spark-connect/src/functions.rs")
+DISPATCH_FILE = Path("crates/pyspark-rs/src/dispatch_generated.rs")
+WRAPPERS_FILE = Path("python/pyspark/sql/functions_generated.py")
+
+
+class GeneratorError(Exception):
+    """The Rust source and the tables of this generator disagree."""
+
+
+# 
---------------------------------------------------------------------------------------
+# Parsing crates/spark-connect/src/functions.rs
+# 
---------------------------------------------------------------------------------------
+
+
+def _matching(src: str, start: int, opening: str, closing: str) -> int:
+    """The index of the `closing` that balances the `opening` at `start`."""
+    depth = 0
+    for i in range(start, len(src)):
+        ch = src[i]
+        if ch == opening:
+            depth += 1
+        elif ch == closing and not (closing == ">" and src[i - 1] == "-"):  # 
not a `->`
+            depth -= 1
+            if depth == 0:
+                return i
+    raise GeneratorError(f"unbalanced {opening!r} at offset {start} of 
{FUNCTIONS_RS}")
+
+
+def _split_top_level(text: str) -> list[str]:
+    """Split on the commas that are outside any bracket."""
+    parts, current, depth = [], "", 0
+    for i, ch in enumerate(text):
+        if ch in "<([":
+            depth += 1
+        elif ch in ")]" or (ch == ">" and text[i - 1] != "-"):
+            depth -= 1
+        elif ch == "," and depth == 0:
+            parts.append(current.strip())
+            current = ""
+            continue
+        current += ch
+    if current.strip():
+        parts.append(current.strip())
+    return parts
+
+
+def parse_rust_functions(src: str) -> dict[str, dict]:
+    """The top-level ``pub fn``s that return a ``Column``, in source order.
+
+    name -> {"full_name": the Rust identifier (``r#struct``), "generics": the 
text between
+    ``<`` and ``>`` after the name, "params": [{"name", "type"}], "order": its 
rank}.
+    """
+    functions: dict[str, dict] = {}
+    for match in re.finditer(r"^pub fn ((?:r#)?[A-Za-z0-9_]+)", src, 
re.MULTILINE):
+        full_name = match.group(1)
+        pos = match.end()
+        generics = ""
+        if src[pos] == "<":
+            end = _matching(src, pos, "<", ">")
+            generics = " ".join(src[pos + 1 : end].split())
+            pos = end + 1
+        if src[pos] != "(":
+            raise GeneratorError(f"{full_name}: expected '(' after the 
function name")
+        end = _matching(src, pos, "(", ")")
+        params_text = " ".join(src[pos + 1 : end].split())
+        returns = re.match(r"\s*->\s*([^\s{]+)", src[end + 1 :])
+        if returns is None or returns.group(1) != "Column":
+            continue  # e.g. broadcast(DataFrame) -> DataFrame
+        params = []
+        for part in _split_top_level(params_text):
+            pname, _, ptype = part.partition(":")
+            params.append({"name": pname.strip(), "type": ptype.strip()})
+        name = full_name.replace("r#", "")
+        if name in functions:
+            raise GeneratorError(f"{name}: defined twice in {FUNCTIONS_RS}")
+        functions[name] = {
+            "full_name": full_name,
+            "generics": generics,
+            "params": params,
+            "order": len(functions),
+        }
+    return functions
+
+
+def _is_column(fn: dict, ptype: str) -> bool:
+    return ptype == "Column"
+
+
+def _is_variadic(fn: dict, ptype: str) -> bool:
+    """``Vec<Column>``, or an ``impl IntoIterator`` of ``Column`` or of 
``Into<Column>``."""
+    if ptype == "Vec<Column>":
+        return True
+    item = re.fullmatch(r"impl IntoIterator<Item = (\w+)>", ptype)
+    if item is None:
+        return False
+    if item.group(1) == "Column":
+        return True
+    bounds = dict(
+        (g.partition(":")[0].strip(), g.partition(":")[2].strip())
+        for g in _split_top_level(fn["generics"])
+    )
+    return bounds.get(item.group(1)) == "Into<Column>"
 
-print(f"Found {len(functions)} functions")
 
-# Functions excluded from the generic dispatcher AND the Python wrappers 
because
-# their Rust signatures don't fit the generic Vec<Column> -> Column form.
-skip_functions = {
+# 
---------------------------------------------------------------------------------------
+# Tables
+# 
---------------------------------------------------------------------------------------
+
+# Functions without a generated Python wrapper: functions.py writes them by 
hand or binds
+# them to a dedicated pyfunc_*. Unless DISPATCH_ONLY lists them, they have no 
dispatch arm
+# either, their Rust signature not being a list of columns.
+SKIP_FUNCTIONS = {
     "col",
     "lit",
     "expr",
@@ -159,153 +215,322 @@ skip_functions = {
     "bucket",
 }
 
-# Categorize functions by their parameter types
-no_args = []
-single_col = []
-variadic_cols = []
-multiple_cols = []
-str_only = []
-mixed = []
-
-for name, fn in functions.items():
-    if name in skip_functions:
-        continue
-    if fn["param_count"] == 0:
-        no_args.append(name)
-    elif fn["param_count"] == 1:
-        param_type = fn["params"][0]["type"]
-        if "Vec<Column>" in param_type:
-            variadic_cols.append(name)
-        elif "Column" in param_type:
-            single_col.append(name)
-        elif "&str" in param_type or "str" in param_type:
-            str_only.append(name)
-        else:
-            mixed.append(name)
-    else:
-        # Check if all are Columns
-        all_cols = all("Column" in p["type"] for p in fn["params"])
-        if all_cols:
-            multiple_cols.append(name)
-        else:
-            mixed.append(name)
-
-print(f"  No args: {len(no_args)}")
-print(f"  Single Column: {len(single_col)}")
-print(f"  Multiple Columns: {len(multiple_cols)}")
-print(f"  String only: {len(str_only)}")
-print(f"  Mixed/Other: {len(mixed)}")
-
-# Generate Rust dispatch function
-rust_arms = []
-
-# No-arg functions
-for name in no_args:
-    fn = functions[name]
-    rust_arms.append(f'            "{name}" => 
Ok(spark_funcs::{fn["full_name"]}()),')
-
-# Single column functions
-for name in single_col:
-    fn = functions[name]
-    rust_arms.append(f'            "{name}" => {{')
-    rust_arms.append(
-        '                if args.is_empty() { return 
Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>("Missing required column 
argument")); }'
-    )
-    rust_arms.append(f"                
Ok(spark_funcs::{fn['full_name']}(args[0].clone()))")
-    rust_arms.append("            },")
-
-# Variadic (Vec<Column>) functions - forward all column args
-for name in variadic_cols:
-    fn = functions[name]
-    rust_arms.append(f'            "{name}" => 
Ok(spark_funcs::{fn["full_name"]}(args.clone())),')
-
-# String-only functions - convert first arg to string literal
-for name in str_only:
-    fn = functions[name]
-    param_name = fn["params"][0]["name"]
-    rust_arms.append(f'            "{name}" => {{')
-    rust_arms.append("                // String parameter - use empty string 
as default")
-    rust_arms.append(f'                Ok(spark_funcs::{fn["full_name"]}(""))')
-    rust_arms.append("            },")
-
-# Multiple column functions
-for name in multiple_cols:
-    fn = functions[name]
-    col_count = sum(1 for p in fn["params"] if "Column" in p["type"])
-    rust_arms.append(f'            "{name}" => {{')
-    rust_arms.append(
-        f'                if args.len() < {col_count} {{ return 
Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!("Missing required 
arguments for {name}: expected at least {col_count}, got {{}}", args.len()))); 
}}'
-    )
-    col_args = ", ".join([f"args[{i}].clone()" for i in range(col_count)])
-    rust_arms.append(f"                
Ok(spark_funcs::{fn['full_name']}({col_args}))")
-    rust_arms.append("            },")
-
-# Mixed/other - try to handle generically
-for name in mixed:
-    fn = functions[name]
-    # Special case for window(Column, &str)
-    if name == "window":
-        rust_arms.append('            "window" => {')
-        rust_arms.append(
-            '                if args.len() < 1 { return 
Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>("window() requires at least 
1 column argument")); }'
+# The SKIP_FUNCTIONS that still have a dispatch arm: their Python wrapper is 
written by
+# hand in functions.py (which dispatches count_distinct, listagg_distinct and
+# string_agg_distinct by name), but call_builtin resolves them.
+DISPATCH_ONLY = {
+    "bucket",
+    "countDistinct",
+    "count_distinct",
+    "days",
+    "hours",
+    "listagg_distinct",
+    "months",
+    "string_agg_distinct",
+    "variant_delete",
+    "when",
+    "years",
+}
+
+# PySpark functions with trailing optional arguments, which the Rust core 
spells as one
+# function per arity: base -> the functions taking one more argument, two 
more, ... The
+# arm of the base picks the function by the number of arguments it gets, and 
the longer
+# functions have no arm (nor Python wrapper) of their own.
+OPTIONAL_ARG_VARIANTS = {
+    "approx_count_distinct": ["approx_count_distinct_rsd"],
+    "bround": ["bround_scale"],
+    "ceil": ["ceil_scale"],
+    "counter_diff": ["counter_diff_with_start_time"],
+    "floor": ["floor_scale"],
+    "hmac": ["hmac_with_algorithm"],
+    "instr": ["instr_with_start", "instr_with_start_and_occurrence"],
+    "listagg_distinct": ["listagg_distinct_with_delimiter"],
+    "ltrim": ["ltrim_with"],
+    "regexp_replace": ["regexp_replace_with_position"],
+    "round": ["round_scale"],
+    "rtrim": ["rtrim_with"],
+    "string_agg_distinct": ["string_agg_distinct_with_delimiter"],
+    "to_binary": ["to_binary_format"],
+    "trim": ["trim_with"],
+    "try_variant_set": ["try_variant_set_with_create_if_missing"],
+    "variant_set": ["variant_set_with_create_if_missing"],
+    "vector_norm": ["vector_norm_with_degree"],
+    "vector_normalize": ["vector_normalize_with_degree"],
+}
+
+# Functions of a column followed by any number of columns: name -> the Rust 
function
+# ``f(Column, impl IntoIterator<..>)`` that the arm calls with ``args[0]`` and 
the rest.
+# A target under another name has no arm (nor Python wrapper) of its own.
+HEAD_REST_ARMS = {
+    "countDistinct": "count_distinct_columns",
+    "count_distinct": "count_distinct_columns",
+    "variant_delete": "variant_delete",
+}
+
+# Rust functions that are not reachable through call_builtin, and why. (They 
have no
+# generated Python wrapper either.) Listing one here is a decision; a function 
that fits
+# no rule and no table fails the generation instead of being dropped silently.
+NOT_DISPATCHED = {
+    # Window function without arguments: the Python wrapper is generated from 
its PySpark
+    # Connect implementation (UPSTREAM_EXTRA), which does not go through 
call_builtin.
+    "cume_dist": "generated from its PySpark Connect implementation",
+    # An alias of rand() in the Rust core only; the Python `random` is not 
generated here.
+    "random": "Rust-only alias of rand",
+    # The seeded forms take the seed as an i64, not as a column.
+    "rand_with_seed": "takes an i64 seed",
+    "randn_with_seed": "takes an i64 seed",
+    "random_with_seed": "takes an i64 seed",
+    # Seeded forms of the Rust core. The Python wrappers of their bases are 
generated from
+    # the PySpark Connect implementations, which send the seed themselves.
+    "count_min_sketch_with_seed": "the Python wrapper of the base sends the 
seed",
+    "randstr_with_seed": "the Python wrapper of the base sends the seed",
+    "shuffle_with_seed": "the Python wrapper of the base sends the seed",
+    "uniform_with_seed": "the Python wrapper of the base sends the seed",
+    "uuid_with_seed": "the Python wrapper of the base sends the seed",
+    # Higher-order functions: they take Rust closures. functions.py builds 
their lambdas
+    # with _invoke_higher_order_function.
+    "aggregate": "takes a Rust closure",
+    "aggregate_with_finish": "takes a Rust closure",
+    "exists": "takes a Rust closure",
+    "filter": "takes a Rust closure",
+    "forall": "takes a Rust closure",
+    "map_filter": "takes a Rust closure",
+    "map_zip_with": "takes a Rust closure",
+    "reduce": "takes a Rust closure",
+    "transform": "takes a Rust closure",
+    "transform_idx": "takes a Rust closure",
+    "transform_keys": "takes a Rust closure",
+    "transform_values": "takes a Rust closure",
+    "zip_with": "takes a Rust closure",
+}
+
+# The arms come in four sections -- no argument, one column, any number of 
columns,
+# several columns -- and in the order of functions.rs within a section. The 
two tables
+# below record where an arm stands when that is not the place its signature 
gives it.
+# They only keep the generated file stable (the order of the arms of a match 
on distinct
+# string literals has no effect); a new function needs no entry.
+SECTIONS = ("no_args", "single", "variadic", "multiple")
+# Variadic functions that stand in another section than "variadic".
+SECTION_OVERRIDES = {
+    "concat_ws": "single",
+    "format_string": "single",
+    "json_tuple": "multiple",
+    "lag": "single",
+    "lead": "single",
+}
+# name -> the function at whose place in functions.rs the arm is ordered.
+ORDER_AS = {
+    "variant_delete": "variant_strip_nulls",
+}
+
+
+# 
---------------------------------------------------------------------------------------
+# The Rust dispatch
+# 
---------------------------------------------------------------------------------------
+
+_TYPE_ERROR = "PyErr::new::<pyo3::exceptions::PyTypeError, _>"
+_ARM = " " * 12
+_BODY = " " * 16
+_NESTED = " " * 20
+
+
+def _call(full_name: str, count: int) -> str:
+    args = ", ".join(f"args[{i}].clone()" for i in range(count))
+    return f"spark_funcs::{full_name}({args})"
+
+
+def _guard(name: str, count: int, section: str) -> str:
+    """The line that rejects a call with fewer than the `count` required 
arguments."""
+    if section == "single":
+        return (
+            f"{_BODY}if args.is_empty() {{ return Err({_TYPE_ERROR}"
+            '("Missing required column argument")); }'
         )
-        rust_arms.append("                // window takes a column and a 
string duration parameter")
-        rust_arms.append('                
Ok(spark_funcs::window(args[0].clone(), ""))')
-        rust_arms.append("            },")
-    else:
-        # For other mixed functions, try generic handling
-        col_count = fn["param_count"]
-        rust_arms.append(f'            "{name}" => {{')
-        rust_arms.append("                // Mixed/special case: trying 
generic handling")
-        col_args = ", ".join([f"args[{i}].clone()" for i in 
range(min(col_count, 1))])
-        if col_count <= 1:
-            if col_count == 0:
-                rust_arms.append(f"                
Ok(spark_funcs::{fn['full_name']}())")
-            else:
-                rust_arms.append(
-                    '                if args.is_empty() { return 
Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>("Missing arguments")); }'
-                )
-                rust_arms.append(
-                    f"                
Ok(spark_funcs::{fn['full_name']}(args[0].clone()))"
+    return (
+        f"{_BODY}if args.len() < {count} {{ return Err({_TYPE_ERROR}(format!("
+        f'"Missing required arguments for {name}: expected at least {count}, 
got {{}}", '
+        "args.len()))); }"
+    )
+
+
+def plan_dispatch(
+    functions: dict[str, dict],
+    *,
+    skip=None,
+    dispatch_only=None,
+    optional_arg_variants=None,
+    head_rest_arms=None,
+    not_dispatched=None,
+    section_overrides=None,
+    order_as=None,
+) -> list[dict]:
+    """The arms of call_builtin, in the order they are written.
+
+    Each arm is {"name", "section", "kind", ...} with kind one of "plain" (the 
function,
+    with its `count` column arguments), "variadic" (all the arguments), 
"optional" (the
+    function or one of its longer `variants`) and "head_rest" (`target`, with 
the first
+    argument and the rest). Raises GeneratorError when a function of the Rust 
core is not
+    accounted for, or when a table names a function that does not fit it.
+    """
+    skip = SKIP_FUNCTIONS if skip is None else skip
+    dispatch_only = DISPATCH_ONLY if dispatch_only is None else dispatch_only
+    variants_of = OPTIONAL_ARG_VARIANTS if optional_arg_variants is None else 
optional_arg_variants
+    head_rest = HEAD_REST_ARMS if head_rest_arms is None else head_rest_arms
+    not_dispatched = NOT_DISPATCHED if not_dispatched is None else 
not_dispatched
+    section_overrides = SECTION_OVERRIDES if section_overrides is None else 
section_overrides
+    order_as = ORDER_AS if order_as is None else order_as
+
+    def known(name: str, table: str) -> dict:
+        if name not in functions:
+            raise GeneratorError(f"{table} names {name}, which {FUNCTIONS_RS} 
does not define")
+        return functions[name]
+
+    def column_count(name: str, table: str) -> int:
+        fn = known(name, table)
+        if not all(_is_column(fn, p["type"]) for p in fn["params"]):
+            raise GeneratorError(f"{table}: {name} does not take only columns")
+        return len(fn["params"])
+
+    stale = sorted(dispatch_only - skip)
+    if stale:
+        raise GeneratorError(f"DISPATCH_ONLY names {', '.join(stale)}, not in 
SKIP_FUNCTIONS")
+    for name in section_overrides:
+        known(name, "SECTION_OVERRIDES")
+    for name, anchor in order_as.items():
+        known(name, "ORDER_AS")
+        if anchor not in functions:
+            raise GeneratorError(f"ORDER_AS orders {name} as {anchor}, which 
is not defined")
+    for name in not_dispatched:
+        known(name, "NOT_DISPATCHED")
+
+    # The functions that another arm calls and that have no arm of their own.
+    absorbed: dict[str, str] = {}
+    for base, variants in variants_of.items():
+        count = column_count(base, "OPTIONAL_ARG_VARIANTS")
+        if count == 0 or not variants:
+            raise GeneratorError(f"OPTIONAL_ARG_VARIANTS: {base} needs an 
argument and a variant")
+        for extra, variant in enumerate(variants, start=1):
+            if column_count(variant, "OPTIONAL_ARG_VARIANTS") != count + extra:
+                raise GeneratorError(
+                    f"OPTIONAL_ARG_VARIANTS: {variant} must take {count + 
extra} columns, "
+                    f"{extra} more than {base}"
                 )
+            if absorbed.setdefault(variant, base) != base:
+                raise GeneratorError(f"{variant} is a variant of both 
{absorbed[variant]}, {base}")
+    for name, target in head_rest.items():
+        known(name, "HEAD_REST_ARMS")
+        params = known(target, "HEAD_REST_ARMS")["params"]
+        if not (
+            len(params) == 2
+            and _is_column(functions[target], params[0]["type"])
+            and _is_variadic(functions[target], params[1]["type"])
+        ):
+            raise GeneratorError(f"HEAD_REST_ARMS: {target} is not f(Column, 
columns)")
+        if target != name:
+            absorbed.setdefault(target, name)
+
+    excluded = (skip - dispatch_only) | set(not_dispatched) | set(absorbed)
+    for name in sorted(excluded & (set(variants_of) | set(head_rest))):
+        raise GeneratorError(f"{name} has an arm in a table but is also 
excluded from dispatch")
+
+    arms = []
+    for name, fn in functions.items():
+        if name in excluded:
+            continue
+        types_ = [p["type"] for p in fn["params"]]
+        all_columns = all(_is_column(fn, t) for t in types_)
+        arm = {"name": name, "full_name": fn["full_name"], "count": 
len(types_)}
+        if name in head_rest:
+            arm.update(kind="head_rest", section="single", 
target=head_rest[name])
+            arm["target_full_name"] = functions[head_rest[name]]["full_name"]
+        elif name in variants_of:
+            arm.update(
+                kind="optional",
+                section="single" if len(types_) == 1 else "multiple",
+                variants=[functions[v]["full_name"] for v in 
variants_of[name]],
+            )
+        elif not types_:
+            arm.update(kind="plain", section="no_args")
+        elif len(types_) == 1 and _is_variadic(fn, types_[0]):
+            arm.update(kind="variadic", section="variadic")
+        elif all_columns:
+            arm.update(kind="plain", section="single" if len(types_) == 1 else 
"multiple")
         else:
-            rust_arms.append(f"                // TODO: special handling for 
{name}")
-            rust_arms.append(
-                f'                
Err(PyErr::new::<pyo3::exceptions::PyNotImplementedError, _>(format!("Function 
{name} not yet implemented in dispatch")))'
+            signature = ", ".join(f"{p['name']}: {p['type']}" for p in 
fn["params"])
+            raise GeneratorError(
+                f"{name}({signature}) is not a function of columns: add it to "
+                "SKIP_FUNCTIONS (hand-written in functions.py), 
OPTIONAL_ARG_VARIANTS, "
+                "HEAD_REST_ARMS or NOT_DISPATCHED in 
scripts/gen_fn_dispatch.py"
             )
-        rust_arms.append("            },")
-
-# Generate the dispatch code
-dispatch_code = (
-    """/// Auto-generated dispatch function for Spark SQL functions.
+        if name in section_overrides:
+            if arm["kind"] != "variadic":
+                raise GeneratorError(f"SECTION_OVERRIDES: {name} is not a 
variadic function")
+            arm["section"] = section_overrides[name]
+        arm["order"] = functions[order_as.get(name, name)]["order"]
+        arms.append(arm)
+
+    arms.sort(key=lambda a: (SECTIONS.index(a["section"]), a["order"]))
+    return arms
+
+
+def render_arm(arm: dict) -> list[str]:
+    name, full_name, count = arm["name"], arm["full_name"], arm["count"]
+    if arm["kind"] == "variadic":
+        return [f'{_ARM}"{name}" => 
Ok(spark_funcs::{full_name}(args.clone())),']
+    if arm["kind"] == "plain" and count == 0:
+        return [f'{_ARM}"{name}" => Ok(spark_funcs::{full_name}()),']
+    lines = [f'{_ARM}"{name}" => {{', _guard(name, count, arm["section"])]
+    if arm["kind"] == "plain":
+        lines.append(f"{_BODY}Ok({_call(full_name, count)})")
+    elif arm["kind"] == "head_rest":
+        lines.append(
+            f"{_BODY}Ok(spark_funcs::{arm['target_full_name']}"
+            "(args[0].clone(), args[1..].to_vec()))"
+        )
+    elif len(arm["variants"]) == 1:
+        lines.append(
+            f"{_BODY}if args.len() >= {count + 1} "
+            f"{{ Ok({_call(arm['variants'][0], count + 1)}) }} "
+            f"else {{ Ok({_call(full_name, count)}) }}"
+        )
+    else:
+        lines.append(f"{_BODY}match args.len() {{")
+        lines.append(f"{_NESTED}{count} => Ok({_call(full_name, count)}),")
+        for extra, variant in enumerate(arm["variants"][:-1], start=1):
+            lines.append(f"{_NESTED}{count + extra} => Ok({_call(variant, 
count + extra)}),")
+        last = len(arm["variants"])
+        lines.append(f"{_NESTED}_ => Ok({_call(arm['variants'][-1], count + 
last)}),")
+        lines.append(f"{_BODY}}}")
+    lines.append(f"{_ARM}}},")
+    return lines
+
+
+_DISPATCH_HEADER = """/// Auto-generated dispatch function for Spark SQL 
functions.
 /// Generated by scripts/gen_fn_dispatch.py - do not edit directly.
 pub fn call_builtin(name: &str, args: Vec<spark_connect::column::Column>) -> 
PyResult<spark_connect::column::Column> {
     use spark_connect::functions as spark_funcs;
     match name {
 """
-    + "\n".join(rust_arms)
-    + """
+_DISPATCH_FOOTER = """
         _ => Err(PyErr::new::<pyo3::exceptions::PyNameError, _>(
             format!("Unknown function: {}", name)
         )),
     }
 }
 """
-)
-
-# Write dispatch file (guarded: the committed file is hand-tuned; see 
--write-dispatch).
-dispatch_file = Path("crates/pyspark-rs/src/dispatch_generated.rs")
-if _args.write_dispatch:
-    dispatch_file.write_text(dispatch_code)
-    print(f"\nGenerated dispatch function in {dispatch_file}")
-else:
-    print(f"\nSkipped {dispatch_file} (pass --write-dispatch to regenerate the 
Rust dispatch)")
-
-# Generate Python wrapper functions
-# (skip_functions is defined above, before categorization.)
+
+
+def render_dispatch(arms: list[dict]) -> str:
+    lines = [line for arm in arms for line in render_arm(arm)]
+    return _DISPATCH_HEADER + "\n".join(lines) + _DISPATCH_FOOTER
+
+
+# 
---------------------------------------------------------------------------------------
+# The Python wrappers
+# 
---------------------------------------------------------------------------------------
 #
-# When a reference PySpark is available, emit an explicit ``def`` per function 
carrying
-# the reference's real parameter names/order, so keyword calls (``F.first(col,
+# With the reference PySpark, an explicit ``def`` is emitted per function, 
carrying the
+# reference's real parameter names/order, so keyword calls (``F.first(col,
 # ignorenulls=True)``) work. Optional params default to the ``_UNSET`` 
sentinel and are
 # forwarded only when supplied, reproducing the historical ``*args`` dispatch 
exactly
 # (same columns, same order) — see functions.py ``_dispatch`` / ``_UNSET``.
@@ -360,7 +585,7 @@ def _emit_def(name, sig):
 # when it is given, the defaults that PySpark fills in, a NULL for an explicit 
None where
 # PySpark sends one, and PySpark's errors for arguments of other types. The 
globals that
 # such a body may read are those that the generated module provides:
-_UPSTREAM_GLOBALS = {
+UPSTREAM_GLOBALS = {
     "ArrayType",
     "Column",
     "DataType",
@@ -386,7 +611,7 @@ _UPSTREAM_GLOBALS = {
 # The helpers of pyspark.sql.connect.functions.builtin that the generated 
module defines
 # with their PySpark Connect bodies. functions.py injects lit, column, 
_invoke_function and
 # _invoke_higher_order_function, which the Rust core implements.
-_UPSTREAM_HELPERS = [
+UPSTREAM_HELPERS = [
     "_to_col",
     "_invoke_function_over_columns",
     "_invoke_binary_math_function",
@@ -395,7 +620,7 @@ _UPSTREAM_HELPERS = [
 ]
 # Functions that functions.py used to write by hand and that are now generated 
from their
 # PySpark Connect implementations, which they must have.
-_UPSTREAM_EXTRA = {
+UPSTREAM_EXTRA = {
     "array",
     "avg",
     "counter_diff",
@@ -423,6 +648,14 @@ _UPSTREAM_EXTRA = {
 }
 
 
+def wrapper_names(arms: list[dict], *, skip=None, upstream_extra=None) -> 
list[str]:
+    """The functions of functions_generated.py: those with a dispatch arm, 
less the ones
+    functions.py writes by hand, and those generated from PySpark Connect."""
+    skip = SKIP_FUNCTIONS if skip is None else skip
+    upstream_extra = UPSTREAM_EXTRA if upstream_extra is None else 
upstream_extra
+    return sorted({arm["name"] for arm in arms if arm["name"] not in skip} | 
upstream_extra)
+
+
 def _code_objects(code):
     yield code
     for const in code.co_consts:
@@ -430,20 +663,20 @@ def _code_objects(code):
             yield from _code_objects(const)
 
 
-def _upstream_impl(name):
+def _upstream_impl(ref_builtin, name):
     """The PySpark Connect implementation of `name`, when it is a plain 
function."""
-    fn = getattr(_ref_builtin, name, None) if _ref_builtin is not None else 
None
+    fn = getattr(ref_builtin, name, None)
     if not isinstance(fn, types.FunctionType) or inspect.unwrap(fn) is not fn:
         return None  # Absent, or decorated (as col and lit are, with 
_with_origin).
     return fn
 
 
-def _upstream_eligible(names):
+def _upstream_eligible(ref_builtin, names):
     """The names whose implementation reads only the provided globals (or 
other such
     functions) and imports nothing."""
     reads = {}
     for name in names:
-        fn = _upstream_impl(name)
+        fn = _upstream_impl(ref_builtin, name)
         if fn is None:
             continue
         loaded, imports = set(), False
@@ -458,7 +691,7 @@ def _upstream_eligible(names):
             reads[name] = {n for n in loaded if n in fn.__globals__}
     eligible = set(reads)
     while True:
-        kept = {n for n in eligible if reads[n] <= _UPSTREAM_GLOBALS | 
eligible}
+        kept = {n for n in eligible if reads[n] <= UPSTREAM_GLOBALS | eligible}
         if kept == eligible:
             return eligible
         eligible = kept
@@ -478,7 +711,7 @@ def _upstream_def(name, fn):
     params = []
     for p in sig.parameters.values():
         if p.default is not inspect.Parameter.empty and not 
_is_literal(p.default):
-            raise SystemExit(f"{name}: the default {p.default!r} of {p.name} 
is not a literal")
+            raise GeneratorError(f"{name}: the default {p.default!r} of 
{p.name} is not a literal")
         params.append(p.replace(annotation=inspect.Parameter.empty))
     sig = sig.replace(parameters=params, 
return_annotation=inspect.Signature.empty)
     src = textwrap.dedent(inspect.getsource(fn))
@@ -494,53 +727,6 @@ def _upstream_def(name, fn):
     return f"def {name}{sig}:\n" + "\n".join(lines)
 
 
-# The wrapper set is the names already in functions_generated.py (the shipped,
-# golden-verified set) and _UPSTREAM_EXTRA. Deriving it from the Rust 
functions.rs regex is
-# fragile: generic signatures (e.g. `pub fn concat_ws<C: Into<Column>>(...)`) 
are silently
-# missed.
-wrappers_file = Path("python/pyspark/sql/functions_generated.py")
-_existing = wrappers_file.read_text() if wrappers_file.exists() else ""
-_wrapper_names = 
re.findall(r"^([A-Za-z][A-Za-z0-9_]*)\s*=\s*_create_wrapper\(", _existing, re.M)
-_wrapper_names += re.findall(r"^def ([A-Za-z][A-Za-z0-9_]*)\(", _existing, 
re.M)
-_wrapper_names = sorted(set(_wrapper_names) | _UPSTREAM_EXTRA)
-if not _existing:
-    # First-time generation: fall back to the Rust-parsed function set.
-    _wrapper_names = sorted({n for n in functions if n not in skip_functions} 
| _UPSTREAM_EXTRA)
-
-_upstream = _upstream_eligible(_wrapper_names)
-_missing = sorted(_UPSTREAM_EXTRA - _upstream)
-if _missing:
-    raise SystemExit(
-        f"{', '.join(_missing)}: not generated from a PySpark Connect 
implementation, which "
-        "functions.py relies on (pass --pyspark-src)"
-    )
-
-python_wrappers = []
-generated_names = []
-n_typed = n_upstream = 0
-for name in _wrapper_names:
-    if name in skip_functions and name not in _UPSTREAM_EXTRA:
-        continue
-    generated_names.append(name)
-    if name in _upstream:
-        python_wrappers.append(_upstream_def(name, _upstream_impl(name)))
-        n_upstream += 1
-        continue
-    ref_fn = getattr(_ref_functions, name, None) if _ref_functions is not None 
else None
-    sig = None
-    if ref_fn is not None and callable(ref_fn):
-        try:
-            sig = inspect.signature(ref_fn)
-        except (TypeError, ValueError):
-            sig = None
-    if sig is not None:
-        python_wrappers.append(_emit_def(name, sig))
-        n_typed += 1
-    else:
-        # Rust-only extra (not in the reference) — keep the historical *args 
form.
-        python_wrappers.append(f'{name} = _create_wrapper("{name}")')
-
-_helpers = [_upstream_def(h, getattr(_ref_builtin, h)) for h in 
_UPSTREAM_HELPERS]
 _MODULE_HEADER = '''"""Auto-generated wrapper functions for Spark SQL 
functions.
 Generated by scripts/gen_fn_dispatch.py - do not edit directly.
 
@@ -568,24 +754,163 @@ from pyspark.sql.utils import enum_to_value as 
_enum_to_value
 
 # Helpers of pyspark.sql.connect.functions.builtin.
 '''
-python_code = (
-    _MODULE_HEADER
-    + "\n\n\n".join(_helpers)
-    + "\n\n\n# Generated functions.\n"
-    + "\n".join(python_wrappers)
-    + "\n\n\n__all__ = [\n"
-    + "".join(f'    "{n}",\n' for n in generated_names)
-    + "]\n"
-)
-
-print(f"Generated {len(python_wrappers)} Python wrapper functions")
-print(f"  From their PySpark Connect implementations: {n_upstream}")
-print(f"  Dispatching to the Rust core with the reference's signatures: 
{n_typed}")
-print("\nSummary:")
-print(f"  Total functions: {len(functions)}")
-print(f"  Hand-written (skipped): {len(skip_functions)}")
-print(f"  Auto-generated: {len(functions) - len(skip_functions)}")
-
-# Write Python wrappers file (to be imported in functions.py)
-wrappers_file.write_text(python_code)
-print(f"\nGenerated Python wrappers in {wrappers_file}")
+
+
+def load_reference(pyspark_src: str):
+    """(pyspark.sql.connect.functions.builtin, pyspark.sql.functions) of the 
reference
+    PySpark whose python/ directory is `pyspark_src`."""
+    root = Path(pyspark_src).resolve()
+    if not (root / "pyspark" / "sql" / "connect" / "functions" / 
"builtin.py").is_file():
+        raise GeneratorError(f"--pyspark-src {pyspark_src}: not the python/ 
directory of Spark")
+    sys.path.insert(0, str(root))
+    import pyspark.sql.connect.functions.builtin as ref_builtin
+    import pyspark.sql.functions as ref_functions
+
+    loaded = Path(ref_builtin.__file__).resolve()
+    if root not in loaded.parents:
+        raise GeneratorError(f"pyspark was imported from {loaded}, not from 
--pyspark-src")
+    return ref_builtin, ref_functions
+
+
+def render_wrappers(names: list[str], ref_builtin, ref_functions, *, 
upstream_extra=None):
+    """The text of functions_generated.py, and how many functions come from 
their PySpark
+    Connect implementation and how many dispatch with the reference's 
signature."""
+    upstream_extra = UPSTREAM_EXTRA if upstream_extra is None else 
upstream_extra
+    upstream = _upstream_eligible(ref_builtin, names)
+    missing = sorted(upstream_extra - upstream)
+    if missing:
+        raise GeneratorError(
+            f"{', '.join(missing)}: not generated from a PySpark Connect 
implementation, "
+            "which functions.py relies on"
+        )
+
+    python_wrappers = []
+    n_typed = n_upstream = 0
+    for name in names:
+        if name in upstream:
+            python_wrappers.append(_upstream_def(name, 
_upstream_impl(ref_builtin, name)))
+            n_upstream += 1
+            continue
+        ref_fn = getattr(ref_functions, name, None)
+        sig = None
+        if ref_fn is not None and callable(ref_fn):
+            try:
+                sig = inspect.signature(ref_fn)
+            except (TypeError, ValueError):
+                sig = None
+        if sig is not None:
+            python_wrappers.append(_emit_def(name, sig))
+            n_typed += 1
+        else:
+            # Rust-only extra (not in the reference) — keep the historical 
*args form.
+            python_wrappers.append(f'{name} = _create_wrapper("{name}")')
+
+    helpers = [_upstream_def(h, getattr(ref_builtin, h)) for h in 
UPSTREAM_HELPERS]
+    code = (
+        _MODULE_HEADER
+        + "\n\n\n".join(helpers)
+        + "\n\n\n# Generated functions.\n"
+        + "\n".join(python_wrappers)
+        + "\n\n\n__all__ = [\n"
+        + "".join(f'    "{n}",\n' for n in names)
+        + "]\n"
+    )
+    return code, n_upstream, n_typed
+
+
+# 
---------------------------------------------------------------------------------------
+# Command line
+# 
---------------------------------------------------------------------------------------
+
+
+def generate(root: Path, pyspark_src: str | None = None, log=print) -> 
dict[Path, str]:
+    """The generated files, by path relative to `root`. functions_generated.py 
is among
+    them only with a reference PySpark."""
+    functions = parse_rust_functions((root / FUNCTIONS_RS).read_text())
+    arms = plan_dispatch(functions)
+    log(f"Found {len(functions)} functions returning a Column in 
{FUNCTIONS_RS}")
+    for section in SECTIONS:
+        log(f"  {section}: {sum(1 for a in arms if a['section'] == section)} 
arms")
+    outputs = {DISPATCH_FILE: render_dispatch(arms)}
+    if pyspark_src is not None:
+        ref_builtin, ref_functions = load_reference(pyspark_src)
+        names = wrapper_names(arms)
+        code, n_upstream, n_typed = render_wrappers(names, ref_builtin, 
ref_functions)
+        log(f"Generated {len(names)} Python wrapper functions")
+        log(f"  From their PySpark Connect implementations: {n_upstream}")
+        log(f"  Dispatching to the Rust core with the reference's signatures: 
{n_typed}")
+        outputs[WRAPPERS_FILE] = code
+    return outputs
+
+
+def check(root: Path, outputs: dict[Path, str], log=print) -> bool:
+    """Whether the checked-in files equal `outputs`; logs a unified diff of 
each that
+    does not."""
+    clean = True
+    for path, expected in outputs.items():
+        target = root / path
+        actual = target.read_text() if target.is_file() else ""
+        if actual == expected:
+            log(f"OK    {path} matches its generator")
+            continue
+        clean = False
+        log(f"DRIFT {path} differs from the output of 
scripts/gen_fn_dispatch.py:")
+        diff = difflib.unified_diff(
+            actual.splitlines(keepends=True),
+            expected.splitlines(keepends=True),
+            fromfile=f"{path} (checked in)",
+            tofile=f"{path} (generated)",
+        )
+        for line in diff:
+            log(line.rstrip("\n"))
+    return clean
+
+
+def main(argv=None) -> int:
+    parser = argparse.ArgumentParser(
+        description=__doc__, 
formatter_class=argparse.RawDescriptionHelpFormatter
+    )
+    parser.add_argument(
+        "--pyspark-src",
+        default=None,
+        help="Path to the reference PySpark package root (…/python), with the 
dependencies of "
+        "PySpark Connect importable. A function whose PySpark Connect 
implementation only "
+        "marshals its arguments into a function call is generated with that "
+        "implementation's signature and body; the others carry the reference's 
parameter "
+        "names and dispatch to the Rust core. Without it, 
functions_generated.py is "
+        "neither written nor checked.",
+    )
+    parser.add_argument(
+        "--check",
+        action="store_true",
+        help="Write nothing: regenerate in memory, print a diff of every 
checked-in file "
+        "that differs from its generated text, and exit with status 1 if any 
does.",
+    )
+    args = parser.parse_args(argv)
+
+    try:
+        outputs = generate(REPO_ROOT, args.pyspark_src)
+    except GeneratorError as e:
+        print(f"error: {e}", file=sys.stderr)
+        return 2
+    if WRAPPERS_FILE not in outputs:
+        print(f"NOTE  {WRAPPERS_FILE} needs --pyspark-src: not generated, not 
checked")
+
+    if args.check:
+        if check(REPO_ROOT, outputs):
+            return 0
+        print(
+            "\nGenerated files have drifted. Do not edit them by hand: change "
+            "scripts/gen_fn_dispatch.py (or its tables) and regenerate with\n"
+            "  python scripts/gen_fn_dispatch.py --pyspark-src <spark at the 
tracked tag>/python"
+        )
+        return 1
+
+    for path, text in outputs.items():
+        (REPO_ROOT / path).write_text(text)
+        print(f"Generated {path}")
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/scripts/tests/test_gen_fn_dispatch.py 
b/scripts/tests/test_gen_fn_dispatch.py
new file mode 100644
index 00000000..b0947958
--- /dev/null
+++ b/scripts/tests/test_gen_fn_dispatch.py
@@ -0,0 +1,238 @@
+#
+# 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.
+
+"""The Rust half of gen_fn_dispatch.py: parsing, the override tables and 
--check.
+
+None of this needs a reference PySpark; the generated-drift workflow checks
+functions_generated.py against one.
+"""
+
+import importlib.util
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+SCRIPT = Path(__file__).resolve().parents[1] / "gen_fn_dispatch.py"
+SPEC = importlib.util.spec_from_file_location("gen_fn_dispatch", SCRIPT)
+gen = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = gen
+SPEC.loader.exec_module(gen)
+
+RUST = """
+pub fn broadcast(df: DataFrame) -> DataFrame {
+    df.broadcast()
+}
+
+/// Follows a function that does not return a Column.
+pub fn cume_dist() -> Column {
+    func("cume_dist", vec![])
+}
+
+pub fn round(col1: Column) -> Column {
+    todo!()
+}
+
+pub fn round_scale(col1: Column, scale: Column) -> Column {
+    todo!()
+}
+
+pub fn r#struct<C: Into<Column>>(cols: impl IntoIterator<Item = C>) -> Column {
+    todo!()
+}
+
+pub fn concat_ws<C: Into<Column>>(cols: impl IntoIterator<Item = C>) -> Column 
{
+    todo!()
+}
+
+pub fn instr(col1: Column, col2: Column) -> Column {
+    todo!()
+}
+
+pub fn instr_with_start(col1: Column, col2: Column, start: Column) -> Column {
+    todo!()
+}
+
+pub fn instr_with_start_and_occurrence(
+    col1: Column,
+    col2: Column,
+    start: Column,
+    occurrence: Column,
+) -> Column {
+    todo!()
+}
+
+pub fn count_distinct(col1: Column) -> Column {
+    todo!()
+}
+
+pub fn count_distinct_columns(col1: Column, cols: impl IntoIterator<Item = 
Column>) -> Column {
+    todo!()
+}
+
+pub fn transform<F>(col: Column, f: F) -> Column
+where
+    F: FnOnce(Vec<Column>) -> Column,
+{
+    todo!()
+}
+
+pub fn rand_with_seed(seed: i64) -> Column {
+    todo!()
+}
+"""
+
+TABLES = {
+    "skip": {"count_distinct"},
+    "dispatch_only": {"count_distinct"},
+    "optional_arg_variants": {
+        "round": ["round_scale"],
+        "instr": ["instr_with_start", "instr_with_start_and_occurrence"],
+    },
+    "head_rest_arms": {"count_distinct": "count_distinct_columns"},
+    "not_dispatched": {"transform": "closure", "rand_with_seed": "i64 seed"},
+    "section_overrides": {"concat_ws": "single"},
+    "order_as": {},
+}
+
+
+def plan(src=RUST, **overrides):
+    return gen.plan_dispatch(gen.parse_rust_functions(src), **{**TABLES, 
**overrides})
+
+
+def arm_text(arms, name):
+    (arm,) = [a for a in arms if a["name"] == name]
+    return "\n".join(line.strip() for line in gen.render_arm(arm))
+
+
+class ParseTests(unittest.TestCase):
+    def test_parses_generics_raw_identifiers_and_multiline_parameters(self):
+        functions = gen.parse_rust_functions(RUST)
+        self.assertNotIn("broadcast", functions)  # Returns a DataFrame.
+        # The function after a non-Column one is not swallowed into its 
signature.
+        self.assertEqual(functions["cume_dist"]["params"], [])
+        self.assertEqual(functions["struct"]["full_name"], "r#struct")
+        self.assertEqual(functions["struct"]["generics"], "C: Into<Column>")
+        self.assertEqual(
+            [p["name"] for p in 
functions["instr_with_start_and_occurrence"]["params"]],
+            ["col1", "col2", "start", "occurrence"],
+        )
+        self.assertEqual(functions["transform"]["params"][1], {"name": "f", 
"type": "F"})
+        self.assertEqual(
+            list(functions)[:3], ["cume_dist", "round", "round_scale"], "kept 
in source order"
+        )
+
+
+class PlanTests(unittest.TestCase):
+    def test_sections_then_source_order(self):
+        self.assertEqual(
+            [(a["name"], a["section"]) for a in plan()],
+            [
+                ("cume_dist", "no_args"),
+                ("round", "single"),
+                ("concat_ws", "single"),  # Variadic, moved by 
SECTION_OVERRIDES.
+                ("count_distinct", "single"),
+                ("struct", "variadic"),
+                ("instr", "multiple"),
+            ],
+        )
+
+    def test_optional_argument_picks_the_longer_function(self):
+        self.assertEqual(
+            arm_text(plan(), "round").splitlines()[2],
+            "if args.len() >= 2 { Ok(spark_funcs::round_scale(args[0].clone(), 
args[1].clone())) }"
+            " else { Ok(spark_funcs::round(args[0].clone())) }",
+        )
+
+    def test_several_optional_arguments_match_on_the_count(self):
+        self.assertEqual(
+            arm_text(plan(), "instr").splitlines()[2:7],
+            [
+                "match args.len() {",
+                "2 => Ok(spark_funcs::instr(args[0].clone(), 
args[1].clone())),",
+                "3 => Ok(spark_funcs::instr_with_start"
+                "(args[0].clone(), args[1].clone(), args[2].clone())),",
+                "_ => Ok(spark_funcs::instr_with_start_and_occurrence"
+                "(args[0].clone(), args[1].clone(), args[2].clone(), 
args[3].clone())),",
+                "}",
+            ],
+        )
+
+    def test_head_rest_and_variadic_arms(self):
+        arms = plan()
+        self.assertIn(
+            "Ok(spark_funcs::count_distinct_columns(args[0].clone(), 
args[1..].to_vec()))",
+            arm_text(arms, "count_distinct"),
+        )
+        self.assertEqual(
+            arm_text(arms, "struct"), '"struct" => 
Ok(spark_funcs::r#struct(args.clone())),'
+        )
+
+    def test_order_as_places_an_arm_at_another_function(self):
+        arms = plan(order_as={"concat_ws": "cume_dist"})
+        self.assertEqual([a["name"] for a in arms if a["section"] == 
"single"][0], "concat_ws")
+
+    def test_wrappers_are_the_arms_less_the_hand_written_plus_upstream(self):
+        names = gen.wrapper_names(plan(), skip=TABLES["skip"], 
upstream_extra={"sha2"})
+        self.assertEqual(names, ["concat_ws", "cume_dist", "instr", "round", 
"sha2", "struct"])
+
+    def test_unaccounted_signature_fails_instead_of_being_dropped(self):
+        with self.assertRaisesRegex(gen.GeneratorError, 
r"rand_with_seed\(seed: i64\)"):
+            plan(not_dispatched={"transform": "closure"})
+
+    def test_stale_or_ill_fitting_table_entries_fail(self):
+        cases = {
+            "names gone": {"not_dispatched": {**TABLES["not_dispatched"], 
"gone": "removed"}},
+            "must take 2 columns": {"optional_arg_variants": {"round": 
["instr_with_start"]}},
+            "not f\\(Column, columns\\)": {"head_rest_arms": 
{"count_distinct": "round_scale"}},
+            "not a variadic": {"section_overrides": {"round": "multiple"}},
+            "not in SKIP_FUNCTIONS": {"dispatch_only": {"count_distinct", 
"round"}},
+        }
+        for message, overrides in cases.items():
+            with self.subTest(message), 
self.assertRaisesRegex(gen.GeneratorError, message):
+                plan(**overrides)
+
+
+class CheckedInTests(unittest.TestCase):
+    """The checked-in Rust dispatch is what the generator writes."""
+
+    def test_dispatch_generated_rs_is_reproducible(self):
+        outputs = gen.generate(gen.REPO_ROOT, log=lambda *_: None)
+        self.assertEqual(list(outputs), [gen.DISPATCH_FILE])
+        self.assertEqual(
+            outputs[gen.DISPATCH_FILE],
+            (gen.REPO_ROOT / gen.DISPATCH_FILE).read_text(),
+            "run scripts/gen_fn_dispatch.py --check for the diff",
+        )
+
+    def test_check_reports_a_perturbed_file(self):
+        outputs = gen.generate(gen.REPO_ROOT, log=lambda *_: None)
+        with tempfile.TemporaryDirectory() as td:
+            root = Path(td)
+            target = root / gen.DISPATCH_FILE
+            target.parent.mkdir(parents=True)
+            target.write_text(outputs[gen.DISPATCH_FILE])
+            self.assertTrue(gen.check(root, outputs, log=lambda *_: None))
+
+            
target.write_text(outputs[gen.DISPATCH_FILE].replace("round_scale", "round", 1))
+            logged = []
+            self.assertFalse(gen.check(root, outputs, log=logged.append))
+            self.assertTrue(logged[0].startswith(f"DRIFT {gen.DISPATCH_FILE}"))
+            self.assertTrue(any(line.startswith("+") and "round_scale" in line 
for line in logged))
+
+
+if __name__ == "__main__":
+    unittest.main()


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to