Skip to content

feat(bird_interact): run BIRD-Interact Lite and Full on PostgreSQL - #5473

Merged
ffrujeri merged 3 commits into
ffrujeri/bird-interact-environment-serverfrom
ffrujeri/bird-interact-postgres
Nov 23, 2026
Merged

ffrujeri merged 3 commits into
ffrujeri/bird-interact-environment-serverfrom
ffrujeri/bird-interact-postgres

Conversation

@ffrujeri

@ffrujeri ffrujeri commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Merges only together with #5534. This PR's PostgreSQL runner grades some tasks differently from the BIRD-Interact ADK; #5478 and #5534 fix that. Once #5534 is approved, the stack merges from the top: #5534 into #5478's branch, then #5478, #5475 and this PR into their bases, so this branch holds #5534's runner before it reaches main.

Stacked on #5409 (BIRD-Interact in its Environment Server), in the BIRD-Interact stack: #5465 → #5409 → this PR → #5475 (the benchmark recipe), on main. This PR's diff against #5409 is environment_servers/bird_interact only, in two commits: the second moves the image to the recipe and refuses follow-up test cases.

What changed

BIRD-Interact Lite and Full keep their databases in PostgreSQL; #5409 runs only SQLite (Mini-Interact). With database_engine: postgresql, a task's database is <db>_template in the PostgreSQL server of the sandbox image, and each episode starts its own sandbox from that image, so a write in one episode never reaches another. The benchmark recipe (#5475) builds the image with the databases already restored, prepares the data and runs Lite and Full.

  • grading.py has a PostgreSQL engine beside SQLite, behind the same setup, execute and grade commands. setup starts the image's server (socket only) and applies preprocess_sql to <db>_template. Each query then runs in a transaction that is rolled back, as SQLite runs each on a scratch copy.
  • Normalization follows the benchmark's rules for PostgreSQL's types: decimals to two places, half-up; dates and timestamps as YYYY-MM-DD; JSON values as sorted JSON. SQLite never returns these types, so its grading does not change.
  • The server sends the engine and the database with every runner request, uploads no database for PostgreSQL, refuses postgresql without sandbox_config.image, and names the dialect in the instructions (PostgreSQL, a sql fence; a postgresql fence is also read).
  • Follow-up test cases. A task whose follow-up has custom test_cases now fails at seed, as one with its own already did. Every Lite and Full task has a follow-up, and its phase 2 would otherwise be graded by the default test case.
Mini-Interact (#5409) Lite and Full (this PR)
Database <db>.sqlite uploaded into each episode's sandbox <db>_template in the sandbox image's PostgreSQL
Episode start Copy the file Start PostgreSQL; the image's databases are already restored
A query On a scratch copy In a transaction that is rolled back

Why

A sandbox per episode keeps #5409's lifecycle and isolation, and an image with the databases restored at build time removes its cost: BIRD-Interact's official image restores 18 databases whenever a container first starts, which would repeat in every episode. A shared PostgreSQL per worker would be cheaper still in memory, but its sandbox would outlive episodes, need a database per episode cloned from a template, and fail every episode on the worker with it. No public issue: the PRs of the BIRD-Interact stack track the work.

Validation

Command Result
pytest environment_servers/bird_interact/tests/test_app.py 60 passed, 3 skipped (at the 2026-11-19 head). New: a follow-up with custom test cases refused at seed; the normalization rules against rows typed as PostgreSQL's driver types them (decimals half-up, a timestamp as its date, JSON with sorted keys); the runner routing a postgresql request to the image's server, committing preprocess_sql and rolling back a query, and its preview; the server refusing postgresql without an image and running an episode on bookshop_template with the engine in every request, no database uploaded, and the dialect in the instructions
Same, with decimals rounded half-even The normalization test fails, so it checks the rounding mode
ng_test +entrypoint=environment_servers/bird_interact +should_validate_data=true 56 passed, 3 skipped in the server's own venv (before the review fixes)
pre-commit run --files on the changed files Passed

| The same tests in a Debian container with PostgreSQL 15 and the server's venv, at 9509a7b | 63 passed: the 3 real-PostgreSQL tests (TestPostgresDatabase: rollback, statement timeout, numeric and date grading) among them. On the host and in CI, which have no initdb, they skip |

Rollout evidence

N/A for now: Lite and Full withhold sol_sql, so no task runs without the ground truth, and the recipe's image is not built yet. The SQLite path is unchanged; its 37 episode tests pass as before.

Compatibility

database_engine defaults to sqlite, and sandbox_config.image to python:3.12-slim for SQLite, so existing configs run as before. Management tasks, which have custom test_cases, still fail at seed: Lite runs 195 query tasks of 300, Full 410 of 600.

Team review fixes (2026-11-19)

A team review found that agent SQL ran as PostgreSQL's superuser, so it could log and read the solution SQL; that SQL breaking the driver masked the sample; and that the real-PostgreSQL fixture leaked a server. All are fixed where the runner is final, in #5534 (a role that is not a superuser, bird_agent; driver errors as query errors; the fixture's try/finally). This PR should land with #5534, not alone, as the review recommends.

Review fixes (2026-11-19, second round)

From the second review, in 9509a7b:

  • The shipped config no longer pins sandbox_config.image, so database_engine: postgresql without an image is refused at startup; the SQLite image stays the server's default.
  • The real-PostgreSQL fixture creates its database outside a transaction (psycopg2 2.9's with connection opens one), and psycopg2-binary==2.9.13 is a server dependency, so the class runs wherever initdb is on PATH.
  • A bytea value shows as bytes in an execute preview, not as a memoryview's address.
  • The README names both engines and the PostgreSQL fences; the JSON grading case uses floats, as psycopg2 decodes JSON.
  • The other untested lines (a failed setup, a-Interact's dialect, the SQLite image fallback) have tests in feat(bird_interact): grade BIRD-Interact's management tasks by their test cases #5534 (971dbae), where the code is final.

@ffrujeri ffrujeri added feature New capabilities, enhancements, or enablement work area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers labels Nov 3, 2026
@copy-pr-bot

copy-pr-bot Bot commented Nov 3, 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.

@ffrujeri
ffrujeri added this pull request to stack #5470 November 3, 2026 02:01
@ffrujeri

ffrujeri commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 1299b61

@ffrujeri

ffrujeri commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test d7e2431

@ffrujeri

ffrujeri commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test c4d1e49

@ffrujeri

ffrujeri commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 58c6c91

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test d792755

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test f74ca39

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 3377aa5

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 4d4fab7

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 03b2d1e

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 6c02552

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test b16dcf1

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 1f7b123

@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

I inspected all five changed files and the affected task, tool and sandbox paths. This was a read-only review; I did not execute tests. The checks below are proposed, not observed results.

RISK: Real PostgreSQL execution and rollout evidence are missing. The PR reports 56 passed, 3 skipped and explicitly says the PostgreSQL runner and new releases have not been exercised against a real server. The episode test supplies a successful grading response, while the real-server tests can skip without PostgreSQL and its driver. Neither validates image startup, real query execution or model behavior through the new path.

Could you attach representative PostgreSQL model rollouts and reward-profiling evidence before merge? Repository guidance requires real smoke rollouts for behavior-changing environment work, and the review rubric requires baseline reward numbers for fixed benchmark integrations. Record the image, task sample and model revision, aggregate reward, and execution/verification failure counts. Inspect c-Interact and a-Interact trajectories, including a follow-up, and verify sandbox cleanup. Keep the existing SQLite examples' rewards unchanged. PostgreSQL-compatible synthetic bookshop tasks can validate startup and integration while official ground truth is unavailable, but Lite/Full benchmark coverage must still be reported as unvalidated until their profiling runs exist.

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


Inline comments (escaped v1):

  • environment_servers/bird_interact/grading.py line 230: BLOCKER: Submitted transaction control can change the grading oracle.

    Could you enforce query isolation before executing arbitrary scripts? Every statement reaches PostgreSQL unchanged, including COMMIT; the final rollback cannot undo an earlier committed write. Prediction and solution then use the same modified database in grade.

    Using the existing sales fixture, grade UPDATE sales SET amount = 0; COMMIT; SELECT amount, sold FROM sales against SELECT amount, sold FROM sales. Independent executions should reject this prediction because the baseline amounts are 1.005 and 2.5. This implementation lets the prediction commit zero amounts before running the solution, so both queries can return the modified rows and incorrectly pass. Later calls in that episode also inherit the write.

    Restore an immutable post-preprocess_sql baseline for every exploratory query, prediction and solution. A disposable execution database is one option; an alternative must enforce transaction boundaries and account for nontransactional state such as sequences. Rejecting all writes would break supported write-then-query scripts. I cannot give a complete patch without the image's database roles and creation privileges.

    Proposed checks: the example returns passed=False, and the next query still returns the original amounts. Retain the existing assertion that DELETE FROM sales; SELECT COUNT(*) FROM sales returns [(0,)], followed by [(2,)] on the next execution. Verify that setup changes stay visible and that a query using nextval does not advance the baseline sequence.

  • environment_servers/bird_interact/grading.py line 227: RISK: Each statement receives a fresh timeout budget.

    A multi-statement execution can exceed timeout_seconds because each cursor.execute receives the same statement_timeout. For example, eight SELECT pg_sleep(0.15) statements with a 0.2-second budget can succeed after roughly 1.2 seconds. SQLite instead carries one deadline across the script. Longer scripts reach the outer sandbox timeout, which retries an agent-generated timeout as an infrastructure failure and can mask the sample.

    Could you bound the complete execution? Replace the initial timeout assignment and statement loop inside _execute with a remaining-budget calculation, keeping the existing exception handling and rollback:

    deadline = None if timeout_seconds is None else time.monotonic() + timeout_seconds
    rows: list[tuple] | None = None
    for statement in split_statements(sql):
        if deadline is not None:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                return QueryResult(rows=None, error=f"Query timed out after {timeout_seconds} seconds")
            cursor.execute("SET LOCAL statement_timeout = %s", (max(1, int(remaining * 1000)),))
        cursor.execute(statement)
        if cursor.description is not None:
            rows = cursor.fetchall()

    Verify this suggestion before adopting it. It keeps setup unbounded when timeout_seconds=None and resets the limit before each submitted statement.

    Proposed checks: the eight-statement example returns Query timed out after 0.2 seconds without a sandbox retry. Retain the single-statement timeout and missing-column assertions. A short script within the total budget must still return its last row-producing statement.

  • environment_servers/bird_interact/grading.py line 144: RISK: Equivalent numeric and floating-point results compare unequal.

    _round_nested keeps floats as float and numerics as Decimal. Consequently, (0.1,) and (Decimal("0.10"),) compare unequal in both branches of grade, despite representing the same value at the advertised two-place precision. A prediction using double precision can therefore be rejected against an equivalent numeric solution.

    Could you use a comparison representation whose equality and hash agree for PostgreSQL numbers after their respective rounding rules? Apply that contract to scalar and array numbers without turning genuine JSON strings into numbers. I do not have a safe one-line replacement: converting every Decimal to float loses large-number precision, while changing the shared float branch can alter SQLite grading.

    Proposed regression: grade(_TypedRows([(0.1,)], [(Decimal("0.10"),)]), "SELECT x", "SELECT x", ordered=False, timeout_seconds=5) should pass; repeat with ordered=True. Confirm the real-server equivalent using SELECT 0.1::double precision and SELECT 0.1::numeric. Cover numeric versus floating-point arrays too. Preserve the existing Decimal half-up and unequal-value cases, keep 0.10 versus 0.11 unequal, and keep JSON string "0.10" distinct from numeric 0.1. Retain SQLite's existing float and ordering assertions.

  • environment_servers/bird_interact/grading.py line 144: RISK: Large valid numerics crash normalization.

    Quantizing Decimal("1E+30") to 0.01 needs 33 digits, exceeding the runner's default Decimal context precision of 28. Even identical nonempty results therefore raise decimal.InvalidOperation. main does not handle it, so the caller retries the nonzero exit as a sandbox failure rather than grading valid SQL.

    Could you size a local Decimal context for finite values? Add localcontext to the decimal import and replace the Decimal branch with:

    if isinstance(value, Decimal):
        with localcontext() as context:
            context.prec = max(context.prec, value.adjusted() + _FLOAT_PLACES + 2)
            return value.quantize(_DECIMAL_STEP, rounding=ROUND_HALF_UP)

    The extra digit allows a rounding carry. Verify this suggestion before adopting it; it addresses finite numerics without changing process-wide precision or defining new non-finite behavior.

    Proposed checks: identical _TypedRows results containing Decimal("1E+30") pass in ordered and unordered modes without an exception. Include a nested Decimal because this helper recurses through arrays and dictionaries. Retain 3.145 versus 3.15 passing and 1.01 versus 1.02 failing; add -3.145 versus -3.15 and 9.999 versus 10.00. Confirm the caller's Decimal precision stays unchanged.

  • environment_servers/bird_interact/schemas.py line 27: NOTE (suggestion): PostgreSQL tools still ask the model for SQLite SQL.

    With PostgreSQL a-Interact enabled, the system instructions name PostgreSQL, but both execute and submit use this shared argument model. TypedToolset exposes its JSON schema, so the model still receives "The SQLite query." for each tool's sql argument over direct HTTP and MCP.

    Could you make the shared description engine-neutral?

        sql: str = Field(description="The SQL query.")
    

    This keeps the argument name, required string type and strict validation unchanged for SQLite while removing the conflicting PostgreSQL instruction.

    Proposed check: inspect both tool declarations in a PostgreSQL a-Interact episode over each transport and confirm their argument descriptions no longer request SQLite. Keep the existing SQLite tool execution and malformed-argument behavior unchanged.

  • environment_servers/bird_interact/README.md line 152: NOTE (suggestion): The PostgreSQL setup link has no target in this head.

    The new section directs users to a benchmark README that is not present in the immutable tree. Because the recipe is deferred, readers cannot follow the advertised image-building instructions.

    Could you document the current image contract here and describe the recipe as follow-up work until its target exists? The requirements are visible in PostgresDatabase and start_postgres. A replacement for these two lines could be:

    The image must provide `python3` with importable `psycopg2`, plus `gosu` and `pg_ctl` on `PATH`. It must set
    `PGDATA`, `PGHOST` and `PGUSER` for the restored cluster, and its sandbox commands must be able to run
    `gosu postgres pg_ctl`. The benchmark recipe that builds this image is follow-up work.
    

    Keep the existing <db>_template naming, per-episode sandbox contract and SQLite default instructions. Proposed static acceptance: every setup link resolves in the submitted tree, and the documented image prerequisites cover the commands and imports the runner uses. This does not require moving the image build back into this PR.

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

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 6728ce6

@ffrujeri

Copy link
Copy Markdown
Contributor Author

Answers to the review's findings. The PostgreSQL runner is rewritten in #5478 and changed again in #5534, so the fixes are in 42448ce5, where it reaches its final form in this stack.

  • BLOCKER: transaction control can change the grading oracle. Fixed, as the ADK isolates it: the ADK resets its task database from the template before each submission. Agent SQL now runs only on copies of the episode's database: exploratory queries on a working copy, each submission on a fresh copy, after which the working copy starts again from the episode's database. Only setup and a passing phase 1 write the episode's database. Checked on a real server in the Lite image: your UPDATE sales SET amount = 0; COMMIT; ... leaves the episode's amounts unchanged, both as an exploratory query and as a submission, and the next submission is graded on the original rows. Note that within one grade the submission's writes are still visible to the solution, by design: the ADK runs the submission and the solution in turn on one state, and grades this example the same way.
  • One timeout budget per script. Fixed: the runner cancels the query when the script's deadline passes, so eight pg_sleep(0.15) statements with a 0.5 s budget time out, and so does a script that COMMITs and then sleeps (checked in the image).
  • Numeric and float compare unequal. Kept, for parity with the ADK: its preprocess_results also rounds a Decimal with quantize and a float with round, and compares the results as they are, so (0.1,) and (Decimal("0.10"),) differ there too.
  • Large numerics crash normalization. Fixed as a failed comparison, which is what the ADK's submit_sql returns when test_case_default raises, rather than widening the precision, which would change the verdict.
  • The tools ask for SQLite. Already "The SQL query." since feat(bird_interact): match the BIRD-Interact ADK's c-Interact, simulator and grading #5478.
  • The README links the recipe. The link resolves from feat(benchmarks): add the BIRD-Interact Lite and Full benchmark recipe #5475, the next PR in this stack.
  • Real PostgreSQL rollouts. See feat(bird_interact): match the BIRD-Interact ADK's c-Interact, simulator and grading #5478 and feat(bird_interact): run BIRD-Interact in its Environment Server, with no Resources Server #5409 for the current runs; Lite ran through the recipe's image on PostgreSQL, 6 of 6 episodes completed. Real-ground-truth profiles wait on the ground truth (GYMINT-592).

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 83fb1fa

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test b5fffdd

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test f11f7ad

@ananthsub

Copy link
Copy Markdown
Contributor

This PR's PostgreSQL runner should reach main only together with #5534. The description already says so, but the stack does not enforce it: once #5409 merges, this PR can merge on its own. Beyond the points already raised in the earlier review, this PR's head grades or fails some tasks differently from BIRD-Interact's reference evaluation code (its ADK). Only #5478 or #5534 fix these:

  • Agent SQL can switch off its own timeout with SET statement_timeout = 0, so a slow query runs until the sandbox command times out. The rollout is then masked instead of failing.
  • split_statements also splits preprocess_sql and sol_sql, so a $$ body or an E'...' string there fails setup or the solution.
  • Arrays of numerics or dates compare through json.dumps(..., default=str), which the reference does not do. A timestamp inside an array also keeps its time of day.
  • The grade uses the last statement that returns rows, where the reference uses the last statement. It also fetches every row instead of stopping at the reference's 10,000-row cap.
  • When PostgreSQL fails to start, the error drops pg_ctl's output. The PostgreSQL log is lost when the sandbox stops.

Could you either merge #5534 down into this branch before this PR merges, or squash the PostgreSQL runner changes into one PR? The inline comments are the points that still apply at #5534, plus the config fix this PR needs for its own validator.

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 9509a7b

@ffrujeri

Copy link
Copy Markdown
Contributor Author

Agreed: this PR reaches main only together with #5534. We will merge the stack from the top. Once #5534 is approved, it merges into #5478's branch, then #5478, #5475 and this PR merge into their bases. This branch therefore holds #5534's runner before it moves toward main. The note is now at the top of the description. I kept the PRs separate so that each diff stays reviewable.

The five points you list are fixed where the runner is final, in #5478 and #5534. The inline points are fixed here in 9509a7bd, and the untested lines have tests in #5534 (971dbae9). The real-PostgreSQL tests now run: 63 passed at this head and 110 at #5534's, in a container with PostgreSQL 15.

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test b17d9ca

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 487d86b

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 0f2cac2

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 649d3f0

ffrujeri and others added 3 commits November 23, 2026 03:28
Lite and Full keep their databases in PostgreSQL. With
database_engine: postgresql, each episode starts its own sandbox from an
image whose build restores every database of the release once
(postgres/Dockerfile), so an episode starts PostgreSQL instead of
restoring dumps, and a write in one episode never reaches another.

- grading.py has a PostgreSQL engine beside SQLite. setup starts the
  image's server and applies preprocess_sql to <db>_template; each query
  then runs in a transaction that is rolled back, as SQLite runs each on
  a scratch copy.
- Values are normalized by the benchmark's rules for PostgreSQL's
  types: decimals to two places, half-up; dates and timestamps as
  YYYY-MM-DD; JSON values as sorted JSON. SQLite never returns these
  types, so its grading does not change.
- The server sends the engine and the database with every request,
  uploads no database for PostgreSQL, refuses postgresql without a
  sandbox image, and names the dialect in the instructions.
- Management tasks still fail at seed: their custom test_cases do not
  run yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
…use follow-up test cases

The PostgreSQL image and the Lite and Full how-to move to the benchmark
recipe (benchmarks/bird_interact, next in the stack), which also
prepares the data and runs the benchmark. The server keeps what it needs
to run on any image that holds a release's databases as <db>_template.

A task whose follow-up has custom test_cases now fails at seed, as one
with its own already did: every Lite and Full task has a follow-up, and
its phase 2 would otherwise be graded by the default test case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
… the real-PostgreSQL tests

- The shipped config no longer pins the SQLite image, so `database_engine: postgresql` without an image is refused at
  startup; the server already falls back to the SQLite image.
- The real-PostgreSQL test fixture creates its database outside a transaction (psycopg2 2.9's `with connection`
  opens one), and `psycopg2-binary` is a server dependency, so the tests run wherever `initdb` is on PATH.
- A `bytea` value shows as bytes in a preview, not as a memoryview's address.
- The README names both engines and the PostgreSQL fences; the JSON grading case uses floats, as psycopg2 decodes JSON.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 52b71bd

@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/45125293519

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 feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants