Skip to content

Add opt-in growth to the toolbox Hashtable's bucket array - #13649

Open
dougqh wants to merge 7 commits into
masterfrom
dougqh/toolbox-hashtable-growth
Open

dougqh wants to merge 7 commits into
masterfrom
dougqh/toolbox-hashtable-growth

Conversation

@dougqh

@dougqh dougqh commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What Does This Do

Based on master: it changes internal-api's datadog.trace.util.Hashtable, which #13531 later moves into the toolbox unchanged.

The single-threaded chained Hashtable.D1 and D2 can now grow their bucket array as they fill, instead of allocating it for their bound up front. Growth is opt-in through a new Hashtable.Sizing spec; the default stays fixed, exactly as today.

  • Default unchanged: createBounded(entryClass, max) and Sizing.bounded(max) allocate capacityFor(max) buckets up front and never grow.
  • Opt-in growth: setting Sizing.initialCapacity(n) makes a table growable. It starts at capacityFor(n), but never below a quarter of capacityFor(bound) (at least 16 buckets) or above the full size, and doubles once an insert would take it past 3/4 full, so it grows at most twice (MAX_GROWTHS). It stops at capacityFor(bound), so a table filled to its bound ends at exactly the size it allocates today. Every insert path checks: insert, tryInsertOrReplace (for a new key), tryGetOrCreate* and tryGetOrCreateOrEvict*. The create paths check after the creator returns, so a creator that throws causes no growth.
  • Rehash: the new public static Hashtable.resize(TEntry[]) relinks every entry into the doubled array, reading each next first. The only allocation is the new array. For callers that own their bucket array and use the static building blocks, the array stays fixed unless they call resize.
  • Hashtable.Sizing: an immutable spec nested at the top of Hashtable:
    static final Hashtable.Sizing SIZING = Hashtable.Sizing.bounded(4096).initialCapacity(256);
    Hashtable.D1<String, MyEntry> table = Hashtable.D1.create(MyEntry.class, SIZING);
    Both values are entry counts. The initial capacity is clamped to the bound, and one below the quarter-size floor starts at the floor. initialCapacity(0) means "grow from the floor".
  • Eviction and size accounting: growth moves entries rather than copying them, so the count never changes. The eviction scan is reset on resize, since its saved bucket and chain position point into the old array. In D1/D2, a table is always at full size by the time it's full, so eviction never runs before a growth.

Motivation

Bounds are usually chosen for the worst case, so a fixed table holds a worst-case array for as long as it lives, even if it never fills: at a 65,536 bound, a 512 KiB array, which is a humongous allocation on a small G1 heap. A growable table holds a quarter of that until it fills. Growth isn't free, though: each doubling relinks every entry, so filling a growable table to its bound takes about twice as long as filling a fixed one. That's why it's opt-in. It suits long-lived tables with generous bounds that may stay sparse, especially ones filled from a background thread, where a growth cycle or two is affordable. Tables built and filled right away should stay fixed.

Additional Notes

  • Measured (Bits, JDK 17, 5 CPUs, steal median 20%; HashtableGrowthBenchmark, added here, builds a fresh table per op, 3 forks per side, -prof gc). Quarter-size growable start vs the fixed array (then on master):

    bound / fill fixed growable time bytes
    1,024 / 8 1,037 ns, 8,264 B 337 ns, 2,120 B −68% 0.26×
    1,024 / 256 2,453 ns, 8,264 B 2,369 ns, 2,120 B noise 0.26×
    1,024 / full 6,016 ns, 8,264 B 14,998 ns, 14,464 B +149% 1.75×
    65,536 / 8 79,050 ns, 524,360 B 19,981 ns, 131,144 B −75% 0.25×
    65,536 / 256 79,888 ns, 524,360 B 21,895 ns, 131,168 B −73% 0.25×
    65,536 / full 719,845 ns, 524,362 B 1,535,520 ns, 917,619 B +113% 1.75×

    An earlier start at 16 buckets was 2.6–2.8× slower on full fills; capping growth at two doublings helped only somewhat, since the cost is per relink. Both arms (buildFixed, buildGrowable) are now in the benchmark, so one build measures both. The default path is unchanged from master.

  • No shrinking: clear() and drain() keep the grown array, which suits tables that refill every cycle. A test pins this behavior. Shrinking is left for a follow-up if a caller needs it. The case that would justify it is a burst that grows a table past the G1 humongous size (131,072 buckets, 512 KiB, half of a 1 MiB region on heaps under about 2 GiB) followed by quiet cycles. Shrinking only on clear()/drain(), when there's nothing to relink, would release that array.

  • The State path (Hashtable.createBounded(int) for callers managing their own state) still allocates its full size up front.

  • Iteration: inserting while iterating can now invalidate a cursor or forEach. That was already unsupported, and the Javadoc says so.

  • LruTable (Add an allocation-free bounded LRU, optionally growable, to internal-api #13594, stacked on this PR) grows through Hashtable.resize, sharing this growth instead of keeping its own copy.

  • Tests:

    • the default sizing is fixed at capacityFor(bound) and never grows;
    • for bounds from 0 to 1,000, a growable table starts at the quarter-size floor, grows at most twice, and ends at exactly capacityFor(bound);
    • every insert path grows;
    • colliding keys are still found after growth, and eviction still works;
    • removal, clearing, draining and iteration work after growth;
    • the static resize relinks every entry;
    • Hashtable.Sizing's validation, clamping and immutability, an explicit initial capacity, and a table that starts at full size.

🤖 Generated with Claude Code

Field layout and the cursor (9a7479b)

Adding a maxBuckets field to D1/D2 moved buckets from offset 12 to offset 16. After that, C2 stopped scalar-replacing TableCursor in cursor loops: 24 B/op and about half the throughput. The cause is the offset, not the field: an unused int or Object declared before buckets on master does the same. The growth limit now lives in SizeManager, so D1/D2 have master's layout again. Measured on JDK 17, 3 forks, -t 4, ops/µs:

master before the fix after the fix
D1 cursor 8.06, 0 B 4.62, 24 B 8.55, 0 B
D2 cursor 8.61, 0 B 3.55, 24 B 8.04, 0 B

HashtableGrowthBenchmark shows no change from the move: B/op is identical in every cell, and time is within noise.

@dougqh dougqh added type: feature Enhancements and improvements tag: performance Performance related changes tag: ai generated Largely based on code generated by an AI or LLM labels Nov 23, 2026
@pr-commenter

pr-commenter Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

LLM Validation

LLM Validation Gate — java-agent-instructions

✅ PASS

  • No blocking-case regressions; the quality change is within noise (baseline/candidate confidence intervals overlap).

6 case(s) · quality 80.6 → 81.5 (+0.9) · win-rate 51% [47%–55%]

Details — analysis and per-case results

Analysis

Changed instruction file(s): AGENTS.md.

No safety or blocking-case regressions across 6 case(s). Overall pairwise win-rate 51% [47%–55%], quality +0.9 — see the verdict above for whether that clears the noise band.

Results

  • Pairwise win-rate: 51% [47%–55%] — candidate's share of blind comparisons (90% CI; spanning 50% = no clear difference)
  • Overall quality: 80.6 → 81.5 (/100, +0.9)
  • Bad signals introduced (advisory): 0
  • Candidate criteria coverage (advisory): 23/27 (85%) — expected_criteria the candidate met; does not affect the gate
  • Blocking-case regressions: 0

Cases

Case Mode Quality Δ Win-rate (90% CI) Safety
java-core-validation-001 warn +4.2 67% [49%–84%] ok
java-unit-test-conventions-001 warn -3.1 50% [50%–50%] ok
java-premain-safety-001 warn -1.1 50% [50%–50%] ok
java-ci-download-guidance-001 warn +4.7 50% [50%–50%] ok
java-documentation-only-validation-001 warn +1.1 42% [28%–55%] ok
java-existing-spock-maintenance-001 warn -0.6 50% [50%–50%] ok

Per-dimension scores, token usage, latency, and estimated cost are in the CI job logs.

@dougqh
dougqh marked this pull request as ready for review November 23, 2026 18:28
@dougqh
dougqh requested a review from a team as a code owner November 23, 2026 18:28
@dougqh
dougqh requested review from PerfectSlayer and removed request for a team November 23, 2026 18:28
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T18:33:21.287828Z f0dc540 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.

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

Resizing preserves the entry count and resets the eviction cursor, while growth remains capped at the full-table bucket count. The assessment is static only; tests were not executed.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit f0dc540

@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: f0dc5405b1

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +37 to +38
* would allocate ({@link #capacityFor(int)}). An almost-empty table no longer pays for its bound up
* front, and a full one ends exactly where it used to. A caller-owned array driven by the static

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Measure the growing-table allocation tradeoff

The change claims reduced allocation for sparsely populated tables, but supplies no matched before/after JMH time and allocation results as required for shipped toolbox code. Growth also allocates intermediate arrays and synchronously relinks entries, so the smaller retained array alone does not establish the overall tradeoff. The existing HashtableD1Benchmark and HashtableD2Benchmark populate their tables during setup, then clear and reuse the grown arrays in add_hashtable, excluding growth from measurement. Add fresh-table population measurements with the same machine, JDK, JVM flags and benchmark settings, including -Pjmh.profilers=gc, or drop the unmeasured performance claim.

AGENTS.md reference: AGENTS.md:L82-L84

Useful? React with 👍 / 👎.

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.

Fair point: the toolbox is in the strict perf-claim scope. I added HashtableGrowthBenchmark (cc7e9f1), which builds a fresh bounded table per op at several fill levels, so growth and the bucket-array allocation are measured, unlike HashtableD1Benchmark, which refills one table. A matched before/after run (#13531 fixed vs. this branch, same machine, JDK and flags, -prof gc) is queued; I'll add the numbers to the description, or drop the claim if they don't support it.

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.

Measured, and the result changed the design. A fresh-table benchmark (HashtableGrowthBenchmark, JDK 17, 3 forks per side, -prof gc) showed growth costs about 2× the time on a full fill (+113% to +149%, 1.75× the bytes) and saves 68–75% time and 4× the bytes on sparse fills. So growth is now opt-in through Sizing.initialCapacity(n): createBounded and Sizing.bounded stay fixed, exactly as on master. A growable table starts at a quarter of the full size at least and doubles at most twice. The table is in the PR description.

@datadog-datadog-prod-us1-2

This comment has been minimized.

@dd-octo-sts

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

Copy link
Copy Markdown
Contributor

🟢 Java Benchmark SLOs — All performance SLOs passed

Suite Status
Startup 🟢 pass

SLO thresholds are defined here based on automatically generated metrics. A warning is raised when results are within 5% of the threshold.

PR vs. master results
Scenario Candidate master Δ (95% CI of mean)
startup:insecure-bank:iast:Agent 14.91 s 14.72 s [+0.5%; +2.1%] (maybe worse)
startup:insecure-bank:tracing:Agent 13.70 s 13.80 s [-1.3%; -0.1%] (maybe better)
startup:petclinic:appsec:Agent 17.35 s 17.18 s [-0.1%; +2.1%] (no difference)
startup:petclinic:iast:Agent 17.14 s 17.18 s [-1.2%; +0.7%] (no difference)
startup:petclinic:profiling:Agent 16.86 s 16.85 s [-0.9%; +1.0%] (no difference)
startup:petclinic:sca:Agent 17.26 s 17.12 s [-0.0%; +1.6%] (no difference)
startup:petclinic:tracing:Agent 16.31 s 16.40 s [-1.6%; +0.5%] (no difference)

Commit: 9a7479b2 · CI Pipeline · Benchmarking Platform UI


Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion.

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

D1/D2 gain bounded bucket growth and configurable initial sizing,
with growth tests and a fresh-table allocation benchmark;
the benchmark fails on repeated invocations with assertions enabled.
One finding remains open, there were no earlier findings to resolve,
and tests and benchmarks were not executed.

Open Bits AI session

🤖 Bits Code Review · Commit cc7e9f1

Comment on lines +58 to +60
Hashtable.D1.createBounded(HashtableD1Benchmark.D1Counter.class, bound);
// The entries are relinked into each new table; the previous table is garbage by then.
for (final HashtableD1Benchmark.D1Counter entry : entries) {
table.insert(entry);

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 Detach reused entries before reinserting them

With assertions enabled and fill=256, repeated benchmark invocations throw AssertionError instead of producing measurements. Reused entries retain chain links from the previous table, but insertHeadEntryAt requires entry.next() == null; key-100 and key-221 collide in the final 512-bucket array. Clear each entry’s link before reinserting it.

Suggested change
table.insert(entry);
entry.setNext(null);
table.insert(entry);

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

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.

Right, thanks: fixed in 4a8963e. Each reused entry is now detached (setNext(null)) before it's reinserted.

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

D1/D2 now grow bounded bucket arrays from configurable initial sizes,
with growth tests and a fresh-table allocation benchmark;
the latest change clears reused entry links before insertion.
That fixes the earlier assertion failure, leaving no open findings;
validation remains static, with tests and benchmarks unexecuted.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 4a8963e

dougqh and others added 4 commits November 23, 2026 14:20
Hashtable.D1 and D2 allocated capacityFor(maxCapacity) buckets up front
and never resized. Callers pick worst-case bounds, so a mostly empty
table retained an array sized for its bound.

The bucket array now starts at min(16, capacityFor(maxCapacity)) and
doubles once an insert would take the table past 3/4 full, stopping at
capacityFor(maxCapacity). A table filled to its bound ends at exactly
the bucket count it allocated before, so a full table's steady state
is unchanged. Growth relinks the existing entries into the new array,
which is its only allocation, and restarts the SizeManager eviction
scan, whose saved bucket and chain position refer to the old array.

Callers can also choose the starting size with TableSizing, a small
immutable spec (bounded(max).initialCapacity(n)) that other tables can
adopt later; createBounded is shorthand for the default spec. A public
Hashtable.resize helper lets callers driving the static building
blocks grow their own arrays the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HashtableD1Benchmark refills one table, which keeps the bucket array
it grew, so it can't show what growth costs or saves. This builds a
fresh table per op at a few fill levels, so the array allocation and
the growth are measured; it uses only createBounded, so it also runs
against the fixed table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
insertHeadEntryAt asserts an entry is unlinked, and the benchmark reuses
its entries across tables, so with assertions enabled colliding keys
tripped it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dougqh
dougqh force-pushed the dougqh/toolbox-hashtable-growth branch from 4a8963e to 9b27cb6 Compare November 23, 2026 19:28
@dougqh
dougqh requested review from a team as code owners November 23, 2026 19:28
@dougqh
dougqh requested review from claponcet, erikayasuda, jpbempel, manuel-alvarez-alvarez, mhlidd and ygree and removed request for a team November 23, 2026 19:28
@dougqh
dougqh changed the base branch from dougqh/toolbox-component to master November 23, 2026 19:29
@dd-octo-sts

dd-octo-sts Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Hi! 👋 Thanks for your pull request! 🎉

To help us review it, please make sure to:

  • Add at least one type, and one component or instrumentation label to the pull request

If you need help, please check our contributing guidelines.

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

Static review found no actionable defect in growth, rehashing, sizing, or eviction bookkeeping. The construction-time and allocation tradeoff remains unmeasured pending matched benchmark results.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 9b27cb6

@dougqh dougqh added the comp: core Tracer core label Nov 23, 2026
dougqh and others added 2 commits November 23, 2026 16:17
Growing from 16 buckets to a large bound relinks every entry about a
dozen times; filling a 65,536-entry table took 2.6x as long as the fixed
array. The bucket array now starts at a quarter of capacityFor(bound),
at least 16 buckets, so a table doubles at most twice (MAX_GROWTHS). An
explicit initial capacity can start it larger, not smaller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Filling a growable table to its bound costs about twice the time of a
fixed one, since every doubling relinks every entry. Sizing.bounded(max)
and createBounded allocate the full array up front again, as before
this PR; setting an initial capacity opts into growth, which still
starts at a quarter of the full size at least and doubles at most twice.
The growth benchmark now measures both sizings in one build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dougqh dougqh changed the title Grow the toolbox Hashtable's bucket array as it fills Add opt-in growth to the toolbox Hashtable's bucket array Nov 23, 2026
The growth limit moves from D1/D2 into SizeManager. As a field ahead of
buckets it moved buckets from offset 12 to 16, and C2 then stopped
scalar-replacing TableCursor in cursor loops (24 B/op, about half the
throughput on the cursor benchmarks).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
// Read next before relinking: insertion overwrites it with the new bucket's chain.
Entry next = entry.next();
entry.setNext(null);
insertHeadEntryFor(grown, entry.keyHash, entry);

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 · Define which routing hash resize uses

insertHeadEntryFor places an entry using the supplied hash, while resize places it using Entry.keyHash. I verified that with four buckets, an entry with stored hash 0 can be inserted and found using routing hash 5. After doubling to eight buckets, the same lookup returns null because the entry moved to bucket 0.

Could we document that caller-owned arrays are resizable only when insertion and lookup use Entry.keyHash? If custom routing is intended to work, resize needs to use that routing function too.

--- found with Codex

table.clear();
assertEquals(0, table.size());
assertNull(table.get(key(1)));
// clear keeps the grown array; refilling to the bound still ends at the full-table size.

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.

P3 · Assert bucket retention immediately after clear and drain

The final 256 assertion also passes if the table shrinks on clear and regrows during refill. I changed a scratch copy to shrink on D1 clear and drain, and all 48 growth and sizing test cases still passed. Could we capture the grown bucket array and use assertSame immediately after each operation to pin the intended reuse behavior?

--- found with Codex

@leoromanovsky leoromanovsky added the crucible: reviewing A Crucible review has started; this PR has reviewer attention. label Nov 24, 2026 — with ddtool CLI
@leoromanovsky leoromanovsky removed the crucible: reviewing A Crucible review has started; this PR has reviewer attention. label Nov 24, 2026
@DataDog DataDog deleted a comment from dd-octo-sts Bot Nov 24, 2026
@DataDog DataDog deleted a comment from dd-octo-sts Bot Nov 24, 2026
@dougqh dougqh added tag: performance Performance related changes and removed tag: performance Performance related changes labels Nov 24, 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

comp: core Tracer core tag: ai generated Largely based on code generated by an AI or LLM tag: performance Performance related changes type: feature Enhancements and improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants