Skip to content

fix(birdbench): sanitize Spark table names - #6534

Merged
dkmisra merged 2 commits into
mainfrom
dipendra/birdbench-spark-table-names
Nov 21, 2026
Merged

dkmisra merged 2 commits into
mainfrom
dipendra/birdbench-spark-table-names

Conversation

@dkmisra

@dkmisra dkmisra commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Spark's catalog only accepts \w characters in table names, so ensure_bird_spark fails on BIRD train databases with tables such as air carriers (AnalysisException: 'air carriers' is not a valid name). This registers each table under spark_table_name(table) (non-word characters replaced by _) and renders the same names in the Spark schema context so the model sees the names it can actually query.

  • resources_servers/bird_sql/setup_bird_spark.py: add spark_table_name, use it when creating tables. spark_table_names() maps a database's tables and raises before anything is registered if two tables would load as one (case-folded, as Spark's catalog does), instead of silently keeping only the first.
  • benchmarks/birdbench/build_db_values.py: DbHandle renders table headings and column references with the loaded table names for the Spark dialect (identity for sqlite/postgres).
  • benchmarks/birdbench/prepare.py: is_prepared_data_current() marks a Spark prepared file stale when a table heading in its sql_context is not a name Spark can hold, so a file prepared before this change is rebuilt. eval.sh now always calls gym eval prepare +use_cached_prepared_benchmarks=true so that check runs. SQLite/PostgreSQL files are never invalidated.
  • Tests: sanitized headings and FK rendering (Sales Team / voice-actors), collision refusal, freshness hook (stale, current, other dialects).

Gold SQL is never transpiled (it runs on SQLite), so nothing else changes. Only four train databases have renamed tables (airline, disney, legislator, regional_sales); a scan of every dev and train database found no name collisions.

Test plan

  • pytest benchmarks/birdbench/tests resources_servers/bird_sql/tests (181 passed, JDK 17), pre-commit run clean
  • ensure_bird_spark on the full BIRD train split (70 databases) completes (previously failed on airline); SHOW TABLES IN airline → air_carriers, airlines, airports; SELECT COUNT(*) FROM airline.Air_Carriers → 1656 rows, the old name raises TABLE_OR_VIEW_NOT_FOUND
  • Real smoke rollouts on the fixed branch (qwen3.8-flash-next-512k, temperature 1.0, max 16000 output tokens, 2 rollouts per task, via the birdbench_spark prompt config and the bird_sql reward): 5 train tasks across airline (×2), regional_sales, disney and an unrenamed database (movie_platform). The model wrote `airline`.`Air_Carriers`, `regional_sales`.`Sales_Team` and `disney`.`voice_actors` exactly as displayed; every query resolved; 4 of 10 rollouts matched gold (airline 4481 and regional_sales 1969 both rollouts). The 0-reward rollouts are genuine wrong answers (different result sets re-executed by hand: 1668 vs 54 rows, 1 vs 632 rows), not resolution or scoring errors; the movie_platform task also scores 0/8 on SQLite.
  • is_prepared_data_current returns True for the existing spark/sqlite/postgres prepared files on a machine prepared with sanitized names

🤖 Generated with Claude Code

Spark's catalog only accepts word characters in table names, so register
tables under spark_table_name() and render the same names in the schema.
Fixes ensure_bird_spark failing on the train split (e.g. 'air carriers' is
not a valid name).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Dipendra Misra <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 20, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@dkmisra
dkmisra enabled auto-merge November 20, 2026 04:54
@svcnvidia-nemo-ci svcnvidia-nemo-ci added bug Something isn't working risk:mid Autobot PR risk: mid area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers needs-review PR is ready for code review and waiting on a reviewer labels Nov 20, 2026
dhruvnathawani
dhruvnathawani previously approved these changes Nov 20, 2026

@dhruvnathawani dhruvnathawani 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.

LGTM!

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

HOLD

The table-name mapping can silently bind two source tables to one Spark table. I also found a prepared-data compatibility risk and missing required rollout evidence.

RISK: Provide representative real Spark rollout evidence

The PR reports 173 unit-test passes, but supplies no real model rollout and leaves the train-split loader check unchecked. This changes Spark registration and the model-visible identifiers. Trusted repository guidance requires representative real smoke rollouts for behavior-changing environment work; unit tests alone do not cover this requirement.

Could you run and attach a Spark/train smoke rollout covering an affected database such as airline, plus an unchanged-name table? Include the command, model/config, prepared prompt, generated SQL and inspected verifier result. Acceptance is successful train startup, agreement between prompt identifiers and registered tables, and no table-resolution failure for a query using the displayed names. Keep ordinary table names working and keep the original gold SQL on SQLite, as the comparison contract requires. This is missing validation evidence, not a claim that a real rollout failed; no code patch is implied.

I inspected all three changed files and their directly affected preparation, execution and cache paths. This was static review only. I did not execute tests or inspect the downloaded BIRD databases, so I have not confirmed whether that dataset contains a sanitized-name collision.

Note: formal approval is not available for this request, so this review is posted as a comment only.


Inline comments (escaped v1):

  • resources_servers/bird_sql/setup_bird_spark.py line 150: BLOCKER: Reject duplicate sanitized names before registering tables.

    A SQLite database containing Sales Team with row 1 and Sales_Team with row 2 reproduces the problem. spark_table_name maps both names to Sales_Team. This loop then issues the same CREATE TABLE IF NOT EXISTS identifier with different locations. The second registration is skipped, so querying the original Sales_Team reads the other table's rows. Schema rendering also displays both under that identifier. This silently changes the data used for grading in databases with colliding names; the previous loader failed on the invalid name instead.

    Could you validate the complete name set before registering any table? The smallest safe correction is to reject collisions with both original names, restoring the invariant that a loaded identifier never represents two source tables. A suggested replacement for the loop at lines 148–152 is:

    table_dirs = sorted(p for p in db_dir.iterdir() if p.is_dir())
    original_by_name: dict[str, str] = {}
    for table_dir in table_dirs:
        name = spark_table_name(table_dir.name)
        if name in original_by_name:
            raise ValueError(
                f"BIRD Spark table-name collision in {db_id!r}: "
                f"{original_by_name[name]!r} and {table_dir.name!r} map to {name!r}"
            )
        original_by_name[name] = table_dir.name
    for table_dir in table_dirs:
        spark.sql(
            f"CREATE TABLE IF NOT EXISTS `{db_id}`.`{spark_table_name(table_dir.name)}` "
            f"USING parquet LOCATION '{table_dir.resolve()}'"
        )

    This guard leaves noncolliding names, Parquet paths and cached re-registration unchanged. Supporting colliding databases instead would require a shared unique mapping in both registration and DbHandle; changing only one would leave the prompt inconsistent. Please verify the suggested code before adopting it.

    Proposed acceptance checks, not executed here: the two-table fixture above must raise an actionable collision error before registering either table. Separately load noncolliding Sales Team, voice-actors and t; queries against Sales_Team, voice_actors and t must return their respective rows, including after a second call using the cached warehouse. Retain the existing regression assertions for sanitized headings and their foreign-key relationship.

  • benchmarks/birdbench/eval.sh line 188: RISK: Invalidate prepared Spark schemas when changing registered names.

    A user can already have birdbench_spark_train.jsonl from preparation before this fix, even if server startup subsequently failed on air carriers. Preparation persists sql_context, but this existence-only branch skips rebuilding that file after upgrading. The model therefore still sees air carriers while registration now creates air_carriers. Execution sends model SQL directly to Spark, so copying the displayed identifier produces a table-resolution error and a scored wrong answer.

    Could you add a freshness check before this reuse branch and regenerate stale Spark data, or stop with an actionable regeneration command? Keep any preparation-level reuse check consistent with it. The framework supports an is_prepared_data_current hook, but this shell branch currently bypasses preparation entirely. The cache has no naming version today, so the exact invalidation implementation needs a design choice rather than a one-line replacement.

    The invariant is that reused Spark schema identifiers match the current loader. Preserve SQLite/PostgreSQL prepared files, ordinary Spark identifiers and the existing Parquet warehouse, whose physical paths did not change.

    Proposed regression check, not executed here: seed a pre-change Spark/train prepared file containing a schema reference to air carriers, then exercise the upgrade/evaluation path. It must regenerate or stop before sending the stale prompt to a model. Regenerated context must show air_carriers, while gt_sql still uses the original SQLite name. Verify that an unchanged-name Spark table renders identically and that SQLite/PostgreSQL files are not invalidated.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the ready-to-merge PR is approved, current, and waiting for final CI or merge label Nov 20, 2026
…rk prepared data

spark_table_names() maps a database's tables to their Spark names and raises
before anything is registered if two tables would load as one (case-folded,
as Spark's catalog does), instead of silently keeping only the first. No BIRD
dev or train database has such a pair.

prepare.is_prepared_data_current() marks a Spark prepared file stale when a
table heading in its sql_context is not a name Spark can hold, so a file
prepared before the sanitized names is rebuilt rather than showing the model
names its SQL cannot resolve. eval.sh now always calls gym eval prepare with
+use_cached_prepared_benchmarks=true so that check runs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Dipendra Misra <[email protected]>
@dkmisra

dkmisra commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed in 1931715:

BLOCKER, collision guard — added. spark_table_names(db_id, tables) maps every table of a database first and raises ValueError("BIRD Spark table-name collision in 'shop': 'Sales Team' and 'Sales_Team' both load as 'Sales_Team'") before any CREATE TABLE runs. It folds case as Spark's catalog does, so Sales Team vs sales_team is refused too. Tests cover both the sanitized mapping and three colliding pairs. I also scanned every BIRD dev and train database: no collisions exist, and only airline, disney, legislator and regional_sales have renamed tables at all.

RISK, stale prepared Spark data — added is_prepared_data_current(fpath) to benchmarks/birdbench/prepare.py, the hook the framework already honours. For a birdbench_spark_*.jsonl it returns False when any table heading in sql_context is not a \w+ name, so a file prepared before this fix (showing air carriers) is rebuilt; sqlite/postgres files are always current. eval.sh now calls gym eval prepare +use_cached_prepared_benchmarks=true unconditionally instead of its own existence check, so the hook runs there as well. Tests: stale spark file → False, sanitized spark file → True, postgres/sqlite files with spaces → True.

RISK, rollout evidence — a real smoke rollout is in the test plan above: 5 train tasks (airline ×2, regional_sales, disney, movie_platform) × 2 rollouts with qwen3.8-flash-next-512k through the birdbench_spark prompt and the bird_sql reward on the fixed branch. The model used `airline`.`Air_Carriers`, `regional_sales`.`Sales_Team` and `disney`.`voice_actors` as displayed, every query resolved, 4/10 rollouts matched gold, and the 0-reward ones are wrong answers (different result sets when re-executed), not table-resolution errors. The 70-database train warehouse that previously failed on airline builds, and gold still runs on SQLite unchanged.

@dkmisra

dkmisra commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 1931715

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 20, 2026 22:35
@yaoyu-33
yaoyu-33 requested a review from mpatel31415 November 20, 2026 22:37
@github-actions

Copy link
Copy Markdown
Contributor

@dkmisra
dkmisra added this pull request to the merge queue Nov 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44881810242

Merged via the queue into main with commit 41dfe06 Nov 21, 2026
69 checks passed
@dkmisra
dkmisra deleted the dipendra/birdbench-spark-table-names branch November 21, 2026 08:01
abelatnvidia added a commit to abelatnvidia/Gym that referenced this pull request Nov 22, 2026
Brings the branch up to date with main, which now carries NVIDIA-NeMo#6534
(sanitized Spark table names). One conflict, in the DbHandle docstring
of benchmarks/birdbench/build_db_values.py: NVIDIA-NeMo#6534 rewrote the Spark
sentence (tables named as Spark loads them) and this PR appended the
Snowflake one; both are kept. The code merged cleanly: NVIDIA-NeMo#6534's
_table_name hook is the identity for Snowflake, which keeps BIRD's
names, and its is_prepared_data_current() only checks Spark files.
eval.sh, prepare.py and the build_db_values tests auto-merged. Main
changes no lock this PR touches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abel Brown <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer ready-to-merge PR is approved, current, and waiting for final CI or merge risk:mid Autobot PR risk: mid

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants