File size: 14,650 Bytes
0109502 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | # Python LoRA Dataset Builder
A staged, evidence-first pipeline for building a high-quality Python training dataset.
## Current phase
Run **tier 1 (`basic_python_syntax`)** right now. It's the only tier that's fully
automated end-to-end (extraction β static checks β dedupe β secret scan β
sandbox execution β NIM review β scoring). Tiers 2 and 3 exist as
classification/organization scaffolding for later β see "Three tiers" below.
The first source configured is:
`Riswan-BluBridge/python-codes-25k`
The first run should be a small batch, not the whole dataset.
## Pipeline order
1. Load source rows.
2. Extract Python code from the answer.
3. Run source-record checks.
4. Run AST parsing and compilation.
5. Scan for obvious secrets (Gitleaks; **fails closed** if Gitleaks isn't
installed β see "Gitleaks" below).
6. Deduplicate: exact hash, AST-structural fingerprint, and near-duplicate
(MinHash/LSH-accelerated token-shingle Jaccard) β see "Deduplication at
scale" below.
7. Classify into tier 1 / tier 2 / tier 3 based on imports.
8. Execute eligible tier-1 snippets in an isolated subprocess.
9. Send deterministic-check passes in active tiers to NVIDIA NIM.
10. Validate the returned JSON against a strict schema.
11. Apply score and coverage rules.
12. Save accepted, rejected, skipped, manual-review, and raw NIM records,
organized by tier (and library, for tier 2).
## Three tiers
The pipeline classifies every code sample by its top-level imports
(`pipeline/tiers.py`):
| Tier | Folder | What it means | Executed today? |
|---|---|---|---|
| 1 β `basic_python_syntax` | `data/basic_python_syntax/` | No imports at all | Yes β full pipeline |
| 2 β `per_library` | `data/per_library/<library>/` | Every import is in `config/tier2_libraries.json` | No β no per-library sandbox yet |
| 3 β `real_world_repository` | `data/real_world_repository/` | Any import we don't recognise | No β no project-level validation profile yet |
Which tiers are actually processed in a given run is controlled by `--tiers`
(default: `basic`, i.e. tier 1 only). Records outside the active tiers are
still classified and written with `decision=skip`, `decision_reason=tier_not_active:<tier>`
β nothing is thrown away, they just don't spend NIM requests or execution
time this run.
```bash
python main.py --limit 50 --dry-run # tier 1 only (today's default)
python main.py --limit 50 --dry-run --tiers basic,library # also classify/NIM-review tier 2
python main.py --limit 50 --dry-run --tiers all # classify everything
```
**Honest limitation:** even when tier 2 or 3 is made "active," those records
are never auto-included β there's no execution environment to verify the
code runs, so the best they can reach is `manual_review`. Building real
per-library, version-pinned execution environments (tier 2) and a
static-analysis/partial-execution validation profile for real-world
repository code (tier 3) is future work, not implemented yet.
## Score policy
- `< 80`: reject
- `80β84`: manual review
- `85β89`: include only when the dominant topic is underrepresented
- `90β100`: include
Hard failures override scores. Tier 2/3 records additionally never auto-include
(see above); an "include"-worthy score is downgraded to `manual_review`.
## Topic policy
The reviewer receives the allowed topic IDs and descriptions (`config/topics_basic_python.json`).
Each example receives:
- exactly one `dominant_topic`
- zero or more `secondary_topics`
The dominant topic is the concept the example primarily teaches, not merely a concept that appears in the code.
## Quick start (recommended): setup scripts
The `scripts/` folder does the manual setup below for you, and never touches
your system Python β everything installs into a `.venv/` folder inside this
project only.
**macOS / Linux:**
```bash
bash scripts/setup.sh # one-time: creates .venv/, installs deps, copies .env
# edit .env with your NIM credentials
bash scripts/run_daily.sh # dry run, 500 rows
bash scripts/run_daily.sh --real 200 # real run, 200 rows this session
```
**Windows (PowerShell):**
```powershell
powershell -ExecutionPolicy Bypass -File scripts\setup.ps1
# edit .env with your NIM credentials
powershell -ExecutionPolicy Bypass -File scripts\run_daily.ps1 # dry run, 500 rows
powershell -ExecutionPolicy Bypass -File scripts\run_daily.ps1 -Real -Limit 200 # real run, 200 rows
```
Run `run_daily` (or `run_daily.ps1`) again any time β today, tomorrow, next
week β and it automatically continues from wherever the last run left off
(see "Running it over multiple days" below). If you'd rather do it by hand,
or you're not on macOS/Linux/Windows, the manual steps are below.
## Manual setup
Create and activate a virtual environment:
```bash
python -m venv .venv
```
Windows:
```powershell
.venv\Scripts\Activate.ps1
```
Linux/macOS:
```bash
source .venv/bin/activate
```
Install dependencies:
```bash
pip install -r requirements.txt
```
Copy `.env.example` to `.env`, then set:
```env
NIM_API_KEY=your_key
NIM_BASE_URL=https://integrate.api.nvidia.com/v1
NIM_MODEL=your_nim_model_id
```
## What you need installed
- **Python 3.10+** β everything else (the `datasets`, `httpx`, `python-dotenv`
packages in `requirements.txt`) installs automatically into the project's
own `.venv/` folder and never touches your system Python or other projects.
- **Gitleaks** (one-time, system-level CLI tool) β the pipeline **fails
closed** and refuses to run without it, unless you explicitly set
`ALLOW_MISSING_GITLEAKS=1` in `.env` for local testing (not recommended for
a real/unattended run). Install: `brew install gitleaks` (macOS),
`winget install gitleaks` (Windows), or see the
[Gitleaks install docs](https://github.com/gitleaks/gitleaks#installing).
- **Docker** (optional, recommended for any unattended/multi-day run) β see
"Sandbox status" below. Not required for the default local executor, but
the local executor is explicitly not a hardened boundary.
- A **NIM API key** in `.env` for real (non-`--dry-run`) runs.
## Run tests
```bash
pytest -q
```
## First dry run
This tests loading, extraction, static checks, execution, and file output without spending NIM requests:
```bash
python main.py --limit 50 --dry-run
```
## First real NIM test
```bash
python main.py --limit 50
```
After inspecting the results, run:
```bash
python main.py --limit 500
```
Do not run the whole source until the 50- and 500-record audits look correct.
## Running it over multiple days
You don't need to leave this running continuously. Every run of
`python main.py` (or `scripts/run_daily.sh` / `run_daily.ps1`) processes up
to `--limit` **new** rows and then stops on its own. Progress is stored in
`data/metadata/checkpoint.json`, so the next time you run it β later today,
tomorrow, next week β it automatically **resumes exactly where it left off**:
it does not reprocess rows or restart the source dataset from scratch.
```bash
python main.py --limit 500 --dry-run # day 1: processes rows 0-499
python main.py --limit 500 --dry-run # day 2: resumes at row 500, processes 500-999
python main.py --limit 500 --dry-run # day 3: resumes at row 1000, ...
```
When the whole source dataset has been consumed, the pipeline tells you and
exits without doing anything (`'<source>' is already fully processed`).
If you genuinely want to reprocess the source from row 0 (e.g. you changed
scoring thresholds and want a clean pass), either pass `--no-resume` or
delete `data/metadata/checkpoint.json`. Note this doesn't undo dedupe or
coverage state β those live in separate files under `data/metadata/` β so a
`--no-resume` pass will still treat rows as duplicates of what's already in
`data/`. Delete `data/metadata/exact_hashes.txt` and
`data/metadata/topic_coverage.json` too if you want a fully clean slate.
**Scheduling it automatically (optional).** If you'd rather not run it by
hand each day, schedule `scripts/run_daily.sh` / `run_daily.ps1`:
- macOS/Linux (cron), run `crontab -e` and add a line like:
```
0 9 * * * cd /path/to/python_lora_dataset_builder && bash scripts/run_daily.sh --real 500 >> logs/daily.log 2>&1
```
- Windows: Task Scheduler β "Create Basic Task" β Trigger: Daily β Action:
"Start a program" β Program: `powershell.exe` β Arguments:
`-ExecutionPolicy Bypass -File "C:\path\to\python_lora_dataset_builder\scripts\run_daily.ps1" -Real -Limit 500`
Either way, each scheduled run is just one more "day" in the sequence above β
it resumes on its own.
## Stopping and recovering
- **To stop cleanly:** press `Ctrl+C` once. The pipeline finishes writing the
record it's currently on, saves a checkpoint, and exits β nothing is lost,
and the next run resumes right after that record. A second `Ctrl+C` forces
an immediate hard stop if you really don't want to wait even a second.
- **If the power goes out, the process is killed, or your laptop sleeps
mid-run:** nothing special to do β just run the same command again.
Checkpointing happens after every single processed row (not just
periodically), so at most the one row that was in flight when things died
gets reprocessed; everything before it is picked up exactly where it
stopped. The checkpoint file itself is written atomically (temp file +
rename), so even a checkpoint write interrupted mid-write can't corrupt
`checkpoint.json` β you always fall back to the last good checkpoint.
## Executed code and temporary files
Every sandboxed execution (local or Docker mode) runs inside a fresh
temporary directory created just for that one snippet, and that directory β
along with everything written into it β is deleted automatically the moment
execution finishes (success, failure, or timeout), via Python's
`tempfile.TemporaryDirectory` context manager. Nothing from candidate code
execution is left behind on disk.
## Output
```text
data/
βββ basic_python_syntax/
β βββ accepted/records.jsonl
β βββ manual_review/records.jsonl
β βββ rejected/records.jsonl
β βββ skipped/records.jsonl
β βββ retry/records.jsonl
βββ per_library/
β βββ json/... (same accepted/manual_review/rejected/skipped/retry layout)
β βββ requests/...
β βββ ...
βββ real_world_repository/
β βββ ... (same layout; classification only today)
βββ unclassified/
β βββ rejected/records.jsonl # rows with no usable code / empty source
βββ nim_raw/
βββ metadata/
βββ exact_hashes.txt
βββ topic_coverage.json
βββ checkpoint.json
```
## Important limitations in this build
- 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.
- Only tier 1 (import-free) has an execution environment. Tiers 2 and 3 are classified/organized but not executed β see "Three tiers" above.
- 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.
- 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.
- The secret scan is intentionally conservative and must be expanded before real-world repository ingestion.
- Real-world repository code needs a different validation profile; it should not be forced to execute as a standalone snippet.
- 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**.
## Deduplication at scale
Near-duplicate detection now uses MinHash/LSH banding (`pipeline/dedupe.py`):
each code sample's shingle set is summarized into a 32-value MinHash
signature, split into 8 bands, and hashed into buckets. A new record only
gets compared (via exact Jaccard) against records that land in the same
bucket in at least one band β not against every previously seen record. Exact
and structural (AST-fingerprint) duplicate checks are O(1) dict lookups.
Dedupe index files written by earlier versions (without a `sig` field) are
still readable; signatures are derived from their stored shingles on load.
## Gitleaks
Install Gitleaks separately and ensure `gitleaks` is on PATH before a
production run. **The pipeline fails closed**: if Gitleaks isn't found and
`ALLOW_MISSING_GITLEAKS` isn't set to `1`, `python main.py` raises
immediately, before processing any records β it will not silently mark
records as scanned when no scanner ran. The `ALLOW_MISSING_GITLEAKS=1`
override is for local development only; every record processed under it
carries a `gitleaks_not_installed_override_allowed` warning in its metadata
so the run stays auditable.
### Sandbox status
The local executor is still **not a hardened security boundary** and should
not be used for unattended execution of untrusted code at scale. For
production runs, use the Docker executor (`EXECUTOR_MODE=docker`) with
network disabled, a read-only root filesystem, a non-root user, dropped
capabilities, PID/memory/CPU limits, and a small tmpfs β all of which
`pipeline/docker_sandbox.py` already sets up. The current local `resource`
limits are defense-in-depth for development, not a replacement for container
isolation.
## Windows-specific execution guidance
If you're developing on **Windows**: the local executor is suitable only for
small, trusted development tests. It has a timeout and a temporary working
directory, but Windows does not provide the Linux `resource.setrlimit`
controls used by the Linux local executor.
For any unattended run over unknown Hugging Face code, use Docker mode:
```powershell
docker build -t python-lora-sandbox -f docker/Dockerfile .
$env:EXECUTOR_MODE="docker"
$env:ALLOW_MISSING_GITLEAKS="0"
python main.py --limit 50
```
Install Gitleaks and ensure it is on `PATH`. Do not treat Windows local mode
as a hardened sandbox.
|