Skip to content

Commit 97a773b

Browse files
authored
Merge pull request #5 from vidit-16/pipeline/postgres-spark-s3
Add a data pipeline: S3, Spark, PostgreSQL and Redshift
2 parents 287283d + 54c526b commit 97a773b

39 files changed

Lines changed: 3682 additions & 28 deletions

‎.dockerignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ data/raw/generated
1111
# The external dataset cache is 44 MB and downloads on demand.
1212
data/raw/external
1313

14+
# The pipeline's lake: a 96 MB raw CSV and Spark's output. The pipeline
15+
# service mounts ./data instead, and baking it in copied it into every image.
16+
data/lake
17+
1418
# Build outputs, not inputs.
1519
reports
1620
**/*.xlsx

‎.github/workflows/ci.yml‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,26 @@ jobs:
1919
# the floor was the only version anyone had ever run.
2020
python-version: ["3.12", "3.13"]
2121

22+
# The warehouse tests compare every query on PostgreSQL with SQLite. Without
23+
# a server they skip, so CI provides one rather than letting them pass by
24+
# not running.
25+
services:
26+
postgres:
27+
image: postgres:16
28+
env:
29+
POSTGRES_USER: rootsignal
30+
POSTGRES_PASSWORD: rootsignal
31+
POSTGRES_DB: rootsignal
32+
ports:
33+
- 5432:5432
34+
options: >-
35+
--health-cmd "pg_isready -U rootsignal"
36+
--health-interval 5s
37+
--health-retries 10
38+
39+
env:
40+
ROOTSIGNAL_WAREHOUSE_URL: postgresql://rootsignal:rootsignal@localhost:5432/rootsignal
41+
2242
steps:
2343
- name: Checkout repository
2444
uses: actions/checkout@v5
@@ -29,14 +49,21 @@ jobs:
2949
python-version: ${{ matrix.python-version }}
3050
cache: pip
3151

52+
# Spark runs on the JVM; the conform job's tests need one.
53+
- name: Set up Java
54+
uses: actions/setup-java@v5
55+
with:
56+
distribution: temurin
57+
java-version: "17"
58+
3259
- name: Install project and development dependencies
33-
run: python -m pip install -e ".[dev]"
60+
run: python -m pip install -e ".[dev,pipeline]"
3461

3562
- name: Generate controlled sample dataset
3663
run: python scripts/generate_sample_data.py --output-dir data/raw/generated
3764

3865
- name: Run test suite
39-
run: pytest
66+
run: pytest -rs
4067

4168
- name: Run Ruff checks
4269
run: ruff check .

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,6 @@ mutants/
4040
.vscode/
4141
.idea/
4242
.DS_Store
43+
44+
# The pipeline's local lake (rebuilt by scripts/run_pipeline.py)
45+
data/lake/

‎Dockerfile‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,19 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
2222

2323
WORKDIR /app
2424

25+
# Spark runs on the JVM. The conform job is tested in here, on Linux, which is
26+
# also what Glue and EMR run it on.
27+
RUN apt-get update \
28+
&& apt-get install -y --no-install-recommends openjdk-17-jre-headless \
29+
&& rm -rf /var/lib/apt/lists/*
30+
2531
# Dependencies are installed from pyproject.toml alone, against a placeholder
2632
# package, so that editing source code does not invalidate the layer holding
2733
# pandas, numpy and streamlit.
2834
COPY pyproject.toml README.md ./
2935
RUN mkdir -p src/rootsignal \
3036
&& touch src/rootsignal/__init__.py \
31-
&& pip install --no-cache-dir ".[dev,dashboard,ai]" \
37+
&& pip install --no-cache-dir ".[dev,dashboard,ai,pipeline]" \
3238
&& rm -rf src
3339

3440
COPY . .

‎README.md‎

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,10 @@ Reproduced by the committed test suite and evaluation scripts.
9393
| **Data quality** | **8 errors** detected across 10 raw tables; cleaning imputes 3 fields, drops 2 exact duplicates, quarantines 1 impossible line; **zero errors** after |
9494
| **Plan vs actual** | Attainment spans **87.4% to 125.6%** across 64 region/category/channel segments, evenly split 32 above plan and 32 below. KAM quota attainment runs **89.8% to 106.0%** across four managers, three ahead and one behind |
9595
| **Reproducibility** | Identical results on **numpy 1.26 under Windows and numpy 2.5 under Linux** — same signal, same impact to the cent, same forecast improvement. The container resolves the top of the declared dependency range rather than a lockfile, which is how the numpy 2.x break was found |
96-
| **Tests** | **316 automated tests**, passing on both dependency sets. One asserts that no output ever claims causation |
97-
| **Mutation testing** | `scripts/mutation_test.py` applies 37 operator and constant mutations to the KPI layer; the suite kills **34 (91.9%)**. The 3 survivors are equivalent mutants (`> 0` vs `>= 0` on a count that is never zero, or on a ratio where 0/0 is already NaN) |
96+
| **Data pipeline** | The same 1,067,371 lines landed in S3, conformed by a **PySpark** job, cleaned, and loaded into **PostgreSQL** (996,528 sales lines) and **Redshift Serverless** (996,531, loaded before stock codes were made case-insensitive). Spark's output is **identical to the pandas adapter's in all six tables**, compared column by column on the full dataset |
97+
| **Warehouse parity** | Every staging view and all seven analytical queries return the **same rows on PostgreSQL and Redshift as on SQLite**. The one tolerance is `aov`, which may differ by a cent on an exact half cent because the engines round ties differently |
98+
| **Tests** | **427 automated tests**, passing on both dependency sets. One asserts that no output ever claims causation |
99+
| **Mutation testing** | `scripts/mutation_test.py` applies 37 operator and constant mutations to the KPI layer; the suite kills **34 (91.9%)**. The 3 survivors are equivalent mutants (`> 0` vs `>= 0` on a count that is never zero, or on a ratio where 0/0 is already NaN). On the pipeline, `scripts/mutation_test_pipeline.py` applies **28 realistic bugs** (Spark's rounding, a lost CSV option, a dropped tie-breaker, a spending cap that only logs) and the suite catches **all 28**, up from 22 before the gaps it found were tested. Operator mutants on the pipeline code: **93 of 108** caught; the 15 survivors are wait times, output file counts and print formatting |
98100

99101
**On that false-alarm figure.** The 12 counts every signal that matched nothing
100102
planted, wherever it was raised: 9 on the two control windows and 3 alongside
@@ -119,6 +121,13 @@ Or don't, and check the claims instead:
119121
docker build -t rootsignal . && docker run --rm rootsignal pytest
120122
```
121123

124+
Or run the whole pipeline on the real dataset, from download to warehouse:
125+
126+
```bash
127+
docker compose up -d warehouse
128+
docker compose run --rm pipeline # land, conform in Spark, load, publish
129+
```
130+
122131
Then, in rough order of what is worth seeing first:
123132

124133
```bash
@@ -182,9 +191,35 @@ Evidence package — evidence, pattern, impact, confidence criteria, alternati
182191
Recommended investigation
183192
```
184193

185-
**Stack:** Python, pandas, NumPy, SQL (SQLite/PostgreSQL), Streamlit, Plotly,
186-
pytest, GitHub Actions, and an optional OpenAI-compatible LLM that the system
187-
works fully without. Power BI is deliberately out of scope.
194+
**Stack:** Python, pandas, NumPy, PySpark, SQL (SQLite, PostgreSQL, Amazon
195+
Redshift), AWS S3, Streamlit, Plotly, Power BI, pytest, Docker, GitHub Actions,
196+
and an optional OpenAI-compatible LLM that the system works fully without.
197+
198+
### Data pipeline
199+
200+
```text
201+
UCI workbook -> S3 raw zone -> Spark conform job -> S3 curated zone (Parquet)
202+
-> cleaning + validation (nothing loads while an error remains)
203+
-> PostgreSQL warehouse + S3 clean zone -> Redshift Serverless (COPY)
204+
-> report tables (rate/mix split, drivers, forecast accuracy) -> Power BI
205+
```
206+
207+
`jobs/conform_online_retail.py` is a PySpark version of the Online Retail
208+
adapter with no imports from the package, so the same file runs locally, in the
209+
container and on a Spark cluster. `scripts/compare_spark_to_pandas.py` checks it
210+
against the pandas adapter on the full dataset. Cleaning stays in pandas: it
211+
owns the audit trail and the quarantine, and a second implementation would mean
212+
a second definition of every rule.
213+
214+
Locally the lake is a folder and the warehouse a PostgreSQL container
215+
(`docker compose run --rm pipeline`). `scripts/run_pipeline_aws.py` runs the same
216+
stages with the lake in S3 and a Redshift Serverless warehouse, capped at 8 RPU
217+
with a usage limit that switches it off, and a teardown step that removes
218+
everything that bills. Glue and EMR Serverless subcommands exist for the Spark
219+
step but have not been run: the account used is not yet permitted Glue jobs,
220+
and its EMR Serverless quota had not taken effect. The Spark job itself has only
221+
run locally so far. [power_bi.md](docs/power_bi.md) describes the report on the
222+
warehouse.
188223

189224
## What's built
190225

@@ -204,6 +239,8 @@ works fully without. Power BI is deliberately out of scope.
204239
| RootSignal engine | Evidence, pattern, impact, confidence and recommended investigation, ranked | [signals.md](docs/signals.md) |
205240
| Scenario evaluation | Measures whether the engine tells three planted situations apart and stays silent on two controls | [signals.md](docs/signals.md) |
206241
| SQL layer | Staging views, commercial mart and seven business queries, all executed by tests | [sql.md](docs/sql.md) |
242+
| Warehouse | The same SQL on PostgreSQL and Redshift, translated from one source and held row for row to SQLite | [power_bi.md](docs/power_bi.md) |
243+
| Pipeline | Raw, curated and clean zones on disk or in S3, a PySpark conform job, and report tables for BI | [power_bi.md](docs/power_bi.md) |
207244
| Excel reporting | Six operational workbooks, each opening with what its figures mean | [reporting.md](docs/reporting.md) |
208245
| Dashboard | Five Streamlit pages over a Streamlit-free, tested data layer | [dashboard.md](docs/dashboard.md) |
209246
| Presentation | One map from schema keys to language a business reader already has | [dashboard.md](docs/dashboard.md#the-words-on-the-screen) |
@@ -251,8 +288,10 @@ against six named criteria rather than a tuned score. It is validated against
251288
five planted scenarios — classifying three of three correctly at a medium
252289
confidence floor, with zero false alarms at a high one — and runs unchanged on
253290
a million real invoice lines from a public dataset, where it beats a naive
254-
forecast baseline by 38.8% across 49 backtest folds. Python, pandas, SQL,
255-
Streamlit; 308 tests, including one asserting that no output ever claims
256-
causation.
291+
forecast baseline by 38.8% across 49 backtest folds. That dataset moves through
292+
a pipeline from S3 through a PySpark job into PostgreSQL and Redshift, with
293+
Spark's output checked against the pandas implementation on every row. Python,
294+
pandas, PySpark, SQL, AWS, Streamlit; 427 tests, including one asserting that no
295+
output ever claims causation.
257296

258297
</details>

‎docker-compose.yml‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,38 @@ services:
2424
image: rootsignal
2525
profiles: ["tools"]
2626
command: pytest
27+
28+
# Source to warehouse: land the published data, conform it in Spark, load
29+
# it into the warehouse below. The lake is ./data/lake on the host.
30+
pipeline:
31+
build: .
32+
image: rootsignal
33+
profiles: ["tools"]
34+
depends_on:
35+
warehouse:
36+
condition: service_healthy
37+
environment:
38+
- ROOTSIGNAL_WAREHOUSE_URL=postgresql://rootsignal:rootsignal@warehouse:5432/rootsignal
39+
volumes:
40+
- ./data:/app/data
41+
command: python scripts/run_pipeline.py
42+
43+
# The warehouse the pipeline loads into. Credentials are for a local
44+
# container only; a deployed warehouse takes its URL from the environment.
45+
warehouse:
46+
image: postgres:16
47+
environment:
48+
- POSTGRES_USER=rootsignal
49+
- POSTGRES_PASSWORD=rootsignal
50+
- POSTGRES_DB=rootsignal
51+
ports:
52+
- "5433:5432"
53+
volumes:
54+
- warehouse-data:/var/lib/postgresql/data
55+
healthcheck:
56+
test: ["CMD-SHELL", "pg_isready -U rootsignal"]
57+
interval: 5s
58+
retries: 10
59+
60+
volumes:
61+
warehouse-data:

‎docs/RootSignal.pbit‎

67.3 KB
Binary file not shown.

‎docs/docker.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ docker run --rm rootsignal pytest
1919

2020
```bash
2121
docker run --rm -p 8501:8501 rootsignal # the dashboard
22-
docker run --rm rootsignal pytest # all 308 tests
22+
docker run --rm rootsignal pytest # the full suite, Spark tests included
2323
docker run --rm rootsignal python scripts/detect_signals.py
2424
```
2525

‎docs/power_bi.md‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Power BI on the RootSignal warehouse
2+
3+
The pipeline loads the cleaned model and the analysis results into PostgreSQL,
4+
and this report reads them from there. It computes nothing the project has not
5+
already computed and tested: revenue comes from the fact table, and the country
6+
contributions, the rate and mix split, month-on-month change and forecast
7+
accuracy come from report tables the pipeline writes.
8+
9+
| Overview | Drivers |
10+
| --- | --- |
11+
| ![Overview](screenshots/powerbi_overview.png) | ![Drivers](screenshots/powerbi_drivers.png) |
12+
| **Returns** | **Forecast** |
13+
| ![Returns](screenshots/powerbi_returns.png) | ![Forecast](screenshots/powerbi_forecast.png) |
14+
15+
## Open it
16+
17+
1. Fill the warehouse:
18+
```bash
19+
docker compose up -d warehouse
20+
docker compose run --rm pipeline
21+
```
22+
2. Open `docs/RootSignal.pbit` in Power BI Desktop. It is a template: the
23+
report and model without data, so it asks for the connection and loads.
24+
3. Credentials: **Database**, user `rootsignal`, password `rootsignal`. These
25+
belong to the local container in `docker-compose.yml`.
26+
4. The container has no TLS certificate, so Power BI asks to connect without
27+
encryption: **OK**.
28+
29+
Loading a million sales lines takes about a minute. On a machine with 8 GB of
30+
RAM, run the report and the Spark pipeline at different times; together they
31+
exhaust Docker's memory.
32+
33+
## What is in it
34+
35+
**Overview.** Net sales, invoices, average order value and units as cards, with
36+
a country slicer that filters them. Net sales by month, and a table of each
37+
month against the one before, taken from `rpt_monthly_trend`.
38+
39+
**Drivers.** How much each country moved net sales between October and
40+
November 2011, from `rpt_country_contribution`.
41+
42+
**Returns.** Why the return rate moved over the same two months, split into a
43+
rate effect (countries returning a different share) and a mix effect (demand
44+
moving toward countries that always return more), from
45+
`rpt_return_rate_components` and `rpt_return_rate_split`. The rate effect
46+
carries almost all of the movement.
47+
48+
**Forecast.** Backtested error of each daily revenue model against the naive
49+
baseline, from `rpt_forecast_accuracy`. `seasonal_mean_7` is 38.8% better than
50+
naive over 49 folds, the figure the README reports.
51+
52+
## Building it yourself
53+
54+
The template is the reliable route. To rebuild the report from an empty file:
55+
56+
- **Tables.** Get data → PostgreSQL database, server `localhost:5433`, database
57+
`rootsignal`, Import. Tables appear with the schema as a prefix, as
58+
`rootsignal fact_sales` and so on.
59+
- **Relationships.** `fact_sales` to `dim_date` on `date`, to `dim_customer` on
60+
`customer_id` and to `dim_region` on `region_code`, each many to one, single
61+
direction. Leave the `rpt_` tables unconnected; they are finished results.
62+
- **Products.** `fact_sales` to `dim_sku` on `sku_id` works too. Building the
63+
report found 172 stock codes written in two cases or with a trailing space
64+
(`15056BL` and `15056bl`); Power BI compares text without case and saw
65+
duplicates. The pipeline now trims and upper-cases codes, so the relationship
66+
is many to one like the others.
67+
- **Measures.** Power BI names ignore case, so a measure cannot be called
68+
`Units` next to a column called `units`:
69+
```DAX
70+
Net Sales = SUM ( 'rootsignal fact_sales'[net_sales] )
71+
Total Units = SUM ( 'rootsignal fact_sales'[units] )
72+
Invoices = DISTINCTCOUNT ( 'rootsignal fact_sales'[order_id] )
73+
AOV = DIVIDE ( [Net Sales], [Invoices] )
74+
```
75+
`Invoices` is a distinct count because one invoice lists several products.
76+
Expected totals: £20,972,594 net sales, 40,077 invoices, 11,438,460 units,
77+
£523.31 average order value.
78+
- **Month-on-month change** comes from `rpt_monthly_trend` rather than
79+
`DATEADD`. `dim_date` holds only the days the retailer traded, and Power BI's
80+
time-intelligence functions assume an unbroken calendar.
81+
- **Partial months** are already excluded from the monthly report tables; the
82+
data stops on 9 December 2011 and the pipeline drops that month.
83+
- **Totals.** Turn off the total row on tables of rates and changes. Adding
84+
percentages across rows produces a number that means nothing.
85+
86+
A return rate is not a fill rate. Returns are customers sending goods back, not
87+
a warehouse failing to ship.
64 KB
Loading

0 commit comments

Comments
 (0)