Skip to content

fix(wall): preserve context and sampling-epoch provenance across dumps (PROF-12146) - #890

Open
jbachorik wants to merge 53 commits into
paul.fournillon/wallclock-all-threadsfrom
sphinx/fix-663-review-findings
Open

jbachorik wants to merge 53 commits into
paul.fournillon/wallclock-all-threadsfrom
sphinx/fix-663-review-findings

Conversation

@jbachorik

@jbachorik jbachorik commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?:

Keeps the stack, tracing context and per-epoch weight attached to retained unowned wall-clock tails until a write succeeds, so tails survive call-trace rotation and JFR dumps with their original provenance. Also folds in the follow-ups to #663's review: owner-TLS context-window membership, lock-free thread retirement, timer-join retry, and DEBUG-only test seams.

Motivation:

In filtered precheck mode an unowned blocked thread records about one sample in ten and keeps the rest as pending weight against a cached trace. Before this change the cached trace could be rotated away, the tail was written with the current context instead of the original one, and it was scaled by the epoch in force at flush time rather than at observation time.

Additional Notes:

Human review: mandatory. The change touches signal-reachable sampling, lock ordering (epoch mutex → recording stripes → _rec_lock) and JFR epoch metadata.

Accepted costs (reviewer acknowledgment required):

Cost Why accepted
Closed sampling epochs are kept in Recording::_wall_epochs until a dump or a rare prune (floor 4096 entries, about 400 KiB, charged to wallclock). The prune visits each stripe once as a barrier, never holding all of them. Retained tails need the epoch that was current when they were observed.
Backdated samples and re-emitted epochs can precede a new chunk's start. Consumers scale each sample by the epoch that contains its timestamp.
The block tracker's slots and retained-context chunks are kept until tracker destruction and reported as wall_block_tracker. In-flight owner hooks can carry slot IDs across stop().
A failed timer-thread join keeps the handle; start() retries the join and is refused while it keeps failing. Reusing a live thread handle would be unsafe.
  • Bundled changes outside the PR's purpose are tracked separately: the monotonic wall-timer cadence and DDPROF_WALL_TIMER_DIAGNOSTICS (PROF-16795), the .pi checkout-root fix (PROF-16721), and build/agent tooling changes (PROF-16796, PROF-16797).
  • aarch64 -O0 workaround: WallClockBlockTracker::unownedContextCell() masks the slot as u32. Clang 14 at -O0 on aarch64 lowers the signed masked subscript to a sign-extending byte load, so chunk offsets 128–255 indexed cells −128..−1 (caught by UBSan). UpperHalfChunkOffsetsUseTheirOwnCell fails without it. The comment states when to drop it (clang 15+ floor).
  • Merged with current main through feat(wall): support unfiltered suppression and protect crash bootstrap (PROF-12146) #663: call-trace storage is now recording-scoped, so pending tails are dropped when storage is released at stop. CallTraceStorage::allocateTables() keeps main's exception-free allocation. _collector_set_buffer gets the same load factor and, like the other collections, allocates its buckets on first use.
  • Review: Sphinx standard review of the full range found no Critical or High findings; all Medium findings and the cheap Low findings are fixed with tests. Open Lows: an epoch whose slot root is cleared while segments remain can be pruned mid-recording; a dump can scan the tracker twice inside one critical section.

How to test the change?:

  • ./.claude/commands/build-and-summarize :ddprof-lib:gtestDebug (block tracker, wall epochs, thread filter, call-trace storage).
  • ./.claude/commands/build-and-summarize :ddprof-test:testDebug -Ptests='com.datadoghq.profiler.wallclock.*' and -Ptests='*Lifecycle*'.

For Datadog employees:

  • If this PR touches code that signs or publishes builds or packages, or handles
    credentials of any kind, I've requested a security review (run the dd:platform-security-review
    skill, or file a request via the PSEC review form).
    bewaire also runs automatically on every PR.
  • This PR doesn't touch any of that.
  • JIRA: PROF-12146

