Skip to content

Comments

Guard disk logging and clarify clone/role utilities#33

Merged
riatzukiza merged 2 commits intostagingfrom
chore/guard-logging-clones
Nov 20, 2025
Merged

Guard disk logging and clarify clone/role utilities#33
riatzukiza merged 2 commits intostagingfrom
chore/guard-logging-clones

Conversation

@riatzukiza
Copy link
Collaborator

Summary

  • gate all disk logging behind logging/debug flags and adjust logger tests accordingly
  • document JSON-only cloning, enforce array input for cloneInputItems, and prevent silent role stripping
  • add note to align session prompt cache key derivation with request-transformer logic

Testing

  • pnpm test
  • pnpm test:coverage

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 20, 2025

Summary by CodeRabbit

Release Notes

  • Performance

    • Optimized logging to conditionally write based on system settings, reducing unnecessary I/O operations.
  • Improvements

    • Enhanced input validation with more flexible role formatting.
    • Improved handling of null and undefined inputs in data cloning utilities.
  • Tests

    • Expanded test coverage for logging behavior across various configuration scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Logging persistence and rolling-log appends are now performed only when LOGGING_ENABLED or DEBUG_ENABLED is true. A buildPromptCacheKey helper was added to session manager. cloneInputItems gained null/undefined safety and validation. formatRole now trims and accepts any non-empty role. Tests expanded for logging scenarios.

Changes

Cohort / File(s) Summary
Logging Control Flow
lib/logger.ts
Gate request payload persistence and rolling-log append behind LOGGING_ENABLED or DEBUG_ENABLED; avoid disk I/O when both flags are false; adjust error/path handling accordingly.
Session & Cache Key
lib/session/session-manager.ts
Add buildPromptCacheKey(conversationId, forkId) to consistently compute/sanitize prompt cache keys; comment notes alignment with request-transformer.ts.
Clone Utilities
lib/utils/clone.ts
`cloneInputItems(items?: T[]
Input-item Normalization
lib/utils/input-item-utils.ts
formatRole trims input, treats null as empty, returns empty string for blank input, and otherwise returns the normalized trimmed role (no strict whitelist).
Tests — Logger
test/logger.test.ts
Restructure spies to beforeEach/afterEach, reset modules/env between tests, rename tests, and add coverage for disabled logging, debug-enabled behavior, persist failures, rotation and queue overflow with logging flags toggled.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Req as Request
  participant Logger as lib/logger
  participant FS as FileSystem
  Note over Logger: Decision: LOGGING_ENABLED || DEBUG_ENABLED
  Req->>Logger: logRequest(payload)
  alt Logging enabled (LOGGING_ENABLED || DEBUG_ENABLED)
    Logger->>FS: write stage file
    Logger->>FS: append to rolling log
    Logger-->>Req: success
  else Logging disabled
    Logger-->>Req: skip disk writes
    Logger-->>Req: no rolling log append
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Areas to focus review on:

  • lib/logger.ts: verify flag evaluation, edge error paths, and tests correctly mock file I/O.
  • lib/utils/clone.ts: ensure validation message and behavior align with callers.
  • lib/utils/input-item-utils.ts: confirm relaxed role handling won't break downstream consumers.
  • lib/session/session-manager.ts: confirm cache-key sanitation matches request-transformer logic.

Possibly related PRs

Poem

🎛️ Flags decide if logs may sleep or sing,
Keys are shaped with careful trimming.
Nulls fold gently, roles now roam,
Tests stand ready to guard the home,
Small changes hum — a steadier ring.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: guarding disk logging behind flags and clarifying clone/role utilities, matching the changeset's primary objectives.
Description check ✅ Passed The description is directly related to the changeset, covering all three main areas: logging guards, clone/role utilities, and session cache alignment with appropriate testing guidance.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/guard-logging-clones

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 96a80ad and 1184c21.

⛔ Files ignored due to path filters (1)
  • spec/pr-33-coderabbit-review.md is excluded by none and included by none
📒 Files selected for processing (1)
  • lib/utils/input-item-utils.ts (1 hunks)
🔇 Additional comments (1)
lib/utils/input-item-utils.ts (1)

43-47: The review comment is based on incorrect assumptions about code usage.

The exported formatRole function from input-item-utils.ts is not actually used anywhere in the codebase. The only call to formatRole at line 66 in codex-compaction.ts invokes a different, local formatRole function (defined at line 141 in the same file) that has strict validation—it only accepts "user" or "assistant" roles and returns null for anything else.

The original review's concerns about:

  • Invalid roles flowing to downstream validation functions
  • Lack of safety guardrails causing silent failures

...do not apply here because the local formatRole in codex-compaction.ts already enforces the validation that was removed from the exported function.

The exported formatRole appears to be either dead code or intended for future use, but it's not currently impacting role handling in the codebase.

Likely an incorrect or invalid review comment.


Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 23cee90 and 96a80ad.

📒 Files selected for processing (5)
  • lib/logger.ts (2 hunks)
  • lib/session/session-manager.ts (1 hunks)
  • lib/utils/clone.ts (2 hunks)
  • lib/utils/input-item-utils.ts (1 hunks)
  • test/logger.test.ts (8 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
test/logger.test.ts (1)
lib/logger.ts (3)
  • logRequest (70-87)
  • flushRollingLogsForTest (105-110)
  • logInfo (93-95)
🔇 Additional comments (10)
lib/session/session-manager.ts (1)

153-161: LGTM: Cache key alignment comment is helpful.

The synchronization comment and the buildPromptCacheKey helper clarify the intent to maintain identical cache key derivation across session-managed and stateless flows. The implementation correctly sanitizes the conversation ID and appends fork information when present.

lib/utils/clone.ts (2)

10-10: LGTM: JSON-serializable note clarifies intent.

The added comment appropriately documents that deepClone is intended for JSON-serializable data, which aligns with the implementation using structuredClone or JSON.parse(JSON.stringify()).


31-42: LGTM: Input validation improves type safety.

The signature change to accept optional/null inputs with defensive validation prevents silent failures. Returning an empty array for null/undefined inputs is sensible, and throwing a TypeError for non-array inputs catches misuse early.

lib/logger.ts (2)

77-78: LGTM: Request logging properly gated.

Disk persistence is now conditional on LOGGING_ENABLED || DEBUG_ENABLED, which correctly implements the PR objective to gate all disk logging behind feature flags. This prevents unnecessary I/O when logging is disabled.


122-124: LGTM: Rolling log writes properly gated.

The conditional append to the rolling log ensures that disk writes only occur when logging is enabled, completing the disk I/O gating strategy for the logger module.

test/logger.test.ts (5)

33-64: LGTM: Test setup improved with proper spy lifecycle.

Moving spy declarations to let with initialization in beforeEach and adding afterEach cleanup ensures proper test isolation and prevents spy leakage between tests.


73-96: LGTM: Test correctly validates enabled logging behavior.

The test name update and explicit flag setting clearly document that disk writes occur only when logging is enabled, with proper assertions for both request stage files and rolling log appends.


98-107: LGTM: New test validates disabled logging behavior.

This test correctly verifies that when logging is disabled (no environment flags set), neither writeFile nor appendFile are called, confirming the gating logic works as intended.


109-119: LGTM: Test validates conditional rolling log behavior.

The test properly verifies that debug messages append to the rolling log only when ENABLE_PLUGIN_REQUEST_LOGGING is set, and that console logging remains suppressed in the test environment.


131-148: LGTM: Test validates logInfo behavior across configurations.

The test correctly verifies that info-level messages don't emit to console in test environments regardless of debug flags, while confirming that disk logging still occurs when the debug flag is enabled.

- Remove hardcoded role whitelist in formatRole()
- Return normalized role directly without validation
- Add PR review documentation for CodeRabbit feedback
@riatzukiza riatzukiza merged commit 2caf840 into staging Nov 20, 2025
11 checks passed
@riatzukiza riatzukiza deleted the chore/guard-logging-clones branch November 20, 2025 05:41
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