Skip to content

fix(sql): preserve literal percents in where_in - #44284

Merged
rusackas merged 1 commit into
apache:masterfrom
aminghadersohi:aminghadersohi/fix-where-in-percent
Sep 22, 2026
Merged

rusackas merged 1 commit into
apache:masterfrom
aminghadersohi:aminghadersohi/fix-where-in-percent

Conversation

@aminghadersohi

@aminghadersohi aminghadersohi commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR

Preserve literal percent signs in the where_in Jinja filter. On Athena, filtering for 50% currently sends 50%% and misses matching rows. This fixes the Superset literal-rendering boundary without changing driver behavior or rewriting raw SQL.

SUMMARY

SQLAlchemy's format/pyformat compilers double percent signs for DBAPI interpolation. where_in returns that compiled fragment as literal SQL, but SQL Lab calls cursor.execute(query) without parameters. PyAthena consequently preserves the doubled signs. The same behavior reproduces with PyAthena 2.25.0 and 3.35.4, using SQLAlchemy 2.0.52.

Undo one compiler-escaping layer only within the macro's compiled literals, conditional on identifier_preparer._double_percents. This matches the existing Database.compile_sqla_query convention. It does not change dialect state, inject empty parameter dictionaries, change dependencies, or unescape an entire rendered query. Quote/backslash handling is retained.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

No UI layout change. SQL/result comparison:

Input Before After
{{ ['50%'] | where_in }} ('50%%') ('50%')
{{ ['%%'] | where_in }} ('%%%%') ('%%')
Athena equality/IN against a 50% row 0 matches 1 match

TESTING INSTRUCTIONS

  1. Run pytest tests/unit_tests/jinja_context_test.py — 202 passed locally, with PyAthena installed (no skips).
  2. On an Athena connection with template processing enabled, execute:
    WITH fixture(value) AS (VALUES ('50%'), ('not the value'))
    SELECT value FROM fixture
    WHERE value IN {{ ['50%'] | where_in }}
    Expect exactly one row containing 50%.
  3. Repeat with %%, %(value)s, and a combined percent/underscore/apostrophe/backslash value; compare with a raw literal and a bound-parameter control.

Regression coverage includes MySQL format/pyformat, PostgreSQL pyformat/named, SQLite qmark, MSSQL named, unchanged dialect compilation, numeric/NULL/empty values, and chart recompilation through Database.compile_sqla_query with an unrelated %% literal. A PyAthena formatter test exercises parameterless and bound paths; it is optional when PyAthena is not installed. Generic dialect regressions do not depend on PyAthena.

Removing the fix made 33 new regression cases fail before adding the chart-compilation cases. Live AWS verification replayed 12 queries per PyAthena version with locked runtime dependencies (2.25.0 + boto3/botocore 1.39.13; 3.35.4 + boto3/botocore 1.41.2; SQLAlchemy 2.0.52 and tenacity 8.5.0 in both) (four baseline/fixed payload pairs and four bound controls): baseline doubled percents and matched zero rows; fixed preserved values and matched exactly one. The live harness used exact-source AST extraction of the macro and engine-spec execute method, real Jinja, and the real DBAPI; it was not a browser/API acceptance test. This reproduced the initial two-version run. All 96 result objects across the initial run and locked replays were deleted; no persistent tables were created.

Changed-file pre-commit validation includes mypy, ruff and pylint.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags: ENABLE_TEMPLATE_PROCESSING (existing)
  • Changes UI
  • Includes DB Migration
  • Introduces new feature or API
  • Removes existing feature or API

Risk is limited to where_in output for percent-escaping dialects; rollback is a revert. SQLAlchemy's separate positional-placeholder rewriting behavior is not changed by this patch.

@bito-code-review

bito-code-review Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #5e6e73

Actionable Suggestions - 0
Additional Suggestions - 1
  • tests/unit_tests/jinja_context_test.py - 1
    • Tautological test assertion · Line 1018-1021
      The recompile assertion compares `str(bind.compile(...))` to `before`, which was computed identically on lines 1010-1012. SQLAlchemy literal compilation is deterministic, so this can never fail and adds no coverage. Consider asserting `where_in([value]) == f"({before})"` instead, which genuinely ties the macro output to the dialect's escaping.
Review Details
  • Files reviewed - 3 · Commit Range: 96a18dc..96a18dc
    • docs/docs/using-superset/sql-templating.mdx
    • superset/jinja_context.py
    • tests/unit_tests/jinja_context_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Sep 15, 2026
@netlify

netlify Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 6329ca0
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa9d12d3dfaf600084c4c19
😎 Deploy Preview https://deploy-preview-44284--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

CI update for 96a18dc44f094475de9d65202bb3d3a591b6415f: the integration/browser jobs are blocked during database initialization by pre-existing multiple Alembic heads, before these tests run.

  • PostgreSQL initialization failure: Multiple head revisions are present for given argument 'head'.
  • Playwright initialization failure: same error.
  • Actual Alembic inspection finds heads c7f53d184ea2 and 88a01c781622. The migration tree is byte-identical between base ae240a8e6f0332acb709943d0884eae73927c9de and this head: Git tree 8e763047ee8802b1dca0339be4dc0897279def46.

This PR changes only the macro, its tests, and documentation. I am not adding an unrelated migration repair or repeatedly rerunning deterministically blocked jobs. The local Jinja module remains 202 passed, and all changed-file pre-commit hooks passed. CI unit tests/pre-commit are still running; this is not an all-green claim.

@aminghadersohi

aminghadersohi commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Update 2026-09-15 06:42 UTC: the bounded unit retry passed: 15,431 passed, 6 skipped, 2 xfailed, followed by 1,762 and 437 passing coverage-gate tests. The required unit gate also passed. Head remains 96a18dc44f094475de9d65202bb3d3a591b6415f. Pre-commit is green; integration/browser/dev-image jobs remain blocked by the verified unchanged master migration graph. Human review requested; no approval claimed.


The first unit-test CI run finished with 15,430 passed, 6 skipped, 2 xfailed, and one failure: test_stop_racing_normal_completion_keeps_payload_and_results_write_consistent timed out waiting for its thread pause point. No jinja_context_test.py case failed.

The race-test file and its query execution/DAO code are unchanged. Its complete 13-test module passes locally on both this head and a clean worktree of base ae240a8e6f0332acb709943d0884eae73927c9de. The CI suite-level timing/thread failure is not reproduced locally; I am treating it as an apparently unrelated CI failure, not claiming a proven root cause. One bounded retry of the unit job is queued. No unrelated test changes were added.

Pre-commit CI passed. The integration/browser/dev-image checks remain blocked by the independently verified base migration graph. Review requested from @rusackas; PR remains open and non-draft.

@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.26%. Comparing base (6cfb331) to head (6329ca0).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #44284   +/-   ##
=======================================
  Coverage   80.25%   80.26%           
=======================================
  Files        2927     2927           
  Lines      173198   173240   +42     
  Branches    40161    40170    +9     
=======================================
+ Hits       139003   139045   +42     
- Misses      31601    31603    +2     
+ Partials     2594     2592    -2     
Flag Coverage Δ
hive 37.34% <0.00%> (-0.02%) ⬇️
mysql 56.95% <0.00%> (+0.04%) ⬆️
postgres 56.98% <0.00%> (+0.04%) ⬆️
presto 39.44% <0.00%> (-0.02%) ⬇️
python 84.69% <100.00%> (+<0.01%) ⬆️
sqlite 56.67% <0.00%> (+0.04%) ⬆️
unit 76.20% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@aminghadersohi

aminghadersohi commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Ownership update: rechecked every current check and all reviews. There are no review threads (resolved or unresolved), and @rusackas remains requested. All 15 red checks were inspected: 12 execution jobs fail on the shared multiple-Alembic-head startup error, plus three dependent required gates. No required check is skipped; the skipped frontend/release/bot jobs are conditionally inapplicable. This remains blocked, not acceptable CI. I have coordinated #44288 / #44317 / #44283 to avoid landing duplicate merge heads, and will rebase onto the chosen upstream repair once it lands, then rerun CI here.

Regarding the bot suggestion: the before/after compile assertion intentionally guards against WhereInMacro mutating the shared dialect; deterministic compilation alone does not make that assertion tautological because the macro is called between the two compilations. I have strengthened the test locally with an explicit expected compiler-escaped literal and an explanatory comment. The full Jinja module passes (202 tests), and changed-file pre-commit including mypy/ruff/pylint passes. I am holding the push for the baseline rebase to avoid a predictably blocked duplicate CI run.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Ownership update for 144a0df5e0075905aeabcbb449a82f761922b6dc (rebased onto master a184395eca7c291d0b8b438f00690c633112f4d7).

What changed in this push

  1. Rebase. Clean rebase onto current master, no conflicts. The diff is still exactly three files: superset/jinja_context.py (+5), tests/unit_tests/jinja_context_test.py, and docs/docs/using-superset/sql-templating.mdx. git rev-parse HEAD:superset/migrations equals master:superset/migrations (8e763047ee8802b1dca0339be4dc0897279def46) — this PR does not touch migrations.

  2. Addressed the bot suggestion on test_where_in_literal_percent. The before/after pair was never tautological — where_in is invoked between the two compilations, so the pair is what proves the macro does not unescape the shared dialect globally. But the assertion compared against an opaque value, which is a fair thing to object to. It now pins both compilations to an explicitly computed literal derived from the paramstyle rather than read back off the dialect:

    compiler_escaped = (
        escaped.replace("%", "%%") if paramstyle in {"format", "pyformat"} else escaped
    )
    assert str(bind.compile(...)) == f"'{compiler_escaped}'"
    assert where_in([value]) == f"('{escaped}')"
    # macro ran between the two compilations
    assert str(bind.compile(...)) == f"'{compiler_escaped}'"

    Both assertions are mutation-tested. Deleting the fix from jinja_context.py fails 35 cases; making the macro mutate the dialect (_double_percents = False after unescaping) fails 18 cases. Full module: 202 passed, including test_where_in_athena_parameterless_execution, which genuinely runs here (PyAthena 2.25.0 installed, not skipped). All changed-file pre-commit hooks pass (mypy, ruff, ruff-format, pylint).

CI: 46 pass, 12 skipped-as-inapplicable, 15 fail — all 15 from one master defect

Every required gate that can run is green, including unit-tests (current), unit-tests-required, pre-commit (current), lint-check, enforce-single-migration-head, codecov/patch, Analyze (python), and docker-build (superset) / docker-build (lean). The earlier test_stop_racing_normal_completion_... flake did not recur.

The 15 failures are 12 execution jobs plus 3 aggregator gates, and I opened the log of each of the 12 individually. All 12 fail at database initialization, before any test in this PR runs, with the identical error:

ERROR [flask_migrate] Error: Multiple head revisions are present for given argument 'head'

test-postgres (current), test-mysql, test-sqlite, test-load-examples, test-postgres-hive, test-postgres-presto, cypress-matrix (chrome), playwright-tests (chromium), playwright-tests (chromium, /app/prefix), playwright-tests-experimental (chromium), playwright-tests-experimental (chromium, /app/prefix), docker-build (dev). test-postgres-required, playwright-tests-required, and cypress-matrix-required are aggregators with no failure of their own.

This is a master defect, not a defect in this PR:

I am not adding a migration repair to this PR, and I am not re-running deterministically blocked jobs. This is explicitly not an all-green claim.

The one human action needed

A committer needs to merge a merge-head migration to master. #44288 already does exactly that — it adds e2f3a1b9c640 with down_revision = ("c7f53d184ea2", "88a01c781622"), no schema or data change — and its own CI is fully green (65 pass, 16 skipped, 0 fail), which independently confirms the double head is the sole blocker. It is MERGEABLE and waiting on REVIEW_REQUIRED.

Once #44288 (or an equivalent repair) lands, I will rebase this PR onto it and re-run CI here.

Review still requested from @rusackas. No approval claimed; PR remains open and non-draft.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

@rusackas — Amin has assigned you for review. When you have a moment, could you please take a look? Thank you.

@aminghadersohi
aminghadersohi force-pushed the aminghadersohi/fix-where-in-percent branch from 144a0df to 6329ca0 Compare September 15, 2026 23:13
@bito-code-review

bito-code-review Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #21f093

Actionable Suggestions - 0
Review Details
  • Files reviewed - 3 · Commit Range: 6329ca0..6329ca0
    • docs/docs/using-superset/sql-templating.mdx
    • superset/jinja_context.py
    • tests/unit_tests/jinja_context_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

CI is now fully green on 6329ca06d2c456c751488dfb85a9656c0622c943

The master blocker cleared: #44288 merged upstream at 2026-09-15T20:50:43Z (4c27cbd007efa298c2c1101b85a1ea158ed0502a). Master now has a single Alembic head, e2f3a1b9c640 (388 revisions, verified by AST-parsing every file under superset/migrations/versions).

I rebased this PR onto master 6cfb33197444cbf74590c2803b6dcc06180439f4 — clean, no conflicts — and re-ran CI.

Result: 64 pass, 12 skipped-as-inapplicable, 0 fail. statusCheckRollup.state = SUCCESS across 76 contexts.

Every job that was failing on the previous head now passes, with no change on this branch other than the rebase:

Previously failing Now
test-postgres (current), test-mysql, test-sqlite, test-load-examples pass
test-postgres-hive, test-postgres-presto pass
cypress-matrix (chrome) pass
playwright-tests (chromium), playwright-tests (chromium, /app/prefix) pass
playwright-tests-experimental (chromium), playwright-tests-experimental (chromium, /app/prefix) pass
docker-build (dev) pass
test-postgres-required, playwright-tests-required, cypress-matrix-required pass

Also green: unit-tests (current), unit-tests-required, pre-commit (current), lint-check, enforce-single-migration-head, codecov/patch, codecov/project, Analyze (python), Analyze (javascript), docker-build (superset), docker-build (lean), License Check, check-python-deps, dependency-review, python-dependency-liccheck, check-openapi-spec-drift.

I checked for hidden failures rather than trusting the checks summary alone. Enumerating all 24 workflow runs at this SHA gives success=21, skipped=3 — no failed, cancelled, action_required, or zero-job run. The 3 skipped workflows are Superset Showtime, Dependabot patch auto-approve, and the Python dependency-requirements sync, none of which apply to a three-file Python/docs PR. Check-run conclusions across every app are success=63, skipped=10, neutral=2; the two neutral ones are Netlify informational ("No header rules processed", "1898 new files uploaded"). Combined commit status is success. The 12 skipped checks are the frontend path-filtered gates (lint-frontend, validate-frontend, sharded-jest-tests, test-storybook, bundle-size, report-coverage) plus bot/Netlify-informational jobs — this PR touches no frontend files.

No failures were waived and nothing was re-run to mask a result.

Unchanged since the last push

Diff is still exactly three files: superset/jinja_context.py (+5), tests/unit_tests/jinja_context_test.py, docs/docs/using-superset/sql-templating.mdx. HEAD:superset/migrations equals master:superset/migrations (df1419fdb9ae79b3fa1f5973fe05fbea22b4338c) — this PR adds no migration.

Locally on this head: tests/unit_tests/jinja_context_test.py = 202 passed, with test_where_in_athena_parameterless_execution genuinely executing (PyAthena 2.25.0 installed, not skipped). All changed-file pre-commit hooks pass: mypy, ruff, ruff-format, pylint.

The one piece of review feedback — the bito suggestion about the before/after recompile assertion — was addressed in the previous push and carries forward: both compilations are pinned to an explicitly computed compiler-escaped literal derived from the paramstyle, and the assertions are mutation-tested (deleting the fix fails 35 cases; making the macro mutate the shared dialect fails 18).

Remaining gate

mergeStateStatus is BLOCKED solely because reviewDecision is REVIEW_REQUIRED. There is no failing or missing check. The only remaining action is a committer's approving review — @rusackas is requested. I am not merging and not converting this to a draft.

@rusackas rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Really appreciate the depth here, the SQLAlchemy percent-doubling explanation plus live Athena verification across both PyAthena versions makes this easy to trust. LGTM!

@rusackas
rusackas merged commit 468936a into apache:master Sep 22, 2026
76 checks passed
villebro pushed a commit that referenced this pull request Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

doc Namespace | Anything related to documentation size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants