Skip to content

fix(scratch): keep AcnDyn scratch buffers usable during thread exit - #66

Open
ondrik wants to merge 1 commit into
review/fix-dividefrom
review/fix-scratch
Open

ondrik wants to merge 1 commit into
review/fix-dividefrom
review/fix-scratch

Conversation

@ondrik

@ondrik ondrik commented Dec 2, 2026 •

Copy link
Copy Markdown

This is part 9 of 13 of the split of #56, which fixes the findings of the code review tracked in #5. It is based on the previous PR in the stack, branch review/fix-divide, so its diff shows only the one commit of this part. Please review and merge the PRs in stack order. After the previous PR merges, this one is retargeted to main.

# PR Base Fixes
1 #58 main #6, #10, #18, #27
2 #59 #58 #14, #15, #17, #32, #37
3 #60 #59 #8, #9, #23, #29, #30, #33
4 #61 #60 #22, #39
5 #62 #61 #7, #13, #20, #35
6 #63 #62 #11, #12, #19, #21, #34
7 #64 #63 #16, #36
8 #65 #64 #28
9 #66 (this PR) #65 #31
10 #67 #66 #24, #26, #38
11 #68 #67 #25, #41
12 #69 #68 #40, #42
13 #70 #69 follow-ups only

The performance PRs for #43–#55 are stacked on top of #70: #71, #72, #73, #74, #75, #76, #77, #78, #79.

How to merge this stack: see the merge guide (one at a time, in order, with "Create a merge commit", then delete the merged branch so the next PR retargets to main).

Issues

  • Fixes [L5] thread_local scratch is destroyed before static objects #31: AcnDyn's scratch buffers were function-local thread_local std::vectors. C++ destroys a thread's thread_local objects before any static object, so AcnDyn arithmetic in the destructor of a static object, or of a thread_local created before the thread's first AcnDyn operation, wrote into freed memory (ASan heap-use-after-free; a crash with AcnDyn<BigInt>). Each slot's state is now a constant-initialized, trivially destructible thread_local that is never destroyed, and a thread_local releaser frees the buffer at thread exit and marks the slot released; after that, each borrow gets a buffer of its own, freed when the borrow ends (commit 411590a).

The MWE is in the issue. The issue offered two fixes: document "no AcnDyn arithmetic during static/TLS destruction", or make the slots safe during destruction. This PR does the second.

Behaviour changes

  • AcnDyn arithmetic now works in static destructors and in thread_local destructors that run during thread exit. Once a thread's buffers have been released, every scratch borrow on that thread allocates and frees its own buffer, so this late path is slower but does not leak.
  • detail::scratch_span returns a detail::ScratchSpan<Int> instead of a std::span<Int>. This is detail API only. A ScratchSpan is not copyable, and a temporary one does not convert to a span, so std::span<Int> s = scratch_span<Int, Tag>(n); no longer compiles: the borrow would end with that statement. All call sites in the library already use auto and are unchanged.
  • Performance, from the commit message: the normal path is one capacity compare with no initialization guard on the thread_local. Instructions per AcnDyn add/mul/fma/scale are equal to or lower than before; norm2 is +1%.

Testing

The first CI run failed in the g++ Release jobs: GCC 13.3, the g++ of the ubuntu-24.04 runners, reports a false -Wstringop-overflow in matrix.hpp that GCC 13.4 (used locally) does not. Commit 3d9ece0 in #58 fixes it by making Acn(), zero(), one() and coeff_span() constexpr; the later #42 commit in #69 made them constexpr anyway, so the tree after #69 is unchanged. The local results below were taken before that change. After it, this tip was rebuilt and tested again with g++-13 Release -DACN_WERROR=ON: 272/272 passed, 0 warnings, and CI runs the full matrix.

The tested tree is this branch's tip tree (6e53c59). Every build uses -G Ninja -DACN_WERROR=ON. Each log was checked for No test cases matched, in 0 test cases and No tests ran, and none of them appears.

Configuration ctest
g++-15 (15.2.0) Debug 272/272
g++-13 (13.4.0) Debug 272/272
g++-13 Release 272/272
g++-13 Release, ACN_WITH_GMP=OFF 231/231
g++-13 ASan+UBSan (Debug, -O1) 272/272

The previous PR in the stack runs 271 tests (230 with ACN_WITH_GMP=OFF) in the same configurations, so this PR adds one: scratch_exit. clang++ was not run locally; it runs in CI.

New test:

  • scratch_exit (new plain executable, [L5] thread_local scratch is destroyed before static objects #31). It does AcnDyn<CheckedI64> and AcnDyn<BigInt> (only with GMP) arithmetic in a static object's destructor and, during a thread's exit, in the destructor of a thread_local created before that thread's first AcnDyn operation. In the sanitizer build, AddressSanitizer reports the use after free. The other builds replace operator new/delete with a quarantine that fills freed blocks with a pattern; the test checks that the patterns are intact and that the exiting thread freed everything it allocated. ctest requires both "thread exit ok" and "static destruction ok" lines (the second is printed after main returns) and fails on FAILED, Sanitizer or runtime error. According to the commit message, the test fails before the fix in every build, and also fails for a fallback that re-creates a per-thread buffer (a leak).

A Codacy finding on #56 (CWE-120 on memcpy in tests/scratch_exit.cpp) is addressed by a follow-up folded into this commit (#56's 444b718): the test stores the block size in its header with placement new, reads it back through std::launder, and has a static_assert that it fits. Codacy's two "always true" findings in the same file were left as they are, because freed_blocks_intact() and live_blocks() are stubs in the ASan build on purpose: ASan and LeakSanitizer do those checks there.

Earlier review discussion (CodeRabbit, Codacy) is on #56.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92

…#31)

AcnDyn's scratch buffers were function-local thread_local std::vectors.
C++ destroys a thread's thread_local objects before any static object,
and in reverse order of construction, so AcnDyn arithmetic in the
destructor of a static object, or of a thread_local object created
before the thread's first AcnDyn operation, wrote into freed memory
(ASan: heap-use-after-free; with AcnDyn<BigInt>, a crash).

Each slot's state (buffer, capacity, a "released" flag) is now a
constant-initialized, trivially destructible thread_local, which is
never destroyed. A thread_local Releaser, created with the thread's
first buffer, frees the buffer when the thread exits and marks the slot
released. After that, scratch_span() allocates a buffer per borrow, and
the ScratchSpan it now returns (instead of a std::span; detail API
only) frees it when it goes out of scope, so nothing leaks either. A
temporary ScratchSpan does not convert to a span, so a borrow cannot be
dropped while its span is still in use. The call sites already use
auto and are unchanged. The normal path is one capacity compare with no
initialization guard on the thread_local: instructions per AcnDyn
add/mul/fma/scale are equal or lower than before, norm2 +1%.

The new test scratch_exit does AcnDyn<CheckedI64> and AcnDyn<BigInt>
arithmetic in a static object's destructor and, during a thread's exit,
in the destructor of a thread_local created before that thread's first
AcnDyn operation. AddressSanitizer reports a use after free in the
sanitizer build. The other builds replace operator new/delete with a
quarantine that fills freed blocks with a pattern; the test checks that
the patterns are intact and that the exiting thread freed everything it
allocated. It fails before the fix in every build, and also fails for a
fallback that re-creates a per-thread buffer (a leak).

Fixes #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 17 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8631ce70-6699-4af8-bd06-d9ee6c0d2bc6
Commits

Reviewing files that changed from the base of the PR and between 5004711 and 411590a.

Files selected for processing: 3

  • include/acn/scratch.hpp
  • tests/CMakeLists.txt
  • tests/scratch_exit.cpp
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@codacy-production

Copy link
Copy Markdown

Not up to standards ⛔

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@ondrik
ondrik force-pushed the review/fix-divide branch from 812555e to 5004711 Compare December 2, 2026 13:16
@ondrik
ondrik force-pushed the review/fix-scratch branch from 41e9811 to 411590a Compare December 2, 2026 13:16
@ondrik
ondrik marked this pull request as ready for review December 2, 2026 13:58
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.

1 participant