mekosotto Claude Opus 4.7 (1M context) commited on
Commit
9e9b239
·
1 Parent(s): 8c4e3e2

docs(plan): add Day-4 API/MLOps/frontend implementation plan

Browse files

11-task plan covering core helper extraction (determinism.py,
storage.py, tracking.py), MLflow integration, FastAPI surface,
Docker compose orchestration, and Streamlit B2B dashboard.
Target: ~136 tests green at completion.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

docs/superpowers/plans/2026-05-02-day4-api-mlops-frontend.md ADDED
@@ -0,0 +1,1614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Day 4 — API, Orchestration & Frontend Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended) or `superpowers:executing-plans` to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Wrap the three Day-1/2/3 pipelines (BBB, EEG, MRI) in a productionized, demo-ready stack: shared core utilities, MLflow tracking, FastAPI surface, Docker compose orchestration, and a Streamlit B2B dashboard — without breaking the 106 existing green tests.
6
+
7
+ **Architecture:** Three concentric rings around the pipelines. Inner ring (`src/core/`) deduplicates threading-determinism + Parquet write + MLflow tracking helpers used by all three pipelines. Middle ring (`src/api/`) exposes each pipeline as a FastAPI POST endpoint with shared Pydantic request/response schemas. Outer ring (`src/frontend/`) is a Streamlit dashboard that calls the FastAPI surface (NOT the pipeline modules) and surfaces MLflow run links. `Dockerfile` + `docker-compose.yml` boot FastAPI + an MLflow tracking server side-by-side.
8
+
9
+ **Tech Stack:** FastAPI 0.115, Pydantic 2.9, MLflow 2.16, Streamlit (new dependency, pinned in this plan), Docker Compose v2. All existing pins (numpy/pandas/scipy/scikit-learn/rdkit/mne/nibabel/neuroharmonize/pyarrow) untouched.
10
+
11
+ ---
12
+
13
+ ## File Structure
14
+
15
+ ```
16
+ src/
17
+ ├── core/
18
+ │ ├── logger.py # (existing)
19
+ │ ├── determinism.py # NEW — Task 1: pin_threads()
20
+ │ ├── storage.py # NEW — Task 2: write_parquet()
21
+ │ └── tracking.py # NEW — Task 5: track_pipeline_run()
22
+ ├── pipelines/
23
+ │ ├── bbb_pipeline.py # MODIFY (Tasks 3, 6)
24
+ │ ├── eeg_pipeline.py # MODIFY (Tasks 3, 6)
25
+ │ └── mri_pipeline.py # MODIFY (Tasks 3, 6)
26
+ ├── api/
27
+ │ ├── __init__.py # (existing, empty)
28
+ │ ├── schemas.py # NEW — Task 7
29
+ │ ├── routes.py # NEW — Task 8
30
+ │ └── main.py # NEW — Task 7
31
+ └── frontend/
32
+ ├── __init__.py # NEW — Task 10
33
+ └── app.py # NEW — Task 10
34
+
35
+ tests/
36
+ ├── core/
37
+ │ ├── test_logger.py # (existing)
38
+ │ ├── test_determinism.py # NEW — Task 1
39
+ │ ├── test_storage.py # NEW — Task 2
40
+ │ └── test_tracking.py # NEW — Task 5
41
+ ├── pipelines/
42
+ │ ├── test_bbb_pipeline.py # (existing)
43
+ │ ├── test_eeg_pipeline.py # (existing)
44
+ │ ├── test_mri_pipeline.py # (existing)
45
+ │ └── test_cross_pipeline_smoke.py # NEW — Task 4
46
+ ├── api/
47
+ │ ├── __init__.py # NEW — Task 7
48
+ │ ├── test_main.py # NEW — Task 7
49
+ │ └── test_routes.py # NEW — Task 8
50
+ └── frontend/
51
+ ├── __init__.py # NEW — Task 10
52
+ └── test_app_import.py # NEW — Task 10
53
+
54
+ Dockerfile # NEW — Task 9
55
+ docker-compose.yml # NEW — Task 9
56
+ .dockerignore # NEW — Task 9
57
+ requirements.txt # MODIFY (Task 10: add streamlit)
58
+ AGENTS.md # MODIFY (Task 11: §2 layout, §6 add tracking note)
59
+ README.md # MODIFY (Task 11)
60
+ ```
61
+
62
+ **Test count target:** 106 (existing) + ~30 (new) = **~136 tests green at end of Day 4**.
63
+
64
+ ---
65
+
66
+ ## Task 1: `src/core/determinism.py` — extract thread-pinning helper
67
+
68
+ **Why this task:** All three pipelines copy-paste the same six lines pinning OMP/OPENBLAS/MKL/pyarrow to single-thread mode. Drift risk is real (Day-2 review caught it). Extract into one helper, add tests, rewire pipelines in Task 3.
69
+
70
+ **Files:**
71
+ - Create: `src/core/determinism.py`
72
+ - Create: `tests/core/test_determinism.py`
73
+
74
+ - [ ] **Step 1: Write failing tests**
75
+
76
+ Create `tests/core/test_determinism.py`:
77
+
78
+ ```python
79
+ """Tests for src.core.determinism."""
80
+ from __future__ import annotations
81
+
82
+ import os
83
+
84
+ import pyarrow as pa
85
+
86
+ from src.core import determinism
87
+
88
+
89
+ class TestPinThreads:
90
+ def test_sets_omp_env_var(self):
91
+ os.environ.pop("OMP_NUM_THREADS", None)
92
+ determinism.pin_threads()
93
+ assert os.environ["OMP_NUM_THREADS"] == "1"
94
+
95
+ def test_sets_openblas_env_var(self):
96
+ os.environ.pop("OPENBLAS_NUM_THREADS", None)
97
+ determinism.pin_threads()
98
+ assert os.environ["OPENBLAS_NUM_THREADS"] == "1"
99
+
100
+ def test_sets_mkl_env_var(self):
101
+ os.environ.pop("MKL_NUM_THREADS", None)
102
+ determinism.pin_threads()
103
+ assert os.environ["MKL_NUM_THREADS"] == "1"
104
+
105
+ def test_pins_pyarrow_cpu_count_to_1(self):
106
+ pa.set_cpu_count(4)
107
+ determinism.pin_threads()
108
+ assert pa.cpu_count() == 1
109
+
110
+ def test_pins_pyarrow_io_thread_count_to_1(self):
111
+ pa.set_io_thread_count(4)
112
+ determinism.pin_threads()
113
+ assert pa.io_thread_count() == 1
114
+
115
+ def test_does_not_override_existing_env(self):
116
+ """User explicitly setting OMP_NUM_THREADS=2 must win — pin_threads()
117
+ uses os.environ.setdefault so an upstream override is preserved."""
118
+ os.environ["OMP_NUM_THREADS"] = "2"
119
+ try:
120
+ determinism.pin_threads()
121
+ assert os.environ["OMP_NUM_THREADS"] == "2"
122
+ finally:
123
+ os.environ["OMP_NUM_THREADS"] = "1"
124
+
125
+ def test_idempotent(self):
126
+ determinism.pin_threads()
127
+ determinism.pin_threads()
128
+ assert pa.cpu_count() == 1
129
+ ```
130
+
131
+ - [ ] **Step 2: Run tests to verify they fail**
132
+
133
+ ```
134
+ pytest tests/core/test_determinism.py -v
135
+ ```
136
+ Expected: 7 errors / fails — module `src.core.determinism` does not exist.
137
+
138
+ - [ ] **Step 3: Implement `src/core/determinism.py`**
139
+
140
+ ```python
141
+ """Threading determinism: pin BLAS / OpenMP / pyarrow to single-threaded mode.
142
+
143
+ Multi-threaded floating-point reductions reorder operands non-deterministically
144
+ on each call, breaking the byte-identity guarantee in AGENTS.md §4 rule 3. Each
145
+ pipeline calls `pin_threads()` at import time to lock the process to a single
146
+ thread before any numerical work runs.
147
+
148
+ Honors pre-set env vars: if the caller exported `OMP_NUM_THREADS=4` upstream,
149
+ that value is preserved (we use `setdefault`, not `setitem`). The user is
150
+ responsible for the determinism trade-off in that case.
151
+ """
152
+ from __future__ import annotations
153
+
154
+ import os
155
+
156
+ import pyarrow as pa
157
+
158
+ _ENV_VARS: tuple[str, ...] = (
159
+ "OMP_NUM_THREADS",
160
+ "OPENBLAS_NUM_THREADS",
161
+ "MKL_NUM_THREADS",
162
+ )
163
+
164
+
165
+ def pin_threads() -> None:
166
+ """Pin BLAS / OpenMP / pyarrow to single-threaded mode (idempotent)."""
167
+ for var in _ENV_VARS:
168
+ os.environ.setdefault(var, "1")
169
+ pa.set_cpu_count(1)
170
+ pa.set_io_thread_count(1)
171
+ ```
172
+
173
+ - [ ] **Step 4: Run tests to verify they pass**
174
+
175
+ ```
176
+ pytest tests/core/test_determinism.py -v
177
+ ```
178
+ Expected: 7 passed.
179
+
180
+ - [ ] **Step 5: Commit**
181
+
182
+ ```bash
183
+ git add src/core/determinism.py tests/core/test_determinism.py
184
+ git commit -m "feat(core): extract pin_threads() helper for determinism"
185
+ ```
186
+
187
+ ---
188
+
189
+ ## Task 2: `src/core/storage.py` — extract Parquet write helper
190
+
191
+ **Why this task:** All three pipelines repeat the same `output_path.parent.mkdir(...) / IsADirectoryError check / to_parquet(engine="pyarrow", compression="snappy", index=False)` pattern. Extract once.
192
+
193
+ **Files:**
194
+ - Create: `src/core/storage.py`
195
+ - Create: `tests/core/test_storage.py`
196
+
197
+ - [ ] **Step 1: Write failing tests**
198
+
199
+ Create `tests/core/test_storage.py`:
200
+
201
+ ```python
202
+ """Tests for src.core.storage."""
203
+ from __future__ import annotations
204
+
205
+ import hashlib
206
+ from pathlib import Path
207
+
208
+ import pandas as pd
209
+ import pytest
210
+
211
+ from src.core import storage
212
+
213
+
214
+ def _md5(path: Path) -> str:
215
+ return hashlib.md5(path.read_bytes()).hexdigest()
216
+
217
+
218
+ class TestWriteParquet:
219
+ def test_writes_parquet_at_path(self, tmp_path: Path):
220
+ df = pd.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})
221
+ out = tmp_path / "out.parquet"
222
+ storage.write_parquet(df, out)
223
+ round_trip = pd.read_parquet(out)
224
+ pd.testing.assert_frame_equal(round_trip, df)
225
+
226
+ def test_creates_parent_directories(self, tmp_path: Path):
227
+ df = pd.DataFrame({"a": [1]})
228
+ out = tmp_path / "deep" / "nested" / "out.parquet"
229
+ storage.write_parquet(df, out)
230
+ assert out.exists()
231
+
232
+ def test_overwrites_existing_file(self, tmp_path: Path):
233
+ out = tmp_path / "out.parquet"
234
+ storage.write_parquet(pd.DataFrame({"a": [1]}), out)
235
+ storage.write_parquet(pd.DataFrame({"a": [2]}), out)
236
+ assert pd.read_parquet(out)["a"].tolist() == [2]
237
+
238
+ def test_raises_if_path_is_directory(self, tmp_path: Path):
239
+ (tmp_path / "out.parquet").mkdir()
240
+ with pytest.raises(IsADirectoryError):
241
+ storage.write_parquet(pd.DataFrame({"a": [1]}), tmp_path / "out.parquet")
242
+
243
+ def test_byte_deterministic_on_repeat(self, tmp_path: Path):
244
+ df = pd.DataFrame({"a": list(range(100)), "b": list(range(100, 200))})
245
+ a, b = tmp_path / "a.parquet", tmp_path / "b.parquet"
246
+ storage.write_parquet(df, a)
247
+ storage.write_parquet(df, b)
248
+ assert _md5(a) == _md5(b)
249
+
250
+ def test_preserves_uint8_dtype(self, tmp_path: Path):
251
+ """BBB fingerprints are uint8; writing must not silently widen."""
252
+ df = pd.DataFrame({"fp_0": pd.Series([0, 1], dtype="uint8")})
253
+ out = tmp_path / "out.parquet"
254
+ storage.write_parquet(df, out)
255
+ assert pd.read_parquet(out)["fp_0"].dtype == "uint8"
256
+
257
+ def test_index_not_persisted(self, tmp_path: Path):
258
+ """index=False must be the default — round-trip should reset to RangeIndex."""
259
+ df = pd.DataFrame({"a": [1, 2]}, index=["foo", "bar"])
260
+ out = tmp_path / "out.parquet"
261
+ storage.write_parquet(df, out)
262
+ assert list(pd.read_parquet(out).index) == [0, 1]
263
+ ```
264
+
265
+ - [ ] **Step 2: Run tests to verify they fail**
266
+
267
+ ```
268
+ pytest tests/core/test_storage.py -v
269
+ ```
270
+ Expected: 7 errors — module not found.
271
+
272
+ - [ ] **Step 3: Implement `src/core/storage.py`**
273
+
274
+ ```python
275
+ """Deterministic Parquet I/O for `data/processed/` outputs.
276
+
277
+ Implements AGENTS.md §6 storage convention: pyarrow engine, snappy compression,
278
+ index suppressed. Combined with `src.core.determinism.pin_threads`, this writes
279
+ byte-identical Parquet files across runs.
280
+ """
281
+ from __future__ import annotations
282
+
283
+ from pathlib import Path
284
+
285
+ import pandas as pd
286
+
287
+
288
+ def write_parquet(df: pd.DataFrame, output_path: Path) -> None:
289
+ """Write `df` to `output_path` as deterministic, snappy-compressed Parquet.
290
+
291
+ Creates parent directories as needed. Overwrites any existing file at
292
+ `output_path`. Raises `IsADirectoryError` if `output_path` resolves to an
293
+ existing directory (caller passed a directory by mistake).
294
+
295
+ Args:
296
+ df: DataFrame to persist. Dtypes preserved (uint8 stays uint8, etc.).
297
+ output_path: Destination file path (parent directories auto-created).
298
+
299
+ Raises:
300
+ IsADirectoryError: if `output_path` is an existing directory.
301
+ """
302
+ output_path = Path(output_path)
303
+ output_path.parent.mkdir(parents=True, exist_ok=True)
304
+ if output_path.is_dir():
305
+ raise IsADirectoryError(
306
+ f"output_path must be a file, got a directory: {output_path}"
307
+ )
308
+ df.to_parquet(
309
+ output_path, index=False, engine="pyarrow", compression="snappy",
310
+ )
311
+ ```
312
+
313
+ - [ ] **Step 4: Run tests to verify they pass**
314
+
315
+ ```
316
+ pytest tests/core/test_storage.py -v
317
+ ```
318
+ Expected: 7 passed.
319
+
320
+ - [ ] **Step 5: Commit**
321
+
322
+ ```bash
323
+ git add src/core/storage.py tests/core/test_storage.py
324
+ git commit -m "feat(core): extract write_parquet() helper for §6 storage contract"
325
+ ```
326
+
327
+ ---
328
+
329
+ ## Task 3: Refactor BBB / EEG / MRI pipelines to use core helpers
330
+
331
+ **Why this task:** Replace three duplicate copies of the env-pinning block + the `to_parquet(...)` call with the new helpers. Existing tests must stay green (this is pure refactor — zero behavior change).
332
+
333
+ **Files:**
334
+ - Modify: `src/pipelines/bbb_pipeline.py` (replace env block + to_parquet)
335
+ - Modify: `src/pipelines/eeg_pipeline.py` (same)
336
+ - Modify: `src/pipelines/mri_pipeline.py` (same)
337
+
338
+ - [ ] **Step 1: Refactor `bbb_pipeline.py`**
339
+
340
+ In `src/pipelines/bbb_pipeline.py`:
341
+
342
+ Replace the env-pinning block (currently lines ~28-35, the `os.environ.setdefault(...)` lines + `pa.set_cpu_count(1)` + `pa.set_io_thread_count(1)`):
343
+
344
+ ```python
345
+ # Old:
346
+ os.environ.setdefault("OMP_NUM_THREADS", "1")
347
+ os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
348
+ os.environ.setdefault("MKL_NUM_THREADS", "1")
349
+ pa.set_cpu_count(1)
350
+ pa.set_io_thread_count(1)
351
+ ```
352
+
353
+ With:
354
+
355
+ ```python
356
+ # New:
357
+ from src.core.determinism import pin_threads
358
+
359
+ pin_threads()
360
+ ```
361
+
362
+ Remove the now-unused `import os` and `import pyarrow as pa` lines if they have no other call sites in this file (they don't — verify). Keep the comment block above explaining why determinism matters.
363
+
364
+ In `run_pipeline()`, replace the trailing block:
365
+
366
+ ```python
367
+ # Old:
368
+ output_path.parent.mkdir(parents=True, exist_ok=True)
369
+ if output_path.is_dir():
370
+ raise IsADirectoryError(...)
371
+ features.to_parquet(output_path, index=False, engine="pyarrow", compression="snappy")
372
+ ```
373
+
374
+ With:
375
+
376
+ ```python
377
+ # New:
378
+ from src.core.storage import write_parquet # at top of module
379
+ ...
380
+ write_parquet(features, output_path)
381
+ ```
382
+
383
+ Keep the `logger.info("Wrote processed features to %s ...")` line immediately after — it remains the user-visible trace.
384
+
385
+ - [ ] **Step 2: Run BBB tests**
386
+
387
+ ```
388
+ pytest tests/pipelines/test_bbb_pipeline.py -v
389
+ ```
390
+ Expected: 23 passed (unchanged from Day 1).
391
+
392
+ - [ ] **Step 3: Repeat refactor for `eeg_pipeline.py` and `mri_pipeline.py`**
393
+
394
+ Apply identical replacements. Same imports added (`from src.core.determinism import pin_threads`, `from src.core.storage import write_parquet`). Same env-block deletion. Same `to_parquet → write_parquet` swap.
395
+
396
+ - [ ] **Step 4: Run full pipeline test suite**
397
+
398
+ ```
399
+ pytest tests/pipelines/ -v
400
+ ```
401
+ Expected: 23 (BBB) + 37 (EEG) + 39 (MRI) = 99 passed. Plus 7 logger + 7 determinism + 7 storage = 113 tests green at this point. Verify count.
402
+
403
+ - [ ] **Step 5: Commit each pipeline refactor as its own commit**
404
+
405
+ ```bash
406
+ git add src/pipelines/bbb_pipeline.py
407
+ git commit -m "refactor(bbb): use core.determinism + core.storage helpers"
408
+
409
+ git add src/pipelines/eeg_pipeline.py
410
+ git commit -m "refactor(eeg): use core.determinism + core.storage helpers"
411
+
412
+ git add src/pipelines/mri_pipeline.py
413
+ git commit -m "refactor(mri): use core.determinism + core.storage helpers"
414
+ ```
415
+
416
+ ---
417
+
418
+ ## Task 4: Cross-pipeline smoke test
419
+
420
+ **Why this task:** A single test runs all three pipelines back-to-back against their fixtures and asserts each produces a non-empty Parquet with expected schema. This is the hackathon-judge "does the whole thing work?" test.
421
+
422
+ **Files:**
423
+ - Create: `tests/pipelines/test_cross_pipeline_smoke.py`
424
+
425
+ - [ ] **Step 1: Write the smoke test**
426
+
427
+ Create `tests/pipelines/test_cross_pipeline_smoke.py`:
428
+
429
+ ```python
430
+ """End-to-end smoke test exercising all three pipelines back-to-back.
431
+
432
+ Asserts each pipeline produces a non-empty Parquet at its expected schema —
433
+ the hackathon-judge "does the whole stack still work?" check. Each pipeline
434
+ uses its own fixture (no cross-modality data sharing).
435
+ """
436
+ from __future__ import annotations
437
+
438
+ import shutil
439
+ from pathlib import Path
440
+
441
+ import pandas as pd
442
+ import pytest
443
+
444
+ from src.pipelines import bbb_pipeline, eeg_pipeline, mri_pipeline
445
+
446
+
447
+ _REPO_ROOT = Path(__file__).resolve().parents[2]
448
+ _FIXTURES = _REPO_ROOT / "tests" / "fixtures"
449
+
450
+
451
+ def test_bbb_pipeline_smoke(tmp_path: Path):
452
+ out = tmp_path / "bbb.parquet"
453
+ bbb_pipeline.run_pipeline(
454
+ input_path=_FIXTURES / "bbbp_sample.csv",
455
+ output_path=out,
456
+ )
457
+ df = pd.read_parquet(out)
458
+ assert len(df) > 0
459
+ assert sum(c.startswith("fp_") for c in df.columns) == 2048
460
+
461
+
462
+ def test_eeg_pipeline_smoke(tmp_path: Path):
463
+ """Use the EEG fixture builder to materialize the FIF input."""
464
+ from tests.fixtures.build_eeg_fixture import build as build_eeg
465
+ fif = build_eeg(out_dir=tmp_path / "eeg_fixture")
466
+ out = tmp_path / "eeg.parquet"
467
+ eeg_pipeline.run_pipeline(input_path=fif, output_path=out)
468
+ df = pd.read_parquet(out)
469
+ assert len(df) > 0
470
+ assert "epoch_id" in df.columns
471
+
472
+
473
+ def test_mri_pipeline_smoke(tmp_path: Path):
474
+ """Use the MRI fixture builder to materialize NIfTI inputs + sites.csv."""
475
+ from tests.fixtures.build_mri_fixture import build as build_mri
476
+ fixture_dir = build_mri(out_dir=tmp_path / "mri_fixture")
477
+ out = tmp_path / "mri.parquet"
478
+ mri_pipeline.run_pipeline(
479
+ input_dir=fixture_dir,
480
+ sites_csv=fixture_dir / "sites.csv",
481
+ output_path=out,
482
+ )
483
+ df = pd.read_parquet(out)
484
+ assert len(df) > 0
485
+ assert "subject_id" in df.columns
486
+ assert "site" in df.columns
487
+
488
+
489
+ def test_all_three_pipelines_run_in_one_process(tmp_path: Path):
490
+ """Sanity: nothing in pipeline A leaks state that breaks pipeline B."""
491
+ test_bbb_pipeline_smoke(tmp_path / "bbb")
492
+ test_eeg_pipeline_smoke(tmp_path / "eeg")
493
+ test_mri_pipeline_smoke(tmp_path / "mri")
494
+ ```
495
+
496
+ > **Verify before writing:** confirm `tests/fixtures/build_eeg_fixture.py` and `build_mri_fixture.py` both expose a `build(out_dir: Path)` function. If `build_eeg_fixture.py` doesn't exist or has a different signature, adapt the test to use whatever loader the existing EEG tests use — read `tests/pipelines/test_eeg_pipeline.py` first and mirror its fixture-loading pattern. **Do not invent file paths.**
497
+
498
+ - [ ] **Step 2: Run tests**
499
+
500
+ ```
501
+ pytest tests/pipelines/test_cross_pipeline_smoke.py -v
502
+ ```
503
+ Expected: 4 passed.
504
+
505
+ - [ ] **Step 3: Commit**
506
+
507
+ ```bash
508
+ git add tests/pipelines/test_cross_pipeline_smoke.py
509
+ git commit -m "test: cross-pipeline smoke run for all three modalities"
510
+ ```
511
+
512
+ ---
513
+
514
+ ## Task 5: `src/core/tracking.py` — MLflow helper
515
+
516
+ **Why this task:** Each pipeline needs to log `params` (input path, configuration), `metrics` (row counts, runtime), and the output Parquet as an artifact. Writing four `mlflow.start_run / mlflow.log_param / mlflow.log_metric / mlflow.log_artifact` calls inline in each pipeline is duplication and breaks the existing tests (MLflow writes to a real `mlruns/` dir by default). Wrap in one helper.
517
+
518
+ **Files:**
519
+ - Create: `src/core/tracking.py`
520
+ - Create: `tests/core/test_tracking.py`
521
+ - Create: `conftest.py` at repo root (autouse fixture pinning `MLFLOW_TRACKING_URI` to a tmp path during tests)
522
+
523
+ - [ ] **Step 1: Write `conftest.py` to isolate MLflow during tests**
524
+
525
+ Create `/Users/mertgungor/Desktop/hackathon/conftest.py`:
526
+
527
+ ```python
528
+ """Repo-wide pytest fixtures.
529
+
530
+ Pins MLflow's tracking URI to a per-session tmp directory so pipeline tests
531
+ don't litter `./mlruns/` in the working tree, and so test runs are isolated
532
+ from production MLflow state.
533
+ """
534
+ from __future__ import annotations
535
+
536
+ import os
537
+ import tempfile
538
+ from pathlib import Path
539
+
540
+ import pytest
541
+
542
+
543
+ @pytest.fixture(autouse=True, scope="session")
544
+ def _isolate_mlflow_tracking_uri() -> None:
545
+ tmp_root = Path(tempfile.mkdtemp(prefix="mlflow_test_"))
546
+ os.environ["MLFLOW_TRACKING_URI"] = f"file://{tmp_root}"
547
+ yield
548
+ # Don't rmtree — pytest tmpdir cleanup or OS handles it; rmtree
549
+ # races with mlflow background writes on slow CI.
550
+ ```
551
+
552
+ - [ ] **Step 2: Write failing tests for tracking helper**
553
+
554
+ Create `tests/core/test_tracking.py`:
555
+
556
+ ```python
557
+ """Tests for src.core.tracking."""
558
+ from __future__ import annotations
559
+
560
+ import os
561
+ from pathlib import Path
562
+
563
+ import mlflow
564
+ import pandas as pd
565
+
566
+ from src.core import tracking
567
+
568
+
569
+ class TestTrackPipelineRun:
570
+ def test_creates_run_with_experiment_name(self, tmp_path: Path):
571
+ out = tmp_path / "out.parquet"
572
+ pd.DataFrame({"a": [1]}).to_parquet(out)
573
+ with tracking.track_pipeline_run(
574
+ experiment_name="bbb_pipeline",
575
+ params={"input_path": "x.csv"},
576
+ metrics={"rows_in": 6.0, "rows_out": 4.0},
577
+ artifact_path=out,
578
+ ) as run_id:
579
+ assert run_id is not None
580
+ runs = mlflow.search_runs(experiment_names=["bbb_pipeline"])
581
+ assert len(runs) >= 1
582
+
583
+ def test_logs_params(self, tmp_path: Path):
584
+ out = tmp_path / "out.parquet"
585
+ pd.DataFrame({"a": [1]}).to_parquet(out)
586
+ with tracking.track_pipeline_run(
587
+ experiment_name="bbb_pipeline_params",
588
+ params={"n_bits": 2048, "radius": 2},
589
+ metrics={},
590
+ artifact_path=out,
591
+ ):
592
+ pass
593
+ runs = mlflow.search_runs(experiment_names=["bbb_pipeline_params"])
594
+ assert "params.n_bits" in runs.columns
595
+ assert runs.iloc[0]["params.n_bits"] == "2048"
596
+
597
+ def test_logs_metrics(self, tmp_path: Path):
598
+ out = tmp_path / "out.parquet"
599
+ pd.DataFrame({"a": [1]}).to_parquet(out)
600
+ with tracking.track_pipeline_run(
601
+ experiment_name="eeg_pipeline_metrics",
602
+ params={},
603
+ metrics={"duration_sec": 1.234, "rows_out": 100.0},
604
+ artifact_path=out,
605
+ ):
606
+ pass
607
+ runs = mlflow.search_runs(experiment_names=["eeg_pipeline_metrics"])
608
+ assert runs.iloc[0]["metrics.duration_sec"] == 1.234
609
+ assert runs.iloc[0]["metrics.rows_out"] == 100.0
610
+
611
+ def test_logs_artifact(self, tmp_path: Path):
612
+ out = tmp_path / "out.parquet"
613
+ pd.DataFrame({"a": [1]}).to_parquet(out)
614
+ with tracking.track_pipeline_run(
615
+ experiment_name="mri_pipeline_artifact",
616
+ params={},
617
+ metrics={},
618
+ artifact_path=out,
619
+ ) as run_id:
620
+ pass
621
+ artifacts = mlflow.MlflowClient().list_artifacts(run_id)
622
+ assert any(a.path.endswith("out.parquet") for a in artifacts)
623
+
624
+ def test_disabled_via_env_returns_no_op(self, monkeypatch, tmp_path: Path):
625
+ """Setting NEUROBRIDGE_DISABLE_MLFLOW=1 must skip MLflow entirely
626
+ (used by Docker compose dev mode where the tracking server is down)."""
627
+ monkeypatch.setenv("NEUROBRIDGE_DISABLE_MLFLOW", "1")
628
+ out = tmp_path / "out.parquet"
629
+ pd.DataFrame({"a": [1]}).to_parquet(out)
630
+ with tracking.track_pipeline_run(
631
+ experiment_name="should_not_appear",
632
+ params={"x": 1},
633
+ metrics={"y": 2.0},
634
+ artifact_path=out,
635
+ ) as run_id:
636
+ assert run_id is None
637
+ # No "should_not_appear" experiment was created
638
+ names = [e.name for e in mlflow.search_experiments()]
639
+ assert "should_not_appear" not in names
640
+ ```
641
+
642
+ - [ ] **Step 3: Run tests to verify they fail**
643
+
644
+ ```
645
+ pytest tests/core/test_tracking.py -v
646
+ ```
647
+ Expected: errors — module not found.
648
+
649
+ - [ ] **Step 4: Implement `src/core/tracking.py`**
650
+
651
+ ```python
652
+ """MLflow tracking helper used by all three pipelines.
653
+
654
+ Wraps `mlflow.start_run` so each pipeline can log params, metrics, and an
655
+ output artifact in one block. Honors `NEUROBRIDGE_DISABLE_MLFLOW=1` for
656
+ environments where the tracking server is not reachable (offline demos, CI
657
+ without mlflow service). When disabled, yields `None` and does no I/O.
658
+
659
+ Tracking URI source of truth: the standard `MLFLOW_TRACKING_URI` env var.
660
+ Tests pin this via the repo-wide conftest.py autouse fixture.
661
+ """
662
+ from __future__ import annotations
663
+
664
+ import contextlib
665
+ import os
666
+ from pathlib import Path
667
+ from typing import Iterator
668
+
669
+ import mlflow
670
+
671
+ from src.core.logger import get_logger
672
+
673
+ logger = get_logger(__name__)
674
+
675
+ _DISABLE_FLAG = "NEUROBRIDGE_DISABLE_MLFLOW"
676
+
677
+
678
+ @contextlib.contextmanager
679
+ def track_pipeline_run(
680
+ experiment_name: str,
681
+ params: dict[str, object],
682
+ metrics: dict[str, float],
683
+ artifact_path: Path,
684
+ ) -> Iterator[str | None]:
685
+ """Context manager that creates an MLflow run for one pipeline invocation.
686
+
687
+ On enter: creates/loads `experiment_name`, starts a run, logs params + metrics.
688
+ On exit: logs `artifact_path` as an artifact and ends the run.
689
+
690
+ Yields the active `run_id` (str), or `None` if MLflow is disabled.
691
+
692
+ Args:
693
+ experiment_name: e.g. "bbb_pipeline" / "eeg_pipeline" / "mri_pipeline".
694
+ params: Run parameters (input path, hyper-params, etc.). Stringified by MLflow.
695
+ metrics: Numeric metrics (row counts, durations).
696
+ artifact_path: Path to the produced Parquet — logged as a run artifact.
697
+ """
698
+ if os.environ.get(_DISABLE_FLAG) == "1":
699
+ logger.info("MLflow disabled via %s=1; skipping run tracking", _DISABLE_FLAG)
700
+ yield None
701
+ return
702
+
703
+ mlflow.set_experiment(experiment_name)
704
+ with mlflow.start_run() as run:
705
+ for key, value in params.items():
706
+ mlflow.log_param(key, value)
707
+ for key, value in metrics.items():
708
+ mlflow.log_metric(key, value)
709
+ try:
710
+ yield run.info.run_id
711
+ finally:
712
+ if Path(artifact_path).exists():
713
+ mlflow.log_artifact(str(artifact_path))
714
+ ```
715
+
716
+ - [ ] **Step 5: Run tests to verify they pass**
717
+
718
+ ```
719
+ pytest tests/core/test_tracking.py -v
720
+ ```
721
+ Expected: 5 passed.
722
+
723
+ - [ ] **Step 6: Commit**
724
+
725
+ ```bash
726
+ git add conftest.py src/core/tracking.py tests/core/test_tracking.py
727
+ git commit -m "feat(core): add MLflow tracking helper with disable env-flag"
728
+ ```
729
+
730
+ ---
731
+
732
+ ## Task 6: Wire MLflow tracking into all three pipelines
733
+
734
+ **Why this task:** Each `run_pipeline()` should log params (input/output paths + hyperparams), metrics (rows_in / rows_out / duration_sec), and the output Parquet as an artifact.
735
+
736
+ **Files:**
737
+ - Modify: `src/pipelines/bbb_pipeline.py` (`run_pipeline` function)
738
+ - Modify: `src/pipelines/eeg_pipeline.py` (same)
739
+ - Modify: `src/pipelines/mri_pipeline.py` (same)
740
+ - Modify: `tests/pipelines/test_bbb_pipeline.py` (add 1 test that asserts an MLflow run is created)
741
+ - Modify: `tests/pipelines/test_eeg_pipeline.py` (same)
742
+ - Modify: `tests/pipelines/test_mri_pipeline.py` (same)
743
+
744
+ - [ ] **Step 1: Add MLflow assertion test to BBB**
745
+
746
+ Append to `tests/pipelines/test_bbb_pipeline.py`:
747
+
748
+ ```python
749
+ import mlflow
750
+ from src.pipelines import bbb_pipeline as _bbb_for_mlflow_test
751
+
752
+
753
+ class TestBBBPipelineMLflow:
754
+ def test_run_pipeline_creates_mlflow_run(self, tmp_path):
755
+ fixture = Path(__file__).resolve().parents[1] / "fixtures" / "bbbp_sample.csv"
756
+ out = tmp_path / "out.parquet"
757
+ _bbb_for_mlflow_test.run_pipeline(input_path=fixture, output_path=out)
758
+ runs = mlflow.search_runs(experiment_names=["bbb_pipeline"])
759
+ assert len(runs) >= 1
760
+ assert "metrics.rows_out" in runs.columns
761
+ assert runs.iloc[0]["metrics.rows_out"] > 0
762
+ ```
763
+
764
+ - [ ] **Step 2: Run failing test**
765
+
766
+ ```
767
+ pytest tests/pipelines/test_bbb_pipeline.py::TestBBBPipelineMLflow -v
768
+ ```
769
+ Expected: FAIL — no `bbb_pipeline` experiment.
770
+
771
+ - [ ] **Step 3: Wire MLflow into `bbb_pipeline.run_pipeline`**
772
+
773
+ In `src/pipelines/bbb_pipeline.py`, modify `run_pipeline`:
774
+
775
+ ```python
776
+ import time
777
+
778
+ from src.core.tracking import track_pipeline_run
779
+
780
+ def run_pipeline(
781
+ input_path: Path = DEFAULT_INPUT,
782
+ output_path: Path = DEFAULT_OUTPUT,
783
+ smiles_col: str = "smiles",
784
+ n_bits: int = 2048,
785
+ radius: int = 2,
786
+ ) -> None:
787
+ input_path = Path(input_path)
788
+ output_path = Path(output_path)
789
+ if not input_path.exists():
790
+ raise FileNotFoundError(f"Raw BBBP file not found: {input_path}")
791
+
792
+ started = time.perf_counter()
793
+ logger.info("Reading raw BBBP from %s", input_path)
794
+ df = pd.read_csv(input_path)
795
+ logger.info("Loaded %d rows, %d columns", len(df), len(df.columns))
796
+
797
+ features = extract_features_from_dataframe(
798
+ df, smiles_col=smiles_col, n_bits=n_bits, radius=radius,
799
+ )
800
+ write_parquet(features, output_path)
801
+ duration_sec = time.perf_counter() - started
802
+
803
+ logger.info(
804
+ "Wrote processed features to %s (rows=%d, cols=%d)",
805
+ output_path, len(features), features.shape[1],
806
+ )
807
+
808
+ with track_pipeline_run(
809
+ experiment_name="bbb_pipeline",
810
+ params={
811
+ "input_path": str(input_path),
812
+ "output_path": str(output_path),
813
+ "n_bits": n_bits,
814
+ "radius": radius,
815
+ },
816
+ metrics={
817
+ "rows_in": float(len(df)),
818
+ "rows_out": float(len(features)),
819
+ "rows_dropped": float(len(df) - len(features)),
820
+ "duration_sec": duration_sec,
821
+ },
822
+ artifact_path=output_path,
823
+ ):
824
+ pass
825
+ ```
826
+
827
+ - [ ] **Step 4: Run BBB test suite**
828
+
829
+ ```
830
+ pytest tests/pipelines/test_bbb_pipeline.py -v
831
+ ```
832
+ Expected: 24 passed (was 23 + 1 new MLflow test).
833
+
834
+ - [ ] **Step 5: Commit**
835
+
836
+ ```bash
837
+ git add src/pipelines/bbb_pipeline.py tests/pipelines/test_bbb_pipeline.py
838
+ git commit -m "feat(bbb): log run params, metrics, and parquet artifact to MLflow"
839
+ ```
840
+
841
+ - [ ] **Step 6: Repeat for EEG**
842
+
843
+ Add a TestEEGPipelineMLflow class to `tests/pipelines/test_eeg_pipeline.py` mirroring the BBB pattern (using the EEG fixture). In `src/pipelines/eeg_pipeline.py`, wire MLflow into `run_pipeline` with experiment_name="eeg_pipeline" and EEG-relevant params (input_path, l_freq, h_freq, epoch_duration, etc.) and metrics (epochs_in, epochs_out, channels, duration_sec).
844
+
845
+ Run: `pytest tests/pipelines/test_eeg_pipeline.py -v` → 38 passed.
846
+ Commit: `feat(eeg): log run params, metrics, and parquet artifact to MLflow`.
847
+
848
+ - [ ] **Step 7: Repeat for MRI**
849
+
850
+ Add a TestMRIPipelineMLflow class. Wire MLflow into MRI `run_pipeline` with experiment_name="mri_pipeline" and MRI-relevant params (input_dir, sites_csv, n_roi_axes) and metrics (subjects_in, subjects_out, sites_count, duration_sec).
851
+
852
+ Run: `pytest tests/pipelines/test_mri_pipeline.py -v` → 40 passed.
853
+ Commit: `feat(mri): log run params, metrics, and parquet artifact to MLflow`.
854
+
855
+ - [ ] **Step 8: Run full test suite**
856
+
857
+ ```
858
+ pytest -v
859
+ ```
860
+ Expected total: ~119 tests passed (113 prior + 3 MLflow tests + 3 in-pipeline rewires; verify exact count, fix any reds).
861
+
862
+ ---
863
+
864
+ ## Task 7: FastAPI scaffolding — `schemas.py` + `main.py` + /health
865
+
866
+ **Why this task:** Stand up the FastAPI app with shared Pydantic models before adding pipeline routes. /health returns 200 OK so docker-compose health checks have something to poll.
867
+
868
+ **Files:**
869
+ - Create: `src/api/schemas.py`
870
+ - Create: `src/api/main.py`
871
+ - Create: `tests/api/__init__.py` (empty)
872
+ - Create: `tests/api/test_main.py`
873
+
874
+ - [ ] **Step 1: Write failing tests for /health**
875
+
876
+ Create `tests/api/__init__.py` (empty file).
877
+
878
+ Create `tests/api/test_main.py`:
879
+
880
+ ```python
881
+ """Tests for the FastAPI app surface (health + schema imports)."""
882
+ from __future__ import annotations
883
+
884
+ from fastapi.testclient import TestClient
885
+
886
+ from src.api.main import app
887
+
888
+
889
+ client = TestClient(app)
890
+
891
+
892
+ class TestHealthEndpoint:
893
+ def test_get_health_returns_200(self):
894
+ resp = client.get("/health")
895
+ assert resp.status_code == 200
896
+
897
+ def test_get_health_returns_status_ok(self):
898
+ resp = client.get("/health")
899
+ assert resp.json()["status"] == "ok"
900
+
901
+ def test_get_health_returns_pipeline_list(self):
902
+ resp = client.get("/health")
903
+ body = resp.json()
904
+ assert set(body["pipelines"]) == {"bbb", "eeg", "mri"}
905
+ ```
906
+
907
+ - [ ] **Step 2: Run tests to verify they fail**
908
+
909
+ ```
910
+ pytest tests/api/test_main.py -v
911
+ ```
912
+ Expected: ImportError — module not found.
913
+
914
+ - [ ] **Step 3: Implement `src/api/schemas.py`**
915
+
916
+ ```python
917
+ """Pydantic request / response models for the NeuroBridge FastAPI surface.
918
+
919
+ Each pipeline accepts its own request schema (BBBRequest / EEGRequest /
920
+ MRIRequest) but they all return a unified PipelineResponse — the dashboard
921
+ can render a single result card regardless of modality.
922
+ """
923
+ from __future__ import annotations
924
+
925
+ from pydantic import BaseModel, Field
926
+
927
+
928
+ class BBBRequest(BaseModel):
929
+ input_path: str = Field(..., description="CSV path with a 'smiles' column")
930
+ output_path: str = Field(..., description="Parquet output path")
931
+ smiles_col: str = "smiles"
932
+ n_bits: int = 2048
933
+ radius: int = 2
934
+
935
+
936
+ class EEGRequest(BaseModel):
937
+ input_path: str = Field(..., description="FIF or EDF file")
938
+ output_path: str = Field(..., description="Parquet output path")
939
+ l_freq: float = 1.0
940
+ h_freq: float = 40.0
941
+ epoch_duration_sec: float = 2.0
942
+
943
+
944
+ class MRIRequest(BaseModel):
945
+ input_dir: str = Field(..., description="Directory of .nii.gz files")
946
+ sites_csv: str = Field(..., description="CSV mapping subject_id → site")
947
+ output_path: str = Field(..., description="Parquet output path")
948
+
949
+
950
+ class PipelineResponse(BaseModel):
951
+ """Uniform response for every pipeline route."""
952
+ status: str
953
+ output_path: str
954
+ rows: int
955
+ columns: int
956
+ duration_sec: float
957
+ mlflow_run_id: str | None = None
958
+
959
+
960
+ class HealthResponse(BaseModel):
961
+ status: str
962
+ pipelines: list[str]
963
+ ```
964
+
965
+ - [ ] **Step 4: Implement `src/api/main.py`**
966
+
967
+ ```python
968
+ """NeuroBridge FastAPI entrypoint.
969
+
970
+ Exposes /health for liveness and mounts pipeline routes from src.api.routes.
971
+ """
972
+ from __future__ import annotations
973
+
974
+ from fastapi import FastAPI
975
+
976
+ from src.api.schemas import HealthResponse
977
+
978
+ app = FastAPI(
979
+ title="NeuroBridge Enterprise",
980
+ description="Three-modality clinical-ML pipeline surface (BBB / EEG / MRI).",
981
+ version="0.4.0",
982
+ )
983
+
984
+
985
+ @app.get("/health", response_model=HealthResponse)
986
+ def health() -> HealthResponse:
987
+ return HealthResponse(status="ok", pipelines=["bbb", "eeg", "mri"])
988
+ ```
989
+
990
+ - [ ] **Step 5: Run tests to verify pass**
991
+
992
+ ```
993
+ pytest tests/api/test_main.py -v
994
+ ```
995
+ Expected: 3 passed.
996
+
997
+ - [ ] **Step 6: Commit**
998
+
999
+ ```bash
1000
+ git add src/api/schemas.py src/api/main.py tests/api/__init__.py tests/api/test_main.py
1001
+ git commit -m "feat(api): scaffold FastAPI app + /health + shared Pydantic schemas"
1002
+ ```
1003
+
1004
+ ---
1005
+
1006
+ ## Task 8: FastAPI pipeline routes
1007
+
1008
+ **Why this task:** Three POST endpoints — one per modality — each invokes the corresponding `run_pipeline()` and returns the unified `PipelineResponse`. Errors mapped to HTTP codes: missing input → 404, bad path → 400, pipeline crash → 500.
1009
+
1010
+ **Files:**
1011
+ - Create: `src/api/routes.py`
1012
+ - Create: `tests/api/test_routes.py`
1013
+ - Modify: `src/api/main.py` (mount the router)
1014
+
1015
+ - [ ] **Step 1: Write failing route tests**
1016
+
1017
+ Create `tests/api/test_routes.py`:
1018
+
1019
+ ```python
1020
+ """Tests for /pipeline/{bbb,eeg,mri} POST endpoints."""
1021
+ from __future__ import annotations
1022
+
1023
+ from pathlib import Path
1024
+
1025
+ import pandas as pd
1026
+ from fastapi.testclient import TestClient
1027
+
1028
+ from src.api.main import app
1029
+
1030
+
1031
+ client = TestClient(app)
1032
+ _FIXTURES = Path(__file__).resolve().parents[1] / "fixtures"
1033
+
1034
+
1035
+ class TestBBBRoute:
1036
+ def test_returns_200_with_valid_input(self, tmp_path: Path):
1037
+ out = tmp_path / "out.parquet"
1038
+ resp = client.post(
1039
+ "/pipeline/bbb",
1040
+ json={
1041
+ "input_path": str(_FIXTURES / "bbbp_sample.csv"),
1042
+ "output_path": str(out),
1043
+ },
1044
+ )
1045
+ assert resp.status_code == 200
1046
+ body = resp.json()
1047
+ assert body["status"] == "ok"
1048
+ assert body["rows"] > 0
1049
+ assert out.exists()
1050
+
1051
+ def test_returns_404_when_input_missing(self, tmp_path: Path):
1052
+ resp = client.post(
1053
+ "/pipeline/bbb",
1054
+ json={
1055
+ "input_path": str(tmp_path / "does_not_exist.csv"),
1056
+ "output_path": str(tmp_path / "out.parquet"),
1057
+ },
1058
+ )
1059
+ assert resp.status_code == 404
1060
+
1061
+ def test_returns_422_on_malformed_body(self):
1062
+ resp = client.post("/pipeline/bbb", json={"banana": 1})
1063
+ assert resp.status_code == 422 # pydantic validation
1064
+
1065
+
1066
+ class TestEEGRoute:
1067
+ def test_returns_200_with_valid_input(self, tmp_path: Path):
1068
+ from tests.fixtures.build_eeg_fixture import build as build_eeg
1069
+ fif = build_eeg(out_dir=tmp_path / "eeg_fixture")
1070
+ out = tmp_path / "out.parquet"
1071
+ resp = client.post(
1072
+ "/pipeline/eeg",
1073
+ json={"input_path": str(fif), "output_path": str(out)},
1074
+ )
1075
+ assert resp.status_code == 200
1076
+ assert resp.json()["rows"] > 0
1077
+
1078
+
1079
+ class TestMRIRoute:
1080
+ def test_returns_200_with_valid_input(self, tmp_path: Path):
1081
+ from tests.fixtures.build_mri_fixture import build as build_mri
1082
+ fixture_dir = build_mri(out_dir=tmp_path / "mri_fixture")
1083
+ out = tmp_path / "out.parquet"
1084
+ resp = client.post(
1085
+ "/pipeline/mri",
1086
+ json={
1087
+ "input_dir": str(fixture_dir),
1088
+ "sites_csv": str(fixture_dir / "sites.csv"),
1089
+ "output_path": str(out),
1090
+ },
1091
+ )
1092
+ assert resp.status_code == 200
1093
+ assert resp.json()["rows"] > 0
1094
+ ```
1095
+
1096
+ - [ ] **Step 2: Run failing tests**
1097
+
1098
+ ```
1099
+ pytest tests/api/test_routes.py -v
1100
+ ```
1101
+ Expected: 5 errors — endpoints return 404 (route not mounted).
1102
+
1103
+ - [ ] **Step 3: Implement `src/api/routes.py`**
1104
+
1105
+ ```python
1106
+ """POST /pipeline/{bbb,eeg,mri} routes — thin dispatchers over the pipelines.
1107
+
1108
+ Each route validates its request body via Pydantic, invokes the pipeline,
1109
+ reads back the produced Parquet to populate row/column counts, and returns
1110
+ a uniform PipelineResponse. Pipeline-domain errors map to standard HTTP
1111
+ codes: FileNotFoundError → 404, ValueError → 400, anything else → 500.
1112
+ """
1113
+ from __future__ import annotations
1114
+
1115
+ import time
1116
+ from pathlib import Path
1117
+
1118
+ import mlflow
1119
+ import pandas as pd
1120
+ from fastapi import APIRouter, HTTPException
1121
+
1122
+ from src.api.schemas import (
1123
+ BBBRequest, EEGRequest, MRIRequest, PipelineResponse,
1124
+ )
1125
+ from src.core.logger import get_logger
1126
+ from src.pipelines import bbb_pipeline, eeg_pipeline, mri_pipeline
1127
+
1128
+ logger = get_logger(__name__)
1129
+ router = APIRouter(prefix="/pipeline")
1130
+
1131
+
1132
+ def _wrap(experiment_name: str, output_path: Path, fn) -> PipelineResponse:
1133
+ """Run `fn()` (the pipeline call), gather metrics, return PipelineResponse."""
1134
+ started = time.perf_counter()
1135
+ try:
1136
+ fn()
1137
+ except FileNotFoundError as e:
1138
+ raise HTTPException(status_code=404, detail=str(e))
1139
+ except ValueError as e:
1140
+ raise HTTPException(status_code=400, detail=str(e))
1141
+ duration_sec = time.perf_counter() - started
1142
+
1143
+ df = pd.read_parquet(output_path)
1144
+ runs = mlflow.search_runs(
1145
+ experiment_names=[experiment_name],
1146
+ max_results=1,
1147
+ order_by=["start_time DESC"],
1148
+ )
1149
+ run_id = runs.iloc[0]["run_id"] if len(runs) else None
1150
+
1151
+ return PipelineResponse(
1152
+ status="ok",
1153
+ output_path=str(output_path),
1154
+ rows=len(df),
1155
+ columns=df.shape[1],
1156
+ duration_sec=duration_sec,
1157
+ mlflow_run_id=run_id,
1158
+ )
1159
+
1160
+
1161
+ @router.post("/bbb", response_model=PipelineResponse)
1162
+ def run_bbb(req: BBBRequest) -> PipelineResponse:
1163
+ return _wrap(
1164
+ "bbb_pipeline",
1165
+ Path(req.output_path),
1166
+ lambda: bbb_pipeline.run_pipeline(
1167
+ input_path=Path(req.input_path),
1168
+ output_path=Path(req.output_path),
1169
+ smiles_col=req.smiles_col,
1170
+ n_bits=req.n_bits,
1171
+ radius=req.radius,
1172
+ ),
1173
+ )
1174
+
1175
+
1176
+ @router.post("/eeg", response_model=PipelineResponse)
1177
+ def run_eeg(req: EEGRequest) -> PipelineResponse:
1178
+ return _wrap(
1179
+ "eeg_pipeline",
1180
+ Path(req.output_path),
1181
+ lambda: eeg_pipeline.run_pipeline(
1182
+ input_path=Path(req.input_path),
1183
+ output_path=Path(req.output_path),
1184
+ l_freq=req.l_freq,
1185
+ h_freq=req.h_freq,
1186
+ epoch_duration_sec=req.epoch_duration_sec,
1187
+ ),
1188
+ )
1189
+
1190
+
1191
+ @router.post("/mri", response_model=PipelineResponse)
1192
+ def run_mri(req: MRIRequest) -> PipelineResponse:
1193
+ return _wrap(
1194
+ "mri_pipeline",
1195
+ Path(req.output_path),
1196
+ lambda: mri_pipeline.run_pipeline(
1197
+ input_dir=Path(req.input_dir),
1198
+ sites_csv=Path(req.sites_csv),
1199
+ output_path=Path(req.output_path),
1200
+ ),
1201
+ )
1202
+ ```
1203
+
1204
+ > **Verify before writing:** confirm `eeg_pipeline.run_pipeline` and `mri_pipeline.run_pipeline` accept the parameter names used in the lambdas (`l_freq`, `h_freq`, `epoch_duration_sec` for EEG; `input_dir`, `sites_csv`, `output_path` for MRI). Read the actual function signatures first; if names differ, adjust the request schema in `src/api/schemas.py` to match. **Do not invent parameter names.**
1205
+
1206
+ - [ ] **Step 4: Mount router in `src/api/main.py`**
1207
+
1208
+ Edit `src/api/main.py`, after the `app = FastAPI(...)` line:
1209
+
1210
+ ```python
1211
+ from src.api.routes import router as pipeline_router
1212
+
1213
+ app.include_router(pipeline_router)
1214
+ ```
1215
+
1216
+ - [ ] **Step 5: Run tests**
1217
+
1218
+ ```
1219
+ pytest tests/api/ -v
1220
+ ```
1221
+ Expected: 8 passed (3 main + 5 routes).
1222
+
1223
+ - [ ] **Step 6: Commit**
1224
+
1225
+ ```bash
1226
+ git add src/api/routes.py src/api/main.py tests/api/test_routes.py
1227
+ git commit -m "feat(api): POST /pipeline/{bbb,eeg,mri} dispatch routes"
1228
+ ```
1229
+
1230
+ ---
1231
+
1232
+ ## Task 9: Dockerfile + docker-compose.yml
1233
+
1234
+ **Why this task:** Single-command boot for FastAPI + MLflow tracking server. Judges run `docker compose up`, browse to localhost:8000 / localhost:5000, see the system live.
1235
+
1236
+ **Files:**
1237
+ - Create: `Dockerfile`
1238
+ - Create: `docker-compose.yml`
1239
+ - Create: `.dockerignore`
1240
+
1241
+ - [ ] **Step 1: Write `.dockerignore`**
1242
+
1243
+ ```
1244
+ .venv/
1245
+ .venv312/
1246
+ __pycache__/
1247
+ *.pyc
1248
+ .pytest_cache/
1249
+ .mypy_cache/
1250
+ data/raw/*
1251
+ data/processed/*
1252
+ mlruns/
1253
+ .git/
1254
+ docs/
1255
+ tests/
1256
+ ```
1257
+
1258
+ - [ ] **Step 2: Write `Dockerfile`**
1259
+
1260
+ ```dockerfile
1261
+ # NeuroBridge Enterprise — multi-stage build, FastAPI + pipeline runtime image.
1262
+ # Python 3.12 because RDKit / scikit-learn / numpy pins ship cp310-cp312 wheels only.
1263
+ FROM python:3.12-slim AS runtime
1264
+
1265
+ # System deps required by RDKit (libxrender, libxext) and nibabel/MNE
1266
+ # (libgomp). Slim base lacks them.
1267
+ RUN apt-get update && apt-get install -y --no-install-recommends \
1268
+ libxrender1 \
1269
+ libxext6 \
1270
+ libgomp1 \
1271
+ && rm -rf /var/lib/apt/lists/*
1272
+
1273
+ WORKDIR /app
1274
+
1275
+ # Install dependencies first so the layer is cached when only source changes.
1276
+ COPY requirements.txt .
1277
+ RUN pip install --no-cache-dir -r requirements.txt
1278
+
1279
+ COPY src/ src/
1280
+ COPY AGENTS.md README.md ./
1281
+
1282
+ # Determinism env vars baked in (the pipelines re-pin defensively but
1283
+ # baking them avoids a brief race on container start).
1284
+ ENV OMP_NUM_THREADS=1 \
1285
+ OPENBLAS_NUM_THREADS=1 \
1286
+ MKL_NUM_THREADS=1 \
1287
+ PYTHONUNBUFFERED=1
1288
+
1289
+ EXPOSE 8000
1290
+ CMD ["uvicorn", "src.api.main:app", "--host", "0.0.0.0", "--port", "8000"]
1291
+ ```
1292
+
1293
+ - [ ] **Step 3: Write `docker-compose.yml`**
1294
+
1295
+ ```yaml
1296
+ services:
1297
+ mlflow:
1298
+ image: ghcr.io/mlflow/mlflow:v2.16.0
1299
+ command: >
1300
+ mlflow server
1301
+ --host 0.0.0.0
1302
+ --port 5000
1303
+ --backend-store-uri /mlflow/mlruns
1304
+ --default-artifact-root /mlflow/mlruns
1305
+ ports:
1306
+ - "5000:5000"
1307
+ volumes:
1308
+ - mlflow-data:/mlflow/mlruns
1309
+
1310
+ api:
1311
+ build: .
1312
+ ports:
1313
+ - "8000:8000"
1314
+ environment:
1315
+ MLFLOW_TRACKING_URI: http://mlflow:5000
1316
+ depends_on:
1317
+ - mlflow
1318
+ volumes:
1319
+ - ./data:/app/data
1320
+
1321
+ volumes:
1322
+ mlflow-data:
1323
+ ```
1324
+
1325
+ - [ ] **Step 4: Validate compose syntax**
1326
+
1327
+ ```
1328
+ docker compose config
1329
+ ```
1330
+ Expected: prints the resolved YAML with no errors. (Skip this step if Docker is not installed locally; the file syntax is straightforward.)
1331
+
1332
+ - [ ] **Step 5: Commit**
1333
+
1334
+ ```bash
1335
+ git add Dockerfile docker-compose.yml .dockerignore
1336
+ git commit -m "feat(deploy): Dockerfile + compose for api + mlflow server"
1337
+ ```
1338
+
1339
+ ---
1340
+
1341
+ ## Task 10: Streamlit B2B dashboard
1342
+
1343
+ **Why this task:** The hackathon judges' first impression. Three tabs (Molecule / Signal / Image), each fires a POST to the FastAPI surface and shows the result + an MLflow link.
1344
+
1345
+ **Files:**
1346
+ - Modify: `requirements.txt` (add `streamlit==1.39.0`)
1347
+ - Create: `src/frontend/__init__.py`
1348
+ - Create: `src/frontend/app.py`
1349
+ - Create: `tests/frontend/__init__.py`
1350
+ - Create: `tests/frontend/test_app_import.py`
1351
+
1352
+ - [ ] **Step 1: Add streamlit to requirements**
1353
+
1354
+ In `requirements.txt`, after the `# --- Tooling / tests ---` block (or under a new `# --- Frontend ---` block):
1355
+
1356
+ ```
1357
+ # --- Frontend (B2B dashboard) ---
1358
+ streamlit==1.39.0
1359
+ ```
1360
+
1361
+ Run: `pip install -r requirements.txt` to install it locally.
1362
+
1363
+ - [ ] **Step 2: Write smoke import test**
1364
+
1365
+ Create `tests/frontend/__init__.py` (empty).
1366
+
1367
+ Create `tests/frontend/test_app_import.py`:
1368
+
1369
+ ```python
1370
+ """Smoke-test that the Streamlit app module imports cleanly.
1371
+
1372
+ Streamlit UIs are hard to unit-test without `streamlit.testing` (which
1373
+ spawns a headless app); for hackathon scope we settle for a clean import
1374
+ + presence of the page-config call. Manual UX testing via `streamlit run`.
1375
+ """
1376
+ from __future__ import annotations
1377
+
1378
+
1379
+ def test_app_module_imports():
1380
+ from src.frontend import app # noqa: F401
1381
+
1382
+
1383
+ def test_app_module_defines_main():
1384
+ from src.frontend import app
1385
+ assert hasattr(app, "main")
1386
+ assert callable(app.main)
1387
+ ```
1388
+
1389
+ - [ ] **Step 3: Run failing test**
1390
+
1391
+ ```
1392
+ pytest tests/frontend/ -v
1393
+ ```
1394
+ Expected: ImportError.
1395
+
1396
+ - [ ] **Step 4: Implement `src/frontend/__init__.py`** (empty file).
1397
+
1398
+ - [ ] **Step 5: Implement `src/frontend/app.py`**
1399
+
1400
+ ```python
1401
+ """NeuroBridge Enterprise — Streamlit B2B dashboard.
1402
+
1403
+ Three tabs (Molecule / Signal / Image), each fires a POST request against the
1404
+ sibling FastAPI service and renders a result card with row counts, runtime,
1405
+ and a link to the corresponding MLflow run.
1406
+
1407
+ Launch: `streamlit run src/frontend/app.py`
1408
+ """
1409
+ from __future__ import annotations
1410
+
1411
+ import os
1412
+
1413
+ import httpx
1414
+ import streamlit as st
1415
+
1416
+
1417
+ _API_URL = os.environ.get("NEUROBRIDGE_API_URL", "http://localhost:8000")
1418
+ _MLFLOW_URL = os.environ.get("MLFLOW_TRACKING_URI", "http://localhost:5000")
1419
+
1420
+
1421
+ def _post(endpoint: str, payload: dict) -> dict:
1422
+ resp = httpx.post(f"{_API_URL}{endpoint}", json=payload, timeout=120.0)
1423
+ resp.raise_for_status()
1424
+ return resp.json()
1425
+
1426
+
1427
+ def _render_result(body: dict) -> None:
1428
+ cols = st.columns(3)
1429
+ cols[0].metric("Rows", body["rows"])
1430
+ cols[1].metric("Columns", body["columns"])
1431
+ cols[2].metric("Runtime (sec)", f"{body['duration_sec']:.2f}")
1432
+ st.success(f"Wrote: `{body['output_path']}`")
1433
+ if body.get("mlflow_run_id"):
1434
+ st.markdown(
1435
+ f"**MLflow run:** [{body['mlflow_run_id']}]"
1436
+ f"({_MLFLOW_URL}/#/experiments/0/runs/{body['mlflow_run_id']})"
1437
+ )
1438
+
1439
+
1440
+ def main() -> None:
1441
+ st.set_page_config(
1442
+ page_title="NeuroBridge Enterprise",
1443
+ page_icon="🧠",
1444
+ layout="wide",
1445
+ )
1446
+ st.title("NeuroBridge Enterprise")
1447
+ st.caption(
1448
+ "Three-modality clinical ML platform — solving Data Drift, "
1449
+ "Missing Modalities, and Artifacts."
1450
+ )
1451
+
1452
+ bbb_tab, eeg_tab, mri_tab = st.tabs([
1453
+ "🧪 Molecule (BBB)",
1454
+ "🧠 Signal (EEG)",
1455
+ "📷 Image (MRI)",
1456
+ ])
1457
+
1458
+ with bbb_tab:
1459
+ st.subheader("Blood-Brain-Barrier penetration — Morgan fingerprint")
1460
+ bbb_in = st.text_input("Input CSV path", "data/raw/bbbp.csv")
1461
+ bbb_out = st.text_input("Output Parquet path", "data/processed/bbbp_features.parquet")
1462
+ if st.button("Run BBB Pipeline"):
1463
+ with st.spinner("Computing fingerprints..."):
1464
+ _render_result(_post("/pipeline/bbb", {
1465
+ "input_path": bbb_in, "output_path": bbb_out,
1466
+ }))
1467
+
1468
+ with eeg_tab:
1469
+ st.subheader("EEG — bandpass + ICA artifact removal")
1470
+ eeg_in = st.text_input("Input FIF/EDF path", "data/raw/eeg.fif")
1471
+ eeg_out = st.text_input("Output Parquet path", "data/processed/eeg_features.parquet")
1472
+ if st.button("Run EEG Pipeline"):
1473
+ with st.spinner("Filtering + ICA..."):
1474
+ _render_result(_post("/pipeline/eeg", {
1475
+ "input_path": eeg_in, "output_path": eeg_out,
1476
+ }))
1477
+
1478
+ with mri_tab:
1479
+ st.subheader("MRI — site-level ComBat harmonization")
1480
+ mri_dir = st.text_input("Input NIfTI dir", "data/raw/mri/")
1481
+ sites_csv = st.text_input("Sites CSV", "data/raw/mri/sites.csv")
1482
+ mri_out = st.text_input("Output Parquet path", "data/processed/mri_features.parquet")
1483
+ if st.button("Run MRI Pipeline"):
1484
+ with st.spinner("Masking + ComBat..."):
1485
+ _render_result(_post("/pipeline/mri", {
1486
+ "input_dir": mri_dir,
1487
+ "sites_csv": sites_csv,
1488
+ "output_path": mri_out,
1489
+ }))
1490
+
1491
+
1492
+ if __name__ == "__main__":
1493
+ main()
1494
+ ```
1495
+
1496
+ - [ ] **Step 6: Run tests**
1497
+
1498
+ ```
1499
+ pytest tests/frontend/ -v
1500
+ ```
1501
+ Expected: 2 passed.
1502
+
1503
+ - [ ] **Step 7: Smoke-launch Streamlit (manual)**
1504
+
1505
+ ```
1506
+ streamlit run src/frontend/app.py
1507
+ ```
1508
+ Open <http://localhost:8501>, click each tab. Expect: page loads, three tabs visible, Run buttons present (clicking will fail without the FastAPI service running — that's fine, this is a UI render check).
1509
+
1510
+ - [ ] **Step 8: Commit**
1511
+
1512
+ ```bash
1513
+ git add requirements.txt src/frontend/__init__.py src/frontend/app.py \
1514
+ tests/frontend/__init__.py tests/frontend/test_app_import.py
1515
+ git commit -m "feat(frontend): Streamlit dashboard with 3 modality tabs"
1516
+ ```
1517
+
1518
+ ---
1519
+
1520
+ ## Task 11: AGENTS.md + README.md updates + final DoD
1521
+
1522
+ **Why this task:** Document the new layers in the contract file and roadmap. Run the full smoke verification one more time. Tag the commit.
1523
+
1524
+ **Files:**
1525
+ - Modify: `AGENTS.md` (§2 directory tree, new sub-section in §6 about MLflow tracking)
1526
+ - Modify: `README.md` (status table + Quick Start + Day-4 in roadmap)
1527
+
1528
+ - [ ] **Step 1: Update `AGENTS.md`**
1529
+
1530
+ In §2 Directory Layout, add `src/frontend/` and the new `src/core/{determinism,storage,tracking}.py` files. Add an entry for `Dockerfile` and `docker-compose.yml`.
1531
+
1532
+ After §6 Storage Format Convention, add §7:
1533
+
1534
+ ```markdown
1535
+ ## 7. Experiment Tracking
1536
+
1537
+ Every `run_pipeline()` invocation logs to MLflow via `src.core.tracking.track_pipeline_run`:
1538
+ - **Experiment names** are the pipeline module name (`bbb_pipeline`, `eeg_pipeline`, `mri_pipeline`).
1539
+ - **Params**: input/output paths and pipeline hyperparameters.
1540
+ - **Metrics**: row counts (in/out/dropped) and `duration_sec`.
1541
+ - **Artifact**: the output Parquet at `data/processed/<modality>_features.parquet`.
1542
+
1543
+ The tracking URI is read from `MLFLOW_TRACKING_URI` (defaults to `./mlruns/` when unset).
1544
+ Set `NEUROBRIDGE_DISABLE_MLFLOW=1` to skip tracking entirely (offline / CI fallback).
1545
+
1546
+ The repo-wide `conftest.py` autouse fixture pins `MLFLOW_TRACKING_URI` to a tmp dir for tests
1547
+ so the production `mlruns/` directory is never written from the test suite.
1548
+ ```
1549
+
1550
+ - [ ] **Step 2: Update `README.md`**
1551
+
1552
+ - Status table: replace Day-4 "(planned)" with "Shipped — N tests green" once final count is known.
1553
+ - Add a Quick Start section: `docker compose up`, point browsers at `:8000/docs` (FastAPI Swagger) and `:8501` (Streamlit).
1554
+ - Add to "Where to Look": `docs/superpowers/plans/2026-05-02-day4-api-mlops-frontend.md`, `src/core/{determinism,storage,tracking}.py`, `src/api/`, `src/frontend/`.
1555
+ - Roadmap: mark Day 4 done.
1556
+
1557
+ - [ ] **Step 3: Run full test suite for DoD**
1558
+
1559
+ ```
1560
+ pytest -v
1561
+ ```
1562
+ Expected: ~136 tests passed total. If any reds, debug before continuing.
1563
+
1564
+ - [ ] **Step 4: Verify three CLI smoke runs still produce identical Parquets**
1565
+
1566
+ ```
1567
+ md5 data/processed/bbbp_features.parquet
1568
+ md5 data/processed/eeg_features.parquet
1569
+ md5 data/processed/mri_features.parquet
1570
+ python -m src.pipelines.bbb_pipeline
1571
+ python -m src.pipelines.eeg_pipeline
1572
+ python -m src.pipelines.mri_pipeline
1573
+ md5 data/processed/bbbp_features.parquet
1574
+ md5 data/processed/eeg_features.parquet
1575
+ md5 data/processed/mri_features.parquet
1576
+ ```
1577
+ Expected: each MD5 unchanged across runs (idempotent / byte-deterministic preserved).
1578
+
1579
+ - [ ] **Step 5: Verify FastAPI surface end-to-end (manual)**
1580
+
1581
+ ```
1582
+ uvicorn src.api.main:app --port 8000 &
1583
+ curl -s http://localhost:8000/health | jq
1584
+ curl -s -X POST http://localhost:8000/pipeline/bbb \
1585
+ -H 'Content-Type: application/json' \
1586
+ -d '{"input_path": "data/raw/bbbp.csv", "output_path": "/tmp/bbb.parquet"}' | jq
1587
+ ```
1588
+ Expected: 200 with `{"status":"ok", "rows": >0, ...}`. Kill the uvicorn process when done.
1589
+
1590
+ - [ ] **Step 6: Final commit**
1591
+
1592
+ ```bash
1593
+ git add AGENTS.md README.md
1594
+ git commit -m "docs: Day-4 close-out — AGENTS §7 tracking, README MLOps surface"
1595
+ ```
1596
+
1597
+ ---
1598
+
1599
+ ## Definition of Done (Day 4)
1600
+
1601
+ | Check | Pass criterion |
1602
+ |---|---|
1603
+ | All tests green | `pytest -v` reports ~136 passed |
1604
+ | `src/core/{determinism,storage,tracking}.py` exist with their own test files | yes |
1605
+ | BBB / EEG / MRI pipelines all use `pin_threads()` + `write_parquet()` (no duplicate inline blocks) | grep verifies |
1606
+ | BBB / EEG / MRI pipelines all log to MLflow under their `<modality>_pipeline` experiment | mlflow.search_runs returns ≥1 per pipeline |
1607
+ | `POST /pipeline/{bbb,eeg,mri}` route works with FastAPI `TestClient` | tests/api/test_routes.py green |
1608
+ | `streamlit run src/frontend/app.py` renders 3 tabs without crashing | manual smoke |
1609
+ | `docker compose config` parses cleanly | yes |
1610
+ | Existing 106 tests still green (no regressions from refactor) | yes |
1611
+ | Output Parquets remain byte-identical across runs | md5 stable |
1612
+ | AGENTS.md §7 documents the MLflow contract | yes |
1613
+
1614
+ When all rows are green, push: `git push origin main`. Day 5 (production hardening: rate limits, OpenAPI auth, tracing) becomes optional polish on top of an already shippable system.