Skip to content

fix(security): refuse an overwrite when its backup can't be made - #4314

Merged
kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:claude/refuse-write-on-backup-failure
Sep 26, 2026
Merged

kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:claude/refuse-write-on-backup-failure

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Before: when the backup failed (full disk, or a cache directory GAIA can't write), the overwrite went ahead anyway. The tool result looked exactly like a backed-up write, even though the Agent UI auto-approves overwrites because it expects a backup. After: the write is refused, the file is left unchanged, and the error names the cause and the fix. Backup names also carry microseconds now, so two edits in the same second keep two backups instead of one overwriting the other.

Overlaps with #4029, which edits nearby lines in file_io_tools.py but doesn't change backup behaviour. Whichever merges second needs a small rebase.

Test plan

  • pytest tests/unit/test_file_write_guardrails.py tests/unit/test_security_edge_cases.py -q → 166 passed, 7 skipped. 4 new tests fail on main: a failed backup raises, write_file refuses (tested in both file-tool mixins), and two same-second backups don't collide.
  • Neighbouring file-tool suites (16 files, including test_file_tools.py, test_file_io_confinement.py, and agents/test_file_write_state.py) → 716 passed, 7 skipped
  • black, isort, and flake8 on the changed files; pylint on security.py (exit 0)
  • gaia eval agent: a failed backup now returns a different tool result to the model

Fixes #4232

Overwrites went ahead when the backup failed (full disk, unwritable cache), and
the tool result looked identical to a backed-up write, even though the Agent UI
auto-approves overwrites on the promise of that backup. Now the write is
refused with an error naming the cause, and the file is left unchanged.

- backup_file raises BackupError instead of returning None, so "nothing to
  back up" and "backup failed" are no longer the same answer; every file tool
  already turns the exception into a status=error result before writing.
- Backup names carry microseconds and step past an existing name, so two
  edits in the same second keep two generations instead of clobbering one.
  The prune pattern still matches the older second-resolution names.

Fixes amd#4232
@github-actions github-actions Bot added documentation Documentation changes tests Test changes security Security-sensitive changes labels Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

Good fix, and the right instinct: an overwrite auto-approved on the promise of a backup must not proceed when that promise can't be kept. One follow-on effect needs handling before merge.

The blocking issue — a full disk teaches the agent a permanent lie. The new refusal comes back as a plain error, and GAIA's memory layer can't tell "this tool is refusing, nothing ran" from "this tool ran and failed." So a one-off disk-full or unwritable-cache moment gets written into the agent's long-term memory as a durable "writing this file is broken" lesson, replayed into every later prompt long after the disk is freed. Refusals elsewhere in these same tools already declare themselves as not-executed; this one needs to as well.

Two smaller things worth fixing in the same pass: a copy that dies partway through leaves a truncated backup file sitting in the keep-the-newest-five rotation, where it can push out a good backup and later look like a valid restore point; and the new "no backup, no write" guarantee is documented for some of the file tools but not the others that now behave the same way.

Real-world evidence

N/A — no evidence bundle was produced for this run, and the change is a core library behaviour with no new CLI, REST, or Agent UI surface. The verdict rests on static review plus the unit tests the PR adds; I could not execute them here (no pytest in this environment), so the PR's own "166 passed" result is the only test signal. The unchecked gaia eval agent item is the real gap: this change alters what a write tool hands back to the model, which is the kind of thing unit tests don't measure.

🔍 Technical details

🟡 A backup refusal is stored as durable agent knowledge

BackupError reaches the model as {"status": "error", "error": ...} with no executed key. check_was_executed (src/gaia/agents/base/verification.py:201) then defaults it to executed, so MemoryMixin._auto_store_error (src/gaia/agents/base/memory.py:2747) persists it under "Known errors to avoid". "No space left on device" and "Permission denied" match none of _TRANSIENT_ERROR_MARKERS, so nothing filters it — the exact failure mode that comment block warns about (a since-fixed run_shell_command hang that kept telling users the shell was unavailable).

The validate_write denial three lines above each create_backup call already spreads NOT_EXECUTED; this refusal is the same shape and should too. Add a handler ahead of the existing except Exception in each enclosing tool:

except BackupError as e:
    path_validator.audit_write("write", str(file_path), 0, "denied", str(e))
    return {**NOT_EXECUTED, "status": "error", "error": str(e)}

All eight call sites: src/gaia/agents/tools/file_io_tools.py:473,627,857,956,1109,1377 and src/gaia/agents/tools/file_tools.py:1261,1646. file_io_tools.py doesn't import NOT_EXECUTED yet; file_tools.py does.

Worth a test asserting result["executed"] is False alongside the two new refusal tests.

🟡 A half-written backup survives the failure it caused (src/gaia/security.py:1093)

shutil.copy2 opens the destination and streams into it, so an ENOSPC mid-copy — the headline scenario in the error message — leaves a truncated .bak on disk. The write is correctly refused, but that stub still matches stamped and counts as a generation, so it can evict a real backup from the newest-five rotation, and a user restoring from it gets a silently truncated file.

    except OSError as e:
        logger.error("Failed to back up %s to %s: %s", real_path, backup_path, e)
        # A copy that died mid-stream leaves a truncated .bak in the rotation.
        with contextlib.suppress(OSError):
            backup_path.unlink(missing_ok=True)
        raise BackupError(
            f"Refused to modify {real_path}: backing it up to {backup_path} "
            f"failed ({e}). Nothing was written. Free disk space or make "
            f"{root} writable, then retry."
        ) from e

(needs import contextlib)

🟢 The linked doc section doesn't carry the new guarantee

docs/spec/file-search-mixin.mdx:29 states the refusal in the paragraph that links to /spec/file-io-tools-mixin#concurrent-file-changes — but that target section (docs/spec/file-io-tools-mixin.mdx:30) doesn't mention it. A reader following the link lands somewhere that still only discusses stale state.

🟢 Four write tools changed behaviour without a doc update

write_python_file (:119), write_file (:216), edit_file (:236), and write_markdown_file (:331) in docs/spec/file-io-tools-mixin.mdx all refuse on a failed backup now, but only the two sections with a backup parameter were updated. One shared sentence in "Concurrent file changes" would cover all six.

🟢 Only the write_file refusal is tested

The new tests cover write_file in both mixins. The edit paths (edit_file, edit_python_file, replace_function) route through the same create_backup call and would benefit from one parametrized case rather than four copies.

Strengths

  • The core call is right, and matches CLAUDE.md's fail-loudly rule precisely: None meant two different things, and collapsing "nothing to back up" into "backup failed" is exactly the silent degradation that rule exists to stop. The Raises: docstrings and the _prompt_overwrite comment update keep the auto-approve rationale honest.
  • The error text names the cause, the fix, and the directory to make writable — an actionable error by the project's own three-part definition.
  • The microsecond fix is careful in both directions: the step-past-an-existing-name loop closes the clobber window (real on Windows' ~15ms clock), and making the microseconds group optional in the prune regex keeps pre-existing second-resolution backups collectable instead of orphaning them.
  • The test rewrite is an improvement on what it replaced — the old test_multiple_backups_have_unique_names asserted a collision couldn't be tested and checked os.path.exists instead; the frozen-clock version actually proves the property.

A full disk taught the agent a lasting lie. The refusal came back as a plain
{"status": "error"}, and check_was_executed defaults a result with no executed
key to "it ran and failed" — so MemoryMixin stored a one-off ENOSPC under
"Known errors to avoid" and replayed it into every later prompt, long after
the disk was freed. Neither "No space left on device" nor "Permission denied"
matches a transient marker, so nothing filtered it out.

All eight tools that back up before writing now spread NOT_EXECUTED into the
refusal, the same as the validate_write denial directly above each of them.

A copy that died mid-stream also left a truncated .bak behind. It still
matched the rotation glob, so it counted as a generation and could evict a
good backup, leaving the user restoring from a silently truncated file.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

The blocking issue was real and is fixed: a one-off full disk really would have been written into the agent's long-term memory as a durable "writing this file is broken" lesson.

I traced the whole path before changing anything. The refusal returned a bare {"status": "error"}; check_was_executed defaults a result with no executed key to it ran and failed; _auto_store_error therefore stored it under "Known errors to avoid"; and neither No space left on device nor Permission denied matches any transient marker, so nothing filtered it. All eight backup-guarded tools now declare the refusal as not-executed, matching the validate_write denial that sits a few lines above each one.

Also fixed the truncated-backup case — a copy that died mid-stream left a .bak that still counted as a generation, so it could evict a good backup and later look like a valid restore point.

Docs: rather than repeating the sentence per tool, the link target that was missing the guarantee (Concurrent file changes) now has a No backup, no write section covering all six file-I/O tools, including why the refusal carries executed: False.

Test evidence

Eleven tests fail on the pre-fix branch and pass after — the eight tool paths, the truncated backup, and the two existing refusal tests now that they assert the memory gate:

# before
11 failed, 124 passed, 4 skipped
# after
135 passed, 4 skipped

Broader sweep (13 files — file tools, security, memory, verification): 797 passed, 7 skipped, 1 failure unrelated and pre-existing (test_no_allowlist_still_defaults_to_cwd picks up a persistent allowlist leaking from another worktree; fails identically with the fix reverted). black + isort clean.

🔍 Technical details

All eight create_backup call sites now have a BackupError handler ahead of the existing catchall, verified by AST rather than by eye:

file_io_tools.py  write_python_file, edit_python_file, write_markdown_file,
                  write_file, edit_file, replace_function
file_tools.py     write_file, edit_file

In file_tools.py:1262 the handler is placed before PermissionError/FileNotFoundError/OSError — BackupError is a RuntimeError, so it would otherwise have fallen through to except Exception. Both files import BackupError at module level; gaia.security imports only stdlib, so there is no circularity.

The new test class TestFailedBackupIsNotLearned is parametrized over all eight tool paths and asserts the gate _auto_store_error actually consults, not just the status:

assert result["executed"] is False
assert not check_was_executed(result)

test_a_copy_that_dies_mid_stream_leaves_no_partial_backup patches copy2 to write a short file and then raise ENOSPC, and asserts the good backup is the only survivor in the mirror directory — the old code left the stub in the five-generation rotation.

I did not take the suggestion to collapse the edit-path tests into one parametrized case separate from the write paths; the single parametrization above covers all eight in one test instead.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit a711f84 Sep 26, 2026
41 of 42 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/refuse-write-on-backup-failure branch September 26, 2026 04:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes security Security-sensitive changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(files): overwrites proceed when the backup fails

2 participants