Skip to content

start monotonic_resource at the last block size after release - #1227

Merged
grisumbras merged 1 commit into
boostorg:developfrom
GeekQAQ:fix-monotonic-release
Nov 26, 2026
Merged

grisumbras merged 1 commit into
boostorg:developfrom
GeekQAQ:fix-monotonic-release

Conversation

@GeekQAQ

@GeekQAQ GeekQAQ commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

monotonic_resource::release() returns all blocks to the upstream but keeps the size of the next block, which do_allocate doubles every time it obtains a block. A resource that is reused with release() between rounds of work therefore asks the upstream for a block twice as large on every round, even when every round allocates the same amount. After a couple dozen rounds the requested block can no longer be allocated, and from then on every allocation that needs a new block throws bad_alloc.

release() is documented to release all allocated memory, and the class documentation names the parse-then-free-everything pattern as the use case. A newly constructed resource does each of these rounds with one 4128-byte block.

Repro (develop e93b106, clang 21 -O2, libc++, Linux x86-64):

#include <boost/json.hpp>
#include <cstdio>
#include <new>
#include <string>

namespace json = boost::json;

// forwards to the default resource and prints the size of each block
struct printing_resource : boost::container::pmr::memory_resource
{
    void* do_allocate(std::size_t n, std::size_t align) override
    {
        std::printf("upstream block: %zu bytes\n", n);
        return json::storage_ptr()->allocate(n, align);
    }
    void do_deallocate(void* p, std::size_t n, std::size_t align) override
    {
        json::storage_ptr()->deallocate(p, n, align);
    }
    bool do_is_equal(memory_resource const& mr) const noexcept override
    {
        return this == &mr;
    }
};

int main()
{
    // the same allocation in every round, release() in between
    {
        printing_resource up;
        json::monotonic_resource mr(1024, &up);
        for(int i = 0; i < 6; ++i)
        {
            (void)mr.allocate(4000);
            mr.release();
        }
    }

    // the same with the default upstream, parsing a ~2 KB document per round
    json::monotonic_resource mr;
    std::string const doc = "[\"" + std::string(2000, 'x') + "\"]";
    int failed = 0, first = -1;
    for(int i = 0; i < 100; ++i)
    {
        try
        {
            (void)json::parse(doc, &mr);
        }
        catch(std::bad_alloc const&)
        {
            if(first < 0)
                first = i;
            ++failed;
        }
        mr.release();
    }
    std::printf("bad_alloc in %d of 100 rounds, first in round %d\n", failed, first);
}

Output on develop:

upstream block: 4128 bytes
upstream block: 8224 bytes
upstream block: 16416 bytes
upstream block: 32800 bytes
upstream block: 65568 bytes
upstream block: 131104 bytes
bad_alloc in 75 of 100 rounds, first in round 25

Continuing the first loop, round 20 would ask for 4294967328 bytes. In the second loop the requests to the default resource fail from round 25 on, while the process never uses more than a few MB: it is the size of the request that fails, not a lack of memory. With this change every round asks for 4128 bytes and no round fails.

Cause: do_allocate sets next_size_ = next_pow2(next_size_) after each new block. release() rewinds the initial buffer and the block list (the latter since 1b73c77) but not next_size_.

Fix: in release(), set next_size_ to the size of the last block obtained from the upstream, if there is one. Repeated rounds of the same allocations then settle on a single block that is large enough for a round.

Test: testRelease in test/monotonic_resource.cpp repeats the same three allocations with release() in between and checks that the number of blocks goes down to one and that the size of that block stays the same. It fails on develop and passes with the change.

Copilot AI balanced review requested due to automatic review settings November 20, 2026 14:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@cppalliance-bot

cppalliance-bot commented Nov 20, 2026 •

Copy link
Copy Markdown

An automated preview of the documentation is available at https://1227.json.prtest2.cppalliance.org/libs/json/doc/html/index.html

If more commits are pushed to the pull request, the docs will rebuild at the same URL.

2026-11-25 15:06:03 UTC

@cppalliance-bot

cppalliance-bot commented Nov 20, 2026 •

Copy link
Copy Markdown

GCOVR code coverage report https://1227.json.prtest2.cppalliance.org/gcovr/index.html
LCOV code coverage report https://1227.json.prtest2.cppalliance.org/genhtml/index.html
Coverage Diff Report https://1227.json.prtest2.cppalliance.org/diff-report/index.html

Build time: 2026-11-25 15:37:40 UTC

@cppalliance-bot

Copy link
Copy Markdown

@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.98%. Comparing base (e93b106) to head (1f3ede7).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #1227   +/-   ##
========================================
  Coverage    93.98%   93.98%           
========================================
  Files           85       85           
  Lines         8974     8976    +2     
========================================
+ Hits          8434     8436    +2     
  Misses         540      540           
Files with missing lines Coverage Δ
include/boost/json/impl/monotonic_resource.ipp 100.00% <100.00%> (ø)

Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e93b106...1f3ede7. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@grisumbras

Copy link
Copy Markdown
Member

Thank you for catching this.

I will have to think if I like this approach (restoring to the value calculated during construction). I feel like what it should do is for the first allocation after reset to request the same size as the last allocation prior to it. This would result to eventual discovery of the ideal allocation size via repeated reuse of a monotonic_resource.

@GeekQAQ

GeekQAQ commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

I tried that: in release(), next_size_ is set to the size of the last block obtained from upstream, if there is one. It stops the growth too. With 20 KB allocated in every round, the block sizes requested in each round are:

round  current PR                   last block size
0      1024 2048 4096 8192 16384    1024 2048 4096 8192 16384
1      1024 2048 4096 8192 16384    16384 32768
2      1024 2048 4096 8192 16384    32768
3      1024 2048 4096 8192 16384    32768

So it settles at one block per round. The difference is that the size never goes back down: after a single round that allocates 1000 KB, every later 4 KB round requests a 524288-byte block (1024, 2048 and 4096 with the current PR).

I'm happy to change the PR to that if you prefer it.

@grisumbras

Copy link
Copy Markdown
Member

Yes, let's go with that.

In addition, in the test, rather than writing a new memory resource please reuse fail_resource from test.hpp. In order to prevent it from actually failing an allocation just set fail_max to something very large, e.g. std::size_t(-1).

Make the test something like

  1. Allocate 3 times. Store the number of allocations.
  2. Release.
  3. Allocate in the same pattern. Check that the number of allocations has reduced.
  4. Release.
  5. Allocate in the same pattern again. Check that the number of allocations is now equal to 1. Store the number of bytes allocated.
  6. Release.
  7. Allocate in the same pattern yet again. Check that it's still one allocation, and that it's the same number of bytes allocated.

do_allocate doubles next_size_ for every block it obtains from the
upstream, and release() returns all the blocks but keeps next_size_.
A resource that is reused by calling release() between rounds of work
therefore asks the upstream for a block twice as large on every round,
even when each round allocates the same amount: the 20th round asks for
more than 4 GiB to satisfy a 4000-byte allocation, and soon every
allocation that needs a new block fails with bad_alloc.

Set next_size_ to the size of the last block obtained from the upstream
in release(). Repeated rounds of the same allocations then end up with a
single block of the right size.
@GeekQAQ GeekQAQ changed the title restart monotonic_resource block sizes on release start monotonic_resource at the last block size after release Nov 25, 2026
@GeekQAQ
GeekQAQ force-pushed the fix-monotonic-release branch from 0943eb2 to 1f3ede7 Compare November 25, 2026 14:59
@GeekQAQ

GeekQAQ commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Done: release() now sets next_size_ to the size of the last block obtained from the upstream, if there is one, and the extra member is gone.

testRelease follows your seven steps, using fail_resource. It fails on develop and passes with the change.

b2 libs/json/test passes with gcc 15 (C++11 to 20) and clang 21 (C++11, 17, 20) with warnings=extra warnings-as-errors=on, and with clang 21 under ASan and UBSan. I also updated the PR title and description.

@cppalliance-bot

Copy link
Copy Markdown

@grisumbras
grisumbras merged commit 1f3ede7 into boostorg:develop Nov 26, 2026
3 checks passed
@grisumbras

Copy link
Copy Markdown
Member

Thanks again for the discovdry and the fix.

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