Skip to content

Fix NULL dereference in usUntilEarliestTimer when all timers are deleted - #4353

Closed
Yudis-bit wants to merge 2 commits into
valkey-io:unstablefrom
Yudis-bit:fix/ae-null-deref-all-timers-deleted
Closed

Yudis-bit wants to merge 2 commits into
valkey-io:unstablefrom
Yudis-bit:fix/ae-null-deref-all-timers-deleted

Conversation

@Yudis-bit

Copy link
Copy Markdown

Problem

When all time events in the event loop are lazy-deleted (id == AE_DELETED_EVENT_ID),
usUntilEarliestTimer() in src/ae.c dereferences a NULL earliest pointer.

Issue: #4349

Root Cause

The scan loop on lines 309-313 can leave earliest NULL when every remaining time event has id == AE_DELETED_EVENT_ID. The existing guard on line 307 handles the truly-empty list case (te == NULL), but the list can be non-empty yet contain only zombie events.

Fix

Add a single-line NULL guard after the scan loop:

if (earliest == NULL) return -1;

This is consistent with the existing empty-list guard on line 307 which also returns -1. The caller in aeProcessEvents() already handles -1 correctly (line 441: if (usUntilTimer >= 0)).

Regression Test

Added src/unit/test_ae.cpp with two tests:

  1. SurvivesWhenAllTimeEventsDeleted — creates time events, deletes them all, verifies no crash
  2. HandlesMixedDeletedAndActiveTimers — mixed state of deleted and active timers

Verification

  • Build: make -j4 succeeds
  • The fix is a single added line with no behavioral change for the normal case
  • The existing empty-list guard pattern validates the correctness of returning -1
  • CI will run the full test suite

Limitations

  • gtest was not available in the local environment for unit test compilation
  • The regression test (test_ae.cpp) is included but will be validated by CI
  • Tested on Linux x86_64 only

When all time events have been lazy-deleted (id == AE_DELETED_EVENT_ID),
the scan loop in usUntilEarliestTimer() leaves 'earliest' NULL.
Subsequent dereference of earliest->when causes a crash.

Add a NULL guard that returns -1 when no valid time events exist,
consistent with the existing empty-list guard on line 307.
The caller in aeProcessEvents() already handles -1 correctly.

Fixes: valkey-io#4349
Signed-off-by: Yudistira Putra <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4441015a-05d9-4e44-8ece-2b29ae3b8835

📥 Commits

Reviewing files that changed from the base of the PR and between 2dfee30 and 279c822.

📒 Files selected for processing (2)
  • src/ae.c
  • src/unit/test_ae.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/ae.c
  • src/unit/test_ae.cpp

📝 Walkthrough

Walkthrough

The event loop returns -1 when timer deletion leaves no valid timer. New tests cover fully deleted timers and mixed deleted and rescheduled timers across successive processing cycles.

Changes

Timer deletion safety

