#18724: fix(compaction): add defensive guards for undefined session.messages
agents
size: XS
Cluster:
Memory Management Enhancements
## Summary
- Add null guard in `sanitizeSessionHistory()` for undefined messages param
- Add `session.messages ?? []` guards in `compact.ts` before destructive operations
- Prevents `Cannot read properties of undefined (reading 'filter')` crash during compaction
## Problem
When running `/compact` or when auto-compaction triggers, the following crash can occur:
```
TypeError: Cannot read properties of undefined (reading 'filter')
```
This happens when `session.messages` is undefined in edge cases (e.g., corrupted session file, SDK edge case). The undefined value flows through to `defaultConvertToLlm` in pi-agent-core which calls `.filter()` on it without a null check.
## Root Cause
The compaction flow accesses `session.messages` directly without guarding against undefined:
1. `sanitizeSessionHistory({ messages: session.messages, ... })`
2. `[...session.messages]` spread operation
3. `session.messages.length` property access
If `session.messages` is undefined at any point, the crash occurs.
## Fix
Add defensive null coalescing (`?? []`) at:
1. **google.ts**: `sanitizeSessionHistory` - guard against undefined `params.messages`
2. **compact.ts**: Guard all `session.messages` accesses with null coalescing
## Related
- Similar to #3225 which fixed `Cannot read properties of undefined (reading 'length')` in `limitHistoryTurns`
- This PR adds the same pattern to additional code paths
## Test Plan
- [x] Lint passes (`pnpm lint`)
- [x] No TypeScript errors
- [ ] Manual testing with session that has undefined messages
- [ ] Existing compaction tests should continue to pass
<!-- greptile_comment -->
<h3>Greptile Summary</h3>
Adds defensive null-coalescing guards (`?? []`) for `session.messages` in the compaction flow to prevent `TypeError: Cannot read properties of undefined (reading 'filter')` crashes when session data is corrupted or `messages` is unexpectedly undefined.
- **`compact.ts`**: Guards `session.messages` accesses before and after compaction by caching into `sessionMessages` and `postCompactionMessages` local variables with `?? []` fallback
- **`google.ts`**: Guards `params.messages` inside `sanitizeSessionHistory()`, which protects all callers (including `run/attempt.ts`) from undefined messages at the function boundary
- Import reordering in both files (likely automated formatter output)
<h3>Confidence Score: 5/5</h3>
- This PR is safe to merge — it adds purely defensive null guards with no behavior change for the normal case.
- The changes are minimal and defensive: null-coalescing operators (`?? []`) that fall through to the existing behavior when `session.messages` is defined (the normal case). When `session.messages` is undefined (the bug case), the code now gracefully handles it with an empty array instead of crashing. Import reordering is cosmetic. No logic changes, no new dependencies, no risk of regression.
- No files require special attention.
<sub>Last reviewed commit: efc65f7</sub>
<!-- greptile_other_comments_section -->
<sub>(3/5) Reply to the agent's comments like "Can you suggest a fix for this @greptileai?" or ask follow-up questions!</sub>
<!-- /greptile_comment -->
Most Similar PRs
#22859: fix: guard against undefined fileOps properties in compaction safeg...
by miloudbelarebia · 2026-02-21
77.5%
#20038: (fix): Compaction: preserve recent context and sync session memory ...
by rodrigouroz · 2026-02-18
77.0%
#20851: fix: harden resolveUserPath and compact against undefined workspaceDir
by davidrudduck · 2026-02-19
76.5%
#15999: fix: handle null/undefined in activity feed filters
by pamnlambert · 2026-02-14
75.4%
#16915: fix: await compaction hooks with timeout to prevent cross-session d...
by maximalmargin · 2026-02-15
74.8%
#5817: fix: strip old images during compaction to prevent 413 session bloat
by jduartedj · 2026-02-01
74.4%
#18663: feat: progressive compaction escalation and mechanical flush fallback
by Adamya05 · 2026-02-16
74.4%
#23583: fix(agents): catch session JSONL write failures instead of crashing
by mohandshamada · 2026-02-22
74.3%
#10711: fix: cancel compaction instead of truncating history when summariza...
by DukeDeSouth · 2026-02-06
74.1%
#15945: fix(memory-flush): only write memoryFlushCompactionCount when compa...
by aldoeliacim · 2026-02-14
74.1%