Skip to content

Validate darts-clone trie offsets at model load - #1216

Merged
taku910 merged 1 commit into
google:masterfrom
TristanInSec:validate-trie-array-bounds
Apr 22, 2026
Merged

taku910 merged 1 commit into
google:masterfrom
TristanInSec:validate-trie-array-bounds

Conversation

@TristanInSec

@TristanInSec TristanInSec commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add a validate() method to DoubleArrayImpl that performs a single O(n) scan
of the trie array at model load, verifying that every offset-derived position
stays within the allocated array. This catches malformed trie data early
without adding any overhead to the search hot path.

  • darts.h: add validate() that checks (i ^ offset) | 0xFF < size_ for
    each unit with a non-zero offset
  • normalizer.cc: call validate() after set_array(), reject the model if
    the check fails

Approach

For each unit at position i with offset o, children are reachable at
(i ^ o) ^ c for all byte values c in [0, 255]. The maximum of that
expression is (i ^ o) | 0xFF. If that exceeds the array size, the trie
is structurally invalid.

Running the check once during Normalizer::Init() is sufficient because the
array is immutable after loading.

@taku910

taku910 commented Apr 20, 2026

Copy link
Copy Markdown
Collaborator

Can you provide concrete examples of when this check would be necessary?
It seems like it could be a performance bottleneck. Do you have any analysis or insights on this?

@TristanInSec

Copy link
Copy Markdown
Contributor Author

The check is needed when loading model files from untrusted sources (model marketplaces, user uploads, shared pipelines). A crafted .model file can embed a precompiled_charsmap blob where the first trie unit's offset() field encodes a value up to ~2^30. On the first call to commonPrefixSearch(), node_pos ^= unit.offset() ^ key[0] lands far past the trie allocation, causing a heap out-of-bounds read.

Concrete example: set unit[0] to 0x00080000, which gives offset() = 512. With a minimum-size trie (256 units / 1024 bytes), the first lookup reads 1284 bytes past the allocation. ASan confirms:

heap-buffer-overflow on address ... READ of size 4
0x... is located 1284 bytes after 1024-byte region

On performance: the bounds check is a single node_pos >= size_ comparison per loop iteration. Since size_ stays in a register and the branch is almost never taken in normal operation, the CPU branch predictor will correctly predict it on every call. I'd expect it to be below noise in any benchmark, but I'm happy to run a before/after measurement on a standard model if that would help.

@taku910

taku910 commented Apr 21, 2026

Copy link
Copy Markdown
Collaborator

Thank you for the details.

Currently, the PR is trying to ignore errors and fall back to a generic default process. This isn't ideal because it essentially suppresses the error and can lead to unexpected behavior.

Would it be possible to scan the memory image and perform a range check just once during model loading? That would be much more preferable.

@TristanInSec
TristanInSec force-pushed the validate-trie-array-bounds branch from 1137b1b to 5eed76e Compare April 21, 2026 10:23
Move bounds checking from the hot search path (exactMatchSearch,
commonPrefixSearch, traverse) to a one-time validate() scan at
model load.  For each array unit, verify that (position ^ offset)
stays within the allocated array for all 256 possible child bytes.

Call validate() in Normalizer::Init() right after set_array().
If the trie contains out-of-bounds offsets the model is rejected
before any query is served.
@TristanInSec
TristanInSec force-pushed the validate-trie-array-bounds branch from 5eed76e to 0313764 Compare April 21, 2026 10:24
@TristanInSec TristanInSec changed the title Add bounds checking to darts-clone trie search methods Validate darts-clone trie offsets at model load Apr 21, 2026
@TristanInSec

Copy link
Copy Markdown
Contributor Author

Hi @taku910, thank you for the feedback. I reworked the PR to move all bounds checking to model load time.

The new approach adds a validate() method to DoubleArrayImpl that performs a single O(n) scan of the array right after set_array() in Normalizer::Init(). For each unit at position i with a non-zero offset o, it verifies that the maximum reachable child position `(i ^ o) | 0xFF` stays within the array bounds. Since the array is immutable after loading, a single pass is sufficient to guarantee all subsequent searches stay in bounds.

The search methods (exactMatchSearch, commonPrefixSearch, traverse) are left unchanged.

@taku910
taku910 merged commit 57a257f into google:master Apr 22, 2026
1 check passed
@taku910

taku910 commented Apr 22, 2026

Copy link
Copy Markdown
Collaborator

The unitest has start failing, so let us revert this PR.

@TristanInSec

Copy link
Copy Markdown
Contributor Author

Hi @taku910, the unit test failure appears unrelated to this PR.

The "CI for general build" workflow (which runs all unit tests) passed on all 14 platforms after the merge: ubuntu x64/arm64, macos x64/arm64, windows x64/Win32/ARM64, both internal and module builds.

The only failing workflow is "Build Wheels on windows-latest", which errors out trying to build patchelf on Windows ('.\configure' is not recognized). This is a Windows CI infrastructure issue with patchelf's CMake configure step, not a test failure.

Could you point me to which specific test is failing? Happy to investigate and fix if there is a real issue.

@taku910

taku910 commented May 1, 2026

Copy link
Copy Markdown
Collaborator

You can reproduce the test error with following command:
Some test fails due to the pre-compiled map has out-of-bounds node.

% curl -L https://github.com/google/sentencepiece/pull/1216.patch | git apply 
% mkdir build
% cd build
%  cmake -DSPM_BUILD_TEST=ON -DSPM_ENABLE_SHARED=OFF ..
% ctest
...
% cat Testing/Temporary/LastTest.log
uilder.cc(394) LOG(ERROR) NFK compile is not enabled. rebuild with -DSPM_ENABLE_NFKC_COMPILE=ON
[       OK ] BuilderTest.BuildNFKCMapTest
[ RUN      ] BuilderTest.GetPrecompiledCharsMapTest
sentencepiece_trainer.cc(95) [_status.ok()] Internal: Trie data contains out-of-bounds node references.
Program terminated with an unrecoverable error.
<end of output>
Test time =   3.05 sec
----------------------------

@TristanInSec

Copy link
Copy Markdown
Contributor Author

Thank you for the detailed reproduction steps and for identifying the root cause. You were right that the pre-compiled NFKC maps have leaf units whose stored values decode to large offsets.

I've submitted a fix in #1224. The issue was that validate() checked the offset() field on every unit, but leaf/value units (where label() > 0xFF) store data in that field rather than child pointers. The fix skips those units, matching the same pattern already used in open().

taku910 pushed a commit that referenced this pull request May 1, 2026
Adds a validate() method to DoubleArrayImpl that checks whether
internal node offsets reference positions within the array bounds.
Leaf/value units (identified by label() > 0xFF) are skipped, since
their offset field encodes the stored value rather than a child
pointer. This matches the existing pattern used in open().

Called during Normalizer::Init() after set_array() to reject
corrupted or malicious model files before they can trigger
out-of-bounds reads during trie traversal.

Fixes the test regression from #1216 where pre-compiled NFKC maps
were incorrectly rejected because leaf unit values were being
interpreted as child pointers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants