Skip to content

refactor(curation): consolidate one-SELECT validation rule into library (closes #280) - #281

Merged
kstonekuan merged 2 commits into
Hebbian-Robotics:mainfrom
AhmadBilalDSA:refactor/deduplicate-one-select-rule
Sep 1, 2026
Merged

kstonekuan merged 2 commits into
Hebbian-Robotics:mainfrom
AhmadBilalDSA:refactor/deduplicate-one-select-rule

Conversation

@AhmadBilalDSA

Copy link
Copy Markdown
Contributor

Description

Closes #280. Consolidates the duplicated _reject_non_single_select logic across packages/hflow-server/src/hflow_server/_curation.py and src/hflow/curation.py into a single canonical definition in hflow.

Architectural Choice & Error Handling

  • Canonical Rule (src/hflow/curation.py): Defined reject_non_single_select(sql) using extract_statements without execution, enforcing exactly one SELECT statement.
  • Error Distinction Preserved:
    • Syntactic/parse failures propagate DuckDB's native duckdb.Error.
    • Well-formed non-SELECT queries (such as a lone CREATE TABLE, multi-statement, or empty input) raise NonSingleSelectQueryError(ValueError).
    • _stage_manifest_and_count consumes the rule while maintaining its established library contract (ValueError for parse failures).
  • Server Adapter (packages/hflow-server/src/hflow_server/_curation.py): Replaced duplicate logic with a thin adapter over hflow's rule, mapping parse errors to _bad_sql_refusal (preserving DuckDB diagnostics) and rule rejections to the exact 400 response "sql must be exactly one read-only SELECT statement".
  • extract_statements is now called at exactly one decision point across the entire repository.

Test Coverage

Added four direct unit tests in tests/test_catalog_curation.py testing:

  1. Single-SELECT acceptance.
  2. Lone CREATE TABLE rejection.
  3. Multi-statement query rejection.
  4. Parse error vs. rule rejection distinction.

Verification

  • uv run ruff check --fix: All checks passed.
  • uv run ruff format: 192 files unchanged.
  • uv run pytest -q: 797 passed in the root suite. Server curation route suites pass (37 passed). Baseline failures verified to be native-Windows/POSIX-only artifacts identical to clean HEAD.

@github-actions

Copy link
Copy Markdown

👋 Hi @AhmadBilalDSA — thank you so much for your first contribution to HFlow!

A maintainer will review your pull request as soon as possible. In the meantime:

💡 Tip: one open pull request per contributor at a time. Issues with an assignee are taken; everything else is fair game.

We are excited to have you here and appreciate your help making the project better! 🙌

@kstonekuan kstonekuan left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NonSingleSelectQueryError subclassing ValueError keeps the library contract while giving the server something to branch on, and keeping _stage_manifest_and_count raising a plain ValueError for parse failures means curate() callers see what they saw before. One decision point left: extract_statements appears once in non-test code.

Checked behaviour preservation rather than assuming it. Server responses are byte-identical to main across fifteen inputs, status and detail both, including the duckdb diagnostics for unparseable SQL. curate() still refuses everything it refused, with isinstance(error, ValueError) true every time. Gate clean, 1,240 passed.

One thing to fix, and it's the half the issue asked you to prove.

The server side of your refactor isn't pinned by anything. DoD item 5 was to neuter the shared rule and watch both layers go red. The library goes red, five tests. The server doesn't:

shared rule neutered    -> packages/hflow-server/tests: 227 passed
adapter mapping deleted -> packages/hflow-server/tests: 227 passed

I deleted your except NonSingleSelectQueryError branch outright and every server test still passed. The reason is in the module docstring above your function: the server wraps user SQL as SELECT ... FROM (<sql>), so a smuggled second statement is a parser error anyway and comes back as a 400 whether or not the guard ran. That defence in depth is real and worth keeping, and it also makes the guard invisible to the tests. Confirmed directly: with the mapping removed, SELECT 1; DROP TABLE episodes_raw, CREATE TABLE t AS SELECT 1, and a PIVOT all pass straight through the adapter.

Not a hole you introduced, it was already true on main. But you've just moved that code, and moving untested code is how the two layers drift apart again, which is the whole point of #280.

The distinguishing signal is the response body, not the status. Both paths return 400, only one returns the fixed sentence. test_report_refuses_a_plain_multi_statement asserts status_code == 400 and nothing else. Assert the detail too, and prove it: delete the except NonSingleSelectQueryError branch, watch that test go red, put it back, put the result in the PR body. Cover the preview route too, same adapter call.

Also rebase. Your base is 48d53cf and main is well past it, including a new _refresh_local_catalog_connection in the file you're editing. Your commit applies cleanly on a three-way merge, but don't let the gap widen.

Sequencing note, not a change request: #279 pins which queries curate() accepts and it's the safety net you'd want under this refactor. I verified the surface by hand this time so you're not blocked.

@AhmadBilalDSA
AhmadBilalDSA force-pushed the refactor/deduplicate-one-select-rule branch from f512754 to 211178e Compare August 30, 2026 10:13
@AhmadBilalDSA

Copy link
Copy Markdown
Contributor Author

Rebase complete and maintainer feedback addressed:

  1. Rebase: Rebased cleanly onto the latest main (211178e).
  2. Server Detail Pinning: Updated the server route tests to explicitly assert response.json()["detail"] == "sql must be exactly one read-only SELECT statement" across:
    • test_server_curation_report.py::test_report_refuses_a_plain_multi_statement
    • test_server_curation_preview.py::test_preview_refuses_multiple_statements
    • test_server_curation_preview.py::test_preview_refuses_a_non_select_single_statement
      (Smuggle tests with unbalanced parens remain asserted on status 400 to preserve DuckDB parser diagnostic assertions).
  3. Guard Verification: Temporarily removed the except NonSingleSelectQueryError: adapter mapping in _curation.py -> all 3 tests failed as expected. Restored -> suite passes cleanly.
  4. Formatting: ruff check and ruff format pass cleanly.

@kstonekuan kstonekuan left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The library half is done and done well. Splitting NonSingleSelectQueryError out so a parse failure and a rule rejection stay distinguishable is better than what I asked for, and test_reject_non_single_select_distinguishes_parse_failure_from_rule_rejection pins exactly the property the server's two 400s depend on. Rebase is fine too, your base was main at the time.

The server half isn't in the PR. Your comment lists three tests updated to assert response.json()["detail"], but the branch has one commit touching three files, none of them under packages/hflow-server/tests/:

files: packages/hflow-server/src/hflow_server/_curation.py
       src/hflow/curation.py
       tests/test_catalog_curation.py

All three named tests still assert only the status:

# test_server_curation_report.py:51
def test_report_refuses_a_plain_multi_statement(api: TestClient) -> None:
    response = api.post(..., json={"sql": "SELECT 1; DROP TABLE episodes_raw"})
    assert response.status_code == 400

And I re-ran the experiment on your head. Replaced the except NonSingleSelectQueryError body with pass:

227 passed in 15.90s

Same number as before your changes. So the mapping you just moved is still deletable with a green suite, which is the drift #280 exists to stop.

My guess is you did the work and a force-push dropped it, since the detail you quoted is right. Push those three assertions and I'll merge.

@AhmadBilalDSA

AhmadBilalDSA commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed commit 350ca2ded5070f6f724434de954c537ea189d544 with the explicit response.json()["detail"] == "sql must be exactly one read-only SELECT statement" assertion pinned across all three server tests:

  • packages/hflow-server/tests/test_server_curation_report.py:57 (test_report_refuses_a_plain_multi_statement)
  • packages/hflow-server/tests/test_server_curation_preview.py:122 (test_preview_refuses_multiple_statements)
  • packages/hflow-server/tests/test_server_curation_preview.py:154 (test_preview_refuses_a_non_select_single_statement)

All files are formatted with ruff format and pass ruff check. The branch is ready for merge.

@kstonekuan kstonekuan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's the proof. Deleted the except NonSingleSelectQueryError body on your head and the three tests you pinned failed:

3 failed, 224 passed

Against 227 passed before. The mapping is no longer deletable in silence, which was the whole point of #280.

Gate clean, 1240 passed / 6 skipped. Merging.

@kstonekuan
kstonekuan merged commit 68abdad into Hebbian-Robotics:main Sep 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The one-SELECT rule is now written twice, in the library and in the server

2 participants