Skip to content

fix: initialize log_written from file size to prevent 2x cap drift#16

Open
ricardovfreixo wants to merge 1 commit intomobydeck:mainfrom
ricardovfreixo:fix/double-log-cap-drift
Open

fix: initialize log_written from file size to prevent 2x cap drift#16
ricardovfreixo wants to merge 1 commit intomobydeck:mainfrom
ricardovfreixo:fix/double-log-cap-drift

Conversation

@ricardovfreixo
Copy link

Summary

The on-disk session log can grow to twice the configured -C cap before rotation kicks in.

Root cause

log_written tracks bytes written since the last rotation, not the actual file size. After open_log(), the file can already contain up to log_max_size bytes (trimmed by rotate_log()), but log_written is initialized to 0. Rotation only triggers when log_written >= log_max_size, so another full log_max_size of data is appended before the check fires.

Timeline with -C 512k:

open_log()
  → rotate_log() trims file to 512KB
  → log_written = 0          ← bug: should reflect current file size

... 512KB of pty output ...

  → log_written = 512KB
  → file is now 1MB (2x cap)  ← rotation finally triggers
  → rotate_log() trims back to 512KB

Fix

Initialize log_written from the fd position after rotate_log() in open_log(), so the counter reflects the actual file size from the start:

log_fd = fd;
rotate_log();
log_written = (size_t)lseek(log_fd, 0, SEEK_CUR);

Single line change, no new syscall overhead (piggybacks on the position rotate_log() already established via its final lseek(log_fd, 0, SEEK_END)).

Test plan

  • Start a session with a small cap: atch new test -C 64k -- sh -c 'cat /dev/urandom | base64'
  • Let it run until well past 64KB of output, then detach
  • Check file size: ls -la ~/.cache/atch/test.log — should be at most ~64KB (plus one write batch), not ~128KB
  • Reattach, generate more output, detach again — file should stay near the cap
  • Verify session replay still works: atch test shows recent output, not truncated mid-sequence
  • Build with make clean && make — no new warnings

log_written tracked bytes since last rotation, not actual file size.
After open_log(), the file could already hold log_max_size bytes but
log_written started at 0, so another log_max_size was written before
rotation triggered. Initialize log_written from the fd position after
rotate_log() so the counter reflects reality.
@ricardovfreixo ricardovfreixo force-pushed the fix/double-log-cap-drift branch from 010e671 to a6f6c7f Compare March 13, 2026 07:08
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