Layer / File(s) Summary
Guard empty timer state
src/ae.c
usUntilEarliestTimer returns -1 when no active timer remains.
Validate deleted timer processing
src/unit/test_ae.cpp
Tests cover self-deleting timers and mixed self-deleting and rescheduling timers across multiple event-processing cycles.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related issues

  • valkey-io/valkey issue 4349 — Covers the NULL dereference fixed by updating usUntilEarliestTimer and adding regression tests.

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the NULL dereference fix in usUntilEarliestTimer.
Description check ✅ Passed The description explains the NULL dereference, fix, regression tests, verification, and limitations, all of which match the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/unit/test_ae.cpp`:
- Line 31: Update the registered-time-event tests in src/unit/test_ae.cpp at
lines 31, 59, and 81: use aeProcessEvents with AE_TIME_EVENTS | AE_DONT_WAIT and
an inert file descriptor for the initial passive pass, then assert called1 and
called2 are both 1. Re-register the timers before the active pass and assert
each second callback executes, preventing aeApiPoll from blocking when no
descriptors or valid timers remain.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bb50021f-a134-4f71-9af1-fa1ae4048b18

📥 Commits

Reviewing files that changed from the base of the PR and between 2dfee30 and 853c5d0.

📒 Files selected for processing (2)
  • src/ae.c
  • src/unit/test_ae.cpp

Comment thread src/unit/test_ae.cpp Resolved

@valkey-review-bot valkey-review-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The src/ae.c guard is correct. Compiling ae.c with and without that one line and driving a loop whose only two time events were just lazy-deleted: the unpatched build segfaults on earliest->when in the next aeProcessEvents, the patched build completes. No concerns there.

The problem is the new unit test — as written, both cases block inside aeApiPoll, so make test-unit would hang instead of pass. Details inline.

Comment thread src/unit/test_ae.cpp Outdated
* Before the fix, this would dereference a NULL pointer and crash.
* After the fix, it should return -1 and the caller should handle it.
*/
aeProcessEvents(el, AE_TIME_EVENTS);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This call never returns. No file event is registered, so maxfd == -1 and, with AE_DONT_WAIT unset, aeProcessEvents takes the timer path at src/ae.c:441: usUntilEarliestTimer now returns -1 once every time event is deleted, tvp stays NULL, and aeApiPoll calls epoll_wait with a -1 timeout on an epoll set with no fds. I compiled both tests against the real ae.c and ran them — SurvivesWhenAllTimeEventsDeleted hangs indefinitely here, and HandlesMixedDeletedAndActiveTimers blocks ~1000 s at line 81 because noopProc reschedules 1000000 ms out. make test-unit never finishes either way.

Adding AE_DONT_WAIT is not the fix: src/ae.c:438 short-circuits before usUntilEarliestTimer is ever called, so the test then passes on unpatched ae.c too (verified) and covers nothing. What is needed is a poll that can return while still going through the timer path — e.g. a pipe left readable:

    static void readableNoop(aeEventLoop *el, int fd, void *privdata, int mask) { ... }

    int fds[2];
    ASSERT_EQ(pipe(fds), 0);
    ASSERT_EQ(write(fds[1], "x", 1), 1); /* keep fds[0] permanently readable */
    ASSERT_NE(aeCreateFileEvent(el, fds[0], AE_READABLE, readableNoop, NULL), AE_ERR);
    ...
    aeProcessEvents(el, AE_FILE_EVENTS | AE_TIME_EVENTS);

With that shape both passes return immediately, usUntilEarliestTimer still runs, and the test segfaults on unpatched ae.c and passes with the fix — which is what you want from the regression test. Same change is needed at line 81.

Comment thread src/unit/test_ae.cpp
Comment on lines +1 to +8
/*
* Test: ae event loop survives when all time events are deleted.
*
* This test verifies that aeProcessEvents() does not crash when
* all time events have been lazy-deleted (id == AE_DELETED_EVENT_ID).
* The bug was a NULL dereference in usUntilEarliestTimer() when the
* scan loop found no valid time events.
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Missing the standard file header — 29 of the 31 .cpp files in src/unit/ start with it.

Suggested change
/*
* Test: ae event loop survives when all time events are deleted.
*
* This test verifies that aeProcessEvents() does not crash when
* all time events have been lazy-deleted (id == AE_DELETED_EVENT_ID).
* The bug was a NULL dereference in usUntilEarliestTimer() when the
* scan loop found no valid time events.
*/
/*
* Copyright (c) Valkey Contributors
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* Test: ae event loop survives when all time events are deleted.
*
* This test verifies that aeProcessEvents() does not crash when
* all time events have been lazy-deleted (id == AE_DELETED_EVENT_ID).
* The bug was a NULL dereference in usUntilEarliestTimer() when the
* scan loop found no valid time events.
*/

@Yudis-bit

Copy link
Copy Markdown
Author

Thanks for the detailed review — the feedback was correct. The original test called aeProcessEvents with only AE_TIME_EVENTS, which blocks forever inside aeApiPoll when there are no file events and no valid timers (the poll has no timeout).

I updated the test to register an always-readable pipe as a file event so each aeProcessEvents call returns promptly.

Verified locally:

  • Without the ae.c NULL guard: SurvivesWhenAllTimeEventsDeleted segfaults (exit 139).
  • With the guard: both tests pass (exit 0).
[  PASSED  ] 2 tests.
All UNIT TESTS PASSED!

The original test called aeProcessEvents with only AE_TIME_EVENTS, which
blocks forever inside aeApiPoll when there are no file events and no
valid timers (the poll has no timeout). Register an always-readable pipe
as a file event so each aeProcessEvents call returns promptly.

Verified:
- Without the ae.c NULL guard, SurvivesWhenAllTimeEventsDeleted
  segfaults (exit 139).
- With the guard, both tests pass (exit 0).

Signed-off-by: Yudistira Putra <[email protected]>
@Yudis-bit
Yudis-bit force-pushed the fix/ae-null-deref-all-timers-deleted branch from 65d96bb to 279c822 Compare August 6, 2026 18:05
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

Comment thread src/unit/test_ae.cpp
@@ -0,0 +1,118 @@
/*

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I appreciate adding the unit test, but given this is untriggered code. I don't think we need this, I would just drop this file.

@royenheart

Copy link
Copy Markdown
Contributor

Thanks for pushing this forward, @Yudis-bit — and for linking #4349.

For context: we reported this bug in #4349 with a full reproducer (PoC + gdb backtrace) and a regression test. Since the report, analysis and reproducer came from our investigation, we'd appreciate it if you could add us as co-signers to the commit:

Signed-off-by: Haoze Xie [email protected]
Signed-off-by: Yuan Tan [email protected]

One thing worth the maintainers' attention: #4350 appeared 11 minutes after #4349 was filed, with a description closely mirroring the issue text, and its author has shown no engagement since — it also remains open despite the duplicate PRs, it also made us confused when it just opened 48 seconds earlier before our own pr #4351 (we opened it manually), thus making us closing our PR to avoid duplication. Whatever the explanation (the pattern is consistent with automated issue-watching), it may be worth consolidating on this PR and closing that one.

Happy to help with additional review or testing if needed.

@zuiderkwast

Copy link
Copy Markdown
Contributor

Replaced by #4351. @Yudis-bit Thanks for your effort! There are multiple duplicate PRs fixing the same issue.

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.

4 participants