Skip to content

Comments

fix(utils): prevent ERR_STREAM_WRITE_AFTER_END crash during log rotation#150

Merged
8nevil8 merged 1 commit intomainfrom
fix/logger-rotation-race-condition
Feb 16, 2026
Merged

fix(utils): prevent ERR_STREAM_WRITE_AFTER_END crash during log rotation#150
8nevil8 merged 1 commit intomainfrom
fix/logger-rotation-race-condition

Conversation

@8nevil8
Copy link
Collaborator

@8nevil8 8nevil8 commented Feb 16, 2026

Summary

Fixes a critical race condition in the logger's date-based log rotation that caused ERR_STREAM_WRITE_AFTER_END crashes when Claude sessions crossed midnight. The issue occurred because log rotation was fired asynchronously (fire-and-forget pattern) while the write operation continued immediately, racing against stream closure.

Changes

  • Added defensive checks in writeToLogFile(): Check isRotating flag and stream.writable property before writing to prevent writes during rotation
  • Enhanced close() method: Made async and added wait logic (max 5 seconds with 100ms polling) for in-progress rotation to complete
  • Added comprehensive comments: Documented the race condition scenario and prevention strategy

Impact

Before:

  • Long-running Claude sessions that crossed midnight would crash with ERR_STREAM_WRITE_AFTER_END
  • Application terminated unexpectedly, losing work in progress

After:

  • Sessions continue smoothly through midnight log rotation
  • May skip 1-2 log entries during rotation window (acceptable trade-off vs crash)
  • Proper cleanup sequencing prevents race conditions

Checklist

  • Self-reviewed
  • Manual testing performed (build + lint passed)
  • Documentation updated (inline comments added)
  • No breaking changes

Fixes race condition in date-based log rotation that caused crashes when
Claude sessions crossed midnight. The async rotation fired but writeToLogFile
continued to write to the stream being closed, causing stream write-after-end errors.

Changes:
- Add defensive checks in writeToLogFile() to skip writes during rotation
- Check isRotating flag and stream.writable property before writing
- Enhance close() method to wait for in-progress rotation (max 5 seconds)
- Add detailed comments explaining the race condition scenario

Impact: Prevents application crashes in long-running sessions that span midnight.
Trade-off: May skip 1-2 log entries during rotation (acceptable vs crash).

Generated with AI

Co-Authored-By: codemie-ai <codemie.ai@gmail.com>
@8nevil8 8nevil8 merged commit e40fcc7 into main Feb 16, 2026
5 checks passed
@8nevil8 8nevil8 deleted the fix/logger-rotation-race-condition branch February 16, 2026 09:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant