PERDYPTO commited on
Commit
0109502
·
verified ·
1 Parent(s): aa43fdb

Upload 45 files

Browse files
Files changed (45) hide show
  1. python_lora_dataset_builder/.env.example +8 -0
  2. python_lora_dataset_builder/CHANGELOG.md +109 -0
  3. python_lora_dataset_builder/README.md +344 -0
  4. python_lora_dataset_builder/config/sources.json +9 -0
  5. python_lora_dataset_builder/config/thresholds.json +17 -0
  6. python_lora_dataset_builder/config/tier2_libraries.json +54 -0
  7. python_lora_dataset_builder/config/topics_basic_python.json +30 -0
  8. python_lora_dataset_builder/docker/Dockerfile +5 -0
  9. python_lora_dataset_builder/main.py +87 -0
  10. python_lora_dataset_builder/pipeline/__init__.py +0 -0
  11. python_lora_dataset_builder/pipeline/audit.py +9 -0
  12. python_lora_dataset_builder/pipeline/code_extractor.py +7 -0
  13. python_lora_dataset_builder/pipeline/coverage.py +12 -0
  14. python_lora_dataset_builder/pipeline/dataset_writer.py +40 -0
  15. python_lora_dataset_builder/pipeline/decision.py +20 -0
  16. python_lora_dataset_builder/pipeline/dedupe.py +151 -0
  17. python_lora_dataset_builder/pipeline/docker_sandbox.py +41 -0
  18. python_lora_dataset_builder/pipeline/executor.py +12 -0
  19. python_lora_dataset_builder/pipeline/nim_reviewer.py +75 -0
  20. python_lora_dataset_builder/pipeline/nim_schema.py +11 -0
  21. python_lora_dataset_builder/pipeline/runner.py +386 -0
  22. python_lora_dataset_builder/pipeline/sandbox.py +84 -0
  23. python_lora_dataset_builder/pipeline/secret_scan.py +70 -0
  24. python_lora_dataset_builder/pipeline/source_checks.py +9 -0
  25. python_lora_dataset_builder/pipeline/source_loader.py +19 -0
  26. python_lora_dataset_builder/pipeline/static_checks.py +19 -0
  27. python_lora_dataset_builder/pipeline/tiers.py +33 -0
  28. python_lora_dataset_builder/pipeline/utils.py +8 -0
  29. python_lora_dataset_builder/pytest.ini +2 -0
  30. python_lora_dataset_builder/requirements.txt +4 -0
  31. python_lora_dataset_builder/scripts/run_daily.ps1 +42 -0
  32. python_lora_dataset_builder/scripts/run_daily.sh +47 -0
  33. python_lora_dataset_builder/scripts/setup.ps1 +58 -0
  34. python_lora_dataset_builder/scripts/setup.sh +59 -0
  35. python_lora_dataset_builder/tests/conftest.py +4 -0
  36. python_lora_dataset_builder/tests/test_code_extractor.py +8 -0
  37. python_lora_dataset_builder/tests/test_decision.py +31 -0
  38. python_lora_dataset_builder/tests/test_dedupe.py +67 -0
  39. python_lora_dataset_builder/tests/test_nim_reviewer.py +116 -0
  40. python_lora_dataset_builder/tests/test_nim_schema.py +22 -0
  41. python_lora_dataset_builder/tests/test_runner_regressions.py +121 -0
  42. python_lora_dataset_builder/tests/test_sandbox_contract.py +11 -0
  43. python_lora_dataset_builder/tests/test_secret_scan.py +44 -0
  44. python_lora_dataset_builder/tests/test_static_checks.py +15 -0
  45. python_lora_dataset_builder/tests/test_tiers.py +23 -0
python_lora_dataset_builder/.env.example ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ NIM_API_KEY=
2
+ NIM_BASE_URL=https://integrate.api.nvidia.com/v1
3
+ NIM_MODEL=
4
+
5
+ # local for Windows development; docker for production/untrusted code
6
+ EXECUTOR_MODE=local
7
+ # Only use this temporary override for local development if Gitleaks is not installed.
8
+ ALLOW_MISSING_GITLEAKS=0
python_lora_dataset_builder/CHANGELOG.md ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ ## v0.4 — multi-day resumability + dedupe-before-execution
4
+
5
+ ### Added
6
+ - **Real cross-run resumability.** `runner.run()` now persists a row cursor
7
+ (`rows_completed`) and cumulative stats in `data/metadata/checkpoint.json`,
8
+ and skips already-consumed rows on the next invocation
9
+ (`IterableDataset.skip(n)`). Previously `checkpoint.json` only stored
10
+ end-of-run stats and had no effect on where the *next* run started — every
11
+ run always began at row 0. This is what makes "run it once a day for a few
12
+ weeks" actually work instead of reprocessing the same rows every time.
13
+ - **Graceful stop + crash/power-loss recovery.** `Ctrl+C` (SIGINT) and
14
+ SIGTERM now finish the in-flight record, write a checkpoint, and exit
15
+ cleanly instead of dying mid-write. Checkpointing happens after every
16
+ single row (atomic temp-file-plus-`os.replace` write), so a hard crash or
17
+ power loss can lose at most the one row that was in flight.
18
+ - `main.py --no-resume` to deliberately restart a source from row 0.
19
+ - `scripts/setup.sh` / `setup.ps1` and `scripts/run_daily.sh` / `run_daily.ps1`:
20
+ isolated-venv setup and a daily-run wrapper that keeps dependencies in sync
21
+ with `requirements.txt` automatically, without touching system Python.
22
+
23
+ ### Fixed
24
+ - **Sandbox execution no longer runs on records already known to be
25
+ duplicates.** Duplicate detection (`Deduper.check_and_add`) was already
26
+ computed before execution, but the result wasn't checked until after the
27
+ sandbox subprocess had already run. `runner.py` now gates execution on
28
+ `not duplicate`, so an exact/structural/near-duplicate skips straight to
29
+ its `skip` decision without spending sandbox time (or, for tiers with NIM
30
+ review, an API request) on code that's going to be discarded anyway.
31
+
32
+ ## v0.3 — code review fixes
33
+
34
+ ### Fixed (were blockers before any real run)
35
+ - **Gitleaks fail-closed is now actually implemented.** `secret_scan.py` reads
36
+ `ALLOW_MISSING_GITLEAKS` and `runner.run()` calls a startup check
37
+ (`ensure_secret_scanner_ready()`) that raises immediately if Gitleaks is
38
+ missing and the override isn't `1`. Previously the README/`.env.example`
39
+ claimed this behavior but the code silently passed every record through.
40
+ - **NIM retry logic no longer burns retries on non-retryable errors.**
41
+ `nim_reviewer.py` now checks `r.status_code` explicitly: 429 and 5xx retry
42
+ with backoff, everything else `>= 400` (bad request, bad API key, forbidden,
43
+ etc.) raises immediately with the real HTTP status and body instead of
44
+ retrying 3 times and surfacing a generic `nim_retry_exhausted`.
45
+ - **The regression test now tests the actual code.** `test_runner_regressions.py`
46
+ previously asserted on hand-built dicts and never imported `pipeline.runner`
47
+ — it would have stayed green even with the exact `NameError` crash
48
+ reintroduced. It now mocks `stream_hf_dataset` and calls `runner.run()`
49
+ end-to-end for several scenarios (valid code, syntax error, execution
50
+ failure, tier classification).
51
+
52
+ ### Improved (were flagged as real but non-blocking risks)
53
+ - **Near-duplicate dedupe no longer scans the whole index per record.**
54
+ `dedupe.py` now uses MinHash/LSH banding for near-duplicate candidate
55
+ lookup (exact/structural checks were already O(1) via dict lookup, now
56
+ made explicit). See README "Deduplication at scale."
57
+ - **Added the three-tier classification structure** (`pipeline/tiers.py`,
58
+ `config/tier2_libraries.json`): tier 1 (import-free, fully automated),
59
+ tier 2 (per-library, classified + NIM-reviewable but never auto-included —
60
+ no per-library sandbox exists yet), tier 3 (real-world/project, classified
61
+ only). `main.py --tiers` controls which tiers are active in a given run;
62
+ default is tier 1 only. Output is now organized under
63
+ `data/<tier>/[<library>/]<decision>/records.jsonl` instead of a single flat
64
+ `data/<decision>/` layout.
65
+
66
+ ### Still intentionally not built (unchanged from before this pass)
67
+ - No per-library, version-pinned execution environments for tier 2.
68
+ - No dedicated validation profile (static analysis / partial execution) for
69
+ tier 3 real-world repository code; it should not be forced to run as a
70
+ standalone snippet.
71
+ - No automated license/provenance detection — still a manual, source-level
72
+ approval step (`pipeline/source_checks.py` remains a stub that only checks
73
+ instruction/output aren't both empty).
74
+ - Dual-NIM self-consistency checking (`dual_review_low`/`dual_review_high`/
75
+ `max_review_disagreement` in `config/thresholds.json`) is configured but not
76
+ wired into `decision.py`/`runner.py`.
77
+ - Local (non-Docker) sandbox mode still has no network isolation — only
78
+ Docker mode (`--network none`) blocks outbound calls. Use Docker mode for
79
+ any untrusted/unattended run.
80
+
81
+ ## v3 (prior)
82
+
83
+ ### Fixed
84
+ - Fixed the `NameError: decision is not defined` / `reason is not defined` crash in the hard-failure branch.
85
+ - Hard-failure decisions are now computed directly and never rely on a dummy NIM result.
86
+ - Aligned `runner.py` and `decision.py` on the `execution_status` contract.
87
+
88
+ ### Implemented
89
+ - Added an executor abstraction with a Docker production executor (network
90
+ disabled, read-only root filesystem, dropped capabilities, no-new-privileges,
91
+ PID/memory/CPU limits, non-root user, restricted tmpfs).
92
+ - Added Linux `resource.setrlimit` limits to the local executor (memory, CPU,
93
+ process count, output size, open files).
94
+ - Added explicit Windows behavior: timeout + temp cwd only, no `setrlimit`
95
+ equivalent; production/untrusted execution on Windows must use Docker mode.
96
+ - Exact, AST-structural, and token-shingle near-duplicate layers.
97
+ - NIM retry/backoff and a separate retry queue.
98
+ - Expanded NIM rubric and hard axis gates.
99
+
100
+ ## 0.2.0
101
+
102
+ - Added structural and near-duplicate detection across runs.
103
+ - Added Gitleaks scanner integration (fail-open at the time — fixed in v0.3).
104
+ - Added retry/backoff and a separate retry queue for NIM infrastructure failures.
105
+ - Added instruction alignment and scope-fit scoring.
106
+ - Added deterministic score-axis gates.
107
+ - Removed dummy NIM topic metadata.
108
+ - Added Linux resource limits to the local development executor.
109
+ - Added audit metadata for duplicate matching and secret scanning.
python_lora_dataset_builder/README.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python LoRA Dataset Builder
2
+
3
+ A staged, evidence-first pipeline for building a high-quality Python training dataset.
4
+
5
+ ## Current phase
6
+
7
+ Run **tier 1 (`basic_python_syntax`)** right now. It's the only tier that's fully
8
+ automated end-to-end (extraction → static checks → dedupe → secret scan →
9
+ sandbox execution → NIM review → scoring). Tiers 2 and 3 exist as
10
+ classification/organization scaffolding for later — see "Three tiers" below.
11
+
12
+ The first source configured is:
13
+
14
+ `Riswan-BluBridge/python-codes-25k`
15
+
16
+ The first run should be a small batch, not the whole dataset.
17
+
18
+ ## Pipeline order
19
+
20
+ 1. Load source rows.
21
+ 2. Extract Python code from the answer.
22
+ 3. Run source-record checks.
23
+ 4. Run AST parsing and compilation.
24
+ 5. Scan for obvious secrets (Gitleaks; **fails closed** if Gitleaks isn't
25
+ installed — see "Gitleaks" below).
26
+ 6. Deduplicate: exact hash, AST-structural fingerprint, and near-duplicate
27
+ (MinHash/LSH-accelerated token-shingle Jaccard) — see "Deduplication at
28
+ scale" below.
29
+ 7. Classify into tier 1 / tier 2 / tier 3 based on imports.
30
+ 8. Execute eligible tier-1 snippets in an isolated subprocess.
31
+ 9. Send deterministic-check passes in active tiers to NVIDIA NIM.
32
+ 10. Validate the returned JSON against a strict schema.
33
+ 11. Apply score and coverage rules.
34
+ 12. Save accepted, rejected, skipped, manual-review, and raw NIM records,
35
+ organized by tier (and library, for tier 2).
36
+
37
+ ## Three tiers
38
+
39
+ The pipeline classifies every code sample by its top-level imports
40
+ (`pipeline/tiers.py`):
41
+
42
+ | Tier | Folder | What it means | Executed today? |
43
+ |---|---|---|---|
44
+ | 1 — `basic_python_syntax` | `data/basic_python_syntax/` | No imports at all | Yes — full pipeline |
45
+ | 2 — `per_library` | `data/per_library/<library>/` | Every import is in `config/tier2_libraries.json` | No — no per-library sandbox yet |
46
+ | 3 — `real_world_repository` | `data/real_world_repository/` | Any import we don't recognise | No — no project-level validation profile yet |
47
+
48
+ Which tiers are actually processed in a given run is controlled by `--tiers`
49
+ (default: `basic`, i.e. tier 1 only). Records outside the active tiers are
50
+ still classified and written with `decision=skip`, `decision_reason=tier_not_active:<tier>`
51
+ — nothing is thrown away, they just don't spend NIM requests or execution
52
+ time this run.
53
+
54
+ ```bash
55
+ python main.py --limit 50 --dry-run # tier 1 only (today's default)
56
+ python main.py --limit 50 --dry-run --tiers basic,library # also classify/NIM-review tier 2
57
+ python main.py --limit 50 --dry-run --tiers all # classify everything
58
+ ```
59
+
60
+ **Honest limitation:** even when tier 2 or 3 is made "active," those records
61
+ are never auto-included — there's no execution environment to verify the
62
+ code runs, so the best they can reach is `manual_review`. Building real
63
+ per-library, version-pinned execution environments (tier 2) and a
64
+ static-analysis/partial-execution validation profile for real-world
65
+ repository code (tier 3) is future work, not implemented yet.
66
+
67
+ ## Score policy
68
+
69
+ - `< 80`: reject
70
+ - `80–84`: manual review
71
+ - `85–89`: include only when the dominant topic is underrepresented
72
+ - `90–100`: include
73
+
74
+ Hard failures override scores. Tier 2/3 records additionally never auto-include
75
+ (see above); an "include"-worthy score is downgraded to `manual_review`.
76
+
77
+ ## Topic policy
78
+
79
+ The reviewer receives the allowed topic IDs and descriptions (`config/topics_basic_python.json`).
80
+
81
+ Each example receives:
82
+
83
+ - exactly one `dominant_topic`
84
+ - zero or more `secondary_topics`
85
+
86
+ The dominant topic is the concept the example primarily teaches, not merely a concept that appears in the code.
87
+
88
+ ## Quick start (recommended): setup scripts
89
+
90
+ The `scripts/` folder does the manual setup below for you, and never touches
91
+ your system Python — everything installs into a `.venv/` folder inside this
92
+ project only.
93
+
94
+ **macOS / Linux:**
95
+
96
+ ```bash
97
+ bash scripts/setup.sh # one-time: creates .venv/, installs deps, copies .env
98
+ # edit .env with your NIM credentials
99
+ bash scripts/run_daily.sh # dry run, 500 rows
100
+ bash scripts/run_daily.sh --real 200 # real run, 200 rows this session
101
+ ```
102
+
103
+ **Windows (PowerShell):**
104
+
105
+ ```powershell
106
+ powershell -ExecutionPolicy Bypass -File scripts\setup.ps1
107
+ # edit .env with your NIM credentials
108
+ powershell -ExecutionPolicy Bypass -File scripts\run_daily.ps1 # dry run, 500 rows
109
+ powershell -ExecutionPolicy Bypass -File scripts\run_daily.ps1 -Real -Limit 200 # real run, 200 rows
110
+ ```
111
+
112
+ Run `run_daily` (or `run_daily.ps1`) again any time — today, tomorrow, next
113
+ week — and it automatically continues from wherever the last run left off
114
+ (see "Running it over multiple days" below). If you'd rather do it by hand,
115
+ or you're not on macOS/Linux/Windows, the manual steps are below.
116
+
117
+ ## Manual setup
118
+
119
+ Create and activate a virtual environment:
120
+
121
+ ```bash
122
+ python -m venv .venv
123
+ ```
124
+
125
+ Windows:
126
+
127
+ ```powershell
128
+ .venv\Scripts\Activate.ps1
129
+ ```
130
+
131
+ Linux/macOS:
132
+
133
+ ```bash
134
+ source .venv/bin/activate
135
+ ```
136
+
137
+ Install dependencies:
138
+
139
+ ```bash
140
+ pip install -r requirements.txt
141
+ ```
142
+
143
+ Copy `.env.example` to `.env`, then set:
144
+
145
+ ```env
146
+ NIM_API_KEY=your_key
147
+ NIM_BASE_URL=https://integrate.api.nvidia.com/v1
148
+ NIM_MODEL=your_nim_model_id
149
+ ```
150
+
151
+ ## What you need installed
152
+
153
+ - **Python 3.10+** — everything else (the `datasets`, `httpx`, `python-dotenv`
154
+ packages in `requirements.txt`) installs automatically into the project's
155
+ own `.venv/` folder and never touches your system Python or other projects.
156
+ - **Gitleaks** (one-time, system-level CLI tool) — the pipeline **fails
157
+ closed** and refuses to run without it, unless you explicitly set
158
+ `ALLOW_MISSING_GITLEAKS=1` in `.env` for local testing (not recommended for
159
+ a real/unattended run). Install: `brew install gitleaks` (macOS),
160
+ `winget install gitleaks` (Windows), or see the
161
+ [Gitleaks install docs](https://github.com/gitleaks/gitleaks#installing).
162
+ - **Docker** (optional, recommended for any unattended/multi-day run) — see
163
+ "Sandbox status" below. Not required for the default local executor, but
164
+ the local executor is explicitly not a hardened boundary.
165
+ - A **NIM API key** in `.env` for real (non-`--dry-run`) runs.
166
+
167
+ ## Run tests
168
+
169
+ ```bash
170
+ pytest -q
171
+ ```
172
+
173
+ ## First dry run
174
+
175
+ This tests loading, extraction, static checks, execution, and file output without spending NIM requests:
176
+
177
+ ```bash
178
+ python main.py --limit 50 --dry-run
179
+ ```
180
+
181
+ ## First real NIM test
182
+
183
+ ```bash
184
+ python main.py --limit 50
185
+ ```
186
+
187
+ After inspecting the results, run:
188
+
189
+ ```bash
190
+ python main.py --limit 500
191
+ ```
192
+
193
+ Do not run the whole source until the 50- and 500-record audits look correct.
194
+
195
+ ## Running it over multiple days
196
+
197
+ You don't need to leave this running continuously. Every run of
198
+ `python main.py` (or `scripts/run_daily.sh` / `run_daily.ps1`) processes up
199
+ to `--limit` **new** rows and then stops on its own. Progress is stored in
200
+ `data/metadata/checkpoint.json`, so the next time you run it — later today,
201
+ tomorrow, next week — it automatically **resumes exactly where it left off**:
202
+ it does not reprocess rows or restart the source dataset from scratch.
203
+
204
+ ```bash
205
+ python main.py --limit 500 --dry-run # day 1: processes rows 0-499
206
+ python main.py --limit 500 --dry-run # day 2: resumes at row 500, processes 500-999
207
+ python main.py --limit 500 --dry-run # day 3: resumes at row 1000, ...
208
+ ```
209
+
210
+ When the whole source dataset has been consumed, the pipeline tells you and
211
+ exits without doing anything (`'<source>' is already fully processed`).
212
+
213
+ If you genuinely want to reprocess the source from row 0 (e.g. you changed
214
+ scoring thresholds and want a clean pass), either pass `--no-resume` or
215
+ delete `data/metadata/checkpoint.json`. Note this doesn't undo dedupe or
216
+ coverage state — those live in separate files under `data/metadata/` — so a
217
+ `--no-resume` pass will still treat rows as duplicates of what's already in
218
+ `data/`. Delete `data/metadata/exact_hashes.txt` and
219
+ `data/metadata/topic_coverage.json` too if you want a fully clean slate.
220
+
221
+ **Scheduling it automatically (optional).** If you'd rather not run it by
222
+ hand each day, schedule `scripts/run_daily.sh` / `run_daily.ps1`:
223
+
224
+ - macOS/Linux (cron), run `crontab -e` and add a line like:
225
+ ```
226
+ 0 9 * * * cd /path/to/python_lora_dataset_builder && bash scripts/run_daily.sh --real 500 >> logs/daily.log 2>&1
227
+ ```
228
+ - Windows: Task Scheduler → "Create Basic Task" → Trigger: Daily → Action:
229
+ "Start a program" → Program: `powershell.exe` → Arguments:
230
+ `-ExecutionPolicy Bypass -File "C:\path\to\python_lora_dataset_builder\scripts\run_daily.ps1" -Real -Limit 500`
231
+
232
+ Either way, each scheduled run is just one more "day" in the sequence above —
233
+ it resumes on its own.
234
+
235
+ ## Stopping and recovering
236
+
237
+ - **To stop cleanly:** press `Ctrl+C` once. The pipeline finishes writing the
238
+ record it's currently on, saves a checkpoint, and exits — nothing is lost,
239
+ and the next run resumes right after that record. A second `Ctrl+C` forces
240
+ an immediate hard stop if you really don't want to wait even a second.
241
+ - **If the power goes out, the process is killed, or your laptop sleeps
242
+ mid-run:** nothing special to do — just run the same command again.
243
+ Checkpointing happens after every single processed row (not just
244
+ periodically), so at most the one row that was in flight when things died
245
+ gets reprocessed; everything before it is picked up exactly where it
246
+ stopped. The checkpoint file itself is written atomically (temp file +
247
+ rename), so even a checkpoint write interrupted mid-write can't corrupt
248
+ `checkpoint.json` — you always fall back to the last good checkpoint.
249
+
250
+ ## Executed code and temporary files
251
+
252
+ Every sandboxed execution (local or Docker mode) runs inside a fresh
253
+ temporary directory created just for that one snippet, and that directory —
254
+ along with everything written into it — is deleted automatically the moment
255
+ execution finishes (success, failure, or timeout), via Python's
256
+ `tempfile.TemporaryDirectory` context manager. Nothing from candidate code
257
+ execution is left behind on disk.
258
+
259
+ ## Output
260
+
261
+ ```text
262
+ data/
263
+ ├── basic_python_syntax/
264
+ │ ├── accepted/records.jsonl
265
+ │ ├── manual_review/records.jsonl
266
+ │ ├── rejected/records.jsonl
267
+ │ ├── skipped/records.jsonl
268
+ │ └── retry/records.jsonl
269
+ ├── per_library/
270
+ │ ├── json/... (same accepted/manual_review/rejected/skipped/retry layout)
271
+ │ ├── requests/...
272
+ │ └── ...
273
+ ├── real_world_repository/
274
+ │ └── ... (same layout; classification only today)
275
+ ├── unclassified/
276
+ │ └── rejected/records.jsonl # rows with no usable code / empty source
277
+ ├── nim_raw/
278
+ └── metadata/
279
+ ├── exact_hashes.txt
280
+ ├── topic_coverage.json
281
+ └── checkpoint.json
282
+ ```
283
+
284
+ ## Important limitations in this build
285
+
286
+ - The sandbox is an isolated subprocess with a temporary directory and a timeout. It is **not** a hardened container. Do not run untrusted large-scale code on your main machine with this implementation; use Docker mode (`EXECUTOR_MODE=docker`) for anything unattended or at scale.
287
+ - Only tier 1 (import-free) has an execution environment. Tiers 2 and 3 are classified/organized but not executed — see "Three tiers" above.
288
+ - Deduplication uses exact hash, AST-structural fingerprinting, and MinHash/LSH-accelerated near-duplicate detection (see "Deduplication at scale"). Final near-duplicate decisions are still exact Jaccard, computed only against LSH-bucketed candidates, not the whole index.
289
+ - License/provenance is a source-level, manual approval step and must be completed before processing a source. There is still no automated license/provenance detection in the pipeline (`pipeline/source_checks.py` only checks that instruction/output aren't both empty) — that remains a gap to close before adding more sources.
290
+ - The secret scan is intentionally conservative and must be expanded before real-world repository ingestion.
291
+ - Real-world repository code needs a different validation profile; it should not be forced to execute as a standalone snippet.
292
+ - Dual-NIM self-consistency checking on borderline scores (`dual_review_low`/`dual_review_high`/`max_review_disagreement` in `config/thresholds.json`) is configured but **not wired into `decision.py` or `runner.py` yet**.
293
+
294
+ ## Deduplication at scale
295
+
296
+ Near-duplicate detection now uses MinHash/LSH banding (`pipeline/dedupe.py`):
297
+ each code sample's shingle set is summarized into a 32-value MinHash
298
+ signature, split into 8 bands, and hashed into buckets. A new record only
299
+ gets compared (via exact Jaccard) against records that land in the same
300
+ bucket in at least one band — not against every previously seen record. Exact
301
+ and structural (AST-fingerprint) duplicate checks are O(1) dict lookups.
302
+ Dedupe index files written by earlier versions (without a `sig` field) are
303
+ still readable; signatures are derived from their stored shingles on load.
304
+
305
+ ## Gitleaks
306
+
307
+ Install Gitleaks separately and ensure `gitleaks` is on PATH before a
308
+ production run. **The pipeline fails closed**: if Gitleaks isn't found and
309
+ `ALLOW_MISSING_GITLEAKS` isn't set to `1`, `python main.py` raises
310
+ immediately, before processing any records — it will not silently mark
311
+ records as scanned when no scanner ran. The `ALLOW_MISSING_GITLEAKS=1`
312
+ override is for local development only; every record processed under it
313
+ carries a `gitleaks_not_installed_override_allowed` warning in its metadata
314
+ so the run stays auditable.
315
+
316
+ ### Sandbox status
317
+
318
+ The local executor is still **not a hardened security boundary** and should
319
+ not be used for unattended execution of untrusted code at scale. For
320
+ production runs, use the Docker executor (`EXECUTOR_MODE=docker`) with
321
+ network disabled, a read-only root filesystem, a non-root user, dropped
322
+ capabilities, PID/memory/CPU limits, and a small tmpfs — all of which
323
+ `pipeline/docker_sandbox.py` already sets up. The current local `resource`
324
+ limits are defense-in-depth for development, not a replacement for container
325
+ isolation.
326
+
327
+ ## Windows-specific execution guidance
328
+
329
+ If you're developing on **Windows**: the local executor is suitable only for
330
+ small, trusted development tests. It has a timeout and a temporary working
331
+ directory, but Windows does not provide the Linux `resource.setrlimit`
332
+ controls used by the Linux local executor.
333
+
334
+ For any unattended run over unknown Hugging Face code, use Docker mode:
335
+
336
+ ```powershell
337
+ docker build -t python-lora-sandbox -f docker/Dockerfile .
338
+ $env:EXECUTOR_MODE="docker"
339
+ $env:ALLOW_MISSING_GITLEAKS="0"
340
+ python main.py --limit 50
341
+ ```
342
+
343
+ Install Gitleaks and ensure it is on `PATH`. Do not treat Windows local mode
344
+ as a hardened sandbox.
python_lora_dataset_builder/config/sources.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "primary": {
3
+ "name": "Riswan-BluBridge/python-codes-25k",
4
+ "split": "train",
5
+ "instruction_field": "instruction",
6
+ "input_field": "input",
7
+ "output_field": "output"
8
+ }
9
+ }
python_lora_dataset_builder/config/thresholds.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reject_below": 80,
3
+ "manual_review_min": 80,
4
+ "manual_review_max": 84,
5
+ "coverage_gate_min": 85,
6
+ "coverage_gate_max": 89,
7
+ "auto_include_min": 90,
8
+ "default_topic_target": 250,
9
+ "min_manual_audit_per_bucket": 10,
10
+ "audit_rate": 0.01,
11
+ "nim_retry_attempts": 3,
12
+ "nim_retry_base_seconds": 1.0,
13
+ "dual_review_low": 76,
14
+ "dual_review_high": 93,
15
+ "max_review_disagreement": 10,
16
+ "near_duplicate_similarity": 0.94
17
+ }
python_lora_dataset_builder/config/tier2_libraries.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "os": "Operating system interfaces: paths, environment, processes",
3
+ "sys": "Interpreter internals, argv, stdio, path manipulation",
4
+ "re": "Regular expressions: matching, searching, substitution",
5
+ "json": "JSON encoding and decoding",
6
+ "math": "Standard mathematical functions and constants",
7
+ "random": "Pseudo-random number generation",
8
+ "datetime": "Dates, times, timedeltas, and timezones",
9
+ "time": "Low-level time access and conversions",
10
+ "itertools": "Fast, memory-efficient iterator building blocks",
11
+ "functools": "Higher-order functions: reduce, partial, lru_cache, wraps",
12
+ "collections": "Specialized containers: deque, Counter, defaultdict, namedtuple",
13
+ "pathlib": "Object-oriented filesystem paths",
14
+ "subprocess": "Spawning and communicating with child processes",
15
+ "threading": "Thread-based concurrency",
16
+ "multiprocessing": "Process-based concurrency",
17
+ "asyncio": "Asynchronous I/O, event loops, coroutines",
18
+ "socket": "Low-level networking interface",
19
+ "urllib": "URL handling and HTTP requests from the standard library",
20
+ "sqlite3": "Embedded SQL database access",
21
+ "csv": "Reading and writing CSV files",
22
+ "logging": "Configurable logging framework",
23
+ "argparse": "Command-line argument parsing",
24
+ "unittest": "Standard library test framework",
25
+ "typing": "Type hints and generic type constructs",
26
+ "enum": "Enumerated constant types",
27
+ "dataclasses": "Boilerplate-reduced classes for storing data",
28
+ "copy": "Shallow and deep copy operations",
29
+ "string": "Common string constants and templating helpers",
30
+ "statistics": "Basic descriptive statistics functions",
31
+ "decimal": "Fixed and arbitrary precision decimal arithmetic",
32
+ "io": "Core stream and file-like object handling",
33
+ "hashlib": "Secure hash and message digest algorithms",
34
+ "uuid": "UUID generation and parsing",
35
+ "shutil": "High-level file and directory operations",
36
+ "tempfile": "Temporary file and directory creation",
37
+ "xml": "XML parsing and generation",
38
+ "queue": "Thread-safe FIFO/LIFO queue implementations",
39
+ "requests": "Popular third-party HTTP client",
40
+ "numpy": "Numerical arrays and vectorized computation",
41
+ "pandas": "Tabular data structures and analysis",
42
+ "matplotlib": "Static plotting and data visualization",
43
+ "flask": "Lightweight web application framework",
44
+ "django": "Full-featured web application framework",
45
+ "pytest": "Third-party test framework",
46
+ "click": "Command-line interface creation toolkit",
47
+ "pydantic": "Data validation using Python type annotations",
48
+ "sqlalchemy": "SQL toolkit and object-relational mapper",
49
+ "bs4": "HTML/XML parsing (BeautifulSoup)",
50
+ "PIL": "Image processing (Pillow)",
51
+ "boto3": "AWS SDK for Python",
52
+ "yaml": "YAML parsing and serialization (PyYAML)",
53
+ "pytz": "Timezone database and conversions"
54
+ }
python_lora_dataset_builder/config/topics_basic_python.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "variables_and_assignment": "Variables, assignment, and basic value storage",
3
+ "basic_data_types": "Integers, floats, strings, booleans, and None",
4
+ "string_operations": "String creation, formatting, indexing, slicing, and methods",
5
+ "lists": "List creation, indexing, modification, and list methods",
6
+ "tuples": "Tuple creation, unpacking, and tuple operations",
7
+ "sets": "Set creation, membership, and set operations",
8
+ "dictionaries": "Dictionary creation, access, updates, and dictionary methods",
9
+ "operators": "Arithmetic, comparison, logical, identity, and membership operators",
10
+ "conditional_statements": "if, elif, else, and conditional logic",
11
+ "for_loops": "Iteration using for loops",
12
+ "while_loops": "Repetition using while loops",
13
+ "loop_control": "break, continue, pass, and loop control behavior",
14
+ "functions": "Function definitions, parameters, arguments, and return values",
15
+ "variable_scope": "Local, global, and nonlocal scope",
16
+ "exception_handling": "try, except, else, finally, and raise",
17
+ "classes_and_objects": "Class definitions, instances, attributes, and methods",
18
+ "inheritance": "Class inheritance, super(), and method overriding",
19
+ "comprehensions": "List, dictionary, and set comprehensions",
20
+ "generators": "yield, generator functions, and generator expressions",
21
+ "iterators": "Iterator protocols, iter(), next(), and custom iterators",
22
+ "decorators": "Function and class decorators",
23
+ "context_managers": "with statements and custom context managers",
24
+ "unpacking": "Sequence, iterable, and dictionary unpacking",
25
+ "lambda_functions": "Lambda expressions and anonymous functions",
26
+ "type_hints": "Annotations for variables, parameters, and return values",
27
+ "async_await": "Coroutines, async functions, await, and asynchronous flow",
28
+ "structural_pattern_matching": "match and case statements",
29
+ "modules_and_imports": "Module imports and basic module organization"
30
+ }
python_lora_dataset_builder/docker/Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+ RUN useradd -r -u 65534 sandbox
3
+ USER 65534
4
+ WORKDIR /work
5
+ ENTRYPOINT ["python"]
python_lora_dataset_builder/main.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import argparse
3
+ from pathlib import Path
4
+ from pipeline.runner import run
5
+ from pipeline import tiers as tiers_mod
6
+
7
+ TIER_ALIASES = {
8
+ "basic": tiers_mod.TIER1_BASIC,
9
+ "basic_python_syntax": tiers_mod.TIER1_BASIC,
10
+ "tier1": tiers_mod.TIER1_BASIC,
11
+ "library": tiers_mod.TIER2_PER_LIBRARY,
12
+ "per_library": tiers_mod.TIER2_PER_LIBRARY,
13
+ "tier2": tiers_mod.TIER2_PER_LIBRARY,
14
+ "project": tiers_mod.TIER3_REAL_WORLD,
15
+ "real_world": tiers_mod.TIER3_REAL_WORLD,
16
+ "real_world_repository": tiers_mod.TIER3_REAL_WORLD,
17
+ "tier3": tiers_mod.TIER3_REAL_WORLD,
18
+ "all": None, # expanded below
19
+ }
20
+
21
+
22
+ def _parse_tiers(raw: str) -> tuple[str, ...]:
23
+ names = [x.strip().lower() for x in raw.split(",") if x.strip()]
24
+ if "all" in names:
25
+ return tiers_mod.ALL_TIERS
26
+ out = []
27
+ for n in names:
28
+ if n not in TIER_ALIASES:
29
+ valid = ", ".join(sorted(TIER_ALIASES))
30
+ raise SystemExit(f"Unknown --tiers value '{n}'. Valid values: {valid}")
31
+ out.append(TIER_ALIASES[n])
32
+ return tuple(dict.fromkeys(out)) # dedupe, preserve order
33
+
34
+
35
+ def main():
36
+ parser = argparse.ArgumentParser(description="Python LoRA dataset quality pipeline")
37
+ parser.add_argument("--limit", type=int, default=500, help="Maximum source rows to process")
38
+ parser.add_argument("--dry-run", action="store_true",
39
+ help="Run extraction/static/execution checks without NIM")
40
+ parser.add_argument("--source", default=None, help="Override Hugging Face dataset name")
41
+ parser.add_argument(
42
+ "--tiers", default="basic",
43
+ help=(
44
+ "Comma-separated tiers to actively process this run: "
45
+ "'basic' (import-free, fully automated — the default and the one to run right now), "
46
+ "'library' (per-library, classified + NIM-reviewed but never auto-included; "
47
+ "no per-library execution env yet), "
48
+ "'project' (real-world/project code, classified only, not executed or scored), "
49
+ "or 'all'. Records in inactive tiers are still classified and saved "
50
+ "(decision=skip) so nothing is lost."
51
+ ),
52
+ )
53
+ parser.add_argument(
54
+ "--no-resume", action="store_true",
55
+ help=(
56
+ "Ignore data/metadata/checkpoint.json and start over from row 0 "
57
+ "of the source dataset. By default (no flag) the pipeline resumes "
58
+ "from wherever the last run left off — this is what makes running "
59
+ "it once a day for a few weeks pick up where it stopped instead of "
60
+ "reprocessing rows or restarting the source from scratch."
61
+ ),
62
+ )
63
+ args = parser.parse_args()
64
+
65
+ root = Path(__file__).resolve().parent
66
+ active_tiers = _parse_tiers(args.tiers)
67
+ stats = run(root, limit=args.limit, dry_run=args.dry_run,
68
+ source_name_override=args.source, active_tiers=active_tiers,
69
+ resume=not args.no_resume)
70
+ print("\nPipeline complete (this run)")
71
+ print(f"active tiers: {', '.join(active_tiers)}")
72
+ for key, value in stats.items():
73
+ if key == "cumulative_stats":
74
+ print("cumulative totals across all runs on this source:")
75
+ for ck, cv in value.items():
76
+ print(f" {ck}: {cv}")
77
+ else:
78
+ print(f"{key}: {value}")
79
+ if not stats.get("source_exhausted"):
80
+ print(
81
+ "\nSource not finished yet — run the same command again "
82
+ "(e.g. tomorrow) to continue from here."
83
+ )
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
python_lora_dataset_builder/pipeline/__init__.py ADDED
File without changes
python_lora_dataset_builder/pipeline/audit.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import hashlib
3
+
4
+ def deterministic_audit_selected(record_id: str, rate: float, minimum_counter: int = 0) -> bool:
5
+ """Stable sampling: the same record always gets the same audit decision."""
6
+ if minimum_counter > 0:
7
+ return True
8
+ value = int(hashlib.sha256(record_id.encode()).hexdigest()[:12], 16) / float(16**12)
9
+ return value < rate
python_lora_dataset_builder/pipeline/code_extractor.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import re
2
+ def _norm(x): return "\n".join(line.rstrip() for line in x.replace("\r\n","\n").splitlines()).strip()
3
+ def extract_code(output):
4
+ blocks=[_norm(x) for x in re.findall(r"```(?:python|py)?\s*\n?(.*?)```",output or "",re.I|re.S) if _norm(x)]
5
+ if blocks: return max(blocks,key=len)
6
+ text=_norm(output or "")
7
+ return text if any(x in text for x in ("def ","class ","import ","from ","for ","while ","if ","try:","async ")) else None
python_lora_dataset_builder/pipeline/coverage.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ class CoverageTracker:
4
+ def __init__(self,path:Path,topics,default_target):
5
+ self.path=path; self.default_target=default_target
6
+ self.data={t:{"accepted":0,"target":default_target} for t in topics}
7
+ if path.exists():self.data.update(json.loads(path.read_text(encoding="utf-8")))
8
+ def needs_coverage(self,topic):
9
+ x=self.data[topic]; return int(x.get("accepted",0))<int(x.get("target",self.default_target))
10
+ def add(self,topic):
11
+ self.data[topic]["accepted"]=int(self.data[topic].get("accepted",0))+1
12
+ self.path.parent.mkdir(parents=True,exist_ok=True); self.path.write_text(json.dumps(self.data,indent=2),encoding="utf-8")
python_lora_dataset_builder/pipeline/dataset_writer.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ from pathlib import Path
4
+ from .utils import append_jsonl
5
+
6
+ _DECISION_DIRS = {
7
+ "include": "accepted",
8
+ "manual_review": "manual_review",
9
+ "reject": "rejected",
10
+ "skip": "skipped",
11
+ "retry": "retry",
12
+ }
13
+
14
+
15
+ class DatasetWriter:
16
+ def __init__(self, output_dir: Path):
17
+ self.output_dir = output_dir
18
+
19
+ def write(self, decision: str, record: dict, tier: str | None = None,
20
+ tier_library: str | None = None) -> Path:
21
+ """Write a record under data/<tier>/[<library>/]<decision>/records.jsonl.
22
+
23
+ `tier` defaults to record["tier"] if not passed explicitly, then to
24
+ "unclassified" for records that never made it far enough to be
25
+ classified (e.g. empty source rows).
26
+ """
27
+ tier = tier or record.get("tier") or "unclassified"
28
+ parts = [tier]
29
+ if tier_library:
30
+ parts.append(tier_library)
31
+ parts.append(_DECISION_DIRS[decision])
32
+ path = self.output_dir.joinpath(*parts) / "records.jsonl"
33
+ append_jsonl(path, record)
34
+ return path
35
+
36
+ def write_raw_nim(self, record_id: str, raw: dict) -> Path:
37
+ path = self.output_dir / "nim_raw" / f"{record_id}.json"
38
+ path.parent.mkdir(parents=True, exist_ok=True)
39
+ path.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")
40
+ return path
python_lora_dataset_builder/pipeline/decision.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def decide(c,n,coverage):
2
+ if not c['ast_valid']:return 'reject','syntax_invalid'
3
+ if not c['compile_valid']:return 'reject','compile_failed'
4
+ if not c.get('secret_passed',True):return 'reject','secret_detected'
5
+ if c['duplicate']:return 'skip',f"{c.get('duplicate_kind','duplicate')}_duplicate"
6
+ # Tier activity (whether this tier is being processed this run at all) is
7
+ # decided earlier, in runner.py, before a NIM request is ever spent. By the
8
+ # time a record reaches here it's already an active tier, so we don't gate
9
+ # on basic_tier_allowed again — doing so would incorrectly skip every
10
+ # active tier-2/tier-3 record right after paying for its NIM review.
11
+ if c.get('execution_status')=='failed':return 'reject','execution_failed'
12
+ if not n['valid']:return 'reject','nim_invalid'
13
+ for k in ('correctness','instruction_alignment'):
14
+ if n['scores'][k]<85:return 'reject',f'{k}_below_85'
15
+ if n['scores']['scope_fit']<85:return 'skip','scope_fit_below_85'
16
+ s=n['overall_score']
17
+ if s<80:return 'reject','score_below_80'
18
+ if s<=84:return 'manual_review','score_80_to_84'
19
+ if s<=89:return ('include','coverage_needed') if coverage.needs_coverage(n['dominant_topic']) else ('skip','coverage_full')
20
+ return 'include','score_90_plus'
python_lora_dataset_builder/pipeline/dedupe.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import ast, hashlib, json, random, re, zlib
3
+ from pathlib import Path
4
+
5
+
6
+ def norm(code):
7
+ return "\n".join(x.rstrip() for x in code.replace("\r\n", "\n").splitlines()).strip()
8
+
9
+
10
+ def fp(code):
11
+ try:
12
+ t = ast.parse(code)
13
+ for n in ast.walk(t):
14
+ if isinstance(n, ast.Name):
15
+ n.id = "VAR"
16
+ elif isinstance(n, ast.arg):
17
+ n.arg = "VAR"
18
+ elif isinstance(n, ast.Constant) and isinstance(n.value, (str, int, float, complex)):
19
+ n.value = type(n.value).__name__
20
+ return hashlib.sha256(ast.dump(t, include_attributes=False).encode()).hexdigest()
21
+ except SyntaxError:
22
+ return None
23
+
24
+
25
+ def shingles(code):
26
+ x = re.findall(r"[A-Za-z_]\w*|==|!=|<=|>=|\S", code)
27
+ return set(" ".join(x[i:i + 4]) for i in range(max(1, len(x) - 3)))
28
+
29
+
30
+ def jac(a, b):
31
+ return len(a & b) / len(a | b) if a or b else 1
32
+
33
+
34
+ _MASK = (1 << 32) - 1
35
+
36
+
37
+ def _hash_funcs(num_hashes, seed=1337):
38
+ rng = random.Random(seed)
39
+ # (a, b) pairs for a universal hash family h(x) = (a*x + b) mod MASK
40
+ return [(rng.randrange(1, _MASK), rng.randrange(0, _MASK)) for _ in range(num_hashes)]
41
+
42
+
43
+ class MinHashLSH:
44
+ """Approximate near-duplicate candidate lookup.
45
+
46
+ Instead of comparing a new record's shingle set against every previously
47
+ seen record (O(n) per record, O(n^2) per run), each record's shingle set
48
+ is summarized into a small MinHash signature. Signatures are split into
49
+ bands and hashed into buckets; two records can only ever be compared for
50
+ exact Jaccard similarity if they land in the same bucket in at least one
51
+ band. This turns "find near-duplicate candidates" into an expected O(1)
52
+ bucket lookup instead of a full scan, while keeping the final similarity
53
+ decision an exact Jaccard computation (no false accepts from hashing).
54
+ """
55
+
56
+ def __init__(self, num_hashes: int = 32, bands: int = 8):
57
+ assert num_hashes % bands == 0, "num_hashes must be divisible by bands"
58
+ self.num_hashes = num_hashes
59
+ self.bands = bands
60
+ self.rows_per_band = num_hashes // bands
61
+ self.funcs = _hash_funcs(num_hashes)
62
+ self.buckets: list[dict] = [dict() for _ in range(bands)]
63
+
64
+ def signature(self, shingle_set) -> list[int]:
65
+ hashed = [zlib.crc32(s.encode("utf-8")) for s in shingle_set] or [0]
66
+ return [min((a * h + b) & _MASK for h in hashed) for a, b in self.funcs]
67
+
68
+ def candidates(self, sig: list[int]) -> set:
69
+ out = set()
70
+ for i in range(self.bands):
71
+ band = tuple(sig[i * self.rows_per_band:(i + 1) * self.rows_per_band])
72
+ bucket = self.buckets[i].get(band)
73
+ if bucket:
74
+ out.update(bucket)
75
+ return out
76
+
77
+ def add(self, sig: list[int], record_id: str) -> None:
78
+ for i in range(self.bands):
79
+ band = tuple(sig[i * self.rows_per_band:(i + 1) * self.rows_per_band])
80
+ self.buckets[i].setdefault(band, []).append(record_id)
81
+
82
+
83
+ class Deduper:
84
+ def __init__(self, path, similarity=.94, num_hashes: int = 32, bands: int = 8):
85
+ self.path = Path(path)
86
+ self.similarity = similarity
87
+ self.rows_by_id: dict[str, dict] = {}
88
+ self.by_hash: dict[str, str] = {} # exact hash -> record_id
89
+ self.by_fp: dict[str, str] = {} # ast fingerprint -> record_id
90
+ self.lsh = MinHashLSH(num_hashes=num_hashes, bands=bands)
91
+
92
+ if self.path.exists():
93
+ for line in self.path.read_text().splitlines():
94
+ try:
95
+ row = json.loads(line)
96
+ except Exception:
97
+ continue
98
+ self._index(row)
99
+
100
+ def _index(self, row: dict) -> None:
101
+ rid = row["id"]
102
+ self.rows_by_id[rid] = row
103
+ self.by_hash.setdefault(row["hash"], rid)
104
+ if row.get("fp"):
105
+ self.by_fp.setdefault(row["fp"], rid)
106
+ sig = row.get("sig")
107
+ if sig is None:
108
+ # Backward compatibility with dedupe files written before MinHash
109
+ # signatures existed: derive the signature from stored shingles.
110
+ sig = self.lsh.signature(set(row.get("shingles", [])))
111
+ self.lsh.add(sig, rid)
112
+
113
+ def check_and_add(self, code: str, record_id: str) -> dict:
114
+ h = hashlib.sha256(norm(code).encode()).hexdigest()
115
+ f = fp(code)
116
+ s = shingles(code)
117
+ sig = self.lsh.signature(s)
118
+
119
+ exact_id = self.by_hash.get(h)
120
+ if exact_id is not None:
121
+ return {"duplicate": True, "kind": "exact", "match_id": exact_id,
122
+ "similarity": 1, "exact_hash": h, "ast_fingerprint": f}
123
+
124
+ if f is not None:
125
+ struct_id = self.by_fp.get(f)
126
+ if struct_id is not None:
127
+ return {"duplicate": True, "kind": "structural", "match_id": struct_id,
128
+ "similarity": 1, "exact_hash": h, "ast_fingerprint": f}
129
+
130
+ best_id, best_score = None, 0.0
131
+ for cand_id in self.lsh.candidates(sig):
132
+ cand = self.rows_by_id.get(cand_id)
133
+ if not cand:
134
+ continue
135
+ q = jac(s, set(cand.get("shingles", [])))
136
+ if q > best_score:
137
+ best_id, best_score = cand_id, q
138
+ if best_id is not None and best_score >= self.similarity:
139
+ return {"duplicate": True, "kind": "near", "match_id": best_id,
140
+ "similarity": best_score, "exact_hash": h, "ast_fingerprint": f}
141
+
142
+ row = {"id": record_id, "hash": h, "fp": f, "shingles": sorted(s), "sig": sig}
143
+ self._index(row)
144
+ self.path.parent.mkdir(parents=True, exist_ok=True)
145
+ with self.path.open("a") as z:
146
+ z.write(json.dumps(row) + "\n")
147
+ return {"duplicate": False, "kind": None, "match_id": None, "similarity": 0,
148
+ "exact_hash": h, "ast_fingerprint": f}
149
+
150
+
151
+ ExactDeduper = Deduper
python_lora_dataset_builder/pipeline/docker_sandbox.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json, shutil, subprocess, tempfile
3
+ from pathlib import Path
4
+ from .sandbox import ExecutionResult
5
+
6
+ def docker_available() -> bool:
7
+ return shutil.which("docker") is not None
8
+
9
+ def run_code_docker(code: str, timeout_seconds: int = 3,
10
+ image: str = "python-lora-sandbox:latest") -> ExecutionResult:
11
+ if not docker_available():
12
+ raise RuntimeError("Docker is required for production sandbox mode but was not found on PATH.")
13
+
14
+ with tempfile.TemporaryDirectory(prefix="py_lora_docker_") as td:
15
+ code_path = Path(td) / "candidate.py"
16
+ code_path.write_text(code, encoding="utf-8")
17
+ cmd = [
18
+ "docker", "run", "--rm",
19
+ "--network", "none",
20
+ "--read-only",
21
+ "--cap-drop", "ALL",
22
+ "--security-opt", "no-new-privileges",
23
+ "--pids-limit", "32",
24
+ "--memory", "256m",
25
+ "--cpus", "1",
26
+ "--tmpfs", "/tmp:rw,noexec,nosuid,size=32m",
27
+ "--user", "65534:65534",
28
+ "-v", f"{code_path.resolve()}:/work/candidate.py:ro",
29
+ "-w", "/work",
30
+ image, "python", "-I", "/work/candidate.py",
31
+ ]
32
+ try:
33
+ p = subprocess.run(cmd, text=True, capture_output=True, timeout=timeout_seconds + 5)
34
+ return ExecutionResult(
35
+ True, p.returncode == 0, False, p.returncode,
36
+ p.stdout[-4000:], p.stderr[-4000:],
37
+ "passed" if p.returncode == 0 else "failed",
38
+ "docker_hardened", None
39
+ )
40
+ except subprocess.TimeoutExpired:
41
+ return ExecutionResult(True, False, True, None, "", "", "failed", "docker_hardened", None)
python_lora_dataset_builder/pipeline/executor.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import os
3
+ from .sandbox import run_code as run_local
4
+ from .docker_sandbox import run_code_docker
5
+
6
+ def run_code(code: str, timeout_seconds: int = 3):
7
+ mode = os.getenv("EXECUTOR_MODE", "local").strip().lower()
8
+ if mode == "docker":
9
+ return run_code_docker(code, timeout_seconds=timeout_seconds)
10
+ if mode != "local":
11
+ raise RuntimeError(f"Unknown EXECUTOR_MODE: {mode}")
12
+ return run_local(code, timeout_seconds=timeout_seconds)
python_lora_dataset_builder/pipeline/nim_reviewer.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json, os, random, time, httpx
3
+ from dotenv import load_dotenv
4
+
5
+ load_dotenv()
6
+
7
+ SYSTEM = (
8
+ "Return ONLY JSON with keys valid,scores,overall_score,dominant_topic,"
9
+ "secondary_topics,summary,issues. scores must contain correctness,"
10
+ "instruction_alignment,quality,training_value,scope_fit, all integers 0-100. "
11
+ "Be strict, concise, and do not reward unnecessary complexity."
12
+ )
13
+
14
+
15
+ class NIMReviewer:
16
+ def __init__(self, topics, retries=3, base_delay=1):
17
+ self.topics = topics
18
+ self.retries = retries
19
+ self.base_delay = base_delay
20
+ self.base = os.getenv("NIM_BASE_URL", "https://integrate.api.nvidia.com/v1").rstrip("/")
21
+ self.model = os.getenv("NIM_MODEL")
22
+ self.key = os.getenv("NIM_API_KEY")
23
+ if not self.model or not self.key:
24
+ raise RuntimeError("Set NIM_MODEL and NIM_API_KEY")
25
+
26
+ def review(self, instruction, user_input, code):
27
+ allowed = "\n".join(f"- {k}: {v}" for k, v in self.topics.items())
28
+ prompt = (
29
+ f"Allowed topics:\n{allowed}\n\nInstruction:\n{instruction}\n\n"
30
+ f"Input:\n{user_input}\n\nCode:\n```python\n{code}\n```"
31
+ )
32
+ payload = {
33
+ "model": self.model,
34
+ "messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}],
35
+ "temperature": 0,
36
+ "max_tokens": 800,
37
+ "response_format": {"type": "json_object"},
38
+ }
39
+
40
+ for attempt in range(1, self.retries + 1):
41
+ try:
42
+ with httpx.Client(timeout=60) as c:
43
+ r = c.post(
44
+ self.base + "/chat/completions",
45
+ headers={"Authorization": f"Bearer {self.key}"},
46
+ json=payload,
47
+ )
48
+ except (httpx.TimeoutException, httpx.TransportError) as e:
49
+ # Network-level failures: retryable.
50
+ if attempt == self.retries:
51
+ raise RuntimeError(f"nim_retry_exhausted: {type(e).__name__}: {e}") from e
52
+ time.sleep(self.base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.5))
53
+ continue
54
+
55
+ if r.status_code == 429 or 500 <= r.status_code < 600:
56
+ # Rate limit / server error: retryable.
57
+ if attempt == self.retries:
58
+ raise RuntimeError(
59
+ f"nim_retry_exhausted: HTTPStatusError: {r.status_code} {r.reason_phrase}"
60
+ )
61
+ time.sleep(self.base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.5))
62
+ continue
63
+
64
+ if r.status_code >= 400:
65
+ # Any other 4xx (400 bad request, 401 bad key, 403 forbidden, 404, ...)
66
+ # will fail identically on every attempt. Fail immediately instead of
67
+ # burning retries and obscuring the real error.
68
+ raise RuntimeError(
69
+ f"nim_request_failed_non_retryable: HTTP {r.status_code} {r.reason_phrase}: "
70
+ f"{r.text[:500]}"
71
+ )
72
+
73
+ r.raise_for_status()
74
+ raw = r.json()
75
+ return json.loads(raw["choices"][0]["message"]["content"]), raw, attempt
python_lora_dataset_builder/pipeline/nim_schema.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def validate_nim_response(d,topics):
2
+ req={'valid','scores','overall_score','dominant_topic','secondary_topics','summary','issues'}; axes={'correctness','instruction_alignment','quality','training_value','scope_fit'}
3
+ if set(d)!=req:return False,'unexpected keys'
4
+ if not isinstance(d['valid'],bool) or set(d['scores'])!=axes:return False,'invalid valid/scores'
5
+ if any(type(x)is not int or not 0<=x<=100 for x in d['scores'].values()):return False,'invalid axis score'
6
+ if type(d['overall_score'])is not int or not 0<=d['overall_score']<=100:return False,'invalid overall'
7
+ if d['dominant_topic'] not in topics:return False,'unknown topic'
8
+ if not isinstance(d['secondary_topics'],list) or any(x not in topics for x in d['secondary_topics']):return False,'invalid secondary'
9
+ if d['dominant_topic'] in d['secondary_topics']:return False,'duplicate topic'
10
+ if not isinstance(d['summary'],str) or not isinstance(d['issues'],list):return False,'invalid text'
11
+ return True,None
python_lora_dataset_builder/pipeline/runner.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import os
4
+ import signal
5
+ import time
6
+ from pathlib import Path
7
+
8
+ from .source_loader import stream_hf_dataset, normalize_source_row
9
+ from .source_checks import check_source_record
10
+ from .code_extractor import extract_code
11
+ from .static_checks import inspect_code
12
+ from .executor import run_code
13
+ from .dedupe import Deduper
14
+ from .secret_scan import scan_code, ensure_secret_scanner_ready
15
+ from .nim_reviewer import NIMReviewer
16
+ from .nim_schema import validate_nim_response
17
+ from .coverage import CoverageTracker
18
+ from .decision import decide
19
+ from .dataset_writer import DatasetWriter
20
+ from .utils import load_json
21
+ from . import tiers as tiers_mod
22
+
23
+
24
+ def build_paths(project_root: Path) -> dict:
25
+ return {
26
+ "topics": project_root / "config/topics_basic_python.json",
27
+ "tier2_libraries": project_root / "config/tier2_libraries.json",
28
+ "thresholds": project_root / "config/thresholds.json",
29
+ "sources": project_root / "config/sources.json",
30
+ "output": project_root / "data",
31
+ "dedupe": project_root / "data/metadata/exact_hashes.txt",
32
+ "coverage": project_root / "data/metadata/topic_coverage.json",
33
+ "checkpoint": project_root / "data/metadata/checkpoint.json",
34
+ }
35
+
36
+
37
+ def load_checkpoint(path: Path) -> dict:
38
+ """Load the checkpoint file if present. Returns {} if missing or unreadable
39
+ (e.g. truncated by a power loss mid-write) so a run always falls back to
40
+ starting from row 0 rather than crashing."""
41
+ if not path.exists():
42
+ return {}
43
+ try:
44
+ return json.loads(path.read_text(encoding="utf-8"))
45
+ except Exception:
46
+ return {}
47
+
48
+
49
+ def save_checkpoint(path: Path, payload: dict) -> None:
50
+ """Atomic checkpoint write: write to a sibling temp file, flush+fsync it,
51
+ then os.replace() over the real file. This way a crash or power cut can
52
+ only ever leave the OLD checkpoint intact or the NEW one fully written —
53
+ never a half-written, corrupt checkpoint.json."""
54
+ path.parent.mkdir(parents=True, exist_ok=True)
55
+ tmp = path.with_suffix(path.suffix + ".tmp")
56
+ with tmp.open("w", encoding="utf-8") as f:
57
+ json.dump(payload, f, indent=2)
58
+ f.flush()
59
+ os.fsync(f.fileno())
60
+ os.replace(tmp, path)
61
+
62
+
63
+ def _install_stop_handler():
64
+ """Catch Ctrl+C (SIGINT) and a polite kill (SIGTERM) so the pipeline
65
+ finishes writing the record it's currently on, saves a checkpoint, and
66
+ exits cleanly instead of getting cut off mid-record. A second Ctrl+C
67
+ still forces an immediate exit if the person really wants out now."""
68
+ state = {"stop": False, "count": 0}
69
+
70
+ def handler(signum, frame):
71
+ state["count"] += 1
72
+ state["stop"] = True
73
+ if state["count"] >= 2:
74
+ raise KeyboardInterrupt("Second stop signal: forcing immediate exit.")
75
+ print("\n[stopping after current record — checkpoint will be saved; "
76
+ "press Ctrl+C again to force quit immediately]")
77
+
78
+ signal.signal(signal.SIGINT, handler)
79
+ try:
80
+ signal.signal(signal.SIGTERM, handler)
81
+ except (ValueError, AttributeError):
82
+ pass # SIGTERM not available on some platforms (e.g. Windows consoles)
83
+ return state
84
+
85
+
86
+ def _merge_stats(cumulative: dict, run_stats: dict) -> dict:
87
+ out = dict(cumulative)
88
+ for k, v in run_stats.items():
89
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
90
+ out[k] = out.get(k, 0) + v
91
+ return out
92
+
93
+
94
+ def run(project_root: Path, limit: int = 500, dry_run: bool = False,
95
+ source_name_override: str | None = None,
96
+ active_tiers: tuple[str, ...] = (tiers_mod.TIER1_BASIC,),
97
+ resume: bool = True) -> dict:
98
+ """Run the pipeline for up to `limit` NEW rows this invocation.
99
+
100
+ Resumability: progress (how many source rows have been consumed so far)
101
+ is stored in data/metadata/checkpoint.json. Each call to `run()`:
102
+ - loads that checkpoint (unless resume=False),
103
+ - skips over rows already consumed on a prior run/day,
104
+ - processes up to `limit` more rows,
105
+ - and saves the new cursor + cumulative stats back to the checkpoint —
106
+ after EVERY row, not just at the end, so a crash or closed terminal
107
+ never loses more than the one row that was in flight.
108
+
109
+ This is what makes "run it for a while today, close it, run it again
110
+ tomorrow, repeat for weeks" work: each run just continues from where the
111
+ last one left off, on the same source, until the whole dataset is
112
+ consumed or you stop asking it to run.
113
+
114
+ active_tiers controls which of the three dataset tiers are actually
115
+ processed end-to-end this run:
116
+ - basic_python_syntax : fully automated today (default; run this now).
117
+ - per_library : classified and NIM-reviewed, but never
118
+ auto-included, since there's no per-library
119
+ execution environment yet.
120
+ - real_world_repository : classified only; not executed or scored.
121
+
122
+ Records whose tier isn't in active_tiers are still classified and written
123
+ (decision="skip", reason="tier_not_active:<tier>") so nothing is lost —
124
+ they're just not spending NIM requests or execution time this run.
125
+ """
126
+ # Fail closed, once, before doing any other work: don't burn NIM/API
127
+ # requests or partially process a batch if secret scanning isn't in place.
128
+ ensure_secret_scanner_ready()
129
+
130
+ paths = build_paths(project_root)
131
+ topics = load_json(paths["topics"])
132
+ tier2_libraries = load_json(paths["tier2_libraries"])
133
+ thresholds = load_json(paths["thresholds"])
134
+ source_cfg = load_json(paths["sources"])["primary"]
135
+ source_name = source_name_override or source_cfg["name"]
136
+
137
+ checkpoint = load_checkpoint(paths["checkpoint"]) if resume else {}
138
+ same_source = checkpoint.get("source") == source_name
139
+ rows_completed = int(checkpoint.get("rows_completed", 0)) if same_source else 0
140
+ cumulative_stats = dict(checkpoint.get("cumulative_stats", {})) if same_source else {}
141
+ source_exhausted = bool(checkpoint.get("source_exhausted")) if same_source else False
142
+
143
+ if source_exhausted:
144
+ print(f"'{source_name}' is already fully processed ({rows_completed} rows). "
145
+ "Nothing new to do. Point --source at a different dataset, or delete "
146
+ "data/metadata/checkpoint.json to reprocess from the start.")
147
+ return {"processed": 0, "rows_completed": rows_completed, "source_exhausted": True}
148
+
149
+ if rows_completed:
150
+ print(f"Resuming '{source_name}' at row {rows_completed} "
151
+ f"(already processed in earlier runs).")
152
+
153
+ deduper = Deduper(paths["dedupe"], thresholds.get("near_duplicate_similarity", 0.94))
154
+ coverage = CoverageTracker(
155
+ paths["coverage"], topics, thresholds["default_topic_target"]
156
+ )
157
+ writer = DatasetWriter(paths["output"])
158
+ reviewer = None if dry_run else NIMReviewer(topics)
159
+
160
+ stats = {"processed": 0, "include": 0, "manual_review": 0,
161
+ "reject": 0, "skip": 0, "retry": 0, "nim_schema_failures": 0}
162
+
163
+ dataset = stream_hf_dataset(source_name, source_cfg.get("split", "train"))
164
+ if rows_completed:
165
+ dataset = dataset.skip(rows_completed)
166
+
167
+ stop_state = _install_stop_handler()
168
+ row_index = rows_completed - 1 # kept correct even if the loop body never runs
169
+ exhausted_this_run = True # flipped to False the moment we break instead of exhausting the source
170
+
171
+ def checkpoint_now(exhausted: bool) -> None:
172
+ save_checkpoint(paths["checkpoint"], {
173
+ "source": source_name,
174
+ "rows_completed": row_index + 1,
175
+ "cumulative_stats": _merge_stats(cumulative_stats, stats),
176
+ "last_run_stats": stats,
177
+ "source_exhausted": exhausted,
178
+ "last_updated": time.strftime("%Y-%m-%dT%H:%M:%S"),
179
+ })
180
+
181
+ try:
182
+ for offset, row in enumerate(dataset):
183
+ if offset >= limit:
184
+ exhausted_this_run = False
185
+ break
186
+ if stop_state["stop"]:
187
+ exhausted_this_run = False
188
+ print(f"Stopping early by request, after {stats['processed']} "
189
+ "records this run.")
190
+ break
191
+
192
+ row_index = rows_completed + offset
193
+
194
+ record = normalize_source_row(
195
+ row, source_name, row_index,
196
+ source_cfg.get("instruction_field", "instruction"),
197
+ source_cfg.get("input_field", "input"),
198
+ source_cfg.get("output_field", "output"),
199
+ )
200
+ stats["processed"] += 1
201
+
202
+ source_ok, source_reason = check_source_record(record)
203
+ code = extract_code(record["output"])
204
+
205
+ if not source_ok:
206
+ final = {
207
+ **record, "code": code, "tier": "unclassified",
208
+ "checks": {"source_passed": False},
209
+ "decision": "reject", "decision_reason": source_reason,
210
+ }
211
+ writer.write("reject", final, tier="unclassified")
212
+ stats["reject"] += 1
213
+ checkpoint_now(exhausted=False)
214
+ continue
215
+
216
+ if not code:
217
+ final = {
218
+ **record, "code": None, "tier": "unclassified",
219
+ "checks": {"source_passed": True, "code_extracted": False},
220
+ "decision": "reject", "decision_reason": "no_usable_python_code",
221
+ }
222
+ writer.write("reject", final, tier="unclassified")
223
+ stats["reject"] += 1
224
+ checkpoint_now(exhausted=False)
225
+ continue
226
+
227
+ static = inspect_code(code)
228
+ # Duplicate check happens BEFORE sandbox execution and BEFORE any
229
+ # NIM API call, on purpose: there's no point spending execution
230
+ # time (or worse, a paid API request) testing/reviewing code
231
+ # that's already been seen before. Cheapest check first.
232
+ dup = deduper.check_and_add(code, record["record_id"])
233
+ duplicate, code_hash = dup["duplicate"], dup["exact_hash"]
234
+ secret = scan_code(code)
235
+ tier, tier_library = tiers_mod.classify_tier(static.imports, tier2_libraries)
236
+
237
+ # Only tier 1 (import-free) has an execution environment today.
238
+ # Tiers 2/3 don't have a per-library or per-project sandbox yet, so
239
+ # we classify and (optionally) NIM-review them without executing.
240
+ # Skip execution entirely for duplicates — we're going to `skip`
241
+ # this record regardless of what execution would show.
242
+ execution = None
243
+ if (not duplicate and tier == tiers_mod.TIER1_BASIC
244
+ and static.ast_valid and static.compile_valid
245
+ and not static.secret_found and secret["passed"]):
246
+ execution = run_code(code)
247
+
248
+ checks = {
249
+ "source_passed": True,
250
+ "code_extracted": True,
251
+ "ast_valid": static.ast_valid,
252
+ "compile_valid": static.compile_valid,
253
+ "secret_found": static.secret_found,
254
+ "secret_passed": secret["passed"],
255
+ "secret_scan": secret,
256
+ "duplicate_kind": dup["kind"],
257
+ "duplicate_match_id": dup["match_id"],
258
+ "duplicate_similarity": dup["similarity"],
259
+ "ast_fingerprint": dup["ast_fingerprint"],
260
+ "code_too_short": static.code_too_short,
261
+ "imports": static.imports,
262
+ "static_error": static.error,
263
+ "duplicate": duplicate,
264
+ "code_hash": code_hash,
265
+ "tier": tier,
266
+ "tier_library": tier_library,
267
+ "basic_tier_allowed": tier == tiers_mod.TIER1_BASIC,
268
+ "execution_attempted": bool(execution and execution.attempted),
269
+ "execution_status": execution.status if execution else "not_attempted",
270
+ "execution_isolation": execution.isolation if execution else None,
271
+ "execution_warning": execution.warning if execution else None,
272
+ "execution_passed": bool(execution and execution.passed),
273
+ "execution_timed_out": bool(execution and execution.timed_out),
274
+ "execution_returncode": execution.returncode if execution else None,
275
+ "execution_stdout": execution.stdout if execution else "",
276
+ "execution_stderr": execution.stderr if execution else "",
277
+ }
278
+
279
+ # Hard/static failures are written without spending a NIM request.
280
+ hard_reason = None
281
+ hard_decision = None
282
+ if not static.ast_valid:
283
+ hard_decision, hard_reason = "reject", "syntax_invalid"
284
+ elif not static.compile_valid:
285
+ hard_decision, hard_reason = "reject", "compile_failed"
286
+ elif static.secret_found:
287
+ hard_decision, hard_reason = "reject", "secret_detected"
288
+ elif checks.get("secret_scan", {}).get("passed") is False:
289
+ hard_decision, hard_reason = "reject", "gitleaks_secret_detected"
290
+ elif duplicate:
291
+ hard_decision, hard_reason = "skip", "duplicate"
292
+ elif tier not in active_tiers:
293
+ hard_decision, hard_reason = "skip", f"tier_not_active:{tier}"
294
+ elif execution is not None and not execution.passed:
295
+ hard_decision, hard_reason = "reject", "sandbox_execution_failed"
296
+
297
+ if hard_decision is not None:
298
+ final = {
299
+ **record, "code": code, "tier": tier, "tier_library": tier_library,
300
+ "checks": checks, "nim": None,
301
+ "nim_status": "not_called_hard_check",
302
+ "decision": hard_decision, "decision_reason": hard_reason,
303
+ }
304
+ writer.write(hard_decision, final, tier=tier, tier_library=tier_library)
305
+ stats[hard_decision] += 1
306
+ checkpoint_now(exhausted=False)
307
+ continue
308
+
309
+ if dry_run:
310
+ final = {
311
+ **record, "code": code, "tier": tier, "tier_library": tier_library,
312
+ "checks": checks, "nim": None,
313
+ "decision": "manual_review",
314
+ "decision_reason": "dry_run_nim_not_called",
315
+ }
316
+ writer.write("manual_review", final, tier=tier, tier_library=tier_library)
317
+ stats["manual_review"] += 1
318
+ checkpoint_now(exhausted=False)
319
+ continue
320
+
321
+ try:
322
+ nim, raw, attempts = reviewer.review(record["instruction"], record["input"], code)
323
+ writer.write_raw_nim(record["record_id"], raw)
324
+ nim["review_attempts"] = attempts
325
+ schema_ok, schema_error = validate_nim_response(nim, set(topics))
326
+ except Exception as exc:
327
+ final = {
328
+ **record, "code": code, "tier": tier, "tier_library": tier_library,
329
+ "checks": checks, "nim": None,
330
+ "decision": "retry",
331
+ "decision_reason": f"nim_request_failed: {type(exc).__name__}: {exc}",
332
+ }
333
+ writer.write("retry", final, tier=tier, tier_library=tier_library)
334
+ stats["retry"] = stats.get("retry", 0) + 1
335
+ checkpoint_now(exhausted=False)
336
+ continue
337
+
338
+ if not schema_ok:
339
+ stats["nim_schema_failures"] += 1
340
+ final = {
341
+ **record, "code": code, "tier": tier, "tier_library": tier_library,
342
+ "checks": checks, "nim": nim,
343
+ "decision": "manual_review",
344
+ "decision_reason": f"nim_schema_invalid: {schema_error}",
345
+ }
346
+ writer.write("manual_review", final, tier=tier, tier_library=tier_library)
347
+ stats["manual_review"] += 1
348
+ checkpoint_now(exhausted=False)
349
+ continue
350
+
351
+ decision, reason = decide(checks, nim, coverage)
352
+ if tier != tiers_mod.TIER1_BASIC and decision == "include":
353
+ # Never auto-include a record whose code was never executed.
354
+ decision, reason = "manual_review", f"{reason}_unverified_no_execution_env"
355
+ if decision == "include":
356
+ coverage.add(nim["dominant_topic"])
357
+
358
+ final = {
359
+ **record,
360
+ "code": code,
361
+ "tier": tier,
362
+ "tier_library": tier_library,
363
+ "checks": checks,
364
+ "nim": nim,
365
+ "decision": decision,
366
+ "decision_reason": reason,
367
+ }
368
+ writer.write(decision, final, tier=tier, tier_library=tier_library)
369
+ stats[decision] += 1
370
+
371
+ # Checkpoint after every single row: this is what lets a power
372
+ # failure or a killed terminal lose at most the one in-flight row,
373
+ # not the whole run.
374
+ checkpoint_now(exhausted=False)
375
+ else:
376
+ # The for-loop finished naturally (the dataset ran out of rows)
377
+ # rather than via `break` — that means the entire source has been
378
+ # consumed. exhausted_this_run stays True in that case.
379
+ pass
380
+ finally:
381
+ checkpoint_now(exhausted=exhausted_this_run)
382
+
383
+ stats["rows_completed"] = row_index + 1
384
+ stats["source_exhausted"] = exhausted_this_run
385
+ stats["cumulative_stats"] = _merge_stats(cumulative_stats, stats)
386
+ return stats
python_lora_dataset_builder/pipeline/sandbox.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ from dataclasses import dataclass
8
+
9
+ @dataclass
10
+ class ExecutionResult:
11
+ attempted: bool
12
+ passed: bool
13
+ timed_out: bool
14
+ returncode: int | None
15
+ stdout: str
16
+ stderr: str
17
+ status: str
18
+ isolation: str
19
+ warning: str | None = None
20
+
21
+ def _linux_preexec(memory_limit_mb: int, cpu_seconds: int, process_limit: int):
22
+ def apply_limits():
23
+ import resource
24
+ memory = memory_limit_mb * 1024 * 1024
25
+ resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
26
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds))
27
+ resource.setrlimit(resource.RLIMIT_NPROC, (process_limit, process_limit))
28
+ resource.setrlimit(resource.RLIMIT_FSIZE, (16 * 1024 * 1024, 16 * 1024 * 1024))
29
+ resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
30
+ return apply_limits
31
+
32
+ def run_code(code: str, timeout_seconds: int = 3, memory_limit_mb: int = 1024,
33
+ cpu_seconds: int = 2, process_limit: int = 512) -> ExecutionResult:
34
+ """
35
+ Development executor. On Linux it applies rlimits. On Windows, Python has no
36
+ stdlib equivalent to setrlimit, so execution is explicitly marked limited.
37
+ Production runs should use the Docker executor with network disabled.
38
+ """
39
+ with tempfile.TemporaryDirectory(prefix="py_lora_") as td:
40
+ kwargs = {
41
+ "cwd": td,
42
+ "env": {
43
+ **os.environ,
44
+ "PYTHONIOENCODING": "utf-8",
45
+ "PYTHONDONTWRITEBYTECODE": "1",
46
+ "OPENBLAS_NUM_THREADS": "1",
47
+ "OMP_NUM_THREADS": "1",
48
+ "MKL_NUM_THREADS": "1",
49
+ },
50
+ "text": True,
51
+ "capture_output": True,
52
+ "timeout": timeout_seconds,
53
+ }
54
+ isolation = "windows_limited"
55
+ warning = None
56
+ if sys.platform.startswith("linux"):
57
+ kwargs["preexec_fn"] = _linux_preexec(memory_limit_mb, cpu_seconds, process_limit)
58
+ isolation = "linux_rlimit"
59
+ elif os.name == "nt":
60
+ warning = (
61
+ "Windows local executor has timeout and temporary cwd only. "
62
+ "Use Docker mode for production/untrusted code; Windows has no "
63
+ "stdlib setrlimit equivalent."
64
+ )
65
+ else:
66
+ warning = "No OS resource limits are available in this local executor."
67
+
68
+ try:
69
+ p = subprocess.run(
70
+ [sys.executable, "-I", "-c", code],
71
+ **kwargs,
72
+ )
73
+ status = "passed" if p.returncode == 0 else "failed"
74
+ return ExecutionResult(
75
+ True, p.returncode == 0, False, p.returncode,
76
+ p.stdout[-4000:], p.stderr[-4000:], status, isolation, warning
77
+ )
78
+ except subprocess.TimeoutExpired as e:
79
+ return ExecutionResult(
80
+ True, False, True, None,
81
+ (e.stdout or "")[-4000:] if isinstance(e.stdout, str) else "",
82
+ (e.stderr or "")[-4000:] if isinstance(e.stderr, str) else "",
83
+ "failed", isolation, warning
84
+ )
python_lora_dataset_builder/pipeline/secret_scan.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json, os, shutil, subprocess, tempfile
3
+ from pathlib import Path
4
+
5
+
6
+ def _truthy(value: str | None) -> bool:
7
+ return str(value).strip().lower() in ("1", "true", "yes", "on")
8
+
9
+
10
+ def gitleaks_available() -> bool:
11
+ return shutil.which("gitleaks") is not None
12
+
13
+
14
+ def missing_gitleaks_allowed() -> bool:
15
+ return _truthy(os.getenv("ALLOW_MISSING_GITLEAKS", "0"))
16
+
17
+
18
+ def ensure_secret_scanner_ready() -> None:
19
+ """Fail-closed startup check. Call this once before processing any records.
20
+
21
+ If Gitleaks is not on PATH and ALLOW_MISSING_GITLEAKS is not set to a truthy
22
+ value, this raises immediately so a run cannot silently process records
23
+ without secret scanning coverage.
24
+ """
25
+ if gitleaks_available():
26
+ return
27
+ if missing_gitleaks_allowed():
28
+ return
29
+ raise RuntimeError(
30
+ "Gitleaks was not found on PATH and ALLOW_MISSING_GITLEAKS is not set. "
31
+ "Install Gitleaks (https://github.com/gitleaks/gitleaks) and ensure "
32
+ "`gitleaks` is on PATH before running the pipeline. For local, "
33
+ "non-production development only, you may set ALLOW_MISSING_GITLEAKS=1 "
34
+ "to explicitly opt out of secret scanning; every record processed under "
35
+ "that override is marked with a warning in its metadata."
36
+ )
37
+
38
+
39
+ def scan_code(code: str) -> dict:
40
+ g = shutil.which("gitleaks")
41
+ if not g:
42
+ if missing_gitleaks_allowed():
43
+ return {
44
+ "passed": True,
45
+ "tool": "unavailable",
46
+ "findings": [],
47
+ "warning": "gitleaks_not_installed_override_allowed",
48
+ }
49
+ # Defense in depth: even if ensure_secret_scanner_ready() was skipped
50
+ # or Gitleaks disappeared mid-run, never silently pass records through.
51
+ raise RuntimeError(
52
+ "Gitleaks is not installed and ALLOW_MISSING_GITLEAKS is not set to 1. "
53
+ "Refusing to pass a record through without a secret scan (fail-closed)."
54
+ )
55
+ with tempfile.TemporaryDirectory() as d:
56
+ p = Path(d) / "x.py"
57
+ out = Path(d) / "r.json"
58
+ p.write_text(code, encoding="utf-8")
59
+ x = subprocess.run(
60
+ [g, "detect", "--no-git", "--source", str(p), "--report-format", "json",
61
+ "--report-path", str(out), "--redact", "--exit-code", "1"],
62
+ capture_output=True, text=True, timeout=20,
63
+ )
64
+ fs = []
65
+ if out.exists():
66
+ try:
67
+ fs = [{"rule": a.get("RuleID"), "line": a.get("StartLine")} for a in json.loads(out.read_text())]
68
+ except Exception:
69
+ pass
70
+ return {"passed": x.returncode == 0, "tool": "gitleaks", "findings": fs, "warning": None}
python_lora_dataset_builder/pipeline/source_checks.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ # Dataset-level license/provenance review should be completed before a source
4
+ # is processed. This per-record hook exists for future source metadata rules.
5
+
6
+ def check_source_record(record: dict) -> tuple[bool, str | None]:
7
+ if not record.get("instruction") and not record.get("output"):
8
+ return False, "empty_instruction_and_output"
9
+ return True, None
python_lora_dataset_builder/pipeline/source_loader.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from datasets import load_dataset
3
+
4
+ def stream_hf_dataset(name: str, split: str = "train"):
5
+ """Stream records so the first test does not download the full dataset."""
6
+ return load_dataset(name, split=split, streaming=True)
7
+
8
+ def normalize_source_row(row: dict, source_name: str, row_index: int,
9
+ instruction_field: str = "instruction",
10
+ input_field: str = "input",
11
+ output_field: str = "output") -> dict:
12
+ return {
13
+ "record_id": f"{source_name.replace('/', '__')}__{row_index:08d}",
14
+ "source": {"dataset": source_name, "row": row_index},
15
+ "instruction": str(row.get(instruction_field, "") or "").strip(),
16
+ "input": str(row.get(input_field, "") or "").strip(),
17
+ "output": str(row.get(output_field, "") or "").strip(),
18
+ "raw_row": row,
19
+ }
python_lora_dataset_builder/pipeline/static_checks.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast,re
2
+ from dataclasses import dataclass
3
+ PATS=[re.compile(r"(?i)(api[_-]?key|secret|token|password)\s*[:=]\s*['\"][^'\"]{12,}"),re.compile(r"(?i)-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----")]
4
+ @dataclass
5
+ class CheckResult:
6
+ ast_valid:bool; compile_valid:bool; secret_found:bool; code_too_short:bool; imports:list; error:str|None=None
7
+ def inspect_code(code):
8
+ secret=any(p.search(code) for p in PATS)
9
+ if len(code.strip())<8:return CheckResult(False,False,secret,True,[],"code_too_short")
10
+ try: tree=ast.parse(code)
11
+ except SyntaxError as e:return CheckResult(False,False,secret,False,[],f"SyntaxError: {e.msg} at line {e.lineno}")
12
+ try: compile(code,"<candidate>","exec")
13
+ except Exception as e:return CheckResult(True,False,secret,False,[],repr(e))
14
+ imports=[]
15
+ for n in ast.walk(tree):
16
+ if isinstance(n,ast.Import): imports += [a.name.split(".")[0] for a in n.names]
17
+ elif isinstance(n,ast.ImportFrom) and n.module: imports.append(n.module.split(".")[0])
18
+ return CheckResult(True,True,secret,False,sorted(set(imports)),None)
19
+ def is_basic_syntax_candidate(imports): return len(imports)==0
python_lora_dataset_builder/pipeline/tiers.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ TIER1_BASIC = "basic_python_syntax"
4
+ TIER2_PER_LIBRARY = "per_library"
5
+ TIER3_REAL_WORLD = "real_world_repository"
6
+
7
+ ALL_TIERS = (TIER1_BASIC, TIER2_PER_LIBRARY, TIER3_REAL_WORLD)
8
+
9
+
10
+ def classify_tier(imports: list[str], tier2_libraries: dict) -> tuple[str, str | None]:
11
+ """Classify a code sample into one of the three dataset tiers, based on its
12
+ top-level imports.
13
+
14
+ - No imports at all -> tier 1, basic syntax (fully automated
15
+ end-to-end today: extraction, static checks, sandbox execution, NIM
16
+ review, and scoring all run for this tier).
17
+ - Every import is a library we recognise (config/tier2_libraries.json)
18
+ -> tier 2, per-library, tagged with the primary (alphabetically first)
19
+ recognised library so records can be organized/filtered per library.
20
+ - Any unrecognised import -> tier 3, treated as real-world/project
21
+ code until a dedicated validation profile exists for it (see README).
22
+
23
+ Tier 2 and tier 3 do not yet have execution environments, so the runner
24
+ skips sandbox execution for them and never auto-includes an unexecuted
25
+ record; see runner.py.
26
+ """
27
+ if not imports:
28
+ return TIER1_BASIC, None
29
+ unknown = [lib for lib in imports if lib not in tier2_libraries]
30
+ if unknown:
31
+ return TIER3_REAL_WORLD, None
32
+ primary = sorted(imports)[0]
33
+ return TIER2_PER_LIBRARY, primary
python_lora_dataset_builder/pipeline/utils.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import json, hashlib, re
2
+ from pathlib import Path
3
+ def load_json(path): return json.loads(Path(path).read_text(encoding="utf-8"))
4
+ def append_jsonl(path,record):
5
+ path=Path(path); path.parent.mkdir(parents=True,exist_ok=True)
6
+ with path.open("a",encoding="utf-8") as f:f.write(json.dumps(record,ensure_ascii=False)+"\n")
7
+ def normalize_code(code): return "\n".join(x.rstrip() for x in code.replace("\r\n","\n").splitlines()).strip()
8
+ def sha256_text(text): return hashlib.sha256(text.encode("utf-8","ignore")).hexdigest()
python_lora_dataset_builder/pytest.ini ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [pytest]
2
+ addopts = --import-mode=importlib
python_lora_dataset_builder/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ datasets>=3.0.0
2
+ httpx>=0.27.0
3
+ python-dotenv>=1.0.1
4
+ pytest>=8.0.0
python_lora_dataset_builder/scripts/run_daily.ps1 ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run this once (whenever you sit down to run it - daily, every few days,
2
+ # whatever works) to process the NEXT batch of rows. It always resumes from
3
+ # wherever the last run left off, so running this once a day for a few weeks
4
+ # is exactly the intended usage. It's also fine to interrupt with Ctrl+C -
5
+ # see README "Stopping and recovering" section.
6
+ #
7
+ # Usage:
8
+ # scripts\run_daily.ps1 # dry run, 500 rows (safe default)
9
+ # scripts\run_daily.ps1 -Real # real run (spends NIM API requests), 500 rows
10
+ # scripts\run_daily.ps1 -Real -Limit 200 # real run, 200 rows this session
11
+
12
+ param(
13
+ [switch]$Real,
14
+ [int]$Limit = 500
15
+ )
16
+
17
+ $ErrorActionPreference = "Stop"
18
+
19
+ $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
20
+ $ProjectDir = Split-Path -Parent $ScriptDir
21
+ Set-Location $ProjectDir
22
+
23
+ if (-not (Test-Path ".venv")) {
24
+ Write-Host "No .venv\ found - run scripts\setup.ps1 first."
25
+ exit 1
26
+ }
27
+
28
+ & .\.venv\Scripts\Activate.ps1
29
+
30
+ # Keep dependencies in sync with requirements.txt automatically. Fast when
31
+ # already installed; never touches anything outside .venv\.
32
+ pip install --quiet -r requirements.txt
33
+
34
+ Write-Host "Running: python main.py --limit $Limit $(if (-not $Real) {'--dry-run'})"
35
+ Write-Host "(Ctrl+C once = finish current record, save progress, stop cleanly.)"
36
+ Write-Host ""
37
+
38
+ if ($Real) {
39
+ python main.py --limit $Limit
40
+ } else {
41
+ python main.py --limit $Limit --dry-run
42
+ }
python_lora_dataset_builder/scripts/run_daily.sh ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run this once (whenever you sit down to run it — daily, every few days,
3
+ # whatever works) to process the NEXT batch of rows. It always resumes from
4
+ # wherever the last run left off, so running this once a day for a few weeks
5
+ # is exactly the intended usage. It's also fine to interrupt with Ctrl+C —
6
+ # see README "Stopping and recovering" section.
7
+ #
8
+ # Usage:
9
+ # scripts/run_daily.sh # dry run, 500 rows (safe default)
10
+ # scripts/run_daily.sh --real # real run (spends NIM API requests), 500 rows
11
+ # scripts/run_daily.sh --real 200 # real run, 200 rows this session
12
+ set -euo pipefail
13
+
14
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
15
+ PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
16
+ cd "$PROJECT_DIR"
17
+
18
+ if [ ! -d ".venv" ]; then
19
+ echo "No .venv/ found — run scripts/setup.sh first."
20
+ exit 1
21
+ fi
22
+
23
+ # shellcheck disable=SC1091
24
+ source .venv/bin/activate
25
+
26
+ # Keep dependencies in sync with requirements.txt automatically. This is
27
+ # fast (a few hundred ms) when everything is already installed, and only
28
+ # actually downloads/installs when requirements.txt has changed — it never
29
+ # touches anything outside .venv/.
30
+ pip install --quiet -r requirements.txt
31
+
32
+ MODE="--dry-run"
33
+ LIMIT="500"
34
+
35
+ if [ "${1:-}" = "--real" ]; then
36
+ MODE=""
37
+ LIMIT="${2:-500}"
38
+ elif [ -n "${1:-}" ]; then
39
+ LIMIT="$1"
40
+ fi
41
+
42
+ echo "Running: python main.py --limit $LIMIT $MODE"
43
+ echo "(Ctrl+C once = finish current record, save progress, stop cleanly.)"
44
+ echo
45
+
46
+ # shellcheck disable=SC2086
47
+ python main.py --limit "$LIMIT" $MODE
python_lora_dataset_builder/scripts/setup.ps1 ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # One-time setup for Windows.
2
+ #
3
+ # Creates an isolated virtual environment INSIDE this project folder
4
+ # (.venv\) and installs the pipeline's dependencies into it. This never
5
+ # touches your system Python, any other project's packages, or anything
6
+ # outside this folder — deleting the project folder removes everything
7
+ # this script installed (except Gitleaks, which is a separate one-time
8
+ # system tool; see the message at the end).
9
+
10
+ $ErrorActionPreference = "Stop"
11
+
12
+ $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
13
+ $ProjectDir = Split-Path -Parent $ScriptDir
14
+ Set-Location $ProjectDir
15
+
16
+ $pythonCmd = Get-Command python -ErrorAction SilentlyContinue
17
+ if (-not $pythonCmd) {
18
+ Write-Host "ERROR: python not found on PATH. Install Python 3.10+ from https://www.python.org/downloads/ (check 'Add python.exe to PATH' during install)."
19
+ exit 1
20
+ }
21
+
22
+ Write-Host "Using $(python --version)"
23
+
24
+ if (-not (Test-Path ".venv")) {
25
+ Write-Host "Creating isolated virtual environment in .venv\ ..."
26
+ python -m venv .venv
27
+ } else {
28
+ Write-Host ".venv\ already exists — reusing it."
29
+ }
30
+
31
+ & .\.venv\Scripts\Activate.ps1
32
+
33
+ Write-Host "Installing dependencies into .venv\ (this does not touch system Python) ..."
34
+ pip install --quiet --upgrade pip
35
+ pip install --quiet -r requirements.txt
36
+
37
+ if (-not (Test-Path ".env")) {
38
+ Copy-Item ".env.example" ".env"
39
+ Write-Host "Created .env from .env.example — edit it and fill in NIM_API_KEY, NIM_BASE_URL, NIM_MODEL."
40
+ } else {
41
+ Write-Host ".env already exists — leaving it alone."
42
+ }
43
+
44
+ Write-Host ""
45
+ Write-Host "Checking for Gitleaks (required unless you deliberately set ALLOW_MISSING_GITLEAKS=1) ..."
46
+ $gitleaksCmd = Get-Command gitleaks -ErrorAction SilentlyContinue
47
+ if ($gitleaksCmd) {
48
+ Write-Host " Found: $(gitleaks version)"
49
+ } else {
50
+ Write-Host " NOT found. Install it (one-time, system-level, like installing any CLI tool):"
51
+ Write-Host " winget install gitleaks"
52
+ Write-Host " (or see https://github.com/gitleaks/gitleaks#installing)"
53
+ Write-Host " Until it's installed, real runs will refuse to start (fails closed by design)."
54
+ }
55
+
56
+ Write-Host ""
57
+ Write-Host "Setup complete."
58
+ Write-Host "Next: edit .env with your NIM credentials, then run scripts\run_daily.ps1"
python_lora_dataset_builder/scripts/setup.sh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # One-time setup for macOS/Linux.
3
+ #
4
+ # Creates an isolated virtual environment INSIDE this project folder
5
+ # (.venv/) and installs the pipeline's dependencies into it. This never
6
+ # touches your system Python, any other project's packages, or anything
7
+ # outside this folder — deleting the project folder removes everything
8
+ # this script installed (except Gitleaks, which is a separate one-time
9
+ # system tool; see the message at the end).
10
+ set -euo pipefail
11
+
12
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
14
+ cd "$PROJECT_DIR"
15
+
16
+ PYTHON_BIN="${PYTHON_BIN:-python3}"
17
+
18
+ if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then
19
+ echo "ERROR: $PYTHON_BIN not found. Install Python 3.10+ first: https://www.python.org/downloads/"
20
+ exit 1
21
+ fi
22
+
23
+ echo "Using $($PYTHON_BIN --version)"
24
+
25
+ if [ ! -d ".venv" ]; then
26
+ echo "Creating isolated virtual environment in .venv/ ..."
27
+ "$PYTHON_BIN" -m venv .venv
28
+ else
29
+ echo ".venv/ already exists — reusing it."
30
+ fi
31
+
32
+ # shellcheck disable=SC1091
33
+ source .venv/bin/activate
34
+
35
+ echo "Installing dependencies into .venv/ (this does not touch system Python) ..."
36
+ pip install --quiet --upgrade pip
37
+ pip install --quiet -r requirements.txt
38
+
39
+ if [ ! -f ".env" ]; then
40
+ cp .env.example .env
41
+ echo "Created .env from .env.example — edit it and fill in NIM_API_KEY, NIM_BASE_URL, NIM_MODEL."
42
+ else
43
+ echo ".env already exists — leaving it alone."
44
+ fi
45
+
46
+ echo
47
+ echo "Checking for Gitleaks (required unless you deliberately set ALLOW_MISSING_GITLEAKS=1) ..."
48
+ if command -v gitleaks >/dev/null 2>&1; then
49
+ echo " Found: $(gitleaks version 2>&1 | head -n1)"
50
+ else
51
+ echo " NOT found. Install it (one-time, system-level, like installing any CLI tool):"
52
+ echo " macOS: brew install gitleaks"
53
+ echo " Linux: see https://github.com/gitleaks/gitleaks#installing"
54
+ echo " Until it's installed, real runs will refuse to start (fails closed by design)."
55
+ fi
56
+
57
+ echo
58
+ echo "Setup complete."
59
+ echo "Next: edit .env with your NIM credentials, then run scripts/run_daily.sh"
python_lora_dataset_builder/tests/conftest.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ ROOT = Path(__file__).resolve().parents[1]
4
+ sys.path.insert(0, str(ROOT))
python_lora_dataset_builder/tests/test_code_extractor.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from pipeline.code_extractor import extract_code
2
+
3
+ def test_fenced_python():
4
+ text = "Explanation\n```python\ndef add(a, b):\n return a + b\n```"
5
+ assert extract_code(text).startswith("def add")
6
+
7
+ def test_no_code():
8
+ assert extract_code("This is only an explanation.") is None
python_lora_dataset_builder/tests/test_decision.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pipeline.decision import decide
2
+
3
+ class Coverage:
4
+ def __init__(self, needs=True):
5
+ self.needs = needs
6
+ def needs_coverage(self, topic):
7
+ return self.needs
8
+
9
+ def checks():
10
+ return {
11
+ "ast_valid": True, "compile_valid": True, "secret_found": False,
12
+ "duplicate": False, "basic_tier_allowed": True, "execution_passed": True,
13
+ }
14
+
15
+ def nim(score):
16
+ return {
17
+ "valid": True, "overall_score": score, "dominant_topic": "functions", "scores": {"correctness": 90, "instruction_alignment": 90, "quality": 90, "training_value": 90, "scope_fit": 90}
18
+ }
19
+
20
+ def test_under_80_rejected():
21
+ assert decide(checks(), nim(79), Coverage())[0] == "reject"
22
+
23
+ def test_80_84_manual():
24
+ assert decide(checks(), nim(82), Coverage())[0] == "manual_review"
25
+
26
+ def test_85_89_coverage_gate():
27
+ assert decide(checks(), nim(87), Coverage(True))[0] == "include"
28
+ assert decide(checks(), nim(87), Coverage(False))[0] == "skip"
29
+
30
+ def test_90_plus_include():
31
+ assert decide(checks(), nim(92), Coverage(False))[0] == "include"
python_lora_dataset_builder/tests/test_dedupe.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from pipeline.dedupe import Deduper
3
+
4
+
5
+ def test_exact_duplicate_detected(tmp_path):
6
+ d = Deduper(tmp_path / "idx.txt")
7
+ code = "def add(a, b):\n return a + b\n"
8
+ r1 = d.check_and_add(code, "id-1")
9
+ assert r1["duplicate"] is False
10
+ r2 = d.check_and_add(code, "id-2")
11
+ assert r2["duplicate"] is True
12
+ assert r2["kind"] == "exact"
13
+ assert r2["match_id"] == "id-1"
14
+
15
+
16
+ def test_structural_duplicate_detected_despite_renamed_vars(tmp_path):
17
+ d = Deduper(tmp_path / "idx.txt")
18
+ d.check_and_add("def add(a, b):\n return a + b\n", "id-1")
19
+ r = d.check_and_add("def add(x, y):\n return x + y\n", "id-2")
20
+ assert r["duplicate"] is True
21
+ assert r["kind"] == "structural"
22
+
23
+
24
+ def test_distinct_code_is_not_a_duplicate(tmp_path):
25
+ d = Deduper(tmp_path / "idx.txt")
26
+ d.check_and_add("def add(a, b):\n return a + b\n", "id-1")
27
+ r = d.check_and_add(
28
+ "class Stack:\n def __init__(self):\n self.items = []\n"
29
+ " def push(self, x):\n self.items.append(x)\n",
30
+ "id-2",
31
+ )
32
+ assert r["duplicate"] is False
33
+
34
+
35
+ def test_near_duplicate_detected_with_small_edit(tmp_path):
36
+ d = Deduper(tmp_path / "idx.txt", similarity=0.8)
37
+ base = "def compute(values):\n total = 0\n for v in values:\n total += v\n return total\n"
38
+ d.check_and_add(base, "id-1")
39
+ # Same logic, one extra trivial statement -> should still land above 0.8 Jaccard.
40
+ near = "def compute(values):\n total = 0\n for v in values:\n total += v\n return total # done\n"
41
+ r = d.check_and_add(near, "id-2")
42
+ assert r["duplicate"] is True
43
+ assert r["kind"] in ("near", "structural")
44
+
45
+
46
+ def test_persists_and_reloads_index(tmp_path):
47
+ path = tmp_path / "idx.txt"
48
+ d1 = Deduper(path)
49
+ d1.check_and_add("def add(a, b):\n return a + b\n", "id-1")
50
+
51
+ d2 = Deduper(path) # simulate a fresh process reloading the index
52
+ r = d2.check_and_add("def add(a, b):\n return a + b\n", "id-2")
53
+ assert r["duplicate"] is True
54
+ assert r["match_id"] == "id-1"
55
+
56
+
57
+ def test_scales_past_naive_on_two_thousand_records(tmp_path):
58
+ """Not a strict perf assertion (CI machines vary), just a sanity check
59
+ that adding ~2k distinct records doesn't take an unreasonable amount of
60
+ time the way an O(n^2) full Jaccard scan would."""
61
+ d = Deduper(tmp_path / "idx.txt")
62
+ start = time.time()
63
+ for i in range(2000):
64
+ code = f"def f_{i}(a, b):\n return a + b + {i}\n"
65
+ d.check_and_add(code, f"id-{i}")
66
+ elapsed = time.time() - start
67
+ assert elapsed < 20 # generous ceiling; O(n^2) shingle Jaccard would be far slower
python_lora_dataset_builder/tests/test_nim_reviewer.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import httpx
3
+ import pytest
4
+ from pipeline.nim_reviewer import NIMReviewer
5
+
6
+
7
+ def _reviewer(monkeypatch, retries=3):
8
+ monkeypatch.setenv("NIM_MODEL", "test-model")
9
+ monkeypatch.setenv("NIM_API_KEY", "test-key")
10
+ return NIMReviewer({"functions": "..."}, retries=retries, base_delay=0.001)
11
+
12
+
13
+ class _FakeResponse:
14
+ def __init__(self, status_code, json_body=None, text=""):
15
+ self.status_code = status_code
16
+ self._json_body = json_body or {}
17
+ self.text = text
18
+ self.reason_phrase = "ERR"
19
+ self.request = httpx.Request("POST", "https://example.test/chat/completions")
20
+
21
+ def json(self):
22
+ return self._json_body
23
+
24
+ def raise_for_status(self):
25
+ if self.status_code >= 400:
26
+ raise httpx.HTTPStatusError("err", request=self.request, response=self)
27
+
28
+
29
+ def _good_body():
30
+ content = {
31
+ "valid": True,
32
+ "scores": {"correctness": 90, "instruction_alignment": 90, "quality": 90,
33
+ "training_value": 90, "scope_fit": 90},
34
+ "overall_score": 90, "dominant_topic": "functions", "secondary_topics": [],
35
+ "summary": "ok", "issues": [],
36
+ }
37
+ return {"choices": [{"message": {"content": json.dumps(content)}}]}
38
+
39
+
40
+ def test_401_fails_immediately_without_retry(monkeypatch):
41
+ reviewer = _reviewer(monkeypatch, retries=3)
42
+ calls = {"n": 0}
43
+
44
+ def fake_post(self, url, headers=None, json=None):
45
+ calls["n"] += 1
46
+ return _FakeResponse(401, text="bad api key")
47
+
48
+ monkeypatch.setattr(httpx.Client, "post", fake_post)
49
+
50
+ with pytest.raises(RuntimeError, match="nim_request_failed_non_retryable"):
51
+ reviewer.review("do x", "", "print(1)")
52
+
53
+ assert calls["n"] == 1 # no retries burned on a non-retryable 401
54
+
55
+
56
+ def test_400_fails_immediately_without_retry(monkeypatch):
57
+ reviewer = _reviewer(monkeypatch, retries=3)
58
+ calls = {"n": 0}
59
+
60
+ def fake_post(self, url, headers=None, json=None):
61
+ calls["n"] += 1
62
+ return _FakeResponse(400, text="bad request")
63
+
64
+ monkeypatch.setattr(httpx.Client, "post", fake_post)
65
+
66
+ with pytest.raises(RuntimeError, match="nim_request_failed_non_retryable"):
67
+ reviewer.review("do x", "", "print(1)")
68
+
69
+ assert calls["n"] == 1
70
+
71
+
72
+ def test_429_is_retried_then_succeeds(monkeypatch):
73
+ reviewer = _reviewer(monkeypatch, retries=3)
74
+ calls = {"n": 0}
75
+
76
+ def fake_post(self, url, headers=None, json=None):
77
+ calls["n"] += 1
78
+ if calls["n"] < 3:
79
+ return _FakeResponse(429, text="rate limited")
80
+ return _FakeResponse(200, json_body=_good_body())
81
+
82
+ monkeypatch.setattr(httpx.Client, "post", fake_post)
83
+
84
+ result, raw, attempts = reviewer.review("do x", "", "print(1)")
85
+ assert calls["n"] == 3
86
+ assert attempts == 3
87
+ assert result["overall_score"] == 90
88
+
89
+
90
+ def test_500_retries_and_eventually_exhausts(monkeypatch):
91
+ reviewer = _reviewer(monkeypatch, retries=2)
92
+ calls = {"n": 0}
93
+
94
+ def fake_post(self, url, headers=None, json=None):
95
+ calls["n"] += 1
96
+ return _FakeResponse(503, text="down")
97
+
98
+ monkeypatch.setattr(httpx.Client, "post", fake_post)
99
+
100
+ with pytest.raises(RuntimeError, match="nim_retry_exhausted"):
101
+ reviewer.review("do x", "", "print(1)")
102
+
103
+ assert calls["n"] == 2 # retried up to the configured attempt count, then gave up
104
+
105
+
106
+ def test_200_succeeds_on_first_try(monkeypatch):
107
+ reviewer = _reviewer(monkeypatch, retries=3)
108
+
109
+ def fake_post(self, url, headers=None, json=None):
110
+ return _FakeResponse(200, json_body=_good_body())
111
+
112
+ monkeypatch.setattr(httpx.Client, "post", fake_post)
113
+
114
+ result, raw, attempts = reviewer.review("do x", "", "print(1)")
115
+ assert attempts == 1
116
+ assert result["dominant_topic"] == "functions"
python_lora_dataset_builder/tests/test_nim_schema.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pipeline.nim_schema import validate_nim_response
2
+
3
+ TOPICS = {"functions", "comprehensions"}
4
+
5
+ def good():
6
+ return {
7
+ "valid": True,
8
+ "scores": {"correctness": 95, "instruction_alignment": 94, "quality": 90, "training_value": 92, "scope_fit": 95},
9
+ "overall_score": 93,
10
+ "dominant_topic": "functions",
11
+ "secondary_topics": [],
12
+ "summary": "Defines a function.",
13
+ "issues": [],
14
+ }
15
+
16
+ def test_valid_schema():
17
+ assert validate_nim_response(good(), TOPICS)[0]
18
+
19
+ def test_unknown_topic():
20
+ x = good()
21
+ x["dominant_topic"] = "invented_topic"
22
+ assert not validate_nim_response(x, TOPICS)[0]
python_lora_dataset_builder/tests/test_runner_regressions.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from pipeline import runner
3
+
4
+
5
+ class FakeDataset:
6
+ def __init__(self, rows):
7
+ self._rows = rows
8
+
9
+ def __iter__(self):
10
+ return iter(self._rows)
11
+
12
+
13
+ def _project_root() -> Path:
14
+ return Path(__file__).resolve().parents[1]
15
+
16
+
17
+ def _redirect_paths(monkeypatch, tmp_path):
18
+ """Point every write path at a tmp dir instead of the real config/data dirs
19
+ that ship in the repo, without touching the real dedupe/coverage state."""
20
+ root = _project_root()
21
+ real_paths = runner.build_paths(root)
22
+ real_paths["output"] = tmp_path / "data"
23
+ real_paths["dedupe"] = tmp_path / "data/metadata/exact_hashes.txt"
24
+ real_paths["coverage"] = tmp_path / "data/metadata/topic_coverage.json"
25
+ real_paths["checkpoint"] = tmp_path / "data/metadata/checkpoint.json"
26
+ monkeypatch.setattr(runner, "build_paths", lambda project_root: real_paths)
27
+ return real_paths
28
+
29
+
30
+ def _run_with_rows(monkeypatch, tmp_path, rows, **run_kwargs):
31
+ monkeypatch.setenv("ALLOW_MISSING_GITLEAKS", "1")
32
+ monkeypatch.setenv("EXECUTOR_MODE", "local")
33
+
34
+ def fake_stream(name, split="train"):
35
+ return FakeDataset(rows)
36
+
37
+ monkeypatch.setattr(runner, "stream_hf_dataset", fake_stream)
38
+ paths = _redirect_paths(monkeypatch, tmp_path)
39
+ stats = runner.run(_project_root(), limit=len(rows), dry_run=True, **run_kwargs)
40
+ return stats, paths
41
+
42
+
43
+ def test_end_to_end_smoke_dry_run(monkeypatch, tmp_path):
44
+ """A real call into runner.run() (not hand-built dicts) with a mix of
45
+ accept-shaped and empty rows, exercising extraction, static checks,
46
+ dedupe, secret scan, tier classification, and the hard-check /
47
+ dry-run branches all the way through to disk."""
48
+ rows = [
49
+ {"instruction": "Write a function that adds two numbers.",
50
+ "input": "", "output": "```python\ndef add(a, b):\n return a + b\n```"},
51
+ {"instruction": "", "input": "", "output": "No code here, just prose."},
52
+ ]
53
+ stats, paths = _run_with_rows(monkeypatch, tmp_path, rows)
54
+
55
+ assert stats["processed"] == 2
56
+ assert stats["reject"] == 1 # the prose-only row
57
+ assert stats["manual_review"] == 1 # dry_run manual_review for the valid function
58
+
59
+ manual_review_file = paths["output"] / "basic_python_syntax" / "manual_review" / "records.jsonl"
60
+ assert manual_review_file.exists()
61
+
62
+
63
+ def test_hard_check_branch_does_not_crash_on_real_run(monkeypatch, tmp_path):
64
+ """Regression guard for the historic `NameError: decision/reason is not
65
+ defined` crash in the hard-failure branch. Only calling the real run()
66
+ end-to-end (not asserting on a hand-built dict, as the old version of
67
+ this test did) can actually catch a NameError here: it would surface as
68
+ an uncaught exception propagating out of run()."""
69
+ rows = [
70
+ {"instruction": "x", "input": "", "output": "```python\ndef broken(:\n pass\n```"},
71
+ ]
72
+ stats, paths = _run_with_rows(monkeypatch, tmp_path, rows)
73
+
74
+ assert stats["processed"] == 1
75
+ assert stats["reject"] == 1
76
+ rejected_file = paths["output"] / "basic_python_syntax" / "rejected" / "records.jsonl"
77
+ assert rejected_file.exists()
78
+ assert "syntax_invalid" in rejected_file.read_text()
79
+
80
+
81
+ def test_execution_status_contract_through_real_run(monkeypatch, tmp_path):
82
+ """The execution_status contract (decision.py reads checks['execution_status'])
83
+ is exercised through an actual failing-at-runtime snippet, not a hand-built
84
+ checks dict."""
85
+ rows = [
86
+ {"instruction": "x", "input": "", "output": "```python\nraise RuntimeError('boom')\n```"},
87
+ ]
88
+ stats, paths = _run_with_rows(monkeypatch, tmp_path, rows)
89
+
90
+ assert stats["processed"] == 1
91
+ assert stats["reject"] == 1
92
+ rejected_file = paths["output"] / "basic_python_syntax" / "rejected" / "records.jsonl"
93
+ assert "sandbox_execution_failed" in rejected_file.read_text()
94
+
95
+
96
+ def test_tier2_library_code_is_classified_and_not_auto_included(monkeypatch, tmp_path):
97
+ """Code that imports a single recognised library should be routed to the
98
+ per_library tier, tagged with that library, and — since tier 2 has no
99
+ execution environment yet — skipped by default (tier not active)."""
100
+ rows = [
101
+ {"instruction": "x", "input": "", "output": "```python\nimport json\nprint(json.dumps({}))\n```"},
102
+ ]
103
+ stats, paths = _run_with_rows(monkeypatch, tmp_path, rows)
104
+
105
+ assert stats["processed"] == 1
106
+ assert stats["skip"] == 1
107
+ skipped_file = paths["output"] / "per_library" / "json" / "skipped" / "records.jsonl"
108
+ assert skipped_file.exists()
109
+ assert "tier_not_active" in skipped_file.read_text()
110
+
111
+
112
+ def test_tier3_unknown_library_is_classified_as_real_world(monkeypatch, tmp_path):
113
+ rows = [
114
+ {"instruction": "x", "input": "", "output": "```python\nimport some_totally_unknown_lib\n```"},
115
+ ]
116
+ stats, paths = _run_with_rows(monkeypatch, tmp_path, rows)
117
+
118
+ assert stats["processed"] == 1
119
+ assert stats["skip"] == 1
120
+ skipped_file = paths["output"] / "real_world_repository" / "skipped" / "records.jsonl"
121
+ assert skipped_file.exists()
python_lora_dataset_builder/tests/test_sandbox_contract.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pipeline.sandbox import run_code
2
+
3
+ def test_execution_status_passed():
4
+ result = run_code("x = 1\nprint(x)", timeout_seconds=5)
5
+ assert result.status == "passed"
6
+ assert result.passed
7
+
8
+ def test_execution_status_failed():
9
+ result = run_code("raise RuntimeError('test')", timeout_seconds=5)
10
+ assert result.status == "failed"
11
+ assert not result.passed
python_lora_dataset_builder/tests/test_secret_scan.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from pipeline import secret_scan
3
+
4
+
5
+ def test_ensure_ready_raises_when_gitleaks_missing_and_no_override(monkeypatch):
6
+ monkeypatch.setattr(secret_scan, "gitleaks_available", lambda: False)
7
+ monkeypatch.delenv("ALLOW_MISSING_GITLEAKS", raising=False)
8
+ with pytest.raises(RuntimeError, match="Gitleaks"):
9
+ secret_scan.ensure_secret_scanner_ready()
10
+
11
+
12
+ def test_ensure_ready_passes_when_override_set(monkeypatch):
13
+ monkeypatch.setattr(secret_scan, "gitleaks_available", lambda: False)
14
+ monkeypatch.setenv("ALLOW_MISSING_GITLEAKS", "1")
15
+ secret_scan.ensure_secret_scanner_ready() # must not raise
16
+
17
+
18
+ def test_ensure_ready_passes_when_gitleaks_available(monkeypatch):
19
+ monkeypatch.setattr(secret_scan, "gitleaks_available", lambda: True)
20
+ monkeypatch.delenv("ALLOW_MISSING_GITLEAKS", raising=False)
21
+ secret_scan.ensure_secret_scanner_ready() # must not raise
22
+
23
+
24
+ def test_scan_code_raises_when_gitleaks_missing_and_no_override(monkeypatch):
25
+ monkeypatch.setattr(secret_scan, "shutil", secret_scan.shutil)
26
+ monkeypatch.setattr(secret_scan.shutil, "which", lambda name: None)
27
+ monkeypatch.delenv("ALLOW_MISSING_GITLEAKS", raising=False)
28
+ with pytest.raises(RuntimeError, match="fail-closed"):
29
+ secret_scan.scan_code("x = 1")
30
+
31
+
32
+ def test_scan_code_returns_warning_result_when_override_set(monkeypatch):
33
+ monkeypatch.setattr(secret_scan.shutil, "which", lambda name: None)
34
+ monkeypatch.setenv("ALLOW_MISSING_GITLEAKS", "1")
35
+ result = secret_scan.scan_code("x = 1")
36
+ assert result["passed"] is True
37
+ assert result["warning"] == "gitleaks_not_installed_override_allowed"
38
+
39
+
40
+ def test_truthy_variants():
41
+ for v in ("1", "true", "True", "yes", "on"):
42
+ assert secret_scan._truthy(v)
43
+ for v in ("0", "false", "", None, "no"):
44
+ assert not secret_scan._truthy(v)
python_lora_dataset_builder/tests/test_static_checks.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pipeline.static_checks import inspect_code, is_basic_syntax_candidate
2
+
3
+ def test_valid_code():
4
+ result = inspect_code("x = 1\nprint(x)")
5
+ assert result.ast_valid
6
+ assert result.compile_valid
7
+ assert not result.secret_found
8
+
9
+ def test_invalid_code():
10
+ result = inspect_code("def broken(:\n pass")
11
+ assert not result.ast_valid
12
+
13
+ def test_import_is_later_tier():
14
+ result = inspect_code("import json\nprint(json.dumps({}))")
15
+ assert not is_basic_syntax_candidate(result.imports)
python_lora_dataset_builder/tests/test_tiers.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pipeline.tiers import classify_tier, TIER1_BASIC, TIER2_PER_LIBRARY, TIER3_REAL_WORLD
2
+
3
+ LIBS = {"json": "...", "os": "...", "requests": "..."}
4
+
5
+
6
+ def test_no_imports_is_tier1():
7
+ assert classify_tier([], LIBS) == (TIER1_BASIC, None)
8
+
9
+
10
+ def test_single_known_library_is_tier2():
11
+ assert classify_tier(["json"], LIBS) == (TIER2_PER_LIBRARY, "json")
12
+
13
+
14
+ def test_multiple_known_libraries_tags_alphabetically_first():
15
+ assert classify_tier(["requests", "json"], LIBS) == (TIER2_PER_LIBRARY, "json")
16
+
17
+
18
+ def test_unknown_import_is_tier3():
19
+ assert classify_tier(["some_unknown_pkg"], LIBS) == (TIER3_REAL_WORLD, None)
20
+
21
+
22
+ def test_mixed_known_and_unknown_is_tier3():
23
+ assert classify_tier(["json", "some_unknown_pkg"], LIBS) == (TIER3_REAL_WORLD, None)