Skip to content

Ensure that all Bigarray memory managed by the GC is tracked by Memprof - #13675

Merged
dra27 merged 3 commits into
ocaml:trunkfrom
stedolan:memprof-map-file
May 16, 2025
Merged

dra27 merged 3 commits into
ocaml:trunkfrom
stedolan:memprof-map-file

Conversation

@stedolan

Copy link
Copy Markdown
Contributor

There are a number of memory-management options available when using Bigarrays to represent off-heap memory:

  1. GC-managed: Bigarray.create and friends
  2. User-allocated but GC-freed: using CAML_BA_MANAGED from a C stub passing non-NULL data to caml_ba_create
  3. User-allocated, user-freed: using CAML_BA_EXTERNAL from a C stub
  4. Unix.map_file, GC-freed: using CAML_BA_MAPPED_FILE and a custom finaliser.

It's not obvious exactly which of these should result in Gc.Memprof events.

I think the right criterion that is that we should have Gc.Memprof events when the GC manages the lifetime of an allocation - that is, cases 1, 2 and 4 above. (In case 3, the user is managing the lifetime of the off-heap memory, and it may well extend beyond the point where the bigarray is finalised).

(If you're unfamiliar with the API it might be surprising that Unix.map_file is GC-freed: there is no Unix.unmap_file, but instead the freeing is done by a GC finaliser as with normal Bigarrays).

The behaviour of the runtime is already very close to the criterion identified above. The only difference is the lack of Memprof calls in Unix.map_file, which this patch adds. That is the only functional change in this PR, but there is also a new test for this logic.

@gadmm

gadmm commented Dec 16, 2024

Copy link
Copy Markdown
Contributor

I agree with your criterion:

I think the right criterion that is that we should have Gc.Memprof events when the GC manages the lifetime of an allocation

In this PR you sample a number of blocks equivalent to the size of the mapping, so you are seeing the memory of the file as being managed by the GC. However, neither RAM nor even disk memory is being freed by the finalizer (only virtual memory). Is this what you intend? Maybe I am missing the details from a specific case you have in mind.

@dra27 dra27 closed this Dec 16, 2024
@dra27 dra27 reopened this Dec 16, 2024
Comment thread otherlibs/unix/mmap_ba.c Outdated
}
asize = SIZEOF_BA_ARRAY + num_dims * sizeof(intnat);
res = caml_alloc_custom(&caml_ba_mapped_ops, asize, 0, 1);
mem_bytes = num_elts * caml_ba_element_size[flags & CAML_BA_KIND_MASK];

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.

If you did this after the initialization of b (so before the return resbelow), I think this could reuse caml_ba_byte_size:

  mem_bytes = caml_ba_byte_size(b);
  mem_words = (mem_bytes + sizeof(value) - 1) / sizeof(value);
  caml_memprof_sample_block(res, mem_words, mem_words, CAML_MEMPROF_SRC_CUSTOM);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's much simpler, thanks.

@stedolan

Copy link
Copy Markdown
Contributor Author

However, neither RAM nor even disk memory is being freed by the finalizer (only virtual memory).

This is not really true. In a normal allocation (e.g. when the heap expands), typical OS behaviour is:

  • Virtual memory space is immediately allocated
  • On first use of each page (and not before), RAM is allocated to hold its contents
  • If the memory is unused for a long time and/or there is extreme memory pressure, it is swapped to disk and RAM is freed. Future uses cause disk I/O and RAM allocation.
  • When the memory is unmapped, virtual address space and any used disk/RAM are freed.

For a memory-mapped file, the situation is exactly the same, except that it begins life in the "swapped out" stage. If shared is false, then any backing RAM is freed along with virtual address space by the unmap call in the finaliser, where "freed" means "made available for future allocations" (The kernel is likely to keep the pages around as page cache if nobody wants RAM immediately). If shared is true and it has been modified, then it's more complicated: any backing RAM won't be available for allocations until any modifications have been written out.

Maybe I am missing the details from a specific case you have in mind

The immediate use-case is a couple of programs at Jane Street whose memory consumption consists in a large part of calls to Unix.map_file - currently, memtrace reports misleadingly small amounts of memory usage in such situations.

I can imagine that there are programs where you might want to profile memory use and not count calls to Unix.map_file for some reason, but in those cases it's easy to filter out calls to map_file, while it's impossible to work out where they should be if the data is not present in the first place.

@gadmm

gadmm commented Dec 17, 2024

Copy link
Copy Markdown
Contributor

Thank you @stedolan for providing me with these helpful details.

How about introducing a specific allocation source for file-backed memory?

If I can try to rephrase your point (at least on Linux), it seems that the crucial details are that memory pressure causes both filesystem paging and swapping (in proportions that actually depend on the OS configuration), and that the page cache reclamation is done with a higher priority for pages that underwent the msync+munmap calls (in case this was the last mapping). In this sense the finaliser indeed has an effect on available memory, even if it primarily concerns cached memory. It also seems important to track the memory usage for caching files in this way for the proper functioning of systems.

Given the different nature of the memory usage, a different allocation source seems justified and it would actually make filtering easy and robust.

(It still seems an important difference that with mmapped files, the cached memory can intentionally be less than the total file size, given that the program might not need to access the whole file (unlike your example of extending the heap, where all the pages are touched immediately by the runtime). I note that with caml_ba_create, memory also only needs to be allocated for the pages that are modified, but this is still quite different.)

Lastly, the Memprof interface is still described as experimental, but it might be good to make allocation_source an extensible variant for future-proofing, e.g. to start stabilizing the API soon but still be able to add stack allocations later.

@gasche gasche self-assigned this Jan 8, 2025
@gasche

gasche commented Jan 8, 2025

Copy link
Copy Markdown
Member

@stedolan ping :-)

I understand that @gadmm proposes an even better option, but I wouldn't mind merging the behavior your propose as a temporary measure to makes things slightly better.

@stedolan

Copy link
Copy Markdown
Contributor Author

How about introducing a specific allocation source for file-backed memory?

This is a good idea, done.

it might be good to make allocation_source an extensible variant for future-proofing, e.g. to start stabilizing the API soon but still be able to add stack allocations later.

I thought about this but I don't think an extensible variant type (type t = ..) is a good fit here, as it's hard for users to make sense of an arbitrary value of that type. (Those types are useful when there is a common type shared by many users, who each want to introduce and eliminate just their own constructors, like exn). So, I left the type as a plain variant, but to ensure that there's something a generic user can do with it I also added a conversion to string.

@dinosaure

Copy link
Copy Markdown

I would just like to mention that there is a case (which may correspond to case 3) where a bigarray exists to correspond to a physical memory address corresponding to a device (hardware) and which should not be count by memprof.

@stedolan

Copy link
Copy Markdown
Contributor Author

I would just like to mention that there is a case (which may correspond to case 3) where a bigarray exists to correspond to a physical memory address corresponding to a device (hardware) and which should not be count by memprof.

This does correspond to case 3 (it's CAML_BA_EXTERNAL, as it's not GC-managed memory), so it won't be tracked by memprof (before or after this patch).

@gadmm

gadmm commented Jan 20, 2025 •

Copy link
Copy Markdown
Contributor

Thanks for the separate kind.
I do not think that a conversion to string solves the issue since the goal is to avoid breaking existing code if a new kind is added later (i.e. by forcing code to be written with a catch-all clause at the end). Anyway, this is a concern for another time (I brought it up because it is better to break current code only once even if "experimental").

Comment thread runtime/caml/memprof.h Resolved
@gadmm

gadmm commented Jan 20, 2025

Copy link
Copy Markdown
Contributor

And to be clear my question was about type t = private ..

@gadmm gadmm 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.

There is something missing the adaptation to the new Map_file memprof source (see below). Otherwise this looks fine to me.

Comment thread otherlibs/unix/mmap_ba.c Resolved
custom_words := !custom_words + info.size * Sys.word_size/8;
Some info.size
| _ ->
None

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 test has not yet been adapted to the Map_file source

Specifically, this adds Gc.Memprof calls to Unix.map_file, and adds some
tests (but does not otherwise change behaviour)
@gasche
gasche force-pushed the memprof-map-file branch from 373d6aa to febca81 Compare May 16, 2025 06:01
@gasche

gasche commented May 16, 2025

Copy link
Copy Markdown
Member

I merged @gadmm's review suggestions, and updated the test. This should be good to merge if the CI agrees.

@gasche
gasche force-pushed the memprof-map-file branch from febca81 to 424011d Compare May 16, 2025 06:04
@nojb

nojb commented May 16, 2025

Copy link
Copy Markdown
Contributor

Some failures from the AppVeyor CI:

> Fatal error: cannot load shared library dllunixbyt
> Reason: flexdll error: cannot relocate caml_memprof_sample_block RELOC_REL32, target is too far: fffffff8a44d2ff1  ffffffffa44d2ff1

@dra27

dra27 commented May 16, 2025

Copy link
Copy Markdown
Member

caml_memprof_sample_block in runtime/caml/memprof.h needs CAMLextern added to it

@gasche
gasche force-pushed the memprof-map-file branch 2 times, most recently from 407e7a7 to 07a8956 Compare May 16, 2025 09:44
@dra27
dra27 force-pushed the memprof-map-file branch from 07a8956 to ef05280 Compare May 16, 2025 16:04
@dra27
dra27 merged commit 820bc29 into ocaml:trunk May 16, 2025
@dra27

dra27 commented May 17, 2025

Copy link
Copy Markdown
Member

Is this allowed for 5.4, @Octachron? (given that the alpha isn't yet tagged, I would push for "yes")

@Octachron

Copy link
Copy Markdown
Member

This feels really at the frontier between a bug fix and a new feature.
Ok, for cherry-picking to 5.4.

dra27 added a commit that referenced this pull request May 17, 2025
Ensure that all Bigarray memory managed by the GC is tracked by Memprof

(cherry picked from commit 820bc29)
dra27 added a commit that referenced this pull request May 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants