Scratch RecSys 04: Building `zapudataset` as a Flight Simulator for Recommendation Data Pipelines
Productizing the ZaPudia Data Pipeline. End-to-end guide on leveraging the `zapudataset` Python package with Kaggle API auto-ingestion, BigQuery GA4 blueprints, Polars/DuckDB execution, and containerized REST APIs.
1. Conceptual Hook
Airline pilots do not learn to fly in perfect sunshine. They spend hundreds of hours in simulators that recreate engine failures, wind shear, and broken instruments. The first time an emergency appears should never be the first time the pilot has seen one.
Recommendation systems face the same reality. A model trained on a clean academic benchmark, where every event arrives in order and every product has a category, will encounter production telemetry that looks nothing like its training data. Events arrive late. Bots generate clicks faster than any human could. Catalog metadata disappears during vendor migrations. New products enter the store with zero interaction history. This mismatch between clean training data and messy serving data is called training-serving skew, and it is one of the most expensive failure modes in applied machine learning.
The common response is to clean the data even harder. That is the wrong direction. A model that has never seen a dropped cart event will not learn to rely on secondary signals such as dwell time or session context when the primary signal disappears. A model that has never seen bot traffic will treat a flood of sub-10-millisecond clicks as genuine demand. Clean data does not prepare a model for production. It hides production from the model.
In Part 3, we formulated the mathematical foundations and data-engineering principles required to eliminate training-serving skew in recommendation systems. We proved that hyper-clean academic benchmarks actively sabotage real-world recommendation performance, and we outlined the architecture for injecting five deterministic telemetry failure modes—telemetry drops, bot floods, out-of-order timestamps, schema degradation, and cold-start catalog rot.
zapudataset is the flight simulator for data pipelines. It ingests raw e-commerce telemetry from Kaggle, Google Analytics 4 BigQuery exports, and synthetic event streams. It applies controlled, seeded noise that mimics the five failure modes observed in real systems. It exports model-ready Parquet artifacts with implicit scores, normalized ratings, and confidence weights. The goal is not to make data dirty for its own sake. The goal is to make the training environment as unforgiving as the serving environment, deterministically, reproducibly, and at single-node speed.
2. Intuition and Architecture Diagram
The package follows a deliberately simple data flow. Raw events enter from three source adapters, pass through a dual-engine analytical core, and exit as curated artifacts or as a REST-triggered pipeline job.
DuckDB handles the heavy out-of-core work. It reads Parquet directly from disk, pushes filters and aggregations into SQL, and spills to disk when memory fills. A 50 GB event table does not need to fit in RAM. DuckDB processes it in bounded memory and hands a much smaller projection to the next stage .
Polars handles the low-latency columnar math. Once DuckDB has reduced the data to a manageable size, Polars takes over for categorical encoding, timestamp jitter, bot-traffic injection, schema degradation, and implicit-score construction. Polars uses all available CPU cores and operates on Arrow-backed columns, so the handoff from DuckDB to Polars is a zero-copy transition rather than a serialization bottleneck .
This dual-engine design is the architectural bet. Most production data synthesis workloads fit on a single powerful node. A single node running DuckDB and Polars is often faster and dramatically cheaper than a distributed Spark cluster for the same job. The package does not pretend to replace Spark at petabyte scale. It replaces Spark for the 10 to 500 GB range where most recommendation teams actually operate.
3. Minimal Reproducible Example
To see the full transformation without installing anything, start with a five-row raw interaction table. It contains the minimum columns needed for implicit-feedback modeling.
| user_id | product_id | event_type | timestamp | dwell_time_ms |
|---|---|---|---|---|
| U1 | P1 | view | 2026-10-01 10:00:00 | 1200 |
| U1 | P1 | cart | 2026-10-01 10:00:05 | 800 |
| U1 | P1 | purchase | 2026-10-01 10:00:12 | 0 |
| U2 | P2 | view | 2026-10-01 10:01:00 | 95000 |
| U3 | P3 | view | 2026-10-01 10:02:00 | 8 |
Step 1. Timestamp jitter. An exponential delay with mean 2 seconds simulates out-of-order event arrival. The purchase event may now appear before the cart event in the raw stream, even though the logical sequence is unchanged.
Step 2. Bot traffic. The fifth row has an 8 ms dwell time, which is physically implausible for a human view. The injector flags or resamples sub-10 ms events at a configured bot ratio, preventing the model from treating machine-speed clicks as genuine interest.
Step 3. Schema degradation. Null out 25% of category and brand fields to simulate a catalog migration. The model must learn to rely on product ID embeddings and price when metadata is missing.
Step 4. Implicit scoring. Convert event counts and dwell time into a continuous relevance score:
For U1 and P1, the raw score is approximately 14.25: one view (1.0), one cart (3.0), one purchase (5.0), plus a dwell contribution of roughly 5.25 from the view and cart dwell times.
Step 5. Normalization and confidence. Min-max normalize the raw score to the range to produce , then compute the Hu-Koren-Volinsky confidence weight:
The output matrix below is what the model actually consumes.
| user_id | product_id | implicit_score | normalized_rating () | confidence () |
|---|---|---|---|---|
| U1 | P1 | 14.25 | 3.82 | 153.80 |
| U1 | P2 | 1.00 | 1.00 | 41.00 |
| U2 | P3 | 22.80 | 5.00 | 201.00 |
| U3 | P1 | 4.50 | 1.70 | 69.00 |
The confidence column is not cosmetic. It tells the matrix-factorization model how much to trust each observed interaction. A single view with low dwell time receives a confidence near 41. A multi-event purchase path with sustained dwell time receives a confidence above 150. The model learns that not all positives are equally informative.
4. Comparison Matrix
Three approaches dominate production data synthesis today. They are not interchangeable. Each fits a different scale and team shape.
| Dimension | Conventional Pandas / Python scripts | Distributed Spark pipelines | zapudataset (DuckDB + Polars + noise injection) |
|---|---|---|---|
| Pros | Maximum flexibility. Enormous ecosystem. Easy to prototype. Every data scientist already knows it. | Horizontal scale to petabytes. Fault tolerance. Mature cluster tooling. Handles multi-tenant batch workloads. | Single-node out-of-core processing. Built-in deterministic noise injection. Seeded reproducibility. REST API and Docker deployment. No cluster to operate. |
| Cons | Memory-bound. Slows sharply above a few GB. Manual orchestration. Noise injection is hand-rolled and often not reproducible. | Cluster overhead dominates for small and medium jobs. Expensive. Operational complexity. Overkill for sub-100 GB datasets. | Newer ecosystem. Single-node ceiling (though DuckDB spills to disk). Requires learning the package API. Not a replacement for multi-node Spark at extreme scale. |
| Memory and time complexity | memory, often 5 to 10 times the raw data size. time with Python interpreter overhead. | distributed memory across executors. compute plus shuffle and network overhead. | DuckDB: bounded memory via out-of-core spill. Polars: in-memory on the reduced projection, multi-threaded near-linear scaling. |
| Primary use case | Prototyping and exploratory analysis under roughly 1 GB. | Petabyte-scale batch ETL across a managed cluster. | 10 to 500 GB production data synthesis. Reproducible ML benchmarks. Single-node MLOps pipelines. |
The practical takeaway is simple. If the team already operates a Spark cluster and the data is measured in terabytes, Spark remains the right tool. If the team is spending weeks hand-rolling ingestion and noise scripts for a 50 GB event log on a single workstation, zapudataset collapses that work into a configuration file and a single orchestrator call.
5. Code Implementation
Data engineers can instantiate PipelineOrchestrator to execute the full data synthesis lifecycle and the package exposes three levels of control. First, a high-level orchestrator for the full pipeline, a direct noise injector for custom experiments, and a REST service for containerized deployment. The code below comes directly from the dataset_builder.py file in the repository.
5.1 The Core Pipeline: build_dataset from dataset_builder.py
The build_dataset function wires extractors, noise injectors, implicit builders, feature encoders, train/test splitting, and partitioned Parquet exports into a single callable pipeline . It returns a manifest dictionary so every downstream job knows exactly which artifacts were produced and under which noise configuration.
def build_dataset(
nlimit: int = 5_000_000,
kaggle_dataset_ids: list[str] | None = None,
) -> dict[str, Any]:
start_time = datetime.now()
cfg = deepcopy(configure)
seed = cfg["pipeline"]["seed"]
out_dir = Path(cfg["pipeline"]["output_dir"])
# 0. Auto download raw datasets and get verified filepaths
source_paths = _auto_download_sources(cfg, kaggle_dataset_ids=kaggle_dataset_ids)
# 1. Extract and harmonize Kaggle sources
behavior = load_kaggle_behavior(
str(source_paths["behavior"]),
cfg["sources"]["kaggle_behavior"]["event_type_map"],
)
orders = load_kaggle_orders(str(source_paths["orders"]))
events = (
pl.concat([behavior, orders], how="vertical_relaxed")
.filter(pl.col("user_session").hash(seed=seed).mod(100) < 10)
.limit(nlimit)
.collect(engine="streaming")
)
events = ensure_nonempty_events(events, cfg)
# 2. Augment with GA4 telemetry
events = simulate_ga4_events(events, config=cfg)
# 3. Noise injection
nz = cfg["noise"]
ncfg = NoiseConfig(
telemetry_drop_rate=nz["telemetry_drop_rate"],
bot_fraction=nz["bot_fraction"],
bot_lambda_per_sec=nz["bot_lambda_per_sec"],
bot_interarrival_min_ms=nz["bot_interarrival_min_ms"],
bot_interarrival_max_ms=nz["bot_interarrival_max_ms"],
oo_lambda_per_sec=nz["oo_lambda_per_sec"],
schema_null_rate=nz["schema_null_rate"],
cold_start_rate=nz["cold_start_rate"],
seed=seed,
)
corrupted, cold_items, null_items = inject_all(
events, ncfg, cfg["geo_provinces"]
)
# 4. Train and test split
min_int = cfg["split"]["min_user_interactions"]
user_counts = (
corrupted.group_by(pl.col("user_id"))
.agg(pl.len().alias("n"))
.filter(pl.col("n") >= min_int)
)
eligible = user_counts["user_id"]
n_test = int(cfg["split"]["test_fraction"] * eligible.len())
test_users = set(
eligible.sample(n=n_test, seed=seed).to_list()
)
train = corrupted.filter(~pl.col("user_id").is_in(list(test_users)))
test = corrupted.filter(pl.col("user_id").is_in(list(test_users)))
# 5. Implicit matrix via DuckDB
weights = cfg["implicit_weights"]
imp_cfg = cfg["implicit_normalization"]
implicit_path = write_implicit_matrix(
out_dir / "train_interactions.parquet",
out_dir / "implicit_matrix.parquet",
weights,
norm_min=imp_cfg["min_rating"],
norm_max=imp_cfg["max_rating"],
)
# 6. Feature Parquet exports
full_cat = pl.concat([train, test], how="diagonal_relaxed")
item_path, item_maps = build_item_features(
full_cat, cold_items, out_dir / "item_features.parquet"
)
user_path, user_maps = build_user_features(
train, out_dir / "user_features.parquet"
)
# 7. Manifest
manifest = {
"pipeline": cfg["pipeline"],
"n_events_raw": int(events.height),
"n_events_train": int(train.height),
"n_events_test": int(test.height),
"n_cold_items": len(cold_items),
"n_null_items": len(null_items),
"n_users_train": int(train["user_id"].n_unique()),
"n_users_test": int(test["user_id"].n_unique()),
"n_items_catalog": int(full_cat["item_id"].n_unique()),
"outputs": {
"train_interactions": str(train_path),
"test_interactions": str(test_path),
"item_features": str(item_path),
"user_features": str(user_path),
"implicit_matrix": str(implicit_path),
},
"noise_config": asdict(ncfg),
"built_at": datetime.now(timezone.utc).isoformat(),
}
manifest_path = out_dir / "build_manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2))
return manifest
Every random operation is seeded from the configuration. Two runs with the same YAML file produce byte-identical Parquet outputs. That property is the foundation of reproducible offline benchmarking .
5.2 The Python SDK Interface: DatasetBuilder Facade
For teams that prefer an object-oriented interface, the DatasetBuilder class wraps build_dataset with a backward-compatible facade .
class DatasetBuilder:
"""Backward-compatible facade around build_dataset."""
def __init__(
self,
config_path: str | Path = "src/zapudataset/configs/pipeconf.yaml",
kaggle_dataset_ids: list[str] | None = None,
) -> None:
self.config_path = config_path
self.kaggle_dataset_ids = kaggle_dataset_ids
def build(
self,
nlimit: int = 5_000_000,
kaggle_dataset_ids: list[str] | None = None,
) -> dict[str, Any]:
ds_ids = (
kaggle_dataset_ids
if kaggle_dataset_ids is not None
else self.kaggle_dataset_ids
)
return build_dataset(nlimit=nlimit, kaggle_dataset_ids=ds_ids)
def run(
self,
nlimit: int = 5_000_000,
kaggle_dataset_ids: list[str] | None = None,
) -> dict[str, Any]:
return self.build(nlimit=nlimit, kaggle_dataset_ids=kaggle_dataset_ids)
A complete run from Python looks like this:
from zapudataset.dataset_builder import DatasetBuilder
builder = DatasetBuilder(kaggle_dataset_ids=["kgurl-01", "kgurl-02"])
manifest = builder.run(nlimit=2_000_000)
print(f"Train rows: {manifest['n_events_train']:,}")
print(f"Test rows: {manifest['n_events_test']:,}")
print(f"Cold items: {manifest['n_cold_items']}")
print(f"Manifest: build_manifest.json")
5.3 The SQL Blueprint: Flattening GA4 Nested Events
BigQuery GA4 exports store events in nested items arrays and repeatable event_params structures. The package ships a SQL blueprint that flattens these structures into a single tabular event stream. The excerpt below comes from the ga4_obfuscated_sample_ecommerce.sql blueprint in the repository .
-- Excerpt from zapudataset/blueprint/ga4_obfuscated_sample_ecommerce.sql
SELECT
TIMESTAMP_MICROS(event_timestamp) AS event_time,
LOWER(event_name) AS raw_event_type,
user_id,
user_pseudo_id,
item.item_id AS product_id,
item.item_category AS category_code,
item.item_brand AS brand,
COALESCE(item.price_in_usd * 15500, 0.0) AS price,
(SELECT value.string_value
FROM UNNEST(event_params)
WHERE key = 'ga_session_id') AS user_session,
COALESCE(engagement_time_msec, 0) AS engagement_time_msec,
device.category AS device_category,
geo.province AS geo_province
FROM
`bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,
UNNEST(items) AS item
WHERE
_TABLE_SUFFIX BETWEEN '20201101' AND '20210131'
AND event_name IN (
'page_view', 'select_item', 'add_to_cart',
'begin_checkout', 'purchase'
);
The UNNEST(items) clause turns one row per event into one row per purchased or viewed item. The correlated subquery on event_params extracts the session identifier without requiring a separate join. The COALESCE on price applies a fixed FX normalization to Indonesian Rupiah and defaults missing prices to zero. The result is a flat, typed, and partition-filtered event stream that DuckDB and Polars can consume directly.
5.4 Fine-Grained Noise Injection on Any Polars DataFrame
When the goal is a controlled ablation, such as measuring model sensitivity to metadata loss versus bot traffic, AnomalyInjector can be applied stage by stage on any Polars DataFrame .
import polars as pl
from zapudataset.noise import AnomalyInjector
df = pl.read_parquet("./data/staging/unified_events.parquet")
injector = AnomalyInjector(seed=2026)
# Apply each failure mode independently and in a deterministic order.
df = injector.inject_schema_degradation(df, null_rate=0.25)
df = injector.inject_timestamp_jitter(df, lambda_param=0.5)
df = injector.inject_telemetry_drops(df, drop_rate=0.08)
df = injector.inject_bot_traffic(df, bot_ratio=0.05)
df.write_parquet("./data/curated/ablated_events.parquet")
Because each injector is a pure columnar transformation, the sequence is explicit and auditable. A reviewer can read the four lines and know exactly which failure modes were applied and at what rates. That transparency is what separates reproducible science from ad-hoc data wrangling.
5.5 Package Architecture & Modular Design
Building an enterprise-ready data synthesis engine requires strict separation of concerns. zapudataset is structured as a decoupled, modular Python library where every component—from raw SQL extraction to mathematical noise injection—operates independently.
zapudataset/
├── api/ # FastAPI REST endpoints & HTTP routing
│ ├── api_server.py # Server initialization & ASGI application
│ ├── apimod.py # Request/Response Pydantic models
│ └── routes.py # Pipeline execution & status endpoints
├── blueprint/ # Pre-built, production-tested BigQuery SQL templates
│ ├── ga4_obfuscated_sample_ecommerce.sql
│ ├── thelook_ecommerce.sql
│ └── google_analytics_sample.sql
├── configs/ # Schema and environment management
│ ├── confreader.py # YAML configuration parser
│ ├── pipeconf.yaml # Central pipeline parameters & noise thresholds
│ └── schemaread.py # Schema validation and type coercion rules
├── extractors/ # Multi-source data ingestion handlers
│ ├── bigquery_connect.py # Cloud BigQuery client wrapper
│ ├── ga4_stream_simulator.py # Live telemetry event stream synthesizer
│ ├── kaggle_loader.py # Kaggle API downloader and dataset untar/unzip
│ └── kaggle_setup.py # Kaggle credential validation & setup
├── noise/ # Mathematical anomaly & telemetry flaw injection
│ └── anomaly_injector.py # Vectorized noise injection algorithms
├── pipeline/ # Core execution orchestration
│ ├── generation.py # Synthetic feature synthesizer
│ ├── orchestrator.py # Multi-stage pipeline execution engine
│ └── stages.py # Individual pipeline stage runners
├── transformers/ # High-performance analytical transforms
│ ├── feature_encoder.py # Categorical ordinal mapping & persistence
│ └── implicit_builder.py # Logarithmic implicit rating calculation
└── dataset_builder.py # Top-level entry point and builder interface
5.6 Google Colab Execution Log
Executing !uv run -m src.zapudataset.dataset_builder inside Google Colab validates the entire data synthesis pipeline end-to-end within a single cloud workstation[cite: 2, 3]. The process begins by downloading raw Kaggle e-commerce datasets and converting large CSV logs into Parquet format using parallel worker threads[cite: 2]. Next, the engine concatenates these sources into a unified stream of 7,000,000 raw events representing over 1.4 million unique user sessions[cite: 2]. The pipeline then simulates GA4 telemetry events to replicate real-world analytics streams before passing the data into the noise injection stage[cite: 2]. During noise injection, the system deliberately corrupts events, producing 21,925 cold-start items and 36,494 null metadata entries to simulate operational failures[cite: 2]. The orchestrator filters active users and performs a temporal split, separating 5.18 million training rows from 717,000 evaluation rows[cite: 2]. DuckDB then processes the implicit feedback matrix in just 2.61 seconds using memory-efficient out-of-core execution[cite: 2]. Finally, the entire pipeline completes in 586.70 seconds, proving that complex data synthesis runs reliably on a single node[cite: 2].
5.7 Output Artifacts and Storage Footprint
Upon pipeline completion, dataset_builder exports all processed datasets, feature tables, and metadata files directly into the /content/Zapudia/data/processed/ directory[cite: 3]. The core interaction logs form the main storage footprint, with train_interactions.parquet taking 139 MB and test_interactions.parquet taking 16.9 MB in compressed columnar format[cite: 3]. DuckDB saves the continuous ratings and confidence weights inside implicit_matrix.parquet, which occupies 32.1 MB[cite: 3]. User and item feature tables are saved as separate Parquet files totaling under 6.5 MB, keeping behavioral events decoupled from metadata[cite: 3]. JSON encoder files preserve categorical ID mappings so downstream models can decode features during inference[cite: 3]. Ground-truth tracking files like cold_items.json and null_items.json record missing metadata and unseen products for specialized model evaluation[cite: 3]. Lastly, build_manifest.json logs row counts, runtime parameters, and random seeds to ensure full experiment reproducibility[cite: 3]. This organized output structure allows machine learning models to consume clean, partitioned artifacts directly from disk[cite: 3].
| File Name | Size (KB) | Description |
|---|---|---|
train_interactions.parquet | 139,000.40 | Primary training dataset containing 5.18M corrupted interaction records[cite: 3]. |
implicit_matrix.parquet | 32,165.56 | DuckDB-calculated continuous ratings () and confidence weights ()[cite: 3]. |
test_interactions.parquet | 16,906.77 | Evaluation dataset containing 717K interaction records[cite: 3]. |
user_features.parquet | 4,561.58 | Aggregated behavioral user features[cite: 3]. |
item_features.parquet | 1,777.88 | Item catalog features containing injected metadata degradation[cite: 3]. |
null_items.json & cold_items.json | 675.79 | Ground-truth tracking lists for cold-start and null-attribute items[cite: 3]. |
item_features.encoders.json | 77.71 | Categorical mapping definitions for item feature encoders[cite: 3]. |
user_features.encoders.json | 0.06 | Categorical mapping definitions for user feature encoders[cite: 3]. |
build_manifest.json | 1.09 | Full pipeline configuration, row counts, and seed parameters for reproducibility[cite: 3]. |
6. Key Takeaways and References
Key takeaways
- Clean benchmarks are not neutral. They are actively misleading. A model that has never seen telemetry drops, bot floods, or missing metadata will overfit to signals that disappear in production. Noise injection is not data corruption. It is environment matching.
- Reproducibility is a first-class feature, not an afterthought. Seeded injectors and deterministic orchestration mean every benchmark run can be replayed byte-for-byte. This is what makes offline NDCG and MAP comparisons scientifically valid.
- The dual-engine design removes the cluster tax. DuckDB handles out-of-core SQL on raw Parquet. Polars handles vectorized in-memory math on the reduced projection. For the 10 to 500 GB range, this is faster and dramatically cheaper than operating a Spark cluster.
- The package collapses weeks of plumbing into a single call. Ingestion, schema harmonization, five noise modes, implicit scoring, confidence weighting, and temporal splitting are all encapsulated behind
build_dataset()or a REST endpoint. - Confidence weights make implicit feedback learnable. The formulation distinguishes a casual view from a high-intent purchase path, preventing the model from treating all positives as equally strong evidence.
References
- Hu, Y., Koren, Y., and Volinsky, C. (2008). Collaborative Filtering for Implicit Feedback Datasets. IEEE International Conference on Data Mining, 263 to 272. The foundational paper for confidence-weighted implicit matrix factorization.
- Google Analytics 4 BigQuery Export schema. Google Analytics Help. Documents the nested
itemsand repeatableevent_paramsstructures that the package’s GA4 blueprint flattens. - DuckDB documentation and Polars benchmarking resources. DuckDB’s out-of-core execution model and Polars’ multi-threaded columnar engine are the basis for the single-node performance claims.
zapudatasetsource repository, release v0.1.2. AryDataLabs/002_ZaPudia_data_architect. The reference implementation for the architecture, noise injectors, and REST service described in this article.
Disclosure
Zapudataset package is in the experiment. I (Aryanto) designed the zapudataset architecture, wrote the core Python package, and implemented the data pipeline. An AI assistant (ChatGPT) was used to assist with drafting the MDX formatting, generating the React Flow diagram components, and refining the technical explanations. All code implementation, repository testing, and benchmark execution were done by me.
I designed the benchmark and I ran it myself. I did not receive payment, credits, or early access from any company named here (including DuckDB, Polars, Google Cloud, or Kaggle). I used free tiers and open-source libraries only. The only data is my single implementation and its resulting artifacts. No other developers took part, and I do not combine the results into one score.
All diagrams in this article, including the ASCII architecture and the React Flow interactive canvas, were designed by the author and implemented in collaboration with the AI assistant. The featured image was generated and hosted via the author’s Cloudinary account.
Written By
I’m Aryanto, a Principle Data Scientist and Sr. MLOps Engineer specializing in scalable data pipelines, recommendation systems, AI engineering and enterprise data architectures. I am the author of the Scratch RecSys series, where I build production-grade AI/ML infrastructure from the ground up.