The pyspark-pipeline template¶
The built-in template: a batch PySpark pipeline where pure, lazy DataFrame transformations are isolated from I/O, sessions and orchestration, so each piece is testable on its own. It follows the Palantir PySpark style guide, PEP 8 and the Zen of Python.
init answers¶
archvow init <package> -t pyspark-pipeline -d "<what it does>" -a architects=@<group> [-a <answer>=<value> ...]
| Answer | Default | Meaning |
|---|---|---|
architects |
required | code owners who approve spec and guard changes: @user or @group/subgroup, several separated by spaces |
language |
en |
language of the project's documents: en or fr (details) |
platform |
gitlab |
where the code lives: gitlab, github, none (code owners file, branch rules) |
ci |
auto |
what runs the checks and tests: auto (the platform's own), gitlab, github, jenkins, none |
ai_tools |
copilot |
approved AI assistants, comma-separated (AI assistants) |
scheduler |
none |
none (run entrypoint.sh from your own scheduler), airflow, oozie |
sonar |
no |
yes: sonar-project.properties and a SonarQube step in the CI |
dependencies |
none | approved third-party packages besides pyspark, py4j, pytest, hypothesis, as imported |
git_hooks |
githooks |
local checks before each commit: githooks (plain Git hook), pre-commit (local hooks only), none |
ci_image |
empty | internal CI image with Python, Java 17 and Git (empty: public python image + apt) |
pip_index_url |
empty | internal package index for the CI (empty: public PyPI) |
python_version |
3.11 |
minimum Python: 3.11, 3.12, 3.13 (at most the one the PySpark line runs on: 3.11 for 3.4, 3.12 for 3.5, 3.13 for 4.0) |
spark_version |
3.5 |
PySpark: 3.4, 3.5, 4.0 |
line_length |
88 |
79, 88, 99 |
Also: -t <template> (without it, python-app), -d "<description>" (default: the package
name), --no-git (do not create a Git repository). archvow init --help and
archvow catalog list them with their choices.
Layers¶
| Layer | Holds | May import | Never |
|---|---|---|---|
p0_common |
SparkSession factory, configuration, shared helpers | - | I/O, business logic |
p1_domain |
schemas, pure lazy transformations | p0_common |
read or write, Spark actions (collect, count, show...), a SparkSession; os, pathlib, subprocess, requests, pandas... |
p2_io |
readers and writers: the only place that touches storage | p0_common, p1_domain |
business transformations, subprocess |
p3_jobs |
jobs wiring readers, transformations, writers | p0_common, p1_domain, p2_io |
read or write directly |
p4_entrypoints |
command lines, exit codes | p0_common, p3_jobs |
pipeline logic |
Files live in src/<package>/<layer>/, tests in tests/<layer>/test_<component>.py. Many
components in a layer? -g <group> puts one in a folder of its layer:
archvow component add transformation clean_orders -g orders ... writes
p1_domain/orders/clean_orders.py (see Concepts).
Component types¶
| Type | File | Public API | Test | Questions |
|---|---|---|---|---|
schema |
p1_domain/<name>_schema.py |
<NAME>_SCHEMA: T.StructType |
unit | 2: nullable columns, personal data |
transformation |
p1_domain/<name>.py (name: verb_noun) |
<name>(df: DataFrame) -> DataFrame (overridable: --signature) |
unit | 9: rows kept, columns, grouping, join; empty input, null keys, duplicates, out-of-range values, extra columns |
reader |
p2_io/<name>_reader.py |
read_<name>(spark, path) -> DataFrame |
integration | 4 (kind files): missing path, bad records, one date or all, a shared library |
writer |
p2_io/<name>_writer.py |
write_<name>(df, path) -> None |
integration | 5 (kind files): existing output, partial writes, re-runs, format and folders, a shared library |
job |
p3_jobs/<name>_job.py |
run_<name>(spark, config: JobConfig) -> None |
integration | 3: missing input, retries, run date |
entrypoint |
p4_entrypoints/<name>_main.py |
main(argv=None) -> int |
unit | 2: invalid arguments, exit codes |
utility |
p0_common/<name>.py |
<name>() (overridable) |
unit | 1: invalid input |
Business examples (archvow example add, Concepts) go on job (the whole pipeline on small files, run with the integration tests: the default home of a ticket's examples), transformation (these rows in, these rows out), reader (a raw file, bad lines included, and the DataFrame and rejected rows it must give; integration, like its tests) and utility. Not on writer (the job's example and the "complete or absent" invariant cover it), schema or entrypoint.
init also creates three foundations in p0_common: spark (get_spark_session, the only
place a SparkSession is built), config (JobConfig, the immutable job configuration) and
logging_setup (setup_logging, called once by the entry point: one line per event on stderr,
which the cluster keeps; never a secret, a row or personal data), with their own questions.
The code logs through logging.getLogger(__name__), never print (ruff T20, except in the
entry points and the tests); only logging_setup configures logging (ARCH059), and never to a
file of its own (SPK001): on a cluster, a local file is lost with the
executor.
Readers and writers: -k, the way Spark reads and writes¶
A reader or a writer has a kind, given once with component add ... -k <kind> (default files).
Each kind has its own public function and its own questions; every kind ends with the same one:
does an approved shared library already do this? - if so, the code calls it instead of
rewriting it with Spark (the library is a package approved like any other: -a dependencies=).
| Kind | What Spark does | Reader | Writer | Its questions |
|---|---|---|---|---|
files |
format(...).load(path) / .save(path): parquet, orc, csv, json, text, avro, xml, binaryFile; local, hdfs, s3a, abfss, gs |
read_<name>(spark, path) |
write_<name>(df, path) |
missing path, bad records, one date or all; existing output, partial writes, re-runs, format |
table |
spark.table / insertInto: Hive metastore, Unity, Glue; Delta, Iceberg, Hudi |
(spark, table) |
(df, table) |
which table and which ddl/ script; which rows; append, replace or merge on keys; a changing schema; versions (Delta, Iceberg) |
jdbc |
spark.read.jdbc / df.write.jdbc |
(spark, url, query, properties) |
(df, url, table, properties) |
database and driver; where the password comes from; parallel slices and fetch size; new rows only; a database down; batch size and connections |
connector |
any other Spark connector: BigQuery, Snowflake, Redshift, Synapse, MongoDB, Cassandra, Elasticsearch, Kafka read in batch... | (spark, options) |
(df, options) |
connector, version and jar (from the internal repository, SPARK_ARGS --jars, never --packages); what the source does itself; credentials; staging area; quotas |
custom |
no Spark reader: a REST API, SFTP, a SaaS export, an in-house format - a Python data source (Spark 4.0), or calls on the driver or the executors | (spark, options) |
(df, options) |
paging; driver or executors; the token; limits, timeouts and retries; the source down; nothing sent twice on a re-run |
Credentials never go in the code, the spec or the command line: the questions ask where they come
from (the environment, a secret manager, a Kerberos keytab), and a suggested hazard for the
jdbc, connector and custom kinds is a password or a token appears in the code, the logs or
the command line. Streaming (readStream / writeStream) is not part of this batch template.
Rules¶
On top of archvow's generic rules, the template switches on the PySpark rules: I/O only in
p2_io (SPK001), no actions in p1_domain (SPK002), explicit how= on joins, no right joins,
standard imports (functions as F, types as T, Window as W), no backslash continuations,
limited method chains, explicit window frames... See Rules. Ruff enforces PEP 8,
docstrings, annotations, complexity and the security rules (S) through the generated
ruff.toml.
Tables¶
Tables exist before the job; the job never creates them. Their scripts are versioned in
ddl/NNN_<table>.sql, in Spark SQL, so they work with whatever catalog Spark uses (Hive
metastore, Iceberg, Delta):
-- ddl/001_orders_clean.sql
CREATE TABLE IF NOT EXISTS sales.orders_clean (id STRING, amount DOUBLE, day DATE)
USING parquet PARTITIONED BY (day);
-- later changes are additive, in a new script: ddl/002_orders_clean_currency.sql
-- ALTER TABLE sales.orders_clean ADD COLUMNS (currency STRING);
./entrypoint.sh --ddl (or make ddl) runs them in order with spark-sql; deployment or the
scheduler runs it before the job. Each writer's spec asks which table it writes and which
script creates it; its test runs the scripts on a local catalog and checks that the table and
the code's schema are the same. The writer selects the table's column order and uses
insertInto(table, overwrite=True) with dynamic partition overwrite - never saveAsTable on
an existing table.
Running and packaging¶
entrypoint.sh is the one script every environment runs:
./entrypoint.sh <entry point> <its arguments> # spark-submit, YARN, client mode
SPARK_MASTER="local[*]" ./entrypoint.sh <entry point> ... # on a laptop
./entrypoint.sh --ddl # the table scripts
./entrypoint.sh --package # dist/<package>-<version>-py3-none-any.whl and dist/ddl.zip
Settings by environment variable: SPARK_SUBMIT, SPARK_SQL, SPARK_MASTER (default
yarn), DEPLOY_MODE (client), PYTHON (python3, the one that builds the package),
SPARK_ARGS (extra options, e.g. "--num-executors 4"). The exit code is the entry point's.
The project's own settings and setup go in entrypoint.project.sh, next to it: entrypoint.sh reads
it first when it exists. archvow never writes it, so init --force keeps it, while it rewrites
entrypoint.sh at every upgrade - put nothing of your own there.
# entrypoint.project.sh - written by the team, committed
export SPARK_ARGS="--queue finance --num-executors 8"
export PYSPARK_PYTHON=/opt/python3.12/bin/python3
kinit -kt "$HOME/sales.keytab" sales@ACME.LOCAL
Trying it on a laptop. Once an entry point and everything it uses are coded, archvow next
(and archvow show <entry point>) ends with its run line, the arguments taken from the config
decision (input_path: str, no default = required -> --input-path <input_path>); a parameter typed secret
is never on the command line - the line names the environment variable it needs. Until then it
says what is missing:
✔ Try it locally: SPARK_MASTER="local[*]" ./entrypoint.sh daily_sales --input-path <input_path> --run-date <run_date>
! Not ready to run yet: daily_sales_main needs clean_sales (planned), revenue_writer (started)
The run line is only for a laptop. The deployment - YARN, Kubernetes (SPARK_MASTER=k8s://...,
DEPLOY_MODE=cluster), a serverless platform that takes the wheel - keeps its own settings, and
archvow never changes entrypoint.sh for it.
The wheel is the deployed artifact: versioned in pyproject.toml, published to your
package index or put in your RPM, shipped to the executors with --py-files. It builds offline
when the build tools are installed.
make |
Does |
|---|---|
make install |
the development tools (requirements.txt); then archvow doctor checks the setup |
make check |
what the Git hook runs: ruff check, ruff format --check, archvow check |
make test / make test-fast |
every test with coverage and the CI reports / unit tests only |
make package, make ddl |
./entrypoint.sh --package, --ddl |
make clean |
build and test leftovers |
Scheduling¶
-a scheduler= |
Adds | Runs |
|---|---|---|
none (default) |
nothing | your scheduler calls ./entrypoint.sh --ddl, then ./entrypoint.sh <entry point> ... |
airflow |
dags/<package>_dag.py |
two tasks, tables then run; plain Airflow, no provider. The DAG may import Airflow, the pipeline code may not |
oozie |
oozie/workflow.xml, coordinator.xml, job.properties |
a shell action for the tables, then a Spark action |
Company deployment files (RPM spec, Ansible...) are added by hand or by a company template.
Platforms and CI¶
-a ci= |
File | Runs |
|---|---|---|
auto |
the platform's own: .gitlab-ci.yml or .github/workflows/architecture.yml |
none with platform=none |
jenkins |
Jenkinsfile (Multibranch Pipeline) |
works with any platform; ARCHITECTURE_APPROVED=true (job parameter) accepts what the architects approved |
gitlab, github |
as auto, named explicitly |
only on that platform |
none |
no file | your CI runs archvow check, ruff, pytest, and check --base <target> on merge requests |
Every CI runs the guards (check, ruff), the tests with coverage.xml and
test-results.xml, and on merge requests check --base, the spec-changes report and the docs (archvow doc --base).
-a sonar=yes adds the SonarQube step (withSonarQubeEnv and the quality gate in Jenkins, a
sonarqube job with SONAR_HOST_URL and SONAR_TOKEN in GitLab, the scan action in GitHub).
archvow init my_pipeline -t pyspark-pipeline -a architects=@qa -a platform=gitlab -a ci=jenkins -a sonar=yes # GitLab + Jenkins + SonarQube
Critical projects: no external sources¶
archvow check makes no network call. The generated files can be just as closed:
archvow init my_pipeline -t pyspark-pipeline -a architects=@my-team \
-a ci_image=registry.acme.local/data/python-spark:3.12 \
-a pip_index_url=https://nexus.acme.local/repository/pypi/simple
The CI then uses your image (no Docker Hub, no apt) and your index (no PyPI); the default
githooks downloads nothing. Without them, init and the CI file name the public sources
used. Developer machines use the same index: pip config set global.index-url <url>.
What init writes¶
README.md the project README: the whole flow with its names (only if none)
requirements.txt development tools, archvow pinned like the CI (only if the project has no requirements file or pyproject.toml)
pyproject.toml the package, its version (the wheel deployed) and the test settings: strict
markers, `integration` and `invariant` (only if missing)
Makefile make install / check / test / package / ddl (only if missing)
entrypoint.sh runs an entry point, the table scripts, or builds the wheel
pytest.ini the test settings, only for a project that has its own pyproject.toml without them
ruff.toml PEP 8, Zen of Python, security (only if missing)
AGENTS.md rules for every AI assistant (+ one file per approved assistant)
.gitignore created, or completed without touching your lines
.githooks/pre-commit the local checks
.githooks/post-checkout a warning on a badly named branch (or no ticket pattern yet)
.gitlab/CODEOWNERS or .github/CODEOWNERS
.gitlab-ci.yml or .github/workflows/architecture.yml, or Jenkinsfile
sonar-project.properties with -a sonar=yes
dags/ or oozie/ with -a scheduler=airflow or oozie
.archvow/ the spec: project.vow, features/<feature>/{<feature>.vow, components/<component>.vow}, README.md
No source folder, no stub: the implementer creates exactly the files the specs name. A finished project then looks like:
src/my_pipeline/
├── p0_common/ spark.py config.py
├── p1_domain/ sales_schema.py clean_sales.py
├── p2_io/ sales_reader.py revenue_writer.py
├── p3_jobs/ my_pipeline_job.py
└── p4_entrypoints/ my_pipeline_main.py
tests/
├── p1_domain/ test_input_schema.py test_clean_input.py
├── p2_io/ test_input_reader.py test_output_writer.py
├── p3_jobs/ test_my_pipeline_job.py
├── p4_entrypoints/ test_my_pipeline_main.py
└── integration/ test_my_pipeline.py actuals/ expecteds/
ddl/ 001_<table>.sql
The example¶
The archvow repository holds my_pipeline - the walkthrough of archvow's README, a
little longer than Getting started - in examples/pyspark-pipeline/ (English documents): its spec - components,
decisions, every safety question answered, a brief and its business examples - every file init
writes, and the code with its tests: archvow check --complete, ruff and pytest pass, and
./entrypoint.sh my_pipeline --input-path ... --output-path ... runs it. The FastAPI template has
its own example (The finished example).