Skip to content

fix(agents): stop footering figures a script computed this turn - #6771

Merged
kovtcharov-amd merged 16 commits into
amd:mainfrom
kovtcharov:kalin/footer-run-python-sources
Nov 11, 2026
Merged

kovtcharov-amd merged 16 commits into
amd:mainfrom
kovtcharov:kalin/footer-run-python-sources

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

A correct answer got labelled unverified. Asked for a report of the 3 largest orders by revenue, the agent computed them with run_python, wrote report.md, read it back, and the table was exactly right. Even so, the answer ended with "I haven't confirmed this works — report.md has figures I found no source for this turn: 1410.00 (revenue), 1374.75 (revenue)." Now an amount a script computed from files read this turn counts as its source. Prices the model typed into a script, numbers echoed from a file, and shell output still get the note. Figures that nothing in the turn produced still get the note.

Eval categories to watch: gaia_honesty (this is the note that admits unverified figures), plus data_analysis/file_ops where turns write computed tables.

Related, not fixed here: after the user denied run_python, one DeepSeek turn spent 983 thinking steps and 23.8K output tokens before giving up. The denial already holds: reroutes are refused and the model is told to stop. The cost is the reasoning itself. A cheap cap would be to end the turn as soon as the model's next call is refused for an effect the user already declined, rather than handing the refusal back for another round. A smaller option is a tight output budget on the reply that follows a denial.

🔍 Technical details
  • A revenue header makes its column a money column, and file_findings checked those cells only against _money_evidence: lines tagged with a currency, lines that mention price, and CSV/pipe rows. Plain stdout such as 492 South Doohickey 1410.00 or Decimal('1410.00') matches none of these. Deriving the figure from units × price couldn't help either, because data_numbers keeps only the first 20 numbers of a 500-row CSV.
  • A run_python result counts as the source of an amount only when the script computed it from files read this turn. Each file it opens is a named literal that a read tool, or the check itself, read. It reaches no other data (glob, URL, subprocess, eval) and types no figure above a small count into its arithmetic (numbers in a filter, slice, top-N, date or printed title don't count). Numbers it echoes from those files still need their own source. Scratchpad queries and shell output never count.
  • A read-back of the written file is still not counted as a source. It shows the file, not where its numbers came from (test_reading_back_the_written_file_is_not_a_source).

Test plan

  • pytest tests/unit/agents/test_deliverable_grounding.py tests/unit/agents/test_deliverable_grounding_adversarial.py tests/unit/agents/test_gates_never_damage_work.py: 288 pass. The new revenue tests failed before the fix.
  • Replayed the RC13 turn's records against the real orders.csv fixture with plain, float and Decimal stdout: no footer.
  • pytest tests/unit/agents: 4,896 pass (test_install_hints.py doesn't collect here because the amd-gaia package metadata isn't installed)
  • Re-ask the top-3-orders prompt on DeepSeek/Fireworks in the desktop app: the answer has no footer

…e's figures

A report.md of the top orders by revenue, computed with run_python in the
same turn, was closed with "I haven't confirmed this works — figures I found
no source for". Amounts in a money column were only matched against
currency-tagged, price-worded or CSV lines, and a script's plain stdout is
none of those.

The output of run_python, shell commands and scratchpad queries now sources
a money figure, minus the script's own literals and any number printed with
a unit, so "60 Hz" is still not a price. A read-back of the written file
still doesn't count: it shows the file, not where its numbers came from.
@github-actions github-actions Bot added tests Test changes agents labels Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

This fixes a real false alarm: a correct revenue table that a script computed no longer gets the "figures I found no source for" footer. But the fix loosens the honesty check too far. Any number a script or shell command prints now counts as a price source, including one it only copied out of a file. So if the agent runs cat datasheet.txt and the sheet says "Refresh rate up to 60", a made-up "$60" in a report goes through with no footer. The same file read with the file-read tool is still flagged. Please narrow what counts as "computed" and add a test for the echoed-file case.

Real-world evidence

N/A. No evidence bundle exists for this PR, and the change is an internal answer-checking rule with no CLI, API or UI surface to exercise. I ran the case below locally against the PR code and against the code before it. The verdict otherwise rests on static review and the author's unit-test and replay results.

# Table "| CM5 | 60 |", "| PSU | 27 |" under "Unit price".
# Source text: "Refresh rate up to 60 / PSU rated 27 watts peak"
                       before this PR   with this PR
run_python print(file) flagged          not flagged
run_shell_command cat  flagged          not flagged
read_file              flagged          flagged
🔍 Technical details

🟡 Echoed file text now sources money figures (src/gaia/agents/base/deliverables.py:650, :940)

_computed() is true for every _EXEC_WORDS tool, which matches anything containing run, exec, shell, python or test. Its whole output then goes into the money corpus, and only unit-tagged numbers are stripped first. evidence_text(code_literals=True) removes literals from the code, but a script that prints a file's contents, or a cat, type or Get-Content, passes that file's bare numbers through as if it had computed them. That reopens the BOM-from-a-datasheet case the money gate exists for, through run_python/run_shell_command instead of read_file. test_a_unit_a_script_printed_is_still_not_a_price only covers the 60 Hz form, where the unit is attached.

Some ways to narrow it (maintainer's call):

  • Don't count a computed number that also appears in the text of a file the turn read, or in stdout that just reproduces such a file. A real derived amount (1410.00 = 40 × 35.25) won't be in the CSV.
  • Or treat only run_python and query_data stdout as computed, not shell output, and require stdout lines to look like results (short, tabular or repr) rather than prose.

Either way, add the regression test:

def test_a_datasheet_a_script_echoed_is_not_a_price():
    sheet = "CM5 datasheet\nRefresh rate up to 60\n"
    records = [_run_python("print(open('cm5.txt').read())", sheet)]
    table = "| Item | Unit price |\n|---|---|\n| CM5 | 60 |\n"

    assert _check(_md(table), records)

🟢 _EXEC_WORDS substring matching is broad (deliverables.py:651). Any tool whose name contains test or build (e.g. a pytest run) now also feeds its output, timings and counts included, into the money corpus. This is worth tightening together with the fix above.

Strengths

  • The root cause is diagnosed precisely in the PR body: computed stdout matched none of the _money_evidence shapes, and data_numbers truncation meant re-deriving the figure couldn't help.
  • Good negative tests: an invented row next to computed ones is still flagged, and the read-back of the written file is still excluded.
  • _evidence_texts stays the single source of what counts as evidence. The tuple change is contained, and _evidence_texts has no other callers.

… a price source

A script or shell command that printed a datasheet ("Refresh rate up to
60") made an invented "$60" in a report look sourced. Now only run_python
code that does arithmetic and scratchpad queries that aggregate count as
computed, shell output never does, and a number already in a file the
turn read is left to that file's own money check.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Fixed: printing or cat-ing a file no longer makes its numbers count as prices. Only a computation does. Your echoed-datasheet case is flagged again, whichever tool echoed it.

  • run_python output counts only when the code does arithmetic (operators or sum/round/groupby…), and string literals are ignored, so a hyphenated filename doesn't count. Scratchpad query_data counts only for an aggregate or arithmetic, never for SELECT *. Shell, test and build output never counts as computed.
  • A number the computing script prints that is already in a file the turn read isn't taken from the script. It has to pass that file's normal money check.
🔍 Technical details
  • _computed() now reads the record's code/query argument instead of matching _EXEC_WORDS substrings, so pytest timings and counts stay out of the money corpus.
  • New tests: test_a_file_a_tool_echoed_is_not_a_price covers python-print, shell-cat and select-star, and test_a_computing_script_that_also_echoes_a_read_file_does_not_source_it covers the second guard. Disabling either guard makes its test fail.
  • The Windows unit-test failure was test_daemon_lifetime.py::test_reason_when_the_tied_process_has_exited, a timing test that doesn't touch this code. It passes locally 4 out of 4, and main has similar timing flakes. A fresh run is underway.

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

🟡 The echoed-datasheet case is fixed only when the file was also opened with the file-read tool earlier in the turn. If the script opens the datasheet itself and contains any incidental arithmetic, its whole printout still counts as computed prices. That arithmetic can be as small as line numbering (i+1), a len(s)-1, or a hyphen in a comment like # re-print. A made-up "$60" then goes through with no footer. Please either narrow what counts as computed for those cases or add a test that shows they're flagged.

🔍 Technical details

src/gaia/agents/base/deliverables.py _computed() / file_findings():

  • The seen guard only subtracts numbers from non-computed records and inputs. A run_python that does open('cm5.txt') itself, with no prior read_file, contributes nothing to seen. So once _PY_ARITHMETIC matches anywhere in the code, every bare number on stdout goes into the money corpus.
  • These trip _PY_ARITHMETIC without computing any printed figure:
    • for i, l in enumerate(open('cm5.txt')): print(i+1, l)
    • s = open('cm5.txt').read(); print(s); print(len(s)-1)
    • print(open('cm5.txt').read()) # re-print sheet. Only string literals are stripped, not # comments.
  • Add these as parametrized cases next to test_a_file_a_tool_echoed_is_not_a_price, using ECHOED_SHEET and no _read. Stripping #…$ before matching fixes the third. The first two need the guard to cover files the script itself opened, for example by matching the open(...)/read_csv(...) path literals against inputs.

I traced this through the code by hand; the tests couldn't run in this job because pytest and dotenv weren't installed.

…ithmetic

A script that opened a datasheet and printed it with `i+1` line numbers, a
`len(s)-1`, or a hyphen in a comment was still treated as computing, so the
sheet's bare numbers sourced made-up prices. Comments are now ignored, a
counter or index (`i+1`, `len(x)-1`) is not arithmetic, and arithmetic inside
an f-string field now counts, so `print(f'{u*p:,.2f}')` still sources its
result.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Holding this out of v0.25.4: it also hides the "unconfirmed figures" note for prices the model invented. If the model types made-up prices into run_python and multiplies them, the bill of materials ships with no note, which is the case the money check exists for.

  • Next step: only count a computed number as sourced when the script's inputs came from data read this turn, and add the invented-BOM-via-script case as a test.
🔍 Technical details

Probed at 163267d against the merge base: all 19 probes are flagged on the base, and 14 are not flagged on the PR. The misses:

  • print(1500 - 90)
  • the suite's own INVENTED_BOM fixture computed as v*40, with line items or with totals only
  • a file echoed via glob, a .pdf, requests.get or an os.path.join path, alongside any arithmetic
  • line-number variants i*1, i+2, s[:n-5]
  • SQL with arithmetic in WHERE

Cause: the script's own literals are subtracted from its output, but values derived from them count as computed, and a file the script opens is subtracted only when its path is a plain string literal with a supported extension.

… files read this turn

Prices the model typed into run_python and multiplied still sourced the
bill of materials, so it shipped with no "unconfirmed figures" note. A
script's output now sources an amount only when every file it opens is
named and was read this turn, it reaches no other data (glob, URL,
subprocess, eval), and it types no figure larger than a small count or
rounding. Scratchpad queries no longer count: they read rows the model
inserted.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Fixed: a script's output now counts as the source of an amount only when the script computed it from files read this turn. Prices the model types into run_python and multiplies get the "unconfirmed figures" note again. The real RC13 case, revenue computed from orders.csv, still gets no note.

  • The script must read data the turn read. Every file it opens has to be named, and it must have been read this turn: by a read tool, or by the check itself reading it. The script also can't reach data any other way (glob, a URL, a subprocess, eval).
  • It can't type figures. Any number larger than a small count or a rounding step disqualifies it, written as 95 or as Decimal('95.00'). That covers v*40, 1500 - 90, and INVENTED_BOM computed with line items or with totals only.
  • Scratchpad queries never count. The scratchpad holds rows the model inserted, not data it read. Arithmetic in WHERE is flagged again.
  • Echoed files still don't count. Any number the script prints that is already in a file the turn read has to pass that file's normal money check.
🔍 Technical details
  • _computed(record, read_names) now walks the script's AST instead of matching code shapes. It finds the open/read_csv/load_workbook/Path… calls, requires each to take a string-literal path whose basename is in read_names, rejects numeric literals and numeric strings above 10, and rejects glob/listdir/walk/requests/urllib/subprocess/environ/eval/exec and http(s): strings. The regex helpers from bcaa95d and 163267d are removed.
  • read_names comes from the path arguments of read tools this turn, plus a new file_findings(input_names=...). The agent passes that argument only for inputs it actually read text from, so an unreadable .pdf doesn't count.
  • New tests: test_prices_the_model_typed_into_a_script_are_still_flagged covers line-items, inline-math, subtraction, price-as-string and eval, with each script opening the datasheet the turn read. test_a_script_reading_data_the_turn_never_saw_sources_nothing covers glob, requests, path-join, unread-pdf, i-times-1 and slice. test_a_scratchpad_query_is_not_a_source_for_an_amount covers an aggregate and arithmetic in WHERE. Positive cases cover csv-fstring, pandas and a file only the script opened that the check read. With the literal and eval guards disabled, all five typed-price cases fail. With _computed forced true, 13 tests fail.
  • Results: test_deliverable_grounding*.py and test_gates_never_damage_work.py pass (312), and tests/unit/agents passes (4,920) after merging main. Replaying the RC13 records against the real orders.csv gives no note.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Nov 6, 2026
)

When a computation is denied or fails, a model can make up the result
and the answer looks verified. On Qwen3.6 in v0.25.4-rc13, a denied
Python run for "net revenue by region" from a 500-row CSV produced
totals of $7,798.31 (the truth is $168,645.93), presented with a "How I
computed it" section and no warning. Now the failed computation's result
tells the model nothing was computed, and figures in a chat answer that
no tool produced get the "haven't confirmed" note, not just figures in
written files.

## Test plan
- [x] `tests/unit/agents/test_grounding_unsourced_figures.py` plus the
existing grounding suites: 220 passed (this exact scenario with a
scripted LLM; figures from run_python output stay unflagged, so amd#6771
holds)
- [x] lint clean
- [ ] Desktop app on Qwen3.6: deny the Python prompt for the CSV
question; the answer says it can't compute without it, or its figures
are flagged
- [ ] Eval at the next RC: watch gaia_honesty

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
A script that read orders.csv through `csv_path = r"...orders.csv"`, worked
out revenue and wrote the table into report.md, printing nothing, left a
correct report labelled "figures I found no source for". A path bound once
to a string literal now counts as the file the script opens, and what a
computing script wrote into the deliverable counts as its output, the same
as stdout. Only when that script opened the file and nothing wrote it
after, so prices typed into the script, or a later rewrite, stay flagged.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Fixed a remaining false note: a script that computes the table and writes it straight into the report, printing nothing, now counts as the source of those figures. The release-test shape (Gemma 4 E4B NPU, report_gm15.md) no longer ends with "figures I found no source for". Prices typed into the script stay flagged, and so does a report that something rewrites after the script.

  • A path the script stores in a variable counts. csv_path = r"…\orders.csv" and then open(csv_path) is treated the same as open('orders.csv'), as long as the name is bound once, to a literal.
  • What the script writes into the report counts as its output, the same as stdout would. This applies only when that same computing script opened the report, and no write tool or other script wrote it afterwards.
🔍 Technical details
  • _string_names resolves names bound once to a string literal. _script_opens returns the files a script opens, or None when it types a figure, reaches unseen data or can't be parsed. _computed ignores files the turn wrote, so open(report_path, 'w') doesn't disqualify the script, but it still needs one read file. _script_written adds the deliverable's own text to the computed corpus. Code literals and numbers already in read files are stripped first, the same as for stdout.
  • Tests: test_figures_a_script_computed_into_the_report_itself_are_sourced reproduces the exact shape: analyze_data_file, a failed run_python, a script with a variable path that writes the report, then the read-back. It failed first with the reported note. Guards: …typed_into_a_script_that_writes_the_report_are_still_flagged, …writing_the_report_from_unread_data_sources_nothing, and …rewritten_after_the_computing_script_is_checked_again (write_file and run_python). Removing the rewrite reset fails the last one.
  • The note came from file_findings in deliverables.py, the only place that writes the file-named wording. Merged with fix(agent): flag invented amounts after a computation fails #6818 (fix/failed-computation-figures), the grounding tests pass (269), and fix(agent): flag invented amounts after a computation fails #6818's answer check doesn't flag this shape.
  • tests/unit/agents: 4,955 pass.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

The fixes for the earlier findings hold: typed prices and echoed datasheets are flagged again. But the new "script wrote the report" rule opens a fresh bypass. 🟡 If the model writes a made-up bill of materials with the file-write tool, then runs an ordinary check script that just reads the datasheet and the report, the whole report counts as computed and the "figures I found no source for" note goes away. Count the report as script output only when that script actually wrote it from scratch, and add this case as a test.

🔍 Technical details

src/gaia/agents/base/deliverables.py _script_written(): the condition is name in _script_opens(record), and _script_opens lists every file passed to open(...), whatever the mode. A read-only open('bom.md') therefore sets last, and blocks_text(blocks) (the full report, including what write_file put there) goes into computed. An append ('a') after a write_file has the same problem.

Reproduced against this head:

recs = [
    _read("cm5-datasheet.pdf", DATASHEET),
    _rec("write_file", {"file_path": "bom.md", "content": INVENTED_BOM}, {"ok": 1}),
    _run_python(
        "sheet = open('cm5-datasheet.pdf').read()\n"
        "rep = open('bom.md').read()\n"
        "print('IO Board' in rep, 'Compute' in sheet)",
        "True True\n",
    ),
]
_check(_md(INVENTED_BOM), recs)       # [] (not flagged)
_check(_md(INVENTED_BOM), recs[:2])   # flags $95.00, $60.00, $12.00

Suggested direction: have _script_opens (or a sibling) report which files the script opens in a truncating write mode ('w'/'x', or to_csv/to_markdown/write_text targets), and let _script_written match only those. Then add the read-back and append variants next to test_a_report_rewritten_after_the_computing_script_is_checked_again.

kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Nov 6, 2026
…md#6820)

Asking GAIA to create a report beside a file you shared could end with a
false "I couldn't confirm all of this: No successful write to
`report.md`", even though the report was on disk with the right rows.
Approving the input file grants that one file only, so GAIA wouldn't
even check whether the report it was asked to create existed. Now it
checks the size and timestamp of a file you named as the output (never
its contents), and a script's write to it counts. A file the turn never
touched still gets the note, and a named output that is a symlink is
never checked, so the link can't reach a file outside the grant.

**Eval categories to watch:** `gaia_files`, `gaia_data`, `gaia_code`,
`gaia_honesty`. This isn't on CLAUDE.md's eval list, but these gaps also
drive the correction the agent loop sends the model, so they shape what
it does next.

## Test plan
- [x] `pytest tests/unit/agents/test_completion_evidence.py`: the Gemma
report case (inline CSV, output path in a variable, single-file grant)
fails on main and passes here
- [x] A script that leaves the named file alone, or a file unchanged
since before the turn, still gets the note. Withheld folders and paths
found only in script code are never checked.
- [ ] Linux CI: the symlink tests
(`test_snapshot_without_validator_does_not_follow_external_symlink`,
`test_a_named_file_that_links_outside_the_grant_is_never_probed`) pass.
They skip on Windows without symlink privilege; a forced-`islink` test
covers the same guard there.
- [x] `pytest tests/unit/agents` passes, and so does the flagship
package apart from three tool-registry count tests that fail on main too
- [x] Replay in the app on Gemma NPU: the report task. The report was
written by run_python and read back, and the false "No successful write
… is recorded" note is gone. (A separate false "figures I found no
source for" note on the same answer is amd#6771's case, now being fixed
there.)
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Nov 6, 2026
Asked for net revenue by region from a 500-row CSV, Gemma 4 E4B on the
NPU ran `run_python`, which failed on `No module named 'pandas'` and
printed nothing. It then answered with a confident table: North
$10,342.50, West $10,678.98, and so on. The real totals are about four
times that (North $45,043.62), and none of the answer's figures was in
any tool output. Nothing warned the user, for two reasons:

- **The table was never checked.** The figure check only read bare
numbers, so a cell written as `$10,342.50` didn't count as a value and
the whole table passed. Reading the CSV was not the hole: in a replay
against a 500-row orders file, it didn't count as a source for these
amounts. Now a currency sign in a cell is read like a bare number, so
invented amounts get one correction and then the "not confirmed" note.
- **The failed run said nothing about figures.** amd#6791 added a "the
computation did not run" note, but review limited it to denied runs. Now
a `run_python`, `execute_python_file` or `query_data` call that fails
before printing anything is told plainly that nothing was computed:
don't report figures, fix it and run it again, or tell the user what's
needed. A failing shell command, and a script that printed results
before it crashed, still get no note.

Amounts a script did print still pass, in a table or in prose. This
composes with amd#6771, which only changes the written-file check.

**Eval categories to watch:** `gaia_honesty`, plus `data_analysis` and
`file_ops`, where answers put computed amounts in tables.

**Not fixed here:** the Python environment that `run_python` uses has no
pandas, though models reach for it all the time. That's why this run
failed in the first place. Shipping pandas there, or saying in the tool
description that it's missing, would prevent most of these failures.
That needs its own change.

<details>
<summary>🔍 Technical details</summary>

- `_PURE_VALUE` in `grounding.py` now accepts an optional `$`, `US$`,
`C$`, `A$`, `€`, `£` or `¥` before the number. `_cell_value`'s existing
rule still applies, so `$5` stays unjudged and `$10,342.50` is judged.
- `_with_computation_note` keeps `COMPUTATION_NOT_RUN` for denials. It
adds `COMPUTATION_FAILED` when a script tool
(`SCRIPT_COMPUTATION_TOOLS`, which leaves out `run_shell_command`) fails
and has no `stdout`, `result` or `rows`. `query_data` reports errors as
`"Error: ..."` strings, so the note is appended to the string.
- The `content` row and a short paragraph in
`docs/sdk/core/agent-system.mdx` describe both.
</details>

## Test plan
- [x] `pytest tests/unit/agents/test_grounding_unsourced_figures.py`:
the NPU turn, replayed with a scripted model (summary, pandas-less
`run_python` failure, summary, read, invented table), now gets the
failure note and the correction, and ships with the note naming
`10,342.50`. 6 of the new tests failed against main before the fix.
- [x] Same file: a printed-then-crashed script, a failing pytest, and a
`$` table that a script printed all get no note.
- [x] `pytest tests/unit/agents tests/unit/test_file_tools.py` with
Lemonade unreachable
- [x] Re-ask the orders.csv question on Gemma 4 E4B (NPU) in the desktop
app: the reply gives no figures, or carries the note. On the integration
build Gemma gave no totals and said they were unverified. That run
didn't attempt run_python, so the crashed-script path itself is covered
by the unit tests only.
A bill of materials written with write_file, then read back by a check
script, counted as the script's computed output, so invented prices lost
their "figures I found no source for" note. The report's figures now count
as script output only when that script created or overwrote it
(`open(p, 'w')`, `Path(p).write_text`, `df.to_csv(p)` and the like), not
when it read or appended to it.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Fixed: a script now gets credit for a report's figures only when the script itself wrote the report this turn. A bill of materials written with the file-write tool and then read back by a check script gets the "figures I found no source for" note again. The report_gm15 case, where the script computes the table and writes the report itself, still gets no note.

  • Writes: the script created or overwrote the report with open(p, 'w') or 'x', Path(p).write_text, df.to_csv/to_markdown/to_excel…, or wb.save(p).
  • No credit: a script that only reads the report, or appends to it.
🔍 Technical details
  • _script_written now matches _script_wrote(record), the files the script replaced, instead of every file it opened. _truncates recognises open with a w/x mode, write_text/write_bytes on Path(p), and the to_*/save methods unless mode contains a. Paths resolve through the same bound-once names as before.
  • New tests: test_a_script_that_did_not_write_the_report_does_not_source_it covers your read-back repro and the append variant. Both passed unflagged before this commit. test_a_report_the_script_wrote_another_way_is_its_output covers write-text, to-markdown and exclusive-create. The report_gm15 test and the rewrite tests still pass.
  • test_deliverable_grounding*.py and test_gates_never_damage_work.py: 322 pass. tests/unit/agents: 4,960 pass.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

The read-back and append cases from the last review are fixed and tested. One close variant still hides the note. 🟡 If the model writes a made-up bill of materials with the file-write tool, then runs a script that reads the report, patches one value (a total or a placeholder) and saves it back, the whole report counts as computed, so its invented prices get no "figures I found no source for" note. Models patch reports this way all the time. A script should get credit only for a report it wrote without first reading that same report. Please add this case as a test.

🔍 Technical details

src/gaia/agents/base/deliverables.py _script_written(): _computed() leaves bom.md out of the read check because it is in written, and the datasheet was read this turn, so the check passes. open('bom.md', 'w') puts the file in _script_wrote(), which sets last, and then blocks_text(blocks) (every figure write_file put there) gets credited.

Shape (reasoned from the code; this runner has no deps installed, so I didn't execute it):

recs = [
    _read("cm5-datasheet.pdf", DATASHEET),
    _rec("write_file", {"file_path": "bom.md", "content": INVENTED_BOM}, {"ok": 1}),
    _run_python(
        "sheet = open('cm5-datasheet.pdf').read()\n"
        "rep = open('bom.md').read()\n"
        "n = len(sheet.splitlines()) + 1\n"
        "open('bom.md', 'w').write(rep.replace('Total', 'Total (' + str(n) + ')'))\n",
    ),
]
_check(_md(INVENTED_BOM), recs)  # expected to flag $95.00 etc.; current code likely returns []

Suggested direction: have _script_io also return the files the script opens for reading (a non-w/x/a open or a _PY_READERS call), and make _script_written skip a file the script both reads and replaces. Add this as another report_open parametrisation in test_a_script_that_did_not_write_the_report_does_not_source_it.

A bill of materials written with write_file, then opened by a script that
patched one value and saved it, counted as the script's computed output,
so its invented prices lost the "figures I found no source for" note. A
script now gets credit only for a report it wrote without reading that
same report first.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Fixed: a script that reads the report, patches it, and saves it back no longer gets credit for the report's figures. A bill of materials written with the file-write tool and then touched up by a script, whether a total renamed or a placeholder filled in, gets the "figures I found no source for" note again. A script still gets credit for a report it wrote without first reading that same report, as in report_gm15.

🔍 Technical details
  • _script_io now also collects the files the script reads: open(p) without a w/x mode, Path(p).read_text/read_bytes, and the _PY_READERS calls (read_csv, load_workbook…). It returns replaced - read_from, so a file the script both reads and replaces isn't credited to it.
  • test_a_script_that_did_not_write_the_report_does_not_source_it gains three cases: patch-open (your repro shape), patch-path (write_text(read_text().replace(...))) and patch-pandas (read_csv → to_csv). All three failed before this commit. The report_gm15 test and the write-text/to-markdown/exclusive-create positives still pass.
  • Merged with main: test_deliverable_grounding*.py and test_gates_never_damage_work.py pass (325), and tests/unit/agents passes (5,156).

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Both earlier bypasses are closed on a79d4d4: reading the report back, r+, and read-then-rewrite all get the note again. Two new ones keep this out of the next RC:

  • Invented prices inside a string ("""CM5108032,95,40 ...""" parsed with split or csv, '$95.00', json.loads('...')) let the whole bill of materials through. Main flags it.
  • Reading the report another way (io.open, codecs.open, Path(...).read_text() through a variable) and then overwriting it credits the whole invented report.
🔍 Technical details
  • _script_io only rejects numeric literals and strings that are entirely a number. Rejecting any string literal holding a number above 10 (path arguments excepted) closes the first.
  • Read detection knows a fixed list of spellings. Counting any reference to the report path as a read, unless it is a recognised overwrite, closes the second.
  • Probes are in the verification notes.

A script could still invent a bill of materials and have it count as
computed: prices typed into a string and parsed with split or json.loads,
or built from small literals such as 9*10+5 or int('9'+'5'). Those now
disqualify the script, the same as typing 95 directly. A report read with
io.open, codecs.open or a Path held in a variable and then overwritten no
longer earns the script credit for it. A percentage scaled with *100 from a
ratio of sourced data no longer disqualifies an otherwise sourced script.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Fixed the bypasses from the 2026-11-07 comment plus literal arithmetic: invented prices hidden in a script's strings or built from small literals get the "figures I found no source for" note again, and a report read any other way and then overwritten earns the script no credit. Real computed tables stay quiet, including a share-of-revenue column scaled with *100, which used to get a false note. Merged main in too. Thanks for driving this, Kalin.

🔍 Technical details
  • Strings: a string literal holding a number above the small-count limit disqualifies the script unless it's a path the script opens ('CM5,95,40'.split, json.loads('{"cm5": 95}'), '$95.00'). Format specs ({v:>12}, %10.2f) and encoding= values don't count.
  • Literal arithmetic: any expression built only from literals is folded (9*10+5, int('9'+'5'), ord('_'), ''.join(...), f-strings), and a result above the limit disqualifies the script.
  • Report reads: io.open/codecs.open count as open, and a report path passed to any call other than its overwrite (Path(p) through a variable included) counts as a read, so no credit.
  • Percentages: 100 is allowed only when it scales a ratio with a non-literal divisor (a / b * 100, 100 * a / b); units * 100 and x * 100 / 4 stay disqualified.
  • Tests: 14 new cases failed on a79d4d4 (six literal bypasses, three report-read bypasses, three percent tables, two percent-scale unit cases); the codecs/pathlib positives and existing csv/pandas/gm15 positives pass on both. Grounding + gates suites: 343 pass. tests/unit/agents: 6,018 pass; the one failure, test_registry_load_errors.py::test_broken_agent_dir_records_load_error, fails the same in the fix(agent): call out a line an edit removed when told to change nothing else #6885 worktree and doesn't touch this code.
  • Trade-off: a genuine script with an unrelated big number in a string (a date filter like '2026-01-01') now gets the note. Residual gaps: list repetition (sum([10]*9)+5) and bytes literals aren't folded.
  • Eval categories for the next RC: gaia_honesty, data_analysis, file_ops.

…ices

A script that filtered by date, picked the top 25 rows, compared a year
column, worked in cents or printed a "Revenue report 2026" title lost its
credit for the figures it computed, so correct analyses got the "no
source" note. Numbers in comparisons, slices, selector and date calls,
round digits, loop ranges, string repeats and year-only print titles no
longer count as typed figures; names bound once inherit that when every
use is one of these.

Invented prices now caught that slipped through: list repetition,
'%d%d' % (9, 5), str.format, names bound to small literals (a=9; b=10;
a*b+5), and ''.join over a list or map(str, ...), which failed because
the arguments were evaluated before the join branch. Name folding is
memoised and bounded so long scripts stay cheap.

Adds a 23-script correct-analysis corpus and a 34-script invented-figure
corpus.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Correct analyses that filter by date, pick a top N, compare a year column, work in cents or print a dated title no longer get the "no source" note, and the remaining hidden-price tricks are caught. On two new script corpora: 0 of 23 correct analyses are wrongly noted (the previous head noted all 23), and 34 of 34 invented-figure scripts are caught (previously 26). Merged main in too. Thanks for driving this, Kalin.

🔍 Technical details
  • Numbers in comparisons, slices and subscripts, selector and date calls (head, nlargest, quantile, isin, date, Timestamp, strptime…), round digits, loop ranges, '=' * 40, ISO-date strings and year-only print titles no longer disqualify a script. A name bound once (TOP = 25, YEAR = '2026') is exempt only when every use is one of these.
  • 100 counts as a percent scale through a ratio-valued name (share = v / total; share * 100), and as cents when the script also divides by 100.
  • Folding now covers list repetition, '%d%d' % (9, 5), str.format, map(str, …) and names bound to small literals. The ''.join order bug is fixed: the method is handled before its arguments. Name folding is memoised and size-capped.
  • Adversarial cases are in the invented corpus: a price in 'CM5,2049', print('Total: 950'), a price name also used in a comparison or a slice, and 'CM5108032-95'.
  • Tests: test_deliverable_grounding.py 146 pass; the related agent tests (deliverable, grounding, gate, verification, claim) 1,403 pass.
  • Residual: deliberately obfuscated scripts can still get through, e.g. a price picked out of a range by a comparison.
  • Eval categories for the next RC: gaia_honesty, data_analysis, file_ops.

kovtcharov and others added 2 commits November 10, 2026 17:08
… read-back

A deep review of the script-credit check found:

- Folding had no size cap on concatenation, join or format: a 16-line
  script that doubles a string held the end of the turn for 5 s, and a
  join chain or a huge format width for half a minute. Every folded
  string, list or tuple is now capped, huge widths and Decimals are
  rejected before they are built, and a script is parsed once.
- `$5,000` in a script's string was read as a 5 and a 000, so the invented
  figure was credited. A number with thousands separators is one number.
- Printing the finished report back with run_python stripped its credit,
  so every computed figure was flagged. Only a later call that writes the
  file resets it; reading and then overwriting it still does.
- dtype names, padding widths, pandas display options and a year in a
  written heading no longer disqualify a correct analysis. Arbitrary
  multipliers still do.
- A script that cannot be parsed (lone surrogate, deep nesting) is logged
  and left uncredited instead of raising out of the check.
… too

Python 3.12 on Linux parses 5000 nested unary minuses, so the script was
analysed, folded to 1 and credited, and the Linux unit job failed. 100,000
levels overflow the parser's fixed stack on every OS.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Nov 11, 2026
Merged via the queue into amd:main with commit c26c773 Nov 11, 2026
38 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/footer-run-python-sources branch November 11, 2026 10:30
huong8373tt-beep pushed a commit to huong8373tt-beep/gaia that referenced this pull request Nov 11, 2026
… finished (amd#7143)

Asking for a large document again right as its background index finished
sent the file to the indexer a second time, and the tool reported
"already indexed" where it should have reported the index it had been
waiting on. The tool checked "already indexed?" before looking for a
running job, and the job could record the file and end in between. Now a
job remembers when it ended, and a request that just missed it reuses
its result. A file edited after its last index still re-indexes.

The cost to users is small: the indexer recognises an unchanged file and
skips re-embedding. The main effect is on CI, where the same race made
`test_slow_index_returns_in_progress_then_success` fail at random (seen
on amd#6771: `index_document` called twice).

Known gap, left as is: when a caller waited for the index itself, a
second request arriving while that caller records the result still makes
the same cheap repeat call.

## Test plan
- [x] New test forces the exact interleaving (guard sees the file
unindexed, then the job records it and ends) and fails without the fix;
others confirm an index that ended before the ask is not reused, and
that a reused result clears a stale "failed to index" entry.
- [x] `tests/unit/rag/test_background_indexing.py`: 15 pass on repeated
runs. The new tests also pass with the index thread started 0.3 s late;
five older tests in the file assume it starts within their 0.2 s budget
and are unchanged.
- [x] Wider `rag`/`index` unit tests: same results as main (local
failures are a missing faiss install, identical on main).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants