rich icon indicating copy to clipboard operation
rich copied to clipboard

[BUG]Console.save_text clears recorded output when file write fails

Open sanjay3941 opened this issue 3 months ago • 10 comments

  • [x] I've checked the docs and closed issues for possible solutions.
  • [x] I can't find my issue in the FAQ.

Describe the bug

When using Console(record=True), calling save_text() with clear=True appears to clear the recorded console output even when the file cannot be successfully written.

Minimal Repoduction of the issue:

from rich.console import Console

console = Console(record=True)

console.print("IMPORTANT OUTPUT")

print("Before failed save:")
print(repr(console.export_text()))

try:
    console.save_text(
        r"Z:\this\path\should\not\exist\output.txt"
    )
except Exception as e:
    print("\nSave failed:")
    print(type(e).__name__, e)

print("\nAfter failed save:")
print(repr(console.export_text()))

The output: Before failed save: 'IMPORTANT OUTPUT\n'

Save failed: FileNotFoundError [Errno 2] No such file or directory: 'Z:\this\path\should\not\exist\output.txt'

After failed save: ''

The file was not successfully written, but the record output was also cleared.

i would expect the recorded output to remain available when the save fails since the output was not sucessfully persisted.

but i am not sure whether the current behavior is intentional or not .? if not could it be like the buffer could be preserved until the file write succeeds ?

Platform: Windows 11 Python 3.13 Powershell and VS code terminal

sanjay3941 avatar Aug 16 '26 16:08 sanjay3941

Hi @willmcgugan / @sanjay3941 , this looks like a valid bug. Can I take this up and work on a fix?

vardhans07 avatar Aug 17 '26 08:08 vardhans07

Hi @willmcgugan / @sanjay3941 ,

I have resolved this issue and added regression tests for save_text, save_html, and save_svg. The branch is ready in my fork here: https://github.com/vardhans07/rich/tree/fix-console-save-buffer-preservation

Since repository interactions are currently limited, please let me know once PRs can be opened or feel free to pull directly from the branch!

Image

Put together a fix for this and added regression tests. Here's a summary of what changed:

What was happening

save_text(), save_html(), and save_svg() were calling their export functions with clear=True right away. If the file write ran into an OSError (bad path, permission issues, etc.), the record buffer was already cleared in memory, causing permanent data loss.

Changes made

  1. Deferred buffer clearing (rich/console.py):
    • save_text, save_html, and save_svg now call export_* with clear=False.
    • self._record_buffer only gets wiped inside _record_buffer_lock once the file write actually finishes without error.
  2. Fixed export_svg():
    • Updated export_svg() so it properly checks the clear flag instead of clearing the buffer unconditionally.
  3. Tests (tests/test_console.py):
    • Added unit tests for save_text, save_html, and save_svg checking that the buffer stays intact if an exception is thrown during saving.
Image

vardhans07 avatar Aug 17 '26 18:08 vardhans07

Hey @willmcgugan — confirmed this is a real bug, with a root cause and a fix ready.

Root cause (rich/console.py, current master 9d8f9a3): save_text, save_html and save_svg all call their export_* helper with clear=clear before opening the target file. export_text runs del self._record_buffer[:] (L2220-2221) and only then does save_text do open(path, "w") (L2241). If the write raises (e.g. non-existent path → FileNotFoundError), the recording buffer is already gone. Same ordering in save_html (export clears at L2317-2318, open at L2349) and save_svg (L2471-2472 / L2641).

Reproduced on master:

Before failed save: 'IMPORTANT OUTPUT\n'
Save failed: FileNotFoundError ...
After failed save: ''

Proposed fix: export with clear=False, write the file, and only clear the buffer once the write succeeds (under _record_buffer_lock). This keeps the clear=True default semantics on the happy path but stops data loss when the write fails. Small regression tests for all three save_* methods pass, and the existing save/export tests still pass.

Would you be OK with me opening a PR for this? Per your AI_POLICY.md I'd flag it as AI-generated (Claude / Claude Code) and link back to this issue for your approval.

(Note: I see @vardhans07 above already has a branch for this — happy to defer to them if you'd rather they open it. Just let me know which you prefer.)

pacocartones avatar Aug 24 '26 04:08 pacocartones

Hi @pacocartones @willmcgugan,

Thanks! I am opening the PR now from my branch with the fix and regression tests.

vardhans07 avatar Aug 24 '26 04:08 vardhans07

Hi @willmcgugan,

I have the fix and regression tests ready, but I am unable to open a PR directly due to repository interaction limits.

Please pull directly from my branch: https://github.com/vardhans07/rich/tree/fix-console-save-buffer-preservation

Thanks!

3be33372b9f1d8fc4aff26689f45b83f8bb7daf9

vardhans07 avatar Aug 24 '26 04:08 vardhans07

Hi @willmcgugan,

Quick status update: My branch is fully complete and ready for review/merge: https://github.com/vardhans07/rich/tree/fix-console-save-buffer-preservation

Summary of what is included:

  • Buffer preservation fix: Wipes the buffer only after successful file writes across save_text, save_html, and save_svg under _record_buffer_lock.
  • Regression tests: Full unit tests covering all three save methods on write errors (all tests passing locally).
  • Project files: Updated CHANGELOG.md under [Unreleased] and added entry to CONTRIBUTORS.md.

Because repo interaction limits currently restrict non-collaborators from opening a direct PR, feel free to pull directly from my branch or let me know if access opens up. Thanks!

4df62fbd74570e133910560546498fea213314cd

vardhans07 avatar Aug 30 '26 10:08 vardhans07

Hi @willmcgugan,

I have implemented a clean fix and regression tests for this issue (addressing buffer data loss across save_text, save_html, and save_svg when file writing fails), along with handling PermissionError on os.getcwd() during import (#4201).

Proposed Fix:

  • In save_text, save_html, and save_svg: snapshot uffer_length = len(self._record_buffer) and export with clear=False.
  • After write_file.write(...) succeeds, clear only the exported snapshot via del self._record_buffer[:buffer_length] under _record_buffer_lock. This ensures:
    1. Failed writes preserve the entire buffer without data loss.
    2. Concurrent logs appended during disk I/O are never dropped.
  • In ich/init.py: catch (OSError, ValueError) so restricted environments raising PermissionError do not fail module import.
  • Added comprehensive unit tests in ests/test_console.py and ests/test_traceback.py (all passing).

The branch is ready on my fork: https://github.com/cf3901646/rich/tree/fix-save-error-buffer-retention

(Disclosed per AI_POLICY.md: Assisted by Antigravity AI pair programming agent)

cf3901646 avatar Sep 19 '26 07:09 cf3901646

@willmcgugan Just a gentle reminder that this exact implementation and regression test suite have been complete and available on my branch (https://github.com/vardhans07/rich/tree/fix-console-save-buffer-preservation) since two weeks ago. Ready to merge or open as a PR whenever interaction limits allow.

vardhans07 avatar Sep 19 '26 09:09 vardhans07

Hi @willmcgugan — I'd like to propose a fix for this data-loss bug and request your approval before opening a PR (per AI_POLICY.md, an AI-generated PR must link to an issue where the solution is approved by a maintainer).

Root cause In Console.save_text, the buffer is cleared before the file is written:

def save_text(self, path, *, clear=True, styles=False) -> None:
    text = self.export_text(clear=clear, styles=styles)   # <-- clears the record buffer here
    with open(path, "w", encoding="utf-8") as write_file:
        write_file.write(text)

When open()/write() raises (e.g. FileNotFoundError for a missing directory, or a permission error), the recorded output has already been discarded — so the user loses it even though nothing was persisted.

Proposed fix Export without clearing, write the file, and only clear the buffer after a successful write:

def save_text(self, path, *, clear=True, styles=False) -> None:
    text = self.export_text(clear=False, styles=styles)
    with open(path, "w", encoding="utf-8") as write_file:
        write_file.write(text)
    if clear:
        with self._record_buffer_lock:
            del self._record_buffer[:]

Verification Added a regression test (test_save_text_preserves_buffer_when_write_fails): after a failed save_text, export_text(clear=False) still contains the recorded output. It fails on the current code and passes with the fix; the existing test_save_text still passes.

This is an AI-assisted contribution — the PR will be labelled as AI-generated, name the agent used, and fill in the PR template as required. Could you confirm this approach is acceptable so I can open the PR? Thanks!

zhangxin524 avatar Sep 27 '26 12:09 zhangxin524