Skip to content

feat(log): rotate messages.jsonl when over threshold (Joel's audit 2026-04-28) - #248

Merged
joelteply merged 1 commit into
canaryfrom
feat/messages-jsonl-rotation
Apr 28, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/messages-jsonl-rotation

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Trim-in-place rotation via airc_core.log; wired to heartbeat (host) + monitor_formatter mirror (joiner). Defaults 5000/2500 lines. Joiners with stale offsets caught by #245.

…26-04-28)

Without rotation, the host's log + every joiner's local mirror grew
forever. Joel: 'is messages.log ever getting trimmed down? it could
over time consume the editor/reader if it isnt draining or cycling.'
Answer was no — confirmed by grep, no trim/rotate logic anywhere.

## Fix

New \`airc_core.log\` module: \`rotate_if_needed(path, max, keep)\` —
trim in place via tempfile + atomic rename. POSIX rename on
mac/linux/wsl; Windows fallback to remove-then-rename with a tiny
race window.

Wired in two periodic call sites:
- \`cmd_connect.sh\` heartbeat loop (host side, every 30s)
- \`monitor_formatter.py\` joiner mirror (every 100 mirrored lines)

Defaults: max 5000 lines, keep last 2500. Override via
\`AIRC_LOG_MAX_LINES\` / \`AIRC_LOG_KEEP_LINES\`.

## Why trim-in-place (not archive)

Chat history is conversational, not a permanent record; \`airc logs N\`
only ever shows the tail. Joiners with offsets pointing to discarded
lines are caught by #245's stale-offset detection (offset > current
line count → reset to EOF). New SSH-tail starts fresh on the trimmed
file via \`tail -F\`'s reopen-on-replace.

## Verification

- \`bash -n\` clean on cmd_connect.sh
- \`python ast.parse\` clean on log.py + monitor_formatter.py
- Standalone smoke: 10-line file rotated to last 3 with explicit
  \`max=5 keep=3\` flags — outputs 'line 8 / line 9 / line 10' ✓
- \`test/integration.sh tabs\`:  19/0 ✓
- \`test/integration.sh queue\`: 7/0 ✓

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 28, 2026 22:50
@joelteply
joelteply merged commit effd4c0 into canary Apr 28, 2026
@joelteply
joelteply deleted the feat/messages-jsonl-rotation branch April 28, 2026 22:50

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Adds automatic rotation (trim-in-place) for messages.jsonl to prevent unbounded log growth on both hosts and joiners, wiring rotation into the host heartbeat loop and the joiner-side monitor mirror.

Changes:

  • Introduce lib/airc_core/log.py with rotate_if_needed() and a python -m airc_core.log rotate CLI.
  • Call rotation from the host heartbeat loop in cmd_connect.sh (defaults 5000 max / 2500 keep lines).
  • Call rotation periodically on joiners while mirroring remote log lines in monitor_formatter.py.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 6 comments.

File Description
lib/airc_core/monitor_formatter.py Periodically rotates joiner-side mirrored messages.jsonl while tailing host output.
lib/airc_core/log.py New rotation implementation + CLI entrypoint for trimming messages.jsonl.
lib/airc_bash/cmd_connect.sh Runs rotation on the host during the heartbeat loop to cap log size over time.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread lib/airc_core/log.py
Comment on lines +45 to +60
if max_lines <= keep_lines:
# Caller bug — keep_lines must leave headroom or we'd rotate
# on every append. Fail loud rather than silently.
return "error"
if not os.path.isfile(path):
return "noop"
try:
with open(path, "rb") as f:
lines = f.readlines()
except OSError:
return "error"
if len(lines) <= max_lines:
return "noop"

# Keep the tail. Rebuild the file via an atomic rename.
tail = lines[-keep_lines:]

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

keep_lines can be 0 or negative (e.g., via CLI/env). In Python slicing, lines[-0:] becomes lines[0:], so rotation will not trim anything even though the file exceeded max_lines. Add explicit validation that keep_lines is >= 1 (and ideally max_lines >= 1 too) and return/raise an error when invalid.

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/log.py
Comment on lines +66 to +74
try:
os.rename(tmp, path)
except OSError:
# Windows / cross-volume fallback: remove then rename.
# Tiny race window — concurrent writers may lose one line.
try:
os.remove(path)
os.rename(tmp, path)
except OSError:

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

This uses os.rename(tmp, path) and then falls back to os.remove(path) + os.rename(tmp, path) on error. On Windows, Python provides os.replace(src, dst) specifically to atomically replace an existing destination; using it avoids the remove-then-rename race window (and avoids transient missing-file states for tailers/readers). Consider switching to os.replace and dropping the delete fallback.

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/log.py
Comment on lines +62 to +82
fd, tmp = tempfile.mkstemp(prefix=".airc-log.", dir=parent)
try:
with os.fdopen(fd, "wb") as f:
f.writelines(tail)
try:
os.rename(tmp, path)
except OSError:
# Windows / cross-volume fallback: remove then rename.
# Tiny race window — concurrent writers may lose one line.
try:
os.remove(path)
os.rename(tmp, path)
except OSError:
# Couldn't replace. Drop the tempfile and report.
try: os.unlink(tmp)
except OSError: pass
return "error"
except OSError:
try: os.unlink(tmp)
except OSError: pass
return "error"

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

tempfile.mkstemp() returns an open file descriptor; if os.fdopen(fd, "wb") fails (or any exception occurs before the fd is wrapped/closed), the fd can leak. To make the cleanup robust, ensure the raw fd is closed in all error paths (e.g., os.close(fd) in a finally if you don't successfully enter the with os.fdopen(...)).

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/log.py
"""airc messages.jsonl rotation.

Without rotation, the host's log + every joiner's local mirror grows
forever. Joel asked 2026-04-28: "is messages.log ever getting trimmed

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

Docstring mentions messages.log, but this module/CLI operates on messages.jsonl elsewhere in the codebase/PR. Consider updating the wording to avoid confusion for operators.

Suggested change
forever. Joel asked 2026-04-28: "is messages.log ever getting trimmed
forever. Joel asked 2026-04-28: "is messages.jsonl ever getting trimmed

Copilot uses AI. Check for mistakes.
Comment on lines +1345 to +1348
# Cheap no-op when under threshold.
"$AIRC_PYTHON" -m airc_core.log rotate --path "$_hb_messages" \
--max-lines "${AIRC_LOG_MAX_LINES:-5000}" \
--keep-lines "${AIRC_LOG_KEEP_LINES:-2500}" >/dev/null 2>&1 || true

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

This invocation suppresses both stdout/stderr and ignores the exit code (>/dev/null 2>&1 || true). If rotation fails (permissions, disk full, Windows replace failure, etc.), it will be silently missed even though the surrounding logic explicitly tracks/records heartbeat failures. Consider capturing stderr to the existing $_hb_stderr (or emitting a marker line into messages.jsonl) so repeated rotation failures are diagnosable.

Suggested change
# Cheap no-op when under threshold.
"$AIRC_PYTHON" -m airc_core.log rotate --path "$_hb_messages" \
--max-lines "${AIRC_LOG_MAX_LINES:-5000}" \
--keep-lines "${AIRC_LOG_KEEP_LINES:-2500}" >/dev/null 2>&1 || true
# Cheap no-op when under threshold, but record failures
# so repeated rotate problems are diagnosable.
if ! "$AIRC_PYTHON" -m airc_core.log rotate --path "$_hb_messages" \
--max-lines "${AIRC_LOG_MAX_LINES:-5000}" \
--keep-lines "${AIRC_LOG_KEEP_LINES:-2500}" >/dev/null 2>"$_hb_stderr"; then
local _rotate_stderr_tail; _rotate_stderr_tail=$(tail -1 "$_hb_stderr" 2>/dev/null | tr -d '\n' | tr '"' "'")
local _rotate_marker; _rotate_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[HOST ROTATE FAILED] messages.jsonl rotation failed. last stderr: %s"}' \
"$_hb_now" "$_hb_room" "${_rotate_stderr_tail:-<empty>}")
echo "$_rotate_marker" >> "$_hb_messages" 2>/dev/null || true
fi

Copilot uses AI. Check for mistakes.
Comment on lines +289 to +293
rotate_if_needed(
local_log,
int(os.environ.get("AIRC_LOG_MAX_LINES", "5000")),
int(os.environ.get("AIRC_LOG_KEEP_LINES", "2500")),
)

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

int(os.environ.get(...)) can raise ValueError if the env var is set to a non-integer (e.g., "5k"). Because this is swallowed by the broad except Exception: pass, joiner-side rotation will silently stop working. Consider parsing these env vars with a small helper that falls back to defaults on invalid values (or clamps to sane bounds).

Copilot uses AI. Check for mistakes.
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.

2 participants