Unsure? Have a question? Request a review!

…me safety

Fixes: mutex acquisition from the pthread TLS destructor (retireThreadByTid
lock-free path), TidIndex use-after-free for in-flight lock-free readers in
~ThreadFilter, capacityExhausted() hint/gate contract, and context-window
state update races.
…cker state fixes

Timer loops re-read recordingEpoch() each tick instead of caching it;
stop() keeps the pthread_t when pthread_join fails; flushUnownedBlockedTail
resets only on valid payloads; owned-run admission preserves unflushed
unowned-blocked weight; test-only exitBlockedRun overload gated behind
UNIT_TEST; epoch publish ordering tightened. Adds lazyBackfill timer-path
coverage and positive-path fuzz assertions for owned-block suppression.
…aProfilerTestSupport to test sources

The registry-activity accessor now returns false in release builds; the
hooks live on JavaProfiler (DEBUG-gated natives) instead of a public
support class shipped in the main jar.
…haos threads

stopProfiler() no longer wipes trace context unconditionally; the
force-wall-start-failure toggle is disarmed in @AfterEach; wall-precheck
counter reads use getOrDefault to avoid NPEs; the parked-worker spin loop
yields; the churn antagonist checks join results and reuses one interruptor
thread.
@jbachorik jbachorik added the AI label Oct 23, 2026
@jbachorik
jbachorik marked this pull request as ready for review October 23, 2026 13:15
@jbachorik
jbachorik requested a review from a team as a code owner October 23, 2026 13:15
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T13:20:22.326641Z 3f77b78 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3f77b7836b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@datadog-datadog-prod-us1 datadog-datadog-prod-us1 Bot 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.

Bits Code Review: PASS

More details

The completed static review identified no reportable defects in deferred thread retirement, wall-clock restart handling, or blocked-time accounting. Runtime behavior was not tested.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 3f77b78

@dd-octo-sts

dd-octo-sts Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

CI Test Results

Run: #45696054128 | Commit: bdcce41 | Duration: 24m 30s (longest job)

✅ All 108 test jobs passed

Status Overview

JDK glibc-aarch64/asan glibc-aarch64/debug glibc-aarch64/release glibc-aarch64/tsan glibc-amd64/asan glibc-amd64/debug glibc-amd64/release glibc-amd64/tsan musl-aarch64/debug musl-aarch64/release musl-amd64/debug musl-amd64/release
8 - - - - ✅ ✅ ✅ ✅ - - - -
8-ibm - - - - ✅ ✅ ✅ ✅ - - - -
8-j9 ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
8-librca - - - - - - - - ✅ ✅ ✅ ✅
8-orcl - - - - ✅ ✅ ✅ ✅ - - - -
11 - - - - ✅ ✅ ✅ ✅ - - - -
11-j9 ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
11-librca - - - - - - - - ✅ ✅ ✅ ✅
17 ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
17-graal ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
17-j9 ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
17-librca - - - - - - - - ✅ ✅ ✅ ✅
21 ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
21-graal ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
21-librca - - - - - - - - ✅ ✅ ✅ ✅
25 ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
25-graal ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ - - - -
25-librca - - - - - - - - ✅ ✅ ✅ ✅

Legend: ✅ passed | ❌ failed | ⚪ skipped | 🚫 cancelled

Summary: Total: 108 | Passed: 108 | Failed: 0


Updated: 2026-11-25 21:21:23 UTC

@dd-octo-sts

dd-octo-sts Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ All 40 integration tests passed

📊 Dashboard · 👷 Pipeline · 📦 357bad1b

jbachorik and others added 4 commits November 2, 2026 11:01
Carry the exact SpotlessConventionPlugin content from upstream #955 (e8c3dfb): register Java formatting lazily and use GJF 1.30.0. The stacked #663 base predates that fix; no local formatter variant or formatter-only TestKit is included.
Preserve reusable exact-ID roots and retained context across rotations and recording/context restarts. Keep ordinary sample weight one while accounting for timer work and wake lateness with monotonic deadlines. Add fixed-size phase diagnostics and bounded shutdown/drain regressions without weakening the one-second collapsing oracle.
@dd-octo-sts

dd-octo-sts Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Scan-Build Report

User:runner@runnervmwuk1x
Working Directory:/home/runner/work/java-profiler/java-profiler/ddprof-lib/src/test/make
Command Line:make -j4 all
Clang Version:Ubuntu clang version 21.1.8 (6ubuntu1)
Date:Thu Nov 12 23:30:34 2026

Bug Summary

Bug TypeQuantityDisplay?
All Bugs2
Logic error
Dereference of null pointer1
Unused code
Dead initialization1

Filter Results by File

Reports

Bug Group Bug Type ▾ File Function/Method Line Path Length
Unused codeDead initializationreferenceChains.cppapplyOomRamp4971
Logic errorDereference of null pointerperfEvents_linux.cppunregisterThread72026

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 357bad1 | Docs | Give us feedback!

@dd-octo-sts

dd-octo-sts Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Reliability & Chaos Results

✅ All reliability & chaos checks passed Pipeline: https://gitlab.ddbuild.io/DataDog/java-profiler/-/pipelines/156586968

Keep unified reservoir accounting and original-context tails. Retain up to
four original-window weight segments and serialize deferred observations
at their original epoch timestamps, committing successful writes separately.
Settle prior sampling statistics before changing pass counts and publish
population boundaries before dispatch.

Consumers must scale by the sample timestamp epoch. Unchanged-pool mid-pass
send failures can still leave coalesced straddling units at the prior success
ratio; that disclosed limitation needs a dedicated follow-up. Lazy sidecar
backing is bounded at 256 KiB. Add scale-aware, wire and retry regressions.
Keep the existing reservoir budgets, pass floors and per-thread assertions.
Publish unique-thread coverage and wait for it within the existing 20-second
timeout instead of assuming a fixed number of random draws covers the pool.

On timeout, report observed passes, coverage and every missing tid before
the fatal assertion, including rejected tids. Add deterministic completion
and fatal-diagnostic regressions without changing the production sampler.
@kaahos
kaahos added this pull request to stack #988 November 12, 2026 23:32
Preserve retained context and epoch tails when skipping clean owned-run clears.
Reconcile shared lazy backing and retain root accounting and generation-checked exits.
Import allocation and Java-8 spin-hint regressions.
kaahos added a commit that referenced this pull request Nov 13, 2026
Keep TaskBlock admission and sampled-generation handshakes on the retained
wall-clock transaction path. Preserve unowned trace provenance and epoch
weights across context changes in filtered and unfiltered stackful sampling.

Retain bootstrap test isolation, bounded sidecar allocation, tooling guards,
and the published TaskBlock review corrections. Keep generations monotonic
on ordinary slot reuse so stale owner tokens cannot clear a replacement run.
kaahos added a commit that referenced this pull request Nov 13, 2026
Skip only pushes without a same-repository open PR head at the pushed SHA. Exercise the workflow shell with hermetic event, head, pagination and error regressions.
@kaahos
kaahos force-pushed the sphinx/fix-663-review-findings branch from 60fac3c to e5c07be Compare November 13, 2026 16:22
kaahos added a commit that referenced this pull request Nov 20, 2026
kaahos added a commit that referenced this pull request Nov 20, 2026
kaahos added a commit that referenced this pull request Nov 20, 2026
kaahos added a commit that referenced this pull request Nov 23, 2026
# Conflicts:
#	ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/UnownedWallTailContextTransitionTest.java
kaahos added a commit that referenced this pull request Nov 23, 2026
# Conflicts:
#	ddprof-lib/src/main/cpp/wallClockBlockTracker.cpp
kaahos added a commit that referenced this pull request Nov 23, 2026
@rkennke

rkennke commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Why is this bundling several unrelated stuff into a PR that is supposed to fix review-findings of #663? The agent config stuff should go separately, at least.

@jbachorik

Copy link
Copy Markdown
Collaborator Author

Why is this bundling several unrelated stuff into a PR that is supposed to fix review-findings of #663? The agent config stuff should go separately, at least.

This looks like the merge from main pulled all the changes, but the base branch didn't get those changes?

@rkennke

rkennke commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Review findings

Reviewed range: 366748fab..8ae287f67. The base is the head of #663, so this covers only the commits of this PR. Sphinx standard review; each finding below was checked against the code at 8ae287f67. No Critical, High or Medium findings.

Coverage gap: the Sphinx correctness reviewer did not complete, so that lens is missing from this result. A separate correctness pass is running, and I will post its findings in a follow-up comment.

1. (Low) The two Pi adapters duplicate the toplevel lookup (.pi/extensions/require-fresh-review.ts:13, .pi/extensions/require-gradle-wrapper.ts)

Both adapters now contain the same block: git rev-parse --show-toplevel, the fallback to ctx.cwd, the hook path join, and the CLAUDE_PROJECT_DIR override. A later fix to the lookup, such as worktree or bare-repo handling, must be made in both files, and the adapters can drift apart. Suggestion: extract a small shared helper in .pi/extensions that both adapters import. If the extensions must stay self-contained, say so in a comment.

2. (Nit) test_run_chaos_harness.sh extracts the JVM command by literal text (utils/tests/test_run_chaos_harness.sh:21)

source.index('\njava -javaagent:') and source.index('\n\nRC=$?', start) locate the command in run-chaos-harness.sh. If the runner is reformatted, for example to exec java or a JAVA variable, the test fails with a bare ValueError instead of a message that names the marker. The negative control's .replace('-jar "${CHAOS_JAR}"', ...) also has no check that it matched. The control still asserts the specific different API singletons error, so a no-op replace does not make it pass silently. However, the -cp rewrite can stop having any effect without notice. Suggestion: fail with a clear message when a marker is missing, and assert that each .replace() changed the string.

@rkennke

rkennke commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Correctness pass (follow-up)

This is the follow-up to the earlier review comment. It covers the same range, 366748fab..8ae287f67, and fills in the missing correctness lens. Reviewer: /code-review at high effort, run in a fresh context. I checked findings 1–3, 5 and 8 against the code at 8ae287f67. Findings 4, 6 and 7 are as the reviewer reported them.

1. (High) Epoch close can drop in-flight samples of every type (flightRecorder.cpp:2965 FlightRecorder::wallClockEpoch, :2973 pruneWallEpochs)

At the base, wallClockEpoch() took OptionalSharedLockGuard. It now takes ExclusiveLockGuard on _rec_lock. Signal-side writers (recordSample and the other recorders) still use OptionalSharedLockGuard, and their try-lock fails while the lock is held exclusively.

  • The timer closes an epoch right after it dispatches that tick's signals, so handlers are in flight while the exclusive lock is held.
  • Those handlers drop their samples (wall, CPU, alloc) and count them in SAMPLES_DROPPED_REC_LOCK.
  • The exclusive section is not trivial. It does a std::map insert, which allocates, then flushIfNeeded(buf), which can write to the file.
  • A steady stream of shared holders can also keep the timer spinning on the exclusive lock.

The header documents exclusive writers on purpose (_wall_epochs: "Normal-thread writers hold _rec_lock exclusively"). A try-lock would also be wrong, because a skipped insert loses the epoch that retained tails need. Suggestion: the timer is not in signal context, so it can take a blocking shared lock (SharedLockGuard). The sampling-epoch mutex already serializes writers to _wall_epochs. Please confirm that every reader (the chunk-start re-emit, Recording::pruneWallEpochs) runs under the exclusive lock or under that mutex.

2. (High) This pass's suppressions are credited to the epoch it closes (wallClock.h timer loop, wallClock.cpp closeSamplingEpoch)

closeSamplingEpoch() drains WallClockCounters::drainSuppressedSampledRun() into the epoch it is closing. When !pool_changed && outcomes_changed, the timer calls closeSamplingEpoch(pass_start) after the send loop. By then this pass's suppressAlreadySampled() calls have already added to the counter. The result:

  • the closed epoch's numSuppressedSampledRun includes suppressions from a pass that is not part of it;
  • the new epoch's numSuccessfulSamples counts those selections, but its numSuppressedSampledRun does not.

When outcomes change often, for example under thread churn, this repeats every pass and biases the upscaling weights. Suggestion: read the counter before the send loop, or take this pass's timer-side suppressions out before the early close.

3. (Low) A failed pthread_join disables wall restarts (wallClock.cpp stop())

On a non-zero result, stop() keeps _thread "for retry". None of the pthread_join errors (EDEADLK, EINVAL, ESRCH) clears on a retry, and joining again after ESRCH is undefined behavior. Every later start() then fails because the old timer was not joined, and the warning promises a retry that cannot succeed.

4. (Low) onContextWindowExit returns early without a cached slot id (threadFilter.cpp ThreadFilter::onContextWindowExit)

With filterSlotId() == -1, slotForId() returns null and the function returns. The reviewer reports that the enter path falls back to a TID lookup, and that the fail-open path of ensureOwnerSlot() can clear the cache but keep the slot. The slot then keeps its in-window state, and owned-block suppression is skipped for that thread until it registers again. I did not check the enter-side fallback.

5. (Low) deferUnownedWeight can split one epoch across segments (wallClockBlockTracker.cpp:316)

The loop takes the first empty segment even when a later segment already holds the same epoch_start. After a segment is consumed and frees an earlier slot, one epoch can occupy several of the 4 segments. The array then reports full early, deferral fails open, and those samples are written as ordinary weight-1 samples with extra tail events.

6. (Low) Dump holds the sampling-epoch mutex for the whole copy (profiler.cpp:2772 dump())

The mutex is taken before rotateDictsAndRun() and held until dump() returns, through the JFR copy, clearAll and reportCounters. The wall timer takes this mutex at the start of every pass, so each dump causes a wall-sampling gap as long as the dump.

7. (Low) build/logs is no longer pruned, and AGENTS.md has the old log name (.claude/commands/build-and-summarize:26)

The 20-log retention is removed ("retention is managed by the caller"), but no caller manages it, so the directory grows without limit. The file name is now <timestamp>-<pid>-<task>.log, while root AGENTS.md still says build/logs/<timestamp>-<task>.log.

8. (Low) The hook's retry advice cannot succeed (.claude/hooks/require-fresh-review.py evaluate())

When ready_target() returns None, the hook says "cannot resolve the PR's head commit (gh failed); retry when gh works." This also happens when gh works but the branch has no PR, and then a retry cannot clear the block. AGENTS.md asks operational messages not to advise a retry that cannot clear the condition. Suggestion: tell the two cases apart, or name both causes in the message.

kaahos added a commit that referenced this pull request Nov 24, 2026

@datadog-datadog-prod-us1 datadog-datadog-prod-us1 Bot 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.

Bits Code Review: FAIL

The two most critical concurrency issues are: (1) the exclusive recorder lock in flightRecorder.cpp epoch closure drops concurrent CPU and allocation samples by blocking OptionalSharedLockGuard acquisitions; and (2) the epoch mutex in profiler.cpp is held across the entire dictionary rotation and cleanup path, which can stall wall sampling for up to ~500 ms per dictionary drain.

Open Bits AI session

🤖 Bits Code Review · Commit 65ed68e

}
bool FlightRecorder::wallClockEpoch(int lock_index, WallClockEpochEvent *event) {
DEBUG_ASSERT_NOT_IN_SIGNAL();
ExclusiveLockGuard locker(&_rec_lock);

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.

P2 Preserve concurrent sampling while publishing wall epochs

Epoch closure can run immediately after signal dispatch. Its new exclusive recorder lock makes concurrent sample writers fail their OptionalSharedLockGuard and discard observations, including on other recording stripes. The lock covers map allocation and possible file I/O, while wall-epoch statistics still count the dispatched selections, causing sample loss and underweighting. Publication and pruning both need non-dropping shared lifetime protection with separately serialized epoch-map access.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

// Send results are known only now. Close prior statistics first.
// Units already coalesced across an unchanged-pool success-ratio change
// cannot be split retroactively.
if (!pool_changed && outcomes_changed) closeSamplingEpoch(pass_start);

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.

P2 Attribute current-pass suppressions to the new epoch

With an unchanged population, a pass can suppress an owned run while another signal send fails. Closing the preceding epoch here drains suppressions already accumulated during the current pass into that preceding epoch; the new epoch then receives zero. This misattributes the diagnostic suppression count. Keep current-pass suppressions separate until the preceding epoch is closed.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

// Normal-thread order: epoch mutex -> all recording stripes -> _rec_lock.
// rotateDictsAndRun excludes signal writers before settlement and sealing.
// Dictionary readers drain separately through RefCountGuard.
auto epoch_lock = BaseWallClock::samplingEpochLock();

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.

P2 Exclude dictionary maintenance from the epoch-mutex scope

The epoch mutex now blocks the wall timer throughout dictionary rotation and subsequent cleanup, beyond the pre-existing stripe-locked JFR operation. A delayed JNI dictionary accessor can make rotation drain readers for roughly 500 ms per dictionary, introducing additional sampling gaps. Acquire the epoch mutex after dictionary rotation but before recording stripes, and release it after sealing, before cleanup; this requires restructuring the helper while preserving lock order.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

Comment on lines +314 to +323
for (auto& segment : cell->segments) {
u64 weight = segment.weight.load(std::memory_order_acquire);
if (weight == 0 || segment.epoch_start.load(std::memory_order_acquire) == epoch_start) {
segment.epoch_start.store(epoch_start, std::memory_order_release);
segment.weight.store(weight + 1, std::memory_order_release);
block->unowned_blocked_pending_weight.fetch_add(1, std::memory_order_release);
return true;
}
}
return false;

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.

P2 Prefer a matching epoch segment over an empty entry

A partial tail flush can empty an earlier segment while leaving a later segment for the current epoch pending. This loop then selects the empty entry before finding that matching epoch, creating duplicate segments. This wastes the four-entry provenance capacity and causes premature fallback to ordinary sampling and extra deferred events. Prefer an existing matching epoch before allocating an empty segment.

Suggested change
for (auto& segment : cell->segments) {
u64 weight = segment.weight.load(std::memory_order_acquire);
if (weight == 0 || segment.epoch_start.load(std::memory_order_acquire) == epoch_start) {
segment.epoch_start.store(epoch_start, std::memory_order_release);
segment.weight.store(weight + 1, std::memory_order_release);
block->unowned_blocked_pending_weight.fetch_add(1, std::memory_order_release);
return true;
}
}
return false;
size_t selected = kMaxWeightSegments;
for (size_t i = 0; i < kMaxWeightSegments; ++i) {
auto& segment = cell->segments[i];
u64 weight = segment.weight.load(std::memory_order_acquire);
if (weight != 0 && segment.epoch_start.load(std::memory_order_acquire) == epoch_start) {
selected = i;
break;
}
if (weight == 0 && selected == kMaxWeightSegments) selected = i;
}
if (selected == kMaxWeightSegments) return false;
auto& segment = cell->segments[selected];
u64 weight = segment.weight.load(std::memory_order_acquire);
segment.epoch_start.store(epoch_start, std::memory_order_release);
segment.weight.store(weight + 1, std::memory_order_release);
block->unowned_blocked_pending_weight.fetch_add(1, std::memory_order_release);
return true;

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

kaahos added a commit that referenced this pull request Nov 24, 2026
kaahos added a commit that referenced this pull request Nov 25, 2026
kaahos added a commit that referenced this pull request Nov 25, 2026
@dd-octo-sts

dd-octo-sts Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Memory overhead check: ✅ within budget

Profiler 357bad1bf, pipeline. Budget: utils/memcheck/budget.txt. NMT and /proc values are profiled minus no-profiler runs on the same runner.

scenario metric value Δ since budget set limit headroom
allocs native_mem_live_bytes 21.90 MiB +216 KiB 21.95 MiB 51 KiB ok
allocs native_mem_max_bytes 23.15 MiB +205 KiB 23.20 MiB 51 KiB ok
allocs nmt.class 303 KiB +6 KiB 563 KiB 260 KiB ok
allocs nmt.internal 366 KiB −3 KiB 666 KiB 300 KiB ok
classesM native_mem_live_bytes (coverage-corrected) 23.48 MiB +205 KiB 23.55 MiB 72 KiB ok
classesM native_mem_max_bytes (coverage-corrected) 25.40 MiB +213 KiB 25.45 MiB 53 KiB ok
classesM nmt.class 2.94 MiB −1 KiB 3.20 MiB 267 KiB ok
classesM nmt.internal 3.20 MiB +1 KiB 3.50 MiB 306 KiB ok
mixed native_mem_live_bytes 23.35 MiB +205 KiB 23.45 MiB 102 KiB ok
mixed native_mem_max_bytes 40.98 MiB +268 KiB 41.00 MiB 19 KiB ok
mixed nmt.class 302 KiB −5 KiB 563 KiB 261 KiB ok
mixed nmt.internal 412 KiB +2 KiB 717 KiB 305 KiB ok
threads native_mem_live_bytes 19.27 MiB +179 KiB 19.35 MiB 87 KiB ok
threads native_mem_max_bytes 20.29 MiB +187 KiB 20.40 MiB 110 KiB ok
threads nmt.class 114 KiB +1 KiB 410 KiB 296 KiB ok
threads nmt.internal 159 KiB −5 KiB 461 KiB 302 KiB ok
traces native_mem_live_bytes 20.46 MiB +232 KiB 20.50 MiB 45 KiB ok
traces native_mem_max_bytes 21.67 MiB +263 KiB 21.70 MiB 33 KiB ok
traces nmt.class 470 KiB −1 KiB 768 KiB 298 KiB ok
traces nmt.internal 615 KiB +0 KiB 870 KiB 256 KiB ok

✅ nmt.tracing absent in every scenario.

Not budgeted (too noisy on shared runners)
scenario nmt.code nmt.gc nmt.total proc.VmRSS proc.RssAnon
allocs 1.68 MiB 4 KiB 2.78 MiB 35.49 MiB 30.93 MiB
classesM 5.83 MiB 32 KiB 14.60 MiB 37.10 MiB 32.90 MiB
mixed 1.61 MiB 4 KiB 2.72 MiB 40.14 MiB 35.44 MiB
threads 7 KiB 1 KiB 885 KiB 24.90 MiB 19.92 MiB
traces 5.24 MiB 16 KiB 7.05 MiB 25.27 MiB 20.87 MiB

kaahos added a commit that referenced this pull request Nov 25, 2026
kaahos added a commit that referenced this pull request Nov 25, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI human_review:mandatory Human review required — see PR description test:asan Run CI tests with AddressSanitizer configuration test:fuzz test:release Run CI tests with release configuration test:reliability test:tsan Run CI tests with ThreadSanitizer configuration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants