feat(backend): thin FastAPI wrapper around the ingen CLI - #75
Open
maan-iitd2 wants to merge 1 commit into
Open
Conversation
Adds backend/app/, a local-dev-only HTTP service that shells out to `python -m ingen` and returns structured results — no business logic of its own, just routing, temp-YAML execution, run-history persistence, and a few read helpers the frontend needs (source column introspection, sample file upload/preview). - main.py: routes only, delegates to the modules below. - runner.py: writes posted YAML to a temp file, runs the CLI as a subprocess, parses its log output into a structured RunRecord (stages, real log levels, timing). - store.py: persists RunRecords to INGEN_RUNS_DIR for history/lookup. - schema_validate.py / validation.py: validate a config (and surface a run's validation results) without executing it. - files.py: sample-data upload with size/type caps, reading only headers for column preview (not the whole file). - columns.py: derive the column list a configured source would produce, for the frontend's editor. Deliberately excluded from this PR: the inChat assistant (backend/app/chat.py), which pulls in torch/transformers and is a separable concern — follow-up PR. ## Testing - `pytest backend/tests/` — 42 passed. - Verified backend.app.main imports cleanly and registers all 9 routes with torch/transformers/accelerate/safetensors/tokenizers/ huggingface_hub deliberately blocked at import time (sys.meta_path), proving this PR has no import-time dependency on the inChat stack. - End-to-end: booted `uvicorn backend.app.main:app`, hit /api/health, POSTed a real config to /api/configs/validate, and POSTed a real XML config to /api/runs — the CLI subprocess ran the full read → pre_process → format → validate → write pipeline and the endpoint returned a RunRecord with status "success". - Updated backend/README.md, which had drifted from main.py (missing the files/columns endpoints, wrong default CORS ports) — corrected to describe exactly what this PR ships. Signed-off-by: maan-iitd2 <maan.iitd.ac.in@gmail.com>
Jatin-8898
force-pushed
the
pr/backend-wrapper
branch
from
September 9, 2026 18:56
b003d38 to
82b4fea
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Run and validation results can be inaccurate, while preview and upload paths can perform unbounded work.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds a local FastAPI wrapper around the InGen CLI, including execution, validation, uploads, source previews, and persisted run history.
Changes:
- Adds nine backend API endpoints and supporting services.
- Parses CLI output into structured run records.
- Adds backend dependencies, documentation, and unit tests.
File summaries
| File | Description |
|---|---|
backend/app/__init__.py |
Defines the backend package. |
backend/app/main.py |
Implements HTTP routes and CORS. |
backend/app/runner.py |
Executes and parses CLI runs. |
backend/app/validation.py |
Derives validation reports. |
backend/app/schema_validate.py |
Validates YAML configuration structure. |
backend/app/store.py |
Persists run records. |
backend/app/files.py |
Handles uploads and previews. |
backend/app/columns.py |
Retrieves source columns. |
backend/README.md |
Documents setup and endpoints. |
backend/requirements.txt |
Declares backend dependencies. |
backend/tests/__init__.py |
Defines the test package. |
backend/tests/test_runner.py |
Tests execution result parsing. |
backend/tests/test_validation.py |
Tests validation derivation. |
backend/tests/test_schema_validate.py |
Tests schema checks. |
backend/tests/test_store.py |
Tests run persistence. |
backend/tests/test_columns.py |
Tests file-source columns. |
Review details
Suppressed comments (5)
backend/app/runner.py:76
- A zero exit code does not prove each requested interface ran: the CLI silently filters unknown
--interfacesnames and also catches per-interface failures without changing the process exit code. Consequently, requesting a nonexistent interface produces no markers here but is returned as a successful run with all stagesok. Treat every requested interface lacking its success marker as failed; this also handles a crash after an earlier interface succeeded.
# If the process crashed before any per-interface marker, treat all requested as failed.
if exit_code != 0 and not succeeded and not failed:
failed = set(requested)
backend/app/runner.py:140
- The furthest stage is selected by
_STAGE_MARKERSlist order rather than by where markers occur in the log. Real runs validate raw data before pre-processing, so a later pre-processing failure still contains an earlier validation marker and is incorrectly reported as a validation-stage failure. Compare marker positions and choose the latest occurrence.
reached = "read"
for stage, rx in _STAGE_MARKERS:
if rx.search(slice_):
reached = stage
return reached
backend/app/columns.py:37
- A
jsonsource can never succeed here:SourceFactoryconstructsJsonSourcefrom its thirddynamic_dataargument, but this call omits it, sofetch()always raisesJSON string is not provided. Add dynamic JSON data to this endpoint and pass it through, or reject this source type before claiming it can return columns.
params_map = {"run_date": run_date} if run_date else None
src = SourceFactory().parse_source(source, params_map)
df = src.fetch()
backend/app/runner.py:62
- This stage order reports
post_processbeforeformat, but InGen executes formatting first and then post-processing (ingen/generators/base_interface_generator.py:45-50). The returned stage timeline is therefore out of execution order whenever post-processing is configured.
stages = ["read", "pre_process"]
if iface_cfg.get("post_processing"):
stages.append("post_process")
stages += ["format", "validate", "write"]
return stages
backend/app/columns.py:38
- For MySQL and API sources,
fetch()materializes the complete query/response solely to inspectdf.columns(MYSQLReaderuses unboundedpd.read_sql). This makes a column-preview request execute potentially huge remote workloads despite the stated preview cap. Use source-specific schema/zero-row requests, or require a bounded preview query rather than calling the normal full-data reader.
src = SourceFactory().parse_source(source, params_map)
df = src.fetch()
return {"columns": [str(c) for c in df.columns]}
- Files reviewed: 16/16 changed files
- Comments generated: 9
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Comment on lines
+54
to
+56
| @app.post("/api/files/upload") | ||
| async def upload_file(file: UploadFile = File(...)): | ||
| content = await file.read() |
| from .files import _parse | ||
| except ImportError: # run as a script (self-check) — no package context | ||
| from files import _parse | ||
| cols, _preview = _parse(Path(source["file_path"]), n=PREVIEW_ROWS) |
Comment on lines
+25
to
+26
| elif suffix == ".json": | ||
| df = pd.read_json(path).head(n) |
Comment on lines
+52
to
+56
| dest = DATA_DIR / Path(filename).name # ponytail: strip any path components from the client name | ||
| dest.write_bytes(content) | ||
| cols, preview = _parse(dest) | ||
| meta = {"file_path": dest.as_posix(), "columns": cols, "preview": preview, "cached": False} | ||
| cache_file.write_text(json.dumps(meta)) |
Comment on lines
+26
to
+31
| _STAGE_MARKERS = [ | ||
| ("pre_process", re.compile(r"pre-processing", re.I)), | ||
| ("format", re.compile(r"Formatting column", re.I)), | ||
| ("validate", re.compile(r"Validat", re.I)), | ||
| ("write", re.compile(r"writing file|Successfully generated", re.I)), | ||
| ] |
Comment on lines
+175
to
+179
| with tempfile.TemporaryDirectory() as tmp: | ||
| cfg_path = Path(tmp) / "interface.yml" | ||
| cfg_path.write_text(yaml_text, encoding="utf-8") | ||
|
|
||
| cmd = [sys.executable, "-m", "ingen", str(cfg_path)] |
Comment on lines
+11
to
+13
| # Source of truth: ingen's own enum. Adding a source type to ingen makes this validator accept it | ||
| # automatically — no parallel list to keep in sync. (Killed the drift the code review flagged.) | ||
| _VALID_SOURCE_TYPES = {e.value for e in DataSourceType} |
Comment on lines
+33
to
+35
| sources = doc.get("sources") or [] | ||
| interfaces = doc.get("interfaces") or {} | ||
| source_ids = {s.get("id") for s in sources if isinstance(s, dict)} |
Comment on lines
+27
to
+30
| if name in failed_interfaces: | ||
| status = "warning" if severity == "warning" else "failed" | ||
| else: | ||
| status = "passed" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Adds
backend/app/— a thin, local-dev-only FastAPI service that runs the InGen CLI and returns structured results. It contains no business logic: it shells out topython -m ingen, parses the CLI's output, and hands JSON back to a frontend (the InGen Studio SPA, not part of this PR).main.pyrunner.pyRunRecord(per-stage status, timing, log level)store.pyRunRecords toINGEN_RUNS_DIRfor history/lookupschema_validate.py/validation.pyfiles.pycolumns.pyDeliberately excluded from this PR: the inChat assistant (
backend/app/chat.py), which pulls intorch/transformers/HuggingFace and is a separable concern with its own dependency weight — follow-up PR.main.pyin this PR has no chat import, no/api/chat*routes.Trust boundary
This wrapper executes whatever config is posted (file reads, SQL, API calls — that's InGen's nature). It's intended for local/trusted development only — no auth, sandboxing, or network egress controls, by design.
Testing
pytest backend/tests/— 42 passed.backend.app.mainimports cleanly and registers all 9 routes withtorch/transformers/accelerate/safetensors/tokenizers/huggingface_hubdeliberately blocked at import time (viasys.meta_path), proving this PR carries no import-time dependency on the inChat stack even though those packages happened to be present in the test environment.uvicorn backend.app.main:app --port 8123, then:GET /api/health→{"status": "ok"}POST /api/configs/validatewith a real config → validated correctlyPOST /api/runswith a real XML-source config → the CLI subprocess ran the fullread → pre_process → format → validate → writepipeline and the endpoint returned aRunRecordwith"status": "success"and per-stage logs.backend/README.mdhad drifted frommain.py(missing the files/columns endpoints, wrong default CORS ports/origin). Corrected it to describe exactly what this PR ships.What it looks like
The full API surface this PR ships, at
/docsonceuvicorn backend.app.main:appis running:Nine endpoints, no
/api/chat*— confirming the inChat stack is genuinely absent from this PR, not just unimported.🤖 Generated with Claude Code