Case Study: Resolving Complex Memory Corruption in Milvus Kernel using ASan
First published on Medium
Preface
I highly recommend that my Zilliz teammates use AddressSanitizer when writing unit tests for Milvus kernel components, as memory operations in high-performance database engines can be quite risky. Employing AddressSanitizer for our core codebase can significantly enhance the integrity and security of the Milvus system. In this essay, I will provide a detailed account of a specific debugging process within the Milvus kernel and share practical experiences using this memory analysis tool.
Why Simple Unit Test is not reliable?
Most unit tests for the Milvus kernel primarily focus on the “expected vs. actual” output. While a test may pass as long as the results align with developer expectations, this standard is insufficient for a complex database engine. In high-concurrency systems like ours, various internal memory states and pointer behaviors significantly influence the overall stability of the Milvus cluster. Neglecting these underlying states can pose substantial risks to the reliability of our production environment. To address this issue, AddressSanitizer offers a range of checks that ensure the internal memory states of the database engine are robust and functioning as intended during execution.
Debug Milvus case
Recently, I have been leading the development and architectural optimization of the Milvus database aggregation module. As the core logic of this high-performance engine is implemented in C++, ensuring memory safety through rigorous unit testing is paramount to our system’s reliability. During the implementation of this feature, I developed a suite of unit test cases to validate the internal memory integrity of the kernel. Initially, I designed a unit test case as follows:
data = {{3,3,5,5,6}}
Plan plan(data, group_by(column_a))
auto res = framework.exec(plan);
AssertEqual(res.size, 4)
The initial test worked and passed as expected. However, when I modified the test code as shown below, it crashed with a segmentation fault
unique_ptr<BaseAgg> agg = make_uniuqe<DerivedAgg>();
agg.virutal_method();//ok
framework.input_data(agg, data);
agg.non_virtual_method();//ok
agg.virtual_method();//crushed
The same unique_ptr pointing to derived aggregation (agg) objects crashed after writing a few data entries into the agg. I reviewed my code and am confident that I did not reset or release the unique_ptr, ensuring it remains valid when calling the test1 method for the second time. Additionally, the fact that calling a non-virtual method of agg works supports this observation. Based on this evidence, I suspect a memory corruption in my program that possibly destroys the vtable of the DerivedAgg object, preventing it from locating the derived virtual methods.
Although I have a vague hypothesis, it is still challenging to identify the exact cause by merely reading the code. Therefore, I enabled AddressSanitizer and recompiled my code to gain deeper insights.
add_compile_options(-O0 -fno-stack-protector -fno-omit-frame-pointer -fno-var-tracking -fsanitize=address)
add_link_options(-fno-stack-protector -fno-omit-frame-pointer -fno-var-tracking -fsanitize=address)
Note: -fno-stack-protector, -fno-omit-frame-pointer, -fsanitize=address are critical for Address Santizer, and -O0 is for gdb-conveniency, -fno-var-tracking is to reduce compilation overhead
Error1: Heap-buffer-overflow
Reran the unit test, and it resulted in a heap-buffer-overflow error. AddressSanitizer helped me capture stack traces when the heap buffer overflow occurred.
0x604000021600 is located 8 bytes to the right of 40-byte region
#6 0x7d08eead15ae in milvus::exec::HashLookup::reset(int)
/home/xxxxxx/Documents/project/milvus/internal/core/src/exec/HashTable.h:32
This output indicates that the code attempted a write of 8 bytes at memory address 0x604000021600. The address 0x604000021600 is 8 bytes beyond the allocated region [0x6040000215d0, 0x6040000215f8], signifying an out-of-bounds write to the allocated memory.
Upon reviewing my code, I discovered that I compacted a vector and removed invalid elements within it but did not adjust the access logic accordingly. As a result, the code continued to attempt writing elements to the vector as if it had not been compacted. These out-of-bounds writes incorrectly overwrite the memory space. Since writes still occur within the program’s process space, the test cases run normally in the initial one-column test and do not crash immediately.
AddressSanitizer can detect these silent overwrites because it adds red zones around allocated memory regions. These red zones are intentionally left unallocated, and any access to them triggers an error. After addressing this silent overwrite, I reran my unit test, which revealed further errors as follows:
Error2: memory leaks
“LeakSanitizer: detected memory leaks.” AddressSanitizer (ASan) identified a memory leak in my program and clearly pinpointed the stack trace where the memory was allocated. Upon examining the code, I discovered that I had forgotten to release the dynamically allocated memory for an std::string in payload rows. The following diagram illustrates this memory leak.
Miss to release casading string memory on the heap
In my program, when storing data from multiple columns in one single payload row, I directly save the original values for primitive and fixed-length types such as int8, int16, and float. However, for variable-length columns like string or JSON, I store a pointer within the payload row, which occupies a fixed size of 8 bytes in memory, and allocate the actual content of the string on the heap. The root cause of the AddressSanitizer (ASan) error was that, although the program correctly deleted the memory allocated for the entire payload row, it failed to release the dynamically allocated memory for the strings. This oversight resulted in a memory leak that occurred in this test case.
Error3: Attempting to free not-allocated address
After adding the logic to free the heap memory for variable-length columns, the program crashed with the error: “attempting to free unallocated memory.” I discovered that this issue only occurs with test cases involving null values. The root cause is straightforward: for null strings or null JSON objects in Milvus, the corresponding position does not hold a valid string pointer but rather a segment of meaningless memory. Therefore, attempting to release such a "fake pointer" results in a crash.
After correcting this error, my gTest case ran correctly as expected.
Conclusion
This essay outlined a complex debugging process within the Milvus kernel utilizing AddressSanitizer, a critical diagnostic tool for high-performance database systems. By leveraging this tool, I identified and resolved three critical memory errors in the core codebase during the testing phase, preventing potential system-wide failures in our production environment. While I am deeply familiar with the underlying causes of such memory risks, I advocate for the mandatory use of tools like AddressSanitizer within our engineering team. Given the immense complexity and asynchronous nature of the Milvus architecture, it is virtually impossible to manually mitigate all risks across every code branch. Implementing these rigorous diagnostic protocols is essential to maintaining the industrial-grade stability that Zilliz customers depend on.
— MrPresent-Han





