Skip to content

fix(#5712,#9074,#9169): unordered tagged hash buckets, NULL_STRATEGY ERROR on hash, new page size defaults - #9222

Merged
lvca merged 7 commits into
mainfrom
fix/9169-9074-5712-hash-index
Oct 4, 2026
Merged

lvca merged 7 commits into
mainfrom
fix/9169-9074-5712-hash-index

Conversation

@lvca

@lvca lvca commented Oct 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Test plan

  • HashIndexLayoutVersionTest (both layouts, tiny pages, reopen, rebuild, defaults), Issue9074HashIndexNullStrategyTest, Issue9169HashIndexEqualityLookupTest
  • engine index, schema and engine packages: 2477 tests, 0 failures

Fixes #5712, fixes #9074, fixes #9169

Notes for the release notes

  • Downgrade (important): an older server does not check the layout version in the file name, so it would read the new hash pages as sorted ones and silently corrupt the index. Never open a database holding a new or rebuilt hash index with an older server; drop and recreate the hash indexes first.
  • NULL_STRATEGY ERROR was stored by hash indexes but never enforced; it now is on put, like LSM (a remove or a lookup is not refused, so rows already indexed under a null key stay deletable). Applications that wrote null or missing keys into a hash index created with ERROR will fail at commit after upgrading, and building such an index over existing null rows fails.
  • Page size defaults: 4 KB (16 KB when a key column is STRING, BINARY or DECIMAL) instead of 64 KB, so about 16x more, smaller pages. A key wider than a page is refused at insert on a newly created index (about 16 KB for variable-width keys), where the old default accepted up to about 64 KB; pass an explicit page size for such keys. An explicit hash page size above 16 KB is slower than the default (a lookup scans the page tags). A rebuild of a legacy index with a 64 KB page size takes the new default.
  • Low-cardinality NOTUNIQUE_HASH inserts are slow at every page size, not a regression of this change (NOTUNIQUE_HASH insert cost grows with the number of RIDs per key (rewrites the whole entry per insert) #9228 tracks it, the docs advise NOTUNIQUE for such keys). Measured with HashIndexSkewedNonUniqueBenchmark, 100k inserts: 10 keys 66 s (4 KB) vs 47 s (64 KB) vs 0.28 s (LSM); 200 keys 35 s (4 KB) vs 48 s (64 KB) vs 0.21 s (LSM); 5000 keys 1.4 s (4 KB) vs 6.1 s (64 KB) vs 0.18 s (LSM).

…ATEGY ERROR on hash, 4KB/16KB default page size

- hash bucket pages (file version 2) append entries and slots, with a 1-byte hash tag per slot scanned on lookup; version 1 files keep the sorted layout and still open
- a rebuild moves a legacy index to the current layout and replaces its 64KB default page size
- default page size 4KB (16KB for STRING/BINARY/DECIMAL keys) from the design-space benchmark
- NULL_STRATEGY ERROR is enforced by hash indexes at commit, like LSM
- lookups on an index with a damaged key type metadata keep reporting the actionable error
@lvca lvca added this to the 26.10.1 milestone Oct 4, 2026
@lvca lvca self-assigned this Oct 4, 2026
@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b96d088f-5f0b-4007-8544-3b35d84fb337
📥 Commits

Reviewing files that changed from the base of the PR and between 1addb51 and 8653fbb.

📒 Files selected for processing (8)
  • engine/src/main/java/com/arcadedb/index/hash/HashIndex.java
  • engine/src/main/java/com/arcadedb/index/hash/HashIndexBucket.java
  • engine/src/main/java/com/arcadedb/index/lsm/LSMTreeIndexAbstract.java
  • engine/src/test/java/com/arcadedb/index/HashIndexSkewedNonUniqueBenchmark.java
  • engine/src/test/java/com/arcadedb/index/hash/HashIndexLayoutVersionTest.java
  • engine/src/test/java/com/arcadedb/index/hash/Issue5713HashIndexPageSizeTest.java
  • engine/src/test/java/com/arcadedb/index/hash/Issue9074HashIndexNullStrategyTest.java
  • engine/src/test/java/com/arcadedb/index/hash/Issue9169HashIndexEqualityLookupTest.java

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

The HASH index now uses an unordered, hash-tagged layout for new index files and continues to read the legacy sorted layout. Page-size defaults vary by key type. Immediate puts also check the configured null strategy. New tests cover layout behavior, null handling, and equality lookups.

Changes

HASH index layout and validation

Layer / File(s) Summary
Layout versions and page-size selection
engine/src/main/java/com/arcadedb/index/hash/HashIndex.java, engine/src/main/java/com/arcadedb/index/hash/HashIndexBucket.java, engine/src/test/java/com/arcadedb/index/hash/HashIndexLayoutVersionTest.java, engine/src/test/java/com/arcadedb/index/hash/Issue5713HashIndexPageSizeTest.java
New HASH indexes use layout version 2. The index retains support for version 1 and selects a 4 KB or 16 KB default according to key types. Tests cover reopen, rebuild, version rejection, and page-size behavior.
Tagged bucket lookup and mutation
engine/src/main/java/com/arcadedb/index/hash/HashIndexBucket.java, engine/src/test/java/com/arcadedb/index/hash/HashIndexLayoutVersionTest.java, engine/src/test/java/com/arcadedb/index/hash/HashIndexSkewedNonUniqueBenchmark.java, engine/src/test/java/com/arcadedb/index/hash/Issue9169HashIndexEqualityLookupTest.java
Tagged pages append slots and use one-byte hash tags to filter key comparisons. Lookup, insertion, removal, splits, and overflow handling support tagged and legacy layouts. Tests cover duplicate keys, collisions, churn, concurrent reads, and equality queries; the benchmark compares non-unique HASH and LSM indexes.
HASH null-strategy validation
engine/src/main/java/com/arcadedb/index/hash/HashIndex.java, engine/src/main/java/com/arcadedb/index/lsm/LSMTreeIndexAbstract.java, engine/src/test/java/com/arcadedb/index/hash/Issue9074HashIndexNullStrategyTest.java
Immediate HASH index puts check null keys through a shared validation method. Tests cover the ERROR, SKIP, and INDEX strategies, including direct index puts and index creation over existing null values.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: robfrank

Merge Risk: ⚪ Minimal · up to 8653f

The examined lookup, deletion, and null-validation paths show no confirmed issue preventing merge after normal checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 8653f

The format change affects upgrade and rollback compatibility. Newly enforced null validation can also make rebuilding a legacy index fail after the original index has been removed, putting index availability and data-integrity enforcement continuity at risk.

Retained concerns

  • Medium · reliability · inferred: New ERROR validation makes legacy null-containing HASH indexes fail during rebuild after the original index is dropped. The inspected orchestration retries contention but does not restore the original index on validation failure. This creates a migration recovery and failure-containment concern: index availability, and potentially index-backed uniqueness enforcement, may not survive the failed transition. The exact failed-replacement registration state remains unresolved; loss of uniqueness enforcement is not verified.
Security review details

Security Blast Radius

  • inferred — The identified failure path is bounded to indexes selected for rebuild in a database. It requires schema-maintenance authority; existing null-containing records supply the failing input. No cross-database or unauthenticated trigger was established by the inspected path.

Security Findings and Attack Paths

  • inferred — The material path is legacy null data, followed by authorized rebuild, original-index removal, and newly enforced validation failure during replacement construction. This is a failed-transition risk, not a demonstrated privilege escalation or verified uniqueness bypass.

Trust Boundaries and Controls

  • observed — Rebuild checks UPDATE_SCHEMA permission before maintenance. Schema drop also checks that permission and invokes a guard for indexes backing constraints. These controls limit destructive rebuild reachability and are counterevidence against unrestricted removal of protected constraints.

Resilience and Maintainability Implications

  • observed — Bucket edits use transaction-private mutable pages, and rollback discards modified and new pages. This counters exposure of intermediate slot writes. It does not, by itself, prove whole-operation snapshot consistency across every page participating in a split.

Hardening Proposals

  • proposed — Preserve the original index until a replacement has passed validation and is ready for an atomic swap, or preflight the newly enforced null policy before destructive removal. Define a terminal failure state that retains or explicitly restores index-backed integrity controls.
🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements the unordered tagged layout and legacy-layout support in #5712, tests both layouts and rebuilds, enforces NULL_STRATEGY ERROR for hash puts as required by #9074, and tests SQL/open… Provide benchmark results for the small-index and miss-heavy probe workloads requested by #5712, or retain the prior default until those results are available.
Out of Scope Changes check ⚠️ Warning The page-size default changes to 4 KB and 16 KB exceed the layout change proposed by #5712. That issue explicitly deferred changing the global default until broader workload data was collected. The su… Defer the page-size default changes until the missing #5712 workload evidence is supplied, or include results for those workloads to support the expanded scope.
Docstring Coverage ⚠️ Warning Docstring coverage is 57.32% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 82 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main changes: the hash bucket layout, NULL_STRATEGY ERROR enforcement, and new page-size defaults. It is long, but remains specific and relevant.
Description check ✅ Passed The description explains the changes, related issues, tests, and release risks. It does not include the template’s Motivation heading or explicitly confirm the required mvn clean package build check…
Full details: Linked Issues check

Explanation

The PR implements the unordered tagged layout and legacy-layout support in #5712, tests both layouts and rebuilds, enforces NULL_STRATEGY ERROR for hash puts as required by #9074, and tests SQL/openCypher equality lookups with UNIQUE_HASH for #9169. However, #5712 required broader workload evidence before changing the global page-size default. The PR changes defaults to 4 KB and 16 KB. Its description reports a 200k-entry benchmark, and the added benchmark covers skewed LONG keys and hot-key reads. The evidence does not establish results for small indexes or miss-heavy probes, which #5712 specifically requested.

Full details: Out of Scope Changes check

Explanation

The page-size default changes to 4 KB and 16 KB exceed the layout change proposed by #5712. That issue explicitly deferred changing the global default until broader workload data was collected. The submitted benchmark evidence does not cover the requested small-index and miss-heavy probe cases. The remaining implementation and tests relate to #5712, #9074, or #9169.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · 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

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codacy-production

codacy-production Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 medium

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
Complexity 1 medium

View in Codacy

🟢 Metrics 24 complexity

Metric Results
Complexity 24

View in Codacy

🟢 Coverage 95.10% diff coverage · -5.78% coverage variation

Metric Results
Coverage variation ✅ -5.78% coverage variation
Diff coverage ✅ 95.10% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (1addb51) 212235 180550 85.07%
Head commit (8653fbb) 244879 (+32644) 194174 (+13624) 79.29% (-5.78%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#9222) 102 97 95.10%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

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.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review

I read the full diff and traced the page-level code paths by hand. I did not build or run the tests, so the 2477-test result in the description is taken from the author.

Summary

The change looks correct, and the layout-version split is cleanly done. The new bucket layout is unordered, appends entries and slots, and adds a 1-byte hash tag per slot. Version-1 files keep the sorted binary-search path.

Checked and fine

  • Tag source: tagOf takes the low byte of the hash, while the directory uses the top bits. Every key in a bucket shares the top bits, so the low byte is the right discriminator.
  • Compaction and growth: compactPage and the grow-in-place branch of addRIDToExistingEntry only rewrite slot offsets through writeSlot, which leaves the tag byte alone. That is correct because slot order never changes in the tagged layout.
  • Swap-last removal: removeEntryFromPage moves the last slot (offset and tag) into the freed position. removeFromBucket re-scans from p after each removal, so the moved entry is not skipped. The specificRID loop returns right after the first successful removal, so its p + 1 stride cannot skip the moved entry.
  • Splits and overflow: splitBucket and insertRawEntry recompute the hash per entry, so tags stay consistent after a split. Overflow inserts go through the same appendEntry.
  • Fail-loud on damaged metadata: unsupportedKeyColumn is a good catch. With tag filtering, a key serialized with a damaged type would otherwise silently read as "no such key".
  • Null strategy (9074): checkForNulls sits on the non-transactional branch only. A transaction buffers the operation and the check fires when commit replays it, which matches LSM behaviour and the TransactionException the tests expect.
  • Rebuild page size: getPageSizeForNewFile replaces only the legacy 64 KB default on a legacy layout. An explicit 8 KB is preserved, and rebuildOfALegacyIndexReplacesTheOldDefaultPageSizeOnly pins that.

Issues and suggestions

  1. CLAUDE.md style in Issue9169HashIndexEqualityLookupTest: it uses fully qualified java.util.Map.of(...) several times. Please import Map. It also uses final var, which is not the style elsewhere in these tests.

  2. Static mutable test hook in production code: HashIndexFactoryHandler.layoutVersion is a process-wide static volatile. That is fine while tests run sequentially, but any parallel test creating a hash index during HashIndexLayoutVersionTest would silently get a legacy index. Consider scoping it per database or builder, or enforcing same-thread execution for that class (for example @ResourceLock or @Execution(SAME_THREAD)). The @AfterEach reset is good.

  3. Test coverage gaps:

    • No test for the non-transactional put/remove path of checkForNulls (calling index.put(new Object[]{null}, rid) directly outside a transaction). It is the only branch the SQL-driven tests do not reach.
    • No test with a real version-1 file produced by the previous release. Simulating it with the layoutVersion hook is reasonable since the legacy layout code is unchanged, but a checked-in fixture would pin real on-disk compatibility.
    • The lock-free reader invariant (4743) is not exercised against the new append-then-slot-then-count write order. Readers use committed page snapshots so I believe it is safe, but a short concurrent read/insert test on the tagged layout would make that explicit.
  4. Upgrade and downgrade note: the version is encoded in the file name, so an older binary cannot read a version-2 hash index. The release notes should say that downgrading after a hash index is created or rebuilt requires dropping and recreating hash indexes.

  5. Page-size default: going from 64 KB to 4 KB means about 16x more bucket pages and more directory doublings for the same data, and doubleDirectory leaves the old region behind until a rebuild. Acceptable given the benchmark in the description, but a one-line note on the expected file-size overhead would help.

  6. Minor: the 9169 part is only a pinning test plus an answer to the question. "Fixes 9169" may close an issue that wanted guidance in the docs; consider a short docs note on when to choose UNIQUE_HASH.

Overall this looks good to merge once the style nit (1) is addressed. The test additions in (3) would be nice to have.

…ayout test, direct null put/remove, concurrent reads)
@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review

I read the diff and traced the bucket-page logic. The unordered/tagged layout looks correct, and the tests cover both layouts. I have two behavior questions and a few smaller points.

What I checked and found correct

  • Slot tags survive reordering. compactPage keeps slot order and only rewrites offsets, so the tags stay valid. addRIDToExistingEntry re-finds its entry by key and tag after compaction.
  • Removal. In the tagged layout the last slot (offset and tag) moves into the removed slot. The "remove all matches" loop re-scans from p after the swap, which is right. In the legacy layout the shift-left behavior is unchanged, and the same loop covers it.
  • Tag choice. The tag is the low byte of the hash and the directory uses the top bits, so the tag discriminates entries inside one bucket.
  • Split path. insertRawEntry is given entryHash, so the tag is rebuilt correctly after a split.
  • Page size. Rebuilding a legacy 64 KB index takes the new default, while an explicit 64 KB on a v2 index is preserved.

Concerns

  1. A HASH index accepts NULL_STRATEGY ERROR and then stores null and missing keys without an error #9074 changes behavior for existing databases. NULL_STRATEGY.ERROR is the schema default (LocalSchema ~L3369, and HashIndex L493 when the JSON has no value). It is also the value already persisted in the metadata page of existing hash indexes. Before this PR the strategy was stored but never enforced, so any app that wrote null or missing keys into a default-strategy hash index worked. After upgrade those commits fail, and a REBUILD INDEX over rows that already hold nulls will fail too. This matches LSM and is arguably the right fix. I would still call it out explicitly in the PR description or release notes, and consider a test for REBUILD INDEX on a hash index that already contains null keys, so the failure mode is known and its message is actionable.

  2. Page size 64 KB to 4 KB for non-unique indexes with heavy key duplication. The 200k-entry benchmark in the description is unique-oriented. For a low-cardinality NOTUNIQUE_HASH (say a few keys with 100k+ RIDs each) the overflow chain per key is now about 16x longer. putInternal walks the chain to find the entry or a page with room, and get reads every page of the chain. Hot-key insert latency in particular may regress compared with 64 KB pages. Could you run the same benchmark with a skewed or low-cardinality NOTUNIQUE_HASH workload before settling on 4 KB as the default there?

  3. Production static used as a test hook. HashIndexFactoryHandler.layoutVersion is a static volatile mutable field in main code, used only so tests can create legacy-layout files. HashIndexLayoutVersionTest is SAME_THREAD, but that only serializes this class. Another test class creating a hash index in parallel while the field is lowered would silently get a v1 file. If the surefire config runs classes in parallel, please check. Otherwise, consider passing the version through the package-private HashIndex constructor you already added, so no global state is needed.

  4. Small duplication. HashIndex.checkForNulls is a copy of LSMTreeIndexAbstract.checkForNulls, including the message text. Extracting a small static helper would keep the two messages from drifting apart.

  5. Format compatibility. The file version goes from 1 to 2. Old servers will refuse v2 files, which is expected but means no downgrade path. Worth one line in the release notes.

Minor

  • In HashIndexBucket, the class-level constant comment block and the HashIndex factory comment are long single lines (over 160 columns in a couple of places). Please wrap them for style.
  • removeFromBucket with specificRID: the for header is correct, but the comment "another entry has moved into position p" only applies to the other branch. A short note on why no re-scan is needed there (it returns on first removal) would help readers.
  • Issue9169HashIndexEqualityLookupTest pins the planner using an index, but it does not assert anything about the performance claim in UNIQUE or UNIQUE_HASH for an id that is only looked up by equality? #9169. That is fine as a regression pin, just noting it.

Tests

Coverage is good: both layouts run through insert, lookup, remove, reopen, rebuild and tiny pages (splits and overflow), plus null-strategy cases for the SQL and direct API paths. It would be worth adding one case where the tag byte collides (two different keys with the same low byte in one bucket) so the full-key comparison on a tag hit is exercised deliberately rather than by chance. Also one case that mixes remove and re-insert on the same page in the tagged layout, to exercise the last-slot swap with tags.

Nothing here blocks the merge from a correctness view. Items 1 and 2 are the ones I would resolve or document before merging.

…share the null check message with LSM; skewed non-unique benchmark
@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review

I read the full diff of the three engine files and traced the bucket-page paths. I did not build or run the tests. Two earlier reviews on this PR already covered the tag/compaction/swap-remove/split correctness points and I agree with them, so I only add what is new.

Correctness: looks sound

  • findNextEntry in the tagged layout is a linear scan with a tag filter, and removeFromBucket re-scans from p after the last-slot swap, so no entry is skipped. The specificRID loop returns on the first removal, so its p + 1 stride is safe.
  • splitBucket recomputes the hash from the key part of the raw entry (hashSerializedKey), so tags written by insertRawEntry match what get computes.
  • unsupportedKeyColumn guarding serializeKeys is a good catch: with tag filtering, a damaged key type would otherwise read as "no such key".

Issues

  1. A HASH index accepts NULL_STRATEGY ERROR and then stores null and missing keys without an error #9074 can make existing null-keyed rows undeletable (worth a decision before merge). HashIndex.remove(keys) and remove(keys, rid) now call checkForNulls on the non-transactional branch, and the transaction replay at commit goes through the same methods. For a hash index that already holds entries with null keys (the default strategy was ERROR but never enforced), deleting or updating such a record issues a remove with a null key, which now throws IllegalArgumentException at commit. REBUILD INDEX also fails over those rows, as the PR notes. So the only way out is to fix the data some other way or drop and recreate the index. LSM has the same behavior, but LSM has always had it, whereas for hash this is a behavior change on upgrade. Options: skip the check on remove (a removal can never insert a bad entry), or at least add a test for "delete a record whose key is null in a pre-existing hash index" so the failure mode and message are intentional, and mention it in the release notes (the current notes only mention writes and rebuild).

  2. get is not checked, LSM's is. LSMTreeIndexMutable.get calls checkForNulls, HashIndex.get does not. So WHERE k = null through the index throws on LSM with ERROR and does not on hash. If parity with LSM is the goal of A HASH index accepts NULL_STRATEGY ERROR and then stores null and missing keys without an error #9074, either add it or state that reads are deliberately lenient.

  3. Test-only mutable static in production code. HashIndexFactoryHandler.layoutVersion is a process-wide static volatile. Another test creating a hash index while HashIndexLayoutVersionTest has it lowered silently gets a legacy file. The package-private HashIndex/HashIndexBucket constructors that take a layout version already exist, so the tests could build the index through those rather than flipping a global. A real v1 file checked in as a fixture would pin on-disk compatibility better than a simulated one.

  4. Test coverage gaps.

    • No test that deliberately produces a tag collision (two different keys with the same low hash byte in one bucket) so the full-key comparison after a tag hit is exercised on purpose.
    • No remove-then-reinsert sequence on one page in the tagged layout that pins the last-slot swap carrying its tag.
    • The direct (non-transactional) put/remove null-check branches have no test.
  5. Style (CLAUDE.md).

    • Issue9169HashIndexEqualityLookupTest uses fully qualified java.util.Map.of(...); import Map.
    • HashIndexSkewedNonUniqueBenchmark uses final var builder; elsewhere the explicit type is used. The System.out.printf is acceptable there since printing is the output of a @Tag("benchmark") class.
    • A few comment lines in HashIndex (the factory handler) and HashIndexBucket (the page size constants) exceed 160 columns.
  6. Minor. HashIndexBucket.defaultPageSize hardcodes STRING/BINARY/DECIMAL. If a new variable-width key type is added later, this list silently misses it. Deriving both from one place would avoid drift.

Performance

The tag scan is O(entries per page) per probe, which is fine at 4 KB and is what the benchmark measures. The skewed NOTUNIQUE_HASH regression is acknowledged and tracked in #9228, which is reasonable as a follow-up. The 16x more pages overhead is covered by the release notes.

Verdict

Nothing here is a correctness bug in the new layout. Item 1 is the one I would settle before merging (either relax remove or document and test it); the rest are small.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review of #9222 (unordered tagged hash buckets, NULL_STRATEGY ERROR, new page size defaults)

I read the full diff and traced the new layout through put, get, remove, split, overflow and compaction. I did not run the tests. Overall this is a clean, well-scoped change and I found no blocking issues.

What I checked and found correct

  • Tag consistency across all slot movers. compactPage only rewrites slot offsets in place, so a slot's tag stays attached to the right entry. removeEntryFromPage moves offset and tag together when it swaps the last slot into the freed one. splitBucket and insertRawEntry recompute the hash per entry and pass it to appendEntry.
  • Remove loops after the swap-with-last. Restarting findNextEntry from the same p is right, because the moved entry can itself match. In the legacy layout the same call is a cheap adjacency check, or a binary search when p == 0. The specificRID loop returns on the first removal, so it needs no re-scan.
  • Tag choice. The directory uses the top hash bits and the tag uses the low byte, so the tag stays discriminating inside a bucket until the global depth is very large.
  • Version handling. The slot size follows the file version in both constructors, so v1 files still open and keep their sorted behaviour. tagged = version >= CURRENT_VERSION also tolerates a future version.
  • NULL_STRATEGY. checkForNulls runs only where the entry reaches the index (commit for transactions), the same as LSM. Refusing it only on put, and not on remove or lookup, is sensible, and the comment explains why. Extracting a shared static in LSMTreeIndexAbstract keeps the error message identical.
  • unsupportedKeyColumn. The guard in serializeKeys is a good catch. With tag filtering, a key serialized with a damaged type would otherwise read as "no such key" instead of the actionable error.
  • Tests. Both layouts are covered with 1 KB pages (so splits and overflow chains happen), plus reopen, rebuild, tag collisions, delete/insert churn and a concurrent reader. The tag-collision test finds a real colliding key rather than assuming one.

Suggestions (non-blocking)

  1. Lookup cost at large explicit page sizes. On the new layout every get, non-unique put and remove is an O(entries per page) scan of tag bytes (one readByte per slot). At the 4 KB/16 KB defaults that is fine, and your benchmark backs it. But a user who explicitly asks for 64 KB (still allowed, MAX_PAGE_SIZE is 65536) gets thousands of slot reads per probe, which is worse than the old binary search. A note in the docs or in the page size validation message saying that large pages are now slower for hash indexes would help.
  2. Silent override on rebuild. getPageSizeForNewFile replaces an explicit 65536 on a legacy index, because it cannot tell "default" from "explicitly requested". This is documented in the code and tested. Maybe mention it in the release notes too, since someone who deliberately chose 64 KB will see it change.
  3. Mutable static test hook in production code. HashIndexFactoryHandler.layoutVersion is a static volatile that tests flip. It is safe with @Execution(SAME_THREAD) and the @AfterEach reset, but if other index tests ever run concurrently in the same JVM they could pick up a legacy layout by accident. Consider also resetting it in a @BeforeEach.
  4. Downgrade behaviour. The release note says an older server cannot open a v2 index. It would be good to confirm that an older server fails with a clear error for that one index, rather than failing to start the whole database or silently ignoring the file. Worth a manual check before release.
  5. Test nits.
    • HashIndexSkewedNonUniqueBenchmark uses System.out.printf. That is fine for a @Tag("benchmark") class, but a short comment saying it is intentional would stop a future cleanup from removing it.
    • concurrentReadsDuringInsertsOnTheCurrentLayout could use a @Timeout as a hang detector (per the CLAUDE.md note), since it joins a thread.
  6. Style. The extra else { ... } braces added in HashIndex.remove(keys) and remove(keys, rid) are diff noise only; CLAUDE.md prefers no braces around a single statement. They are only needed in put.

Verdict

Looks good to merge once the downgrade behaviour (point 4) is confirmed. The rest is polish.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review of #9222 (unordered tagged hash buckets, NULL_STRATEGY ERROR on hash, new page size defaults)

I read the main-code diff in full and the new test code in part. I did not run the build or the tests. Overall this is a careful change and I found nothing blocking.

What I checked and found correct

  • Tag scan and removal: findNextEntry scans for a tag match and then compares the full key. The legacy sorted path keeps its binary search. In the remove-all loop, removeEntryFromPage moves the last slot into the freed position and the loop then re-scans from p. That handles the moved entry, and nothing can match before p.
  • Compaction and growth: compactPage and the grown-entry path in addRIDToExistingEntry rewrite only the slot offset in place, so the tag bytes stay valid. Split and overflow insertion recompute the tag from the same hash. The tag is (int) hash & 0xFF and the directory uses the top bits, so the tag adds discrimination inside a bucket.
  • Null strategy: checkForNulls runs only on the direct put, which is where a commit applies the entry. Remove and lookup stay lenient, so rows already indexed under a null key can still be deleted. That is a sensible choice, and the release notes call it out.
  • Damaged key type: the new unsupportedKeyColumn guard in serializeKeys fixes a real side effect of tag matching. A damaged type now fails with the actionable error instead of looking like "no such key".

Points worth addressing

  1. Future layout versions are read as the current one. tagged = version >= CURRENT_VERSION (HashIndexBucket.java, both constructors) means a file with version 3 or higher, for example after a later layout change, is opened as version 2 and misread silently. The opposite direction, an older server opening a v2 file, is already covered in the release notes. I would still make the loader explicit: accept only LEGACY_SORTED_VERSION and CURRENT_VERSION, treat 0 as legacy, and throw a clear IndexException for anything else.
  2. Mutable static test seam in production code. HashIndexFactoryHandler.layoutVersion is a static volatile that tests lower to create legacy files. If another test class creating hash indexes runs concurrently in the same JVM, it can get a v1 file during that window. @Execution(SAME_THREAD) only serializes within the class. It is safe if the engine tests do not run in parallel, so please confirm that. A cleaner option is to pass the layout through the package-private HashIndex constructor the tests already have, instead of a global.
  3. Null message type name. HashIndex.checkForNulls passes getTypeName() and getPropertyNames(). For an index built directly at the bucket level, or before the metadata is attached, these can be null or empty, and the error would read Indexed key null[]. Minor, and Issue9074HashIndexNullStrategyTest probably covers the TypeIndex-backed case.
  4. Lookup cost grows with page size. A lookup now scans the tags of every page in the overflow chain. The 4 KB and 16 KB defaults keep that cheap. The PR text already notes that explicit sizes above 16 KB are slower and that low-cardinality NOTUNIQUE_HASH is slow (NOTUNIQUE_HASH insert cost grows with the number of RIDs per key (rewrites the whole entry per insert) #9228). Consider documenting it in the withPageSize docs, or logging a warning, for hash indexes with a page size above 16 KB.
  5. Rebuild treats an explicit 64 KB as the old default. This is documented. It is a silent override of an explicit request, so I would keep that wording in the user docs and not only in the release notes.

Style and conventions

  • HashIndexSkewedNonUniqueBenchmark uses System.out.printf. The CLAUDE.md rule says to remove debug output, but here the output is the benchmark result and the class is @Tag("benchmark"), so I consider this acceptable. The Javadoc already explains it.
  • A few comment lines in HashIndex.java and HashIndexBucket.java pass 130 characters, outside the surrounding wrapping. Cosmetic.
  • In HashIndexLayoutVersionTest the imports are slightly out of order (Execution/ExecutionMode between Timeout and Test). Cosmetic.

Tests
Coverage looks good. The tests cover both layouts on tiny pages, which exercises splits and overflow chains. They also cover reopen, rebuild from v1 to v2, the page size defaults, the ERROR strategy and the SQL/Cypher equality lookups. Two gaps I would add:

  • a test that opens a file with an unsupported layout version (see point 1);
  • a mixed workload test on the tagged layout, with deletes interleaved with inserts on the same page. It would exercise swap-with-last removal together with compaction and a later insert.

Thanks for the thorough release-note section. The downgrade corruption warning is important, and it may be worth also putting it in the upgrade docs.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review of #9222 (unordered tagged hash buckets, NULL_STRATEGY ERROR on hash, new page size defaults)

Overall this is a careful change. I read the diff and the surrounding HashIndexBucket code (split, compaction, overflow, remove paths) and found no correctness blocker.

What I checked and found correct

  • Tag maintenance on every slot mutation: appendEntry writes slot + tag, removeEntryFromPage moves the last slot's offset and tag together, compactPage only rewrites offsets and keeps slot positions (so tags and pos stay valid), splitBucket/insertRawEntry recompute the hash and pass it down. addRIDToExistingEntry only rewrites the offset, which is right since the key (and tag) is unchanged.
  • Remove loops: after the swap-with-last removal the code re-searches from p instead of advancing, which is correct for the unordered layout and still correct for the legacy sorted one.
  • Tag choice: the directory consumes the top hash bits and the tag takes the low byte, so keys sharing a bucket still spread over the 256 tags.
  • Versioning: isTaggedLayout refuses unknown versions instead of misreading pages, and serializeKeys fails loudly for damaged key-type metadata (needed now that a lookup only parses tag-matching entries).
  • A HASH index accepts NULL_STRATEGY ERROR and then stores null and missing keys without an error #9074: checking only on put (not remove/lookup) is the right call, and sharing the message through LSMTreeIndexAbstract.checkForNulls keeps both index types consistent.
  • Tests: both layouts are parameterized across insert/lookup/remove, reopen, rebuild, forced tag collisions, churn, a miss never matching, and concurrent reads during inserts. Good regression coverage.

Suggestions (non-blocking)

  1. Mutable static test hook in production code: HashIndexFactoryHandler.layoutVersion is a static volatile global that tests flip. If any other test creates hash indexes concurrently in the same JVM (e.g. if parallel test classes are ever enabled) it would silently create legacy-layout files. Since you already added the package-private HashIndex(..., layoutVersion) constructor, the legacy-layout tests could build the index through it directly and drop the global.
  2. Public static overload LSMTreeIndexAbstract.checkForNulls(strategy, typeName, propertyNames, keys) widens the public API of the LSM class just to share one message. Consider a small shared helper if you prefer not to expose it from an LSM class. Minor.
  3. Default page size for NOTUNIQUE_HASH: your own notes say low-cardinality non-unique inserts are slow at every page size. With 4 KB pages a hot key's RID list spills into an overflow chain about 16x longer than at 64 KB, and putInternal walks that chain to find the existing entry on each insert. Not a new class of problem, but the default change makes the constant factor worse for that workload. Worth quoting the HashIndexSkewedNonUniqueBenchmark numbers (4 KB vs 64 KB at 10 / 200 keys) in the PR description so the trade-off is visible, and keeping NOTUNIQUE_HASH insert cost grows with the number of RIDs per key (rewrites the whole entry per insert) #9228 prioritized.
  4. Behavior change for large STRING/BINARY keys: with the new default, a key wider than about 16 KB is refused at insert on a newly created index, where the old 64 KB default accepted it. A rebuild of a legacy index also takes the new default. The release notes mention page size but not this max key length consequence; one sentence would help.
  5. Downgrade hazard: an older server will read new pages as sorted ones and corrupt the index, because the version in the file name is not checked there. That is a silent-corruption failure mode, so it deserves one prominent release-notes entry (currently it appears twice in slightly different words near the end of the PR body).
  6. Benchmark printing: HashIndexSkewedNonUniqueBenchmark prints by design and is tagged @tag("benchmark"), so it is acceptable under the CLAUDE.md rules.

Verdict
No blocking issues from my read. Items 1 and 3 are the ones I would act on before merge; the rest are polish. I did not run the test suite myself; the PR reports 2477 engine index/schema tests passing, so please confirm CI is green.

@codecov

codecov Bot commented Oct 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.13725% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.85%. Comparing base (3f2d6b5) to head (8653fbb).
⚠️ Report is 27 commits behind head on main.

Files with missing lines Patch % Lines
.../java/com/arcadedb/index/hash/HashIndexBucket.java 93.97% 3 Missing and 2 partials ⚠️
...c/main/java/com/arcadedb/index/hash/HashIndex.java 87.50% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9222      +/-   ##
============================================
- Coverage     76.85%   76.85%   -0.01%     
- Complexity     3915     3919       +4     
============================================
  Files          2124     2125       +1     
  Lines        212397   212275     -122     
  Branches      45094    45052      -42     
============================================
- Hits         163239   163137     -102     
- Misses        31691    31697       +6     
+ Partials      17467    17441      -26     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@lvca
lvca merged commit 9fbef12 into main Oct 4, 2026
@lvca
lvca deleted the fix/9169-9074-5712-hash-index branch October 4, 2026 20:13
tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Oct 5, 2026
… UNIQUE_HASH at the 26.10.1 re-pin (#181)

Per the maintainers' answer on ArcadeData#9169 (PR ArcadeData#9222): the lines to change, what stays UNIQUE or LSM and why, the measured effect in the lane's own query patterns (OLTP columns for ArcadeDB, ingest columns against it on ascending keys), the page's condition sentence, and the re-measure on the bench host at the re-pin. Status pending.


Claude-Session: https://claude.ai/code/session_01Ubz3m6QXHESerCkehC1qgi

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Oct 5, 2026
…TION_INTERVAL for hourly time series (ArcadeData#9166), across docs, source, tests, examples (#178)

* bindings: apply the maintainers' index and time-series best practices (UNIQUE_HASH for ids, COMPACTION_INTERVAL for hourly aggregates)

An id that is only read, updated and deleted by equality gets UNIQUE_HASH
(ArcadeData#9169, fixed in ArcadeData#9222, 26.10.1): docs snippets, examples 04
(Link.movieId), 21 and 26, and the create_index docstrings. UNIQUE stays where the
key is also ordered (Movie.movieId in example 04). The queries guide gains an
"Index choice for an id" paragraph with the maintainers' numbers and what we measured
on 26.9.1 (old sorted hash layout, 2.5 to 6 times slower loads), and the schema API
page follows it.

Example 17 declares COMPACTION_INTERVAL 1 HOURS in both CREATE TIMESERIES TYPE
statements, since every query it runs is an hourly bucket (ArcadeData#9166); the async executor
page, the server guide and the example pages carry the pointer.

New test: a UNIQUE_HASH id end to end (SQL and openCypher lookup, update and delete
by id, EXPLAIN shows FETCH FROM INDEX, duplicate rejected). It passes on 26.9.1 and
26.10.1, so it has no version guard. The testing pages follow it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ubz3m6QXHESerCkehC1qgi

* bindings docs: page cache share (ArcadeData#9168) and index default page size (ArcadeData#9175) in Memory Planning, now that PR ArcadeData#9250 merged

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ubz3m6QXHESerCkehC1qgi

* bindings: UNIQUE_HASH rule is equality only and not bulk-loaded in key order, lookup_by_key is O(1) only for a hash index, hash NULL_STRATEGY ERROR is enforced from 26.10.1

Measured on 26.10.1 main (10 runs per arm on Temurin 21 and 25, 200,000 and 2,000,000 LONG ids, same answers): UNIQUE_HASH against UNIQUE answers SQL id = ? 1.5 to 2.3 times faster, an Index.get() hit 1.9 to 3.1 times, an UPDATE by id 1.04 to 1.13 times, a DELETE by id level, and inserts 1.14 to 1.23 times faster for shuffled ids but 9% to 16% slower for ascending ids. The known-issues sentence on hash indexes for identifiers now points at that rule. The hash null strategy note was checked on the 26.9.1 release (accepts null and missing keys) and on 3543960 (REBUILD INDEX over null rows fails and leaves the type without the index; deleting the rows first lets it rebuild).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ubz3m6QXHESerCkehC1qgi

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant