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)¶
- Save the legacy script from the worked example as
legacy_train.pyat the repository root. - Run it twice:
Checkpoint 1: both runs print
python legacy_train.py python legacy_train.pyrows 896 304 MAE 2.777. If they differ, your data or random seed is not fixed; stop and find out why before refactoring. - Record the output in
docs/refactor-evidence.mdunder## 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)¶
- Create
src/raviride_eta/config.pywith project paths and aload_params()function that readsparams.yamlwithyaml.safe_load. - Create
params.yamlholding:data.test_days,data.window_start,data.window_end,model.n_estimators,model.max_depth,model.min_samples_leaf,model.random_state. - 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. - Create
data.pywithload_trips(path)only. Validation arrives in Module 04; do not add it yet. - Create
prepare.py: read the raw CSV, split ontest_days, writedata/processed/train.csvandtest.csv, print row counts and the cutoff date. Checkpoint 2: runningpython -m raviride_eta.preparewrites both files and printstrain: 896andtest: 304. - Create
train.py: build theColumnTransformer+RandomForestRegressorpipeline fromFEATURE_SETS[params["features"]["set"]], fit ondata/processed/train.csv, writemodels/model.joblibandmodels/run_meta.json. - Create
evaluate.py: load the artefact, predict on the test split, compute MAE, RMSE, R², and p95 absolute error, writemetrics.json, print the overall line. Checkpoint 3:python -m raviride_eta.evaluateprintsMAE 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)¶
- 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 - Add an
## Aftersection todocs/refactor-evidence.mdwith the command, row counts, MAE, and the commit hash. - 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)¶
- Write
docs/adr/0001-package-layout.mdusing the format in Concepts. Include one rejected alternative (for example, keeping anotebooks/folder as the source of truth). - Write
docs/adr/0002-configuration-layer.md. State explicitly that secrets are not inparams.yaml, and where they will come from instead. - Write
docs/debt-register.mdwith 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)¶
- Add the
[tool.ruff]block from Concepts topyproject.toml. - Run:
Checkpoint 5:
ruff check .All checks passed!. Fix real findings; do not add# noqato silence a rule you have not read. - 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.pyafter 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-colleaguedirectories. - No services were started.
Optional extensions¶
- Parameter sensitivity. Change only
test_daysfrom 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. - Import graph check. Draw the actual import graph with
pydepsor by grepping imports, and compare it with the intended one. Any arrow that points backwards is a design defect. - Pre-commit. Install
pre-commit, addruffas a hook, attempt a commit with a lint error, and record the blocked commit as evidence.