Skip to content

Guided lab · Refactor the ETA script without moving the metric

Time: 4 hours. Tools: Python 3.11/3.12, Git, ruff (installed with the dev extras in Module 02). No accounts, no data downloads.

Scenario and business problem

RaviRide's ETA model is produced by one script on one laptop. A new test window is needed for next quarter, and the analyst who wrote the script cannot say which numbers in it are choices and which are facts. Your manager asks a narrow question: can we change one parameter without touching code review?

The refactor must preserve the model's measured error exactly. "It looks tidier" is not acceptance evidence, and neither is "the tests pass" - there are no tests yet.

Skills practised

  • Reading a script and locating its four kinds of content.
  • Extracting pure modules and thin stage entry points.
  • Moving literals into a configuration layer.
  • Proving behavioural equivalence with a metric.
  • Writing ADRs and a priced debt register.

Prerequisites

Modules 01–02. Your raviride-eta repository with a working environment, and the RaviRide dataset generated by the course generator (data/raw/trips.csv, 1,200 rows).

Input data

data/raw/trips.csv, generated in Module 02 or supplied by your instructor. Columns: trip_id, requested_at, pickup_zone, dropoff_zone, distance_km, passengers, weather, traffic_index, driver_supply, fare_amount, duration_min.

Directory layout after the lab

raviride-eta/
├── params.yaml
├── src/raviride_eta/
│   ├── __init__.py
│   ├── config.py
│   ├── data.py
│   ├── features.py
│   ├── prepare.py
│   ├── train.py
│   └── evaluate.py
├── docs/
│   ├── adr/0001-package-layout.md
│   ├── adr/0002-configuration-layer.md
│   └── debt-register.md
└── legacy_train.py          # kept until equivalence is proved

Part 1: measure the starting point (30 minutes)

  1. Save the legacy script from the worked example as legacy_train.py at the repository root.
  2. Run it twice:
    python legacy_train.py
    python legacy_train.py
    
    Checkpoint 1: both runs print rows 896 304 MAE 2.777. If they differ, your data or random seed is not fixed; stop and find out why before refactoring.
  3. Record the output in docs/refactor-evidence.md under ## Before.

Recovery: if the row counts differ, check that data/raw/trips.csv came from the course generator and was not edited by hand.

Part 2: extract the library (90 minutes)

  1. Create src/raviride_eta/config.py with project paths and a load_params() function that reads params.yaml with yaml.safe_load.
  2. Create params.yaml holding: data.test_days, data.window_start, data.window_end, model.n_estimators, model.max_depth, model.min_samples_leaf, model.random_state.
  3. Create features.py: add_features(frame) (calendar and log-distance columns), FEATURE_SETS, feature_columns(name), split_xy(frame, name). Keep it pure - no file access.
  4. Create data.py with load_trips(path) only. Validation arrives in Module 04; do not add it yet.
  5. Create prepare.py: read the raw CSV, split on test_days, write data/processed/train.csv and test.csv, print row counts and the cutoff date. Checkpoint 2: running python -m raviride_eta.prepare writes both files and prints train: 896 and test: 304.
  6. Create train.py: build the ColumnTransformer + RandomForestRegressor pipeline from FEATURE_SETS[params["features"]["set"]], fit on data/processed/train.csv, write models/model.joblib and models/run_meta.json.
  7. Create evaluate.py: load the artefact, predict on the test split, compute MAE, RMSE, R², and p95 absolute error, write metrics.json, print the overall line. Checkpoint 3: python -m raviride_eta.evaluate prints MAE 2.777 (your digits may differ in the third decimal if you changed the seed; if so, say why in the evidence file).

Part 3: prove equivalence (30 minutes)

  1. Run the full sequence from a clean state:
    Remove-Item -Recurse -Force data/processed, models, metrics.json -ErrorAction SilentlyContinue
    python -m raviride_eta.prepare
    python -m raviride_eta.train
    python -m raviride_eta.evaluate
    
  2. Add an ## After section to docs/refactor-evidence.md with the command, row counts, MAE, and the commit hash.
  3. Checkpoint 4: the before and after MAE match. If they do not, apply the diagnostic list in the worked example and record which cause it was.

Part 4: decide, and record the decision (60 minutes)

  1. Write docs/adr/0001-package-layout.md using the format in Concepts. Include one rejected alternative (for example, keeping a notebooks/ folder as the source of truth).
  2. Write docs/adr/0002-configuration-layer.md. State explicitly that secrets are not in params.yaml, and where they will come from instead.
  3. Write docs/debt-register.md with at least five items from your own refactor. Each row: ID, category, symptom, risk, fix, cost (S/M/L), owner role, and status (open, accepted until Module 05, fixed).

Part 5: keep style out of review (30 minutes)

  1. Add the [tool.ruff] block from Concepts to pyproject.toml.
  2. Run:
    ruff check .
    
    Checkpoint 5: All checks passed!. Fix real findings; do not add # noqa to silence a rule you have not read.
  3. Commit on a branch (refactor/package-layout) with a message that gives the reason, and open the diff to confirm no generated file is included.

Expected outputs

Output What it shows
params.yaml Every human-chosen value in one reviewable file
Five modules plus two stages A one-way import graph, no cycles
docs/refactor-evidence.md Before/after metrics from commands you ran
Two ADRs Decisions with context and rejected alternatives
docs/debt-register.md At least five priced items, three categories represented
ruff check . → All checks passed! Style is no longer a review topic

Acceptance criteria

Criterion Passes when
Behaviour preserved MAE before and after are equal to the printed precision, with matching row counts
Separation config imports no project module; features performs no I/O; stages are thin
Configuration Changing model.max_depth in params.yaml changes the result with no code edit
Debt made visible Every register item has a cost and an owner role; at least one is explicitly accepted
Reviewability The diff touches only source, config, and docs - no data, models, or .venv

Troubleshooting

Symptom Cause Fix
ModuleNotFoundError: raviride_eta Package not installed or wrong interpreter pip install -e ".[dev]"; check sys.prefix
Metric changed after refactor Split boundary or row order differs Compare len(train) and the cutoff date; use < consistently
ValueError: unknown feature_set Typo in params.yaml The error lists valid names; fix the value, not the code
KeyError: 'test_days' YAML nesting wrong data.test_days means a data: mapping containing test_days
Circular import config imports train, or features imports evaluate Move the shared helper down the graph
ruff reports unused import Leftover from the extraction Remove it; that is the rule doing its job
PermissionError writing model.joblib Run from a protected directory Run from the repository root; paths are relative to it

Cleanup

  • Delete legacy_train.py after the before/after evidence is committed. Keeping it is fine if you prefer, but then say in the ADR why it is retained.
  • Remove any scratch notebooks or .venv-colleague directories.
  • No services were started.

Optional extensions

  1. Parameter sensitivity. Change only test_days from 7 to 14, rerun, and record the metric. This is the first time the configuration layer earns its keep; write one sentence on whether the change is an improvement or a different question.
  2. Import graph check. Draw the actual import graph with pydeps or by grepping imports, and compare it with the intended one. Any arrow that points backwards is a design defect.
  3. Pre-commit. Install pre-commit, add ruff as a hook, attempt a commit with a lint error, and record the blocked commit as evidence.