Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[run]
branch = True
source = scripts
omit =
scripts/test_*.py

[report]
show_missing = True
fail_under = 100
exclude_also =
if __name__ == .__main__.:
4 changes: 3 additions & 1 deletion .github/ISSUE_TEMPLATE/05_technical_bug.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,6 @@ body:
id: supporting_links
attributes:
label: Links & Screenshots
description: Attach screenshots
description: Attach screenshots, query links, or dashboard URLs if available.
validations:
required: false
18 changes: 16 additions & 2 deletions .github/workflows/pr_validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ jobs:
- name: Lint YAML Files
run: yamllint --strict .

- name: Lint & Format Check Python Scripts
run: |
ruff check .
ruff format --check .

- name: Lint SQL Models
run: |
sqlfluff lint models/
Expand All @@ -58,6 +63,14 @@ jobs:
dbt deps --profiles-dir .
dbt parse --profiles-dir .

- name: Run Python Unit Tests (100% Coverage)
run: |
coverage run -m unittest discover -s scripts -v
coverage report

- name: Check dbt Test, Doc & DAG Coverage
run: python3 scripts/check_dbt_coverage.py

bigquery_build:
name: BigQuery Build & Test
needs: static_checks
Expand Down Expand Up @@ -134,5 +147,6 @@ jobs:
run: dbt deps --profiles-dir .

- name: Build and Test Models
# dbt build runs each model then tests it immediately, so tests never target an unbuilt table
run: dbt build --profiles-dir .
# Full-refresh on the shared CI dataset ensures schema/partition changes build cleanly,
# and dbt build runs unit tests, builds each model, then runs data tests immediately.
run: dbt build --full-refresh --profiles-dir .
16 changes: 15 additions & 1 deletion .github/workflows/weekly_run.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ on:
- cron: '0 0 * * 0'
workflow_dispatch:
# Allows the analytics team to trigger a one-off run manually from the GitHub UI
inputs:
full_refresh:
description: "Rebuild incremental tables from scratch (--full-refresh)"
type: boolean
default: false

concurrency:
group: weekly-production-run
Expand Down Expand Up @@ -80,7 +85,16 @@ jobs:
- name: Install dbt Packages (if any)
run: dbt deps --profiles-dir .

# Fail loudly if production GA4 exports have stalled rather than overwriting tables with 0 rows
- name: Check Source Freshness
run: dbt source freshness --target prod --profiles-dir .

- name: Execute and Test Pipeline
# 'dbt build' compiles, runs, and tests every staging, dim, fct, and agg table sequentially.
# If an upstream table fails a test, downstream tables are skipped to preserve data integrity.
run: dbt build --target prod --profiles-dir .
run: |
if [ "${{ inputs.full_refresh }}" = "true" ]; then
dbt build --full-refresh --target prod --profiles-dir .
else
dbt build --target prod --profiles-dir .
fi
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ profiles.yml
*.json
*.pem

# Python virtual environments
# Python virtual environments, bytecode, and caches/coverage
.venv/
venv/
__pycache__/
*.py[cod]
.coverage
.coverage.*
.ruff_cache/
30 changes: 26 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,39 @@ git checkout -b feature/<short-description>
Install dev dependencies once (`pip install -r requirements-dev.txt`), then verify your changes:

```bash
# Offline linting and dbt project validation (no BigQuery credentials needed)
yamllint .
sqlfluff lint models/
# Offline linting, Python unit tests (100% coverage), dbt parsing, and dbt coverage checks
yamllint --strict .
ruff check .
ruff format --check .
coverage run -m unittest discover -s scripts -v && coverage report
sqlfluff lint models/ tests/
dbt parse
python3 scripts/check_dbt_coverage.py

# Full build and data tests in your personal oppia-analytics-test sandbox
dbt build --target dev
```

For SQL conventions, folder placement, and partitioning/clustering rules, see [models/README.md](models/README.md).

#### Testing requirements (enforced in CI)
- **All models:** Must have a `description` and at least one `data_tests` entry in `schema.yml`.
- **`intermediate/` and `marts/` models:** Must also include at least one native dbt `unit_tests:` entry in `schema.yml` to verify transformation logic against mocked rows (use `format: sql` if inputs contain BigQuery `STRUCT`/`ARRAY` columns; trivial passthrough models can opt out with `config: {meta: {unit_test_exempt: true}}`). Example:
```yaml
unit_tests:
- name: test_fct_lesson_completions_dedup
model: fct_lesson_completions
given:
- input: ref('stg_web_analytics__events')
rows:
- {user_pseudo_id: 'u1', event_name: 'lesson_complete', event_date: '20261101'}
expect:
rows:
- {user_pseudo_id: 'u1', completion_count: 1}
```
- **Custom macros (`macros/`):** Must be exercised by at least one model or test in `tests/`.
- **Sources (`src_*.yml`):** Must include a `description`, `config.loaded_at_field`, and `config.freshness` (or `config: {meta: {freshness_exempt: true}}` for static lookup tables).

### 3. Open the PR targeting `develop`
- Keep PRs focused on a single logical change and link the relevant GitHub issue.
- Include a brief summary of what changed, which models/tests were added or updated, and any expected schema or metric impact.
Expand All @@ -45,7 +67,7 @@ Reviewers should verify the following before approving and merging into `develop
- Models use `{{ ref() }}` / `{{ source() }}` (no hardcoded project or dataset names).
- Final `SELECT` lists columns explicitly (no `SELECT *` in final projections) and queries are idempotent.
- High-volume intermediate and mart tables define `partition_by` and `cluster_by` configs.
- **Documentation & tests:** New or changed models have clear descriptions and appropriate assertions (`not_null`, `unique`, etc.) in their colocated `schema.yml`.
- **Documentation & tests:** New or changed models have clear descriptions, `data_tests` (`not_null`, `unique`, etc.) on critical keys, and meaningful `unit_tests` for `intermediate/` and `marts/` logic (verify any `unit_test_exempt` or `freshness_exempt` opt-outs are genuinely justified).
- **Safety & scope:** No credentials or local config files committed, and any changes to `.github/workflows/` or `dbt_project.yml` are intentional and carefully reviewed.

---
Expand Down
27 changes: 18 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,19 @@ and tests beside the models they document.

Before compiling data structures locally, developers must establish active credentials to access the development sandboxes inside `oppia-analytics-test`.

### 1. Initialize Authentication and Local Dependencies
Ensure you have Python 3.11+ installed, then initialize your analytics environment:
### 1. Initialize Local Environment and Dependencies
Ensure you have Python 3.11+ installed, create a virtual environment, and install the project dependencies:

# Install dbt-bigquery and local linters (sqlfluff, yamllint)
pip install -r requirements-dev.txt
```bash
python3 -m venv .venv
source .venv/bin/activate

# Pull down open-source external packages (if any)
dbt deps
# Install dbt-bigquery and local dev tools (ruff, coverage, sqlfluff, yamllint)
pip install -r requirements-dev.txt

# Pull down open-source external packages (if any)
dbt deps
```

### 2. Configure Your Connection Profile
Local credentials are kept strictly out of git version control.
Expand Down Expand Up @@ -83,9 +88,13 @@ Run a diagnostic framework check to ensure dbt can establish a secure handshake
* Build and test models inside your personal schema sandbox:
dbt build --target dev

* Run offline linting and project parsing (same checks run in PR CI):
yamllint .
sqlfluff lint models/
* Run offline linting, tests, and coverage checks (same checks run in PR CI):
yamllint --strict .
ruff check .
ruff format --check .
coverage run -m unittest discover -s scripts -v && coverage report
sqlfluff lint models/ tests/
dbt parse
python3 scripts/check_dbt_coverage.py

For modeling conventions and architecture details, see [models/README.md](models/README.md). For making and reviewing Pull Requests, see [CONTRIBUTING.md](CONTRIBUTING.md).
13 changes: 4 additions & 9 deletions models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,9 @@ When tasked with writing a new SQL query or editing an existing model, do not mo
4. **Add Schema Definitions:** Document your model and columns inside the corresponding `schema.yml` file. Define data quality tests (such as `not_null` or `unique`) on critical keys.

### Phase 2: Pull Request & Automated Code Validation (CI)
Once your local runs compile and pass checks, open a PR targeting `develop` from a feature branch in `oppia/analytics-data-platform`. See [CONTRIBUTING.md](../CONTRIBUTING.md) for the full PR submission and review checklist.
Once your local runs compile and pass checks, open a PR targeting `develop` from a feature branch in `oppia/analytics-data-platform`. See [CONTRIBUTING.md](../CONTRIBUTING.md) for the complete local check commands and PR submission/review checklist.

1. **Run Local Checks:** Verify linting and BigQuery tests before pushing:
```bash
yamllint .
sqlfluff lint models/
dbt build --target dev
```
1. **Run Local Checks:** Run the offline lint/coverage suite and `dbt build --target dev` listed in [CONTRIBUTING.md](../CONTRIBUTING.md#2-run-checks-locally-before-pushing).
2. **Commit and Push:** Push your feature branch directly to `origin` (`oppia/analytics-data-platform`):
```bash
git add .
Expand All @@ -85,8 +80,8 @@ Once your local runs compile and pass checks, open a PR targeting `develop` from
```
3. **Open a Pull Request (PR):** Open a PR targeting `develop`.
4. **Automated Quality Gates:** Opening the PR triggers GitHub Actions CI:
* **Static Checks (`yamllint`, `sqlfluff`, `dbt parse`)** run automatically on all PRs (including forks).
* **BigQuery Build & Test (`dbt build`)** runs automatically against `oppia-analytics-test` for branches pushed to `oppia/analytics-data-platform`.
* **Static Checks** (`yamllint`, `ruff`, Python unit tests with 100% coverage, `sqlfluff`, offline `dbt parse`, and `scripts/check_dbt_coverage.py`) run automatically on all PRs.
* **BigQuery Build & Test** (`dbt build`) runs automatically against `oppia-analytics-test` for branches pushed to `oppia/analytics-data-platform` (and fails with instructions on fork PRs).
5. **Peer Review:** At least one approved reviewer must approve your PR before it can be merged into `develop`.

### Phase 3: Deployment to Production
Expand Down
15 changes: 14 additions & 1 deletion models/staging/web/schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,18 @@ models:
columns:
- name: user_pseudo_id
# user_id is only populated for logged-in users; user_pseudo_id is GA4's always-present device/client identifier
tests:
description: "GA4 client/device identifier."
data_tests:
- not_null
- name: event_name
description: "GA4 event name."
data_tests:
- not_null
- name: event_date
description: "UTC event date (DATE) parsed from GA4 event_date (YYYYMMDD)."
data_tests:
- not_null
- name: event_timestamp
description: "UTC event timestamp converted from GA4 event_timestamp micros."
data_tests:
- not_null
11 changes: 11 additions & 0 deletions models/staging/web/src_web.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,14 @@ sources:
tables:
- name: events_*
description: "Date-sharded GA4/Firebase event export tables (events_YYYYMMDD); query via wildcard with _TABLE_SUFFIX."
config:
# Wildcard tables require a query-based loaded_at_field and _TABLE_SUFFIX filter to avoid full-history scans
loaded_at_field: "TIMESTAMP_MICROS(event_timestamp)"
freshness:
warn_after:
count: 36
period: hour
error_after:
count: 48
period: hour
filter: "_TABLE_SUFFIX >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY))"
34 changes: 30 additions & 4 deletions models/staging/web/stg_web_analytics__events.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,46 @@
-- Purpose: Standardized staging layer capturing core web log interactions.
-- Note: Detailed column descriptions and data quality assertions are managed inside the corresponding schema.yml file.

{{ config(
materialized='incremental',
incremental_strategy='insert_overwrite',
on_schema_change='sync_all_columns',
partition_by={
"field": "event_date",
"data_type": "date",
"granularity": "day"
},
cluster_by=["event_name", "user_pseudo_id"]
) }}

WITH source_data AS (
-- events_* wildcard scans all daily shards; _TABLE_SUFFIX exposes each shard's date suffix
-- events_* wildcard scans daily GA4 shards; _TABLE_SUFFIX exposes each shard's YYYYMMDD date.
-- Incremental runs reprocess the last 10 days (7-day weekly cadence + 3-day GA4 late-export buffer)
-- and overwrite only those daily partitions so runs stay strictly idempotent.
-- Full refreshes scan 90 days in prod (override via --vars '{backfill_days: N}') and 7 days in dev.
SELECT * FROM {{ source('raw_web_server', 'events_*') }}
WHERE
_TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))
AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
{% if is_incremental() %}
_TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 10 DAY))
AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
{% elif target.name == 'prod' %}
_TABLE_SUFFIX BETWEEN FORMAT_DATE(
'%Y%m%d',
DATE_SUB(CURRENT_DATE(), INTERVAL {{ var('backfill_days', 90) }} DAY)
)
AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
{% else %}
_TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY))
AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
{% endif %}
),

final_events AS (
SELECT
user_id,
user_pseudo_id,
event_name,
event_date,
PARSE_DATE('%Y%m%d', event_date) AS event_date,
TIMESTAMP_MICROS(event_timestamp) AS event_timestamp,
device.category AS device_category,
device.operating_system AS operating_system,
Expand Down
2 changes: 2 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# Local development and PR validation dependencies
-r requirements.txt
coverage>=7.17.0,<8.0.0
ruff>=0.17.0,<0.18.0
sqlfluff>=4.5.0,<5.0.0
yamllint>=1.38.0,<2.0.0
6 changes: 6 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
target-version = "py311"
line-length = 88
extend-exclude = ["target", "dbt_packages", "dbt_modules", "logs"]

[lint]
select = ["E", "F", "I", "UP", "B", "SIM"]
Loading
Loading