Skip to content

restart monotonic_resource block sizes on release - #1227

Open
GeekQAQ wants to merge 1 commit into
boostorg:developfrom
GeekQAQ:fix-monotonic-release
Open

GeekQAQ wants to merge 1 commit into
boostorg:developfrom
GeekQAQ:fix-monotonic-release

Conversation

@GeekQAQ

@GeekQAQ GeekQAQ commented Nov 20, 2026

Copy link
Copy Markdown

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: remember the initial block size computed by the constructors and restore next_size_ to it in release(). This adds a std::size_t member to monotonic_resource.

Test: testRelease in test/monotonic_resource.cpp releases and allocates again a few times, with and without an initial buffer, and checks the size of the block requested from the upstream each time. It fails on develop and passes with the change. The other tests that use monotonic_resource (array, object, string, value, stream_parser, memory_resource and the doc tests) also pass, built directly with clang 21 and libc++ under ASan and UBSan.

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.

Remember the initial block size and restore it in release().
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

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-20 14:53:01 UTC

@cppalliance-bot

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-20 15:11:24 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 (0943eb2).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #1227   +/-   ##
========================================
  Coverage    93.98%   93.98%           
========================================
  Files           85       85           
  Lines         8974     8977    +3     
========================================
+ Hits          8434     8437    +3     
  Misses         540      540           
Files with missing lines Coverage Δ
include/boost/json/impl/monotonic_resource.ipp 100.00% <100.00%> (ø)
include/boost/json/monotonic_resource.hpp 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...0943eb2. Read the comment docs.

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

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.

3 participants