Skip to content

fix(tools): reject stale whole-file writes - #3656

Merged
itomek merged 6 commits into
amd:mainfrom
kovtcharov:codex/review-stale-writes
Sep 24, 2026
Merged

itomek merged 6 commits into
amd:mainfrom
kovtcharov:codex/review-stale-writes

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Whole-file writes could overwrite changes made after an agent read a file. The existing stale-edit guard now covers every shared file mutation path, returning current content before any backup or write. Closes #3568.

Test plan

  • 444 tests passed across file write-state, edit semantics, write guardrails and filesystem mixins; three existing Unix-only skips on Windows. Scoped Black, isort, pylint and whitespace checks passed.
  • Changes read back for scope and correctness.
  • Maintainer review and CI completion.
🔍 Evidence and limits

Real temporary files exercise external edits, rejected writes without side effects, corrected retries and ordinary creation. This reuses the existing process-local tracker; it does not claim cross-process atomic check-and-write.

Follow-up: stale-write errors explicitly identify bounded excerpts and require a full read before rewriting. Six new long-file cases pass; the relevant rerun reported 298 passed and 3 existing platform skips.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 11, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

This closes a real hole: whole-file writes (write_file, write_python_file, write_markdown_file, update_gaia_md, replace_function) now go through the same stale-content guard the edit tools already had, so an agent can no longer silently clobber changes someone else made after it read the file. The refactor is clean, the guard runs before any backup or write, and the new parametrized test covers every mutation tool.

One thing to fix before merge: when a whole-file write is rejected, the error tells the model to "reissue the edit against" the content it returns — but for a whole-file write that content is only the first ~25 lines of the file, not the file. A model that follows the instruction literally rewrites a 500-line file from a 25-line excerpt, and because the rejection re-anchors the ledger, the truncating retry succeeds. That's the same data loss this PR exists to prevent, just one step later. The fix is wording: for a whole-file write, tell the model to re-read the file rather than to reuse the excerpt.

Smaller points (details below): stale rejections don't reach the write audit log the way every other rejection in these tools does, and the spec page lists the guarded tools but leaves one out.

Real-world evidence

N/A — no evidence-bundle.md was produced for this run, and the change touches agent tool internals rather than a CLI, REST, MCP, or Agent UI surface, so there is no user-facing surface for the CI lane to exercise. The verdict rests on static review plus the PR's own test-plan claim of 444 passing tests; pytest is not installed in this review environment, so I could not re-run them myself and am not claiming to have.

🔍 Technical details

Issues

🟡 Stale-write guidance is edit-specific and invites a truncated overwrite (src/gaia/agents/tools/file_edit.py:343)

For a whole-file write, check_file_state is called with old_content="". _excerpt then takes the "nothing resembles it" branch — _anchor_line returns None for an empty probe, so the excerpt is lines[0:25] with anchored_on="file_start". current_content_truncated stays False (it only reflects the 4000-char clip), so the payload doesn't signal the shortfall; only current_content_total_lines hints at it. Meanwhile the message says "reissue the edit against that, not against what you read earlier." For edit_file that's right. For write_file it reads as "rewrite the file from this excerpt."

    guidance = (
        "The file's current content is included as `current_content`; "
        "reissue the edit against that, not against what you read earlier."
        if old_content
        else (
            "An excerpt of the current content is in `current_content` — it is "
            "not necessarily the whole file. Re-read the file before rewriting it."
        )
    )
    error = _error(
        f"{operation} rejected: {file_path} changed on disk after it was read — "
        f"{divergence.reason}. Nothing was written. {guidance}",

🟢 Stale rejections bypass the write audit log (file_io_tools.py:364, :735, :820, :1098, file_tools.py:942)

Every other rejection in these tools calls path_validator.audit_write(..., "denied", reason) before returning; the stale path returns straight out. A rejected overwrite of an allowlisted file leaves no audit trace. Worth a single audit_write("write", path, content_size, "denied", "stale") alongside the return, or a deliberate note that ledger rejections are out of audit scope.

🟢 Stale error from file_tools.write_file drops the operation key (src/gaia/agents/tools/file_tools.py:942)

Every other error return in that tool carries "operation": "write_file"; the shared _error payload doesn't. Callers keying off operation will see a gap.

🟢 Spec omits edit_python_file (docs/spec/file-io-tools-mixin.mdx:12)

edit_python_file routes through apply_unique_replacement (file_io_tools.py:472) and is guarded too, but the new "Concurrent file changes" list names only edit_file.

Strengths

  • Hoisting the check into check_file_state and having apply_unique_replacement call it removes the duplicate divergence logic rather than adding a second copy — the ledger semantics stay in one place.
  • Guard placement is right everywhere: after path/permission validation, before create_backup and before any open-for-write. test_denied_write_does_not_read_current_contents pins that ordering so a future refactor can't invert it.
  • backup_path = None moving out of the if path_validator is not None: block also removes a latent unbound-local hazard in the no-validator path.
  • The parametrized writer fixture exercises all six mutation tools against real temp files (stale reject, re-anchored retry, unread file, missing file) instead of mocking the filesystem.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Merged current main into this branch; it's up to date and conflict-free again.

The conflicts were the three whole-file writers in FileIOToolsMixin. main (#3337) made a path validator mandatory: without one, these tools now refuse instead of writing unchecked. So each tool now validates the write first, then runs this PR's stale-file check, then backs up and writes. A stale write is still rejected before any backup or write happens.

🔍 Technical details
  • Merge commit ba0bd2e4 (main at 1a4cccaa).
  • src/gaia/agents/tools/file_io_tools.py, three blocks: write_python_file, write_markdown_file and write_file. Kept main's validate_write + denied-audit path and inserted check_file_state(...) between it and the backup. The branch's path_validator is not None guard on the backup was dropped because main returns early when the validator is missing.
  • Auto-merged and reviewed:
    • update_gaia_md and replace_function checks sit after main's allowlist/blocklist checks.
    • FileSearchToolsMixin.write_file keeps its optional validator, which main didn't change.
    • Main's paged read_file (fix(agent): bound tool output and recover omitted evidence #3670) doesn't record a read, so a page never becomes the baseline for a whole-file write.
  • Tests, with Lemonade pointed at a dead port: file write-state, edit semantics, write-display, write guardrails, file-IO confinement, directory-path errors, file tools, access/search scope, host-attribute contract, replace_function spans, builder host wiring, output artifacts and large-result truncation: 685 passed, 4 skipped. tests/test_chat_agent.py: 17 of its indexing tests need a live embedding server and fail the same way on main; the other 30 pass. Black, isort and pylint (unused/undefined names) clean; internal doc links valid.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Refreshed this branch against current main so it can merge again — the branch had fallen far enough behind that GitHub could no longer compute a merge.

The update was a clean merge: nothing was resolved by hand, and no commit on this branch was rewritten. CI now runs against an up-to-date base.

A stale-write rejection returned without touching the write audit log, so an overwrite blocked by the read ledger left no trace next to every other denial. The search mixin's stale error also dropped the operation key its other errors carry, and the spec omitted edit_python_file from the guarded list.
@itomek

itomek commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

Picked up the three open points from the review and refreshed the branch against current main.

A blocked overwrite now leaves an audit trail. Previously, when the read ledger rejected a stale whole-file write, it returned without recording anything — so the one denial that means "someone else's work was nearly lost" was the only denial missing from the write audit log. It now records as denied/stale alongside every other rejection, and a test asserts it per tool rather than trusting it.

The earlier truncated-overwrite concern was already handled by 67d1d806, which tells the model the payload is a bounded excerpt and to re-read before rewriting.

🔍 Technical details
  • audit_write(..., "denied", "stale") added at all six check_file_state rejection sites: file_io_tools.py (write_python_file, write_markdown_file, write_file, update_gaia_md, replace_function) and file_tools.py (FileSearchToolsMixin.write_file). Operation string and size argument match each site's existing audit call — "edit" for replace_function, "write" elsewhere. Guarded on path_validator is not None in the search mixin, which still allows an absent validator.
  • file_tools.write_file's stale return now carries "operation": "write_file" like its other error returns. Merged at the call site rather than into the shared _error() in file_edit.py, which serves tools with different operation names.
  • Spec's "Concurrent file changes" list now includes edit_python_file — it routes through apply_unique_replacement, so it was already guarded, just undocumented.
  • test_stale_write_is_recorded_as_a_denied_audit_entry asserts exactly one denied entry, its operation string, its path and reason, across all six parametrized tools. test_denied_write_does_not_read_current_contents still passes, so the permission check still precedes the ledger check.

Verified locally on Python 3.12.3:

  • tests/unit/agents/test_file_write_state.py — 42 passed
  • tests/unit/agents/ — 1365 passed, 50 skipped
  • 9 file access/IO/guardrail suites under tests/unit/ — 526 passed, 4 skipped
  • black, isort clean; pylint (undefined/unbound/unused, bad arg counts) exit 0

Also checked against util/check_test_lane_coverage.py, new on main: the 43 files it flags are all pre-existing and this PR's test file is not among them.

@itomek itomek left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving. This closes both halves of #3568 — the write tools now check the read ledger before overwriting, and replace_function / update_gaia_md now record their writes so the next edit isn't rejected as someone else's change.

CI matches main exactly: the two test_chat_system_prompt_owner failures are main's own breakage (a deleted openai_provider module still imported by that test, from #3899), not this branch. The py3.12 leg died on a runner shutdown signal at 38% with no test failures before it. py3.10 ran the full suite: 14312 passed, with only those two pre-existing failures.

@itomek
itomek added this pull request to the merge queue Sep 24, 2026
Merged via the queue into amd:main with commit c98ca71 Sep 24, 2026
34 of 37 checks passed
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
main's amd#3656 added a content-hash stale-write guard to the very tools this
branch re-implements. `FileReadRecord` already refuses both cases amd#3656 cared
about — a file changed on disk since the read, and (unlike amd#3656) one never read
at all — so the hash ledger goes and the read record stays.

Two things amd#3656 contributed that the auto-merge would have dropped:

- **The denied-write audit entries.** Every refusal now logs `audit_write(...,
  "denied", <error_type>)` the way the stale guard did, so a refused overwrite
  is still visible in the audit trail. Covered by TestRefusalIsAudited.
- **Nothing else.** `tests/unit/agents/test_file_write_state.py` is deleted: it
  pins the old contract, including `test_unread_existing_file_still_writes`,
  which is exactly the behaviour this branch removes.

Three call sites in file_io_tools.py and file_tools.py auto-merged main's
`check_file_state` block in *alongside* the branch's `reads.refusal(...)`
without conflicting — duplicate guards that only the import error surfaced.

Docs: the "Concurrent file changes" section still described `stale: true` and
content hashes, neither of which this branch returns; it now points at
"Read before edit". Same for the file-search mixin's cross-reference.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The file-state tracker only guards edit_file — every write tool can still clobber a changed file

3 participants