PySparky Engineering Handbook
Production PySpark work depends on more than transformation code. The driver, executors, Python environment, Spark and connector versions, data contract, catalog, and operational policies must agree. Use this handbook as a review guide, then follow the owning platform's runbooks and each library's versioned documentation for concrete settings.
The runnable example targets CPython 3.11.18, PySpark 3.5.8, and Eclipse Temurin 17.0.21.1+2, the tuple used for this site's local example checks. It is not a compatibility promise for every PySparky repository or production platform. Check the target repository's CI matrix and the cluster vendor's support policy before selecting a deployment tuple.
1. Define the data contract
Write down the input schema, required fields, business keys, duplicate policy, null and malformed-value behavior, timestamp timezone, and expected output before choosing transformations. A schema alone does not enforce every business invariant. For each rule, decide whether a failing row should stop the job, be quarantined, or be reported for later review.
Keep reusable checks as lazy DataFrame expressions. Put actions that evaluate
those checks at an explicit job boundary, where the caller can record the
result and decide whether processing should continue. This makes the cost and
failure behavior visible. count, first, collect, writes, and similar
actions can start Spark work; use driver collection only for a known bounded
result.
The following example uses four synthetic rows, an explicit schema, native expressions, and one aggregation action that returns a single summary row. Duplicate-key count means the number of rows belonging to a repeated, non-null key; a null key is reported separately. In production, choose and document the response to each nonzero count.
from pyspark.sql import SparkSession, Window, functions as F, types as T
schema = T.StructType(
[
T.StructField("event_id", T.LongType(), nullable=True),
T.StructField("amount", T.DoubleType(), nullable=True),
]
)
rows = [
(1, 10.0),
(1, None),
(None, 8.0),
(3, -2.0),
]
spark = (
SparkSession.builder.master("local[1]")
.appName("pysparky-production-data-contract")
.config("spark.ui.enabled", "false")
.getOrCreate()
)
try:
source = spark.createDataFrame(rows, schema)
duplicate_key = F.col("event_id").isNotNull() & (
F.count(F.lit(1)).over(Window.partitionBy("event_id")) > 1
)
checked = source.withColumn("is_duplicate_key", duplicate_key)
summary = checked.agg(
F.count(F.when(F.col("event_id").isNull(), 1)).alias("missing_ids"),
F.count(F.when(F.col("amount").isNull(), 1)).alias("missing_amounts"),
F.count(F.when(F.col("amount") < F.lit(0.0), 1)).alias("negative_amounts"),
F.count(F.when(F.col("is_duplicate_key"), 1)).alias("duplicate_key_rows"),
).first() # one explicit action; the aggregate result is one row
actual = (
summary.missing_ids,
summary.missing_amounts,
summary.negative_amounts,
summary.duplicate_key_rows,
)
assert actual == (1, 1, 1, 2)
print(f"quality counts: {actual}")
finally:
spark.stop()
This example reports counts; it does not silently filter or write failing rows. A production job can use the same explicit boundary to emit metrics, write a separately governed quarantine dataset, or raise an error according to its contract. See the Data Quality source documentation for the independently maintained, source-only validation API. The repository has no published package release yet, so this guide does not give an install command for it.
2. Deploy with a matched runtime
Record the versions used by the driver and workers: Python, Spark/PySpark, Java, and any connector or storage runtime. Keep the tuple aligned with the owning project's tested CI matrix and the cluster's supported versions. CI passing on one tuple verifies that tuple's tests; it does not certify a separate managed platform.
Use the target platform's spark-submit path or managed submission API to
set the entry point, cluster manager, deploy mode, and deploy-time settings.
Properties such as driver memory may need to be set before the driver starts;
Spark documents which configuration belongs on the submission command or in
the properties file. Keep credentials in the platform's secret mechanism,
and do not put secrets in source control, command history, Spark properties
that appear in logs, or diagnostic output.
Make application code and every required Python dependency available in the
environment where they are imported. Spark 3.5.8's --py-files mechanism
distributes .py, .zip, and .egg files. It does not distribute wheel
dependencies or packages with native code. For those dependencies, provision
a compatible Python environment on the cluster or use a packaging mechanism
supported by the selected Spark distribution and cluster manager. Confirm the
driver and executor environments match; an import working only on the
submission host is not enough.
Keep a deployable artifact identifiable by repository, version, and source revision. Pass non-secret environment-specific settings at submission time, not by forking code per environment. Define the output commit or overwrite behavior so that rerunning a failed application is safe or has a documented recovery procedure.
3. Operate Iceberg tables deliberately
Iceberg behavior depends on the configured catalog, Spark/Iceberg runtime artifacts, storage, and permissions. Configure the catalog by name and test the exact connector and Spark versions together. Treat production catalog configuration and credentials as platform operations, not library defaults.
Before maintenance, identify the table owner and write schedule, review the current snapshots and retention requirements, and coordinate concurrent writers. Snapshot expiration removes history older than the chosen retention boundary and data files that are no longer required by retained snapshots. Orphan-file cleanup can physically delete storage objects that are not tracked by table metadata. Set its age threshold beyond the maximum expected duration of in-progress writes and account for clock skew and recovery needs. Confirm the target catalog, namespace, table, procedure arguments, and expected file scope before running a destructive operation. Use a staging catalog or an approved dry-run workflow where the platform supports it; keep the resulting maintenance logs and review outcome.
The PySparky pyiceberg-maintenance source repository
generates Spark SQL CALL text and has unit and Spark-parser checks for its
literal and identifier handling. It does not connect to a catalog, check
permissions, choose retention, or execute statements. Read its
SQL safety notes and verified examples
and verify the procedure arguments against the Iceberg version actually
installed on the cluster. Generated SQL is still an operation request: review
it before execution.
4. Keep dependencies and licences reviewable
Use the repository's pinned mise.toml for developer runtimes and tools, and
uv.lock with uv sync --locked to reproduce its Python environment. Keep
runtime dependencies separate from build, lint, and test groups. Do not add
PySpark as a mandatory package dependency when the cluster supplies it; add an
optional extra only when the package's documented local workflow needs one.
Update the lockfile deliberately, review the dependency diff, and test the
built wheel from a clean environment as well as the source checkout.
For each release, verify that LICENSE, README scope, package metadata,
source archive, wheel, provenance, and third-party notices describe the same
rights. New original PySparky code and documentation default to MIT where the
authors have the rights to license it. Keep existing grants such as CC0-1.0
and Apache-2.0 intact for reused or legacy files; a package metadata field
does not override an existing file-level license. Record upstream sources
and versions when any third-party material is included. See the site's
licensing policy and each repository's provenance
and notices before copying or redistributing content.
Before relying on a PySparky package, verify the owning repository's current release, published artifact, and PyPI publisher status. Use linked source documentation for review; a GitHub repository or PyPI organization profile alone does not establish package availability or package-name ownership.
5. Make operations observable and recoverable
Give each application a useful name and record the artifact version, input scope, configuration revision, application ID, and outcome. Monitor failed tasks, retries, skew, shuffle spill, executor loss, and output freshness in the Spark UI and platform metrics. Log row counts and rule results at an appropriate level, while excluding credentials, personal data, and unbounded row samples.
Retries are useful only when repeating the work is safe. Define how duplicate submissions, partial output, schema changes, and interrupted writes are handled before enabling automatic retries. Keep a runbook that names the owner, alert path, expected recovery point, and any table maintenance that must be paused during recovery. Test that procedure with synthetic data and the same storage/catalog class where possible; a local Spark run does not validate cloud credentials, cluster scheduling, or production storage behavior.
Production review checklist
- Confirm the exact Python, Java, Spark/PySpark, connector, and application versions against both CI evidence and platform support.
- Confirm dependencies are available to executors and native libraries match the worker environment.
- Review input schema, null and duplicate semantics, output behavior, and bounded action/report boundaries.
- Check catalog, permissions, retention, and recovery policies before any Iceberg maintenance procedure.
- Confirm secrets are supplied by the platform, logs are safe, and retries cannot silently duplicate or corrupt outputs.
- Verify the release artifact, licence scope, provenance, and rollback or recovery instructions before rollout.