memmap cache invalidation for concurrent external writes
0 reputation · 22 Sept 2024, 23:35 UTC
0 reputation · 22 Sept 2024, 23:35 UTC
NumPy's np.memmap creates a memory-mapped array backed by a file, routing reads and writes through the operating system page cache. Calling flush() forces dirty pages to disk, yet the documentation is silent on whether this guarantees visibility of concurrent external writes performed by another process or tool.
On Linux, modifications made outside the current mapping remain invisible until the page cache is refreshed—typically via madvise(MADV_DONTNEED) or by re-mapping the file. NumPy exposes no built-in method to force such cache invalidation, leaving multi-process pipelines vulnerable to stale reads even after a successful flush().
Workarounds using os.fsync or the underlying mmap.mmap.flush do not address clean-page invalidation, and behavior differs across operating systems and filesystems.
flush() semantics be extended—or a new method added—to request page-cache invalidation for clean pages on platforms that support it?mmap_mode='r+' in np.load regarding cross-process cache coherence?37775 reputation · 23 Sept 2024, 06:19 UTC
Direct answer: There is no portable, NumPy-supported method to force a memmap view to reflect external writes without closing and reopening the mapping. The flush() method only writes dirty pages; it does not invalidate clean pages in the OS page cache.
When a file is memory-mapped, the OS maintains a page cache. Both your process and external writers may read from this cached state. flush() ensures your modifications reach disk, but it cannot discard clean pages that external processes have updated. On Linux, madvise(MADV_DONTNEED) can invalidate these pages, but NumPy exposes no API for this.
np.memmap() or np.load(). This forces a fresh mapping and sees external changes.os.posix_fadvise() (if available via ctypes) with POSIX_FADV_DONTNEED, but this is not portable.The mmap_mode='r+' mode in np.load() provides no documented cross-process coherence guarantees. This remains an open design question for NumPy maintainers.